Skip to content

Commit 1f9ef78

Browse files
authored
Merge pull request #496 from siyanshen/automated-cherry-pick-of-#493-upstream-release-1.12
Add identity provider into mount options
2 parents 5462a1c + a1092e3 commit 1f9ef78

File tree

6 files changed

+44
-58
lines changed

6 files changed

+44
-58
lines changed

pkg/cloud_provider/auth/fake.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,10 @@ func (tm *fakeTokenManager) GetTokenSourceFromK8sServiceAccount(saNamespace, saN
3131
return &FakeGCPTokenSource{k8sSAName: saName, k8sSANamespace: saNamespace}
3232
}
3333

34+
func (tm *fakeTokenManager) GetIdentityProvider() string {
35+
return "fake.identity.provider"
36+
}
37+
3438
type FakeGCPTokenSource struct {
3539
k8sSAName string
3640
k8sSANamespace string

pkg/cloud_provider/auth/token_manager.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ const (
3131

3232
type TokenManager interface {
3333
GetTokenSourceFromK8sServiceAccount(saNamespace, saName, saToken string) oauth2.TokenSource
34+
GetIdentityProvider() string
3435
}
3536

3637
type tokenManager struct {
@@ -47,6 +48,10 @@ func NewTokenManager(meta metadata.Service, clientset clientset.Interface) Token
4748
return &tm
4849
}
4950

51+
func (tm *tokenManager) GetIdentityProvider() string {
52+
return tm.meta.GetIdentityProvider()
53+
}
54+
5055
func (tm *tokenManager) GetTokenSourceFromK8sServiceAccount(saNamespace, saName, saToken string) oauth2.TokenSource {
5156
return &GCPTokenSource{
5257
meta: tm.meta,

pkg/csi_driver/node.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ package driver
2020
import (
2121
"fmt"
2222
"os"
23-
"strconv"
2423
"strings"
2524
"time"
2625

@@ -141,8 +140,9 @@ func (s *nodeServer) NodePublishVolume(ctx context.Context, req *csi.NodePublish
141140
return nil, status.Errorf(codes.NotFound, "failed to get pod: %v", err)
142141
}
143142

144-
if pod.Spec.HostNetwork {
145-
fuseMountOptions = joinMountOptions(fuseMountOptions, []string{"start-token-server=" + strconv.FormatBool(s.shouldStartTokenServer(pod))})
143+
if s.shouldStartTokenServer(pod) && pod.Spec.HostNetwork {
144+
identityProvider := s.driver.config.TokenManager.GetIdentityProvider()
145+
fuseMountOptions = joinMountOptions(fuseMountOptions, []string{"token-server-identity-provider=" + identityProvider})
146146
}
147147

148148
// Since the webhook mutating ordering is not definitive,
@@ -301,7 +301,7 @@ func (s *nodeServer) prepareStorageService(ctx context.Context, vc map[string]st
301301
func (s *nodeServer) shouldStartTokenServer(pod *corev1.Pod) bool {
302302
for _, vol := range pod.Spec.Volumes {
303303
if vol.Name == webhook.SidecarContainerSATokenVolumeName {
304-
klog.Infof("Pod has sa vol injected")
304+
klog.Infof("Service Account Token Injection feature is turned on.")
305305

306306
return true
307307
}

pkg/sidecar_mounter/sidecar_mounter.go

Lines changed: 8 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,8 @@ import (
2626
"io"
2727
"net"
2828
"net/http"
29-
"net/url"
3029
"os"
3130
"os/exec"
32-
"path"
3331
"path/filepath"
3432
"strings"
3533
"sync"
@@ -64,10 +62,10 @@ func New(mounterPath string) *Mounter {
6462

6563
func (m *Mounter) Mount(ctx context.Context, mc *MountConfig) error {
6664
// Start the token server for HostNetwork enabled pods.
67-
if mc.PodShouldUseTokenServer {
65+
if mc.TokenServerIdentityProvider != "" {
6866
tp := filepath.Join(mc.TempDir, TokenFileName)
6967
klog.Infof("Pod has hostNetwork enabled and token server feature is turned on. Starting Token Server on %s.", tp)
70-
go StartTokenServer(ctx, tp)
68+
go StartTokenServer(ctx, tp, mc.TokenServerIdentityProvider)
7169
}
7270

7371
klog.Infof("start to mount bucket %q for volume %q", mc.BucketName, mc.VolumeName)
@@ -302,13 +300,13 @@ func getK8sTokenFromFile(tokenPath string) (string, error) {
302300
return strings.TrimSpace(string(token)), nil
303301
}
304302

305-
func fetchIdentityBindingToken(ctx context.Context, k8sSAToken string) (*oauth2.Token, error) {
303+
func fetchIdentityBindingToken(ctx context.Context, k8sSAToken string, identityProvider string) (*oauth2.Token, error) {
306304
stsService, err := sts.NewService(ctx, option.WithHTTPClient(&http.Client{}))
307305
if err != nil {
308306
return nil, fmt.Errorf("new STS service error: %w", err)
309307
}
310308

311-
audience, err := getAudienceFromContext(ctx)
309+
audience, err := getAudienceFromContextAndIdentityProvider(ctx, identityProvider)
312310
if err != nil {
313311
return nil, fmt.Errorf("failed to get audience from the context: %w", err)
314312
}
@@ -334,39 +332,23 @@ func fetchIdentityBindingToken(ctx context.Context, k8sSAToken string) (*oauth2.
334332
}, nil
335333
}
336334

337-
func getAudienceFromContext(ctx context.Context) (string, error) {
335+
func getAudienceFromContextAndIdentityProvider(ctx context.Context, identityProvider string) (string, error) {
338336
projectID, err := metadata.ProjectIDWithContext(ctx)
339337
if err != nil {
340338
return "", fmt.Errorf("failed to get project ID: %w", err)
341339
}
342-
// Get all instance metadata attributes
343-
clusterLocation, err := metadata.InstanceAttributeValueWithContext(ctx, "cluster-location")
344-
if err != nil {
345-
return "", fmt.Errorf("failed to get clusterLocation: %w", err)
346-
}
347-
clusterName, err := metadata.InstanceAttributeValueWithContext(ctx, "cluster-name")
348-
if err != nil {
349-
return "", fmt.Errorf("failed to get clusterName: %w", err)
350-
}
351-
352-
klog.Infof("projectID: %s, clusterName: %s, clusterLocation: %s", projectID, clusterName, clusterLocation)
353-
onePlatformClusterResourceURL := &url.URL{
354-
Scheme: "https",
355-
Host: "container.googleapis.com",
356-
Path: path.Join("v1", "projects", projectID, "locations", clusterLocation, "clusters", clusterName),
357-
}
358340

359341
audience := fmt.Sprintf(
360342
"identitynamespace:%s.svc.id.goog:%s",
361343
projectID,
362-
onePlatformClusterResourceURL,
344+
identityProvider,
363345
)
364346
klog.Infof("audience: %s", audience)
365347

366348
return audience, nil
367349
}
368350

369-
func StartTokenServer(ctx context.Context, tokenURLSocketPath string) {
351+
func StartTokenServer(ctx context.Context, tokenURLSocketPath string, identityProvider string) {
370352
// Create a unix domain socket and listen for incoming connections.
371353
tokenSocketListener, err := net.Listen("unix", tokenURLSocketPath)
372354
if err != nil {
@@ -388,7 +370,7 @@ func StartTokenServer(ctx context.Context, tokenURLSocketPath string) {
388370

389371
return
390372
}
391-
stsToken, err = fetchIdentityBindingToken(ctx, k8stoken)
373+
stsToken, err = fetchIdentityBindingToken(ctx, k8stoken, identityProvider)
392374
if err != nil {
393375
klog.Errorf("failed to get sts token from path %v", err)
394376
w.WriteHeader(http.StatusInternalServerError)

pkg/sidecar_mounter/sidecar_mounter_config.go

Lines changed: 21 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -35,27 +35,27 @@ import (
3535
)
3636

3737
const (
38-
GCSFuseAppName = "gke-gcs-fuse-csi"
39-
TempDir = "/temp-dir"
40-
unixSocketBasePath = "unix://"
41-
TokenFileName = "token.sock" // #nosec G101
42-
tokenServerFlag = "start-token-server"
38+
GCSFuseAppName = "gke-gcs-fuse-csi"
39+
TempDir = "/temp-dir"
40+
unixSocketBasePath = "unix://"
41+
TokenFileName = "token.sock" // #nosec G101
42+
identityProviderFlag = "token-server-identity-provider"
4343
)
4444

4545
// MountConfig contains the information gcsfuse needs.
4646
type MountConfig struct {
47-
FileDescriptor int `json:"-"`
48-
VolumeName string `json:"volumeName,omitempty"`
49-
BucketName string `json:"bucketName,omitempty"`
50-
BufferDir string `json:"-"`
51-
CacheDir string `json:"-"`
52-
TempDir string `json:"-"`
53-
ConfigFile string `json:"-"`
54-
Options []string `json:"options,omitempty"`
55-
ErrWriter stderrWriterInterface `json:"-"`
56-
FlagMap map[string]string `json:"-"`
57-
ConfigFileFlagMap map[string]string `json:"-"`
58-
PodShouldUseTokenServer bool `json:"-"`
47+
FileDescriptor int `json:"-"`
48+
VolumeName string `json:"volumeName,omitempty"`
49+
BucketName string `json:"bucketName,omitempty"`
50+
BufferDir string `json:"-"`
51+
CacheDir string `json:"-"`
52+
TempDir string `json:"-"`
53+
ConfigFile string `json:"-"`
54+
Options []string `json:"options,omitempty"`
55+
ErrWriter stderrWriterInterface `json:"-"`
56+
FlagMap map[string]string `json:"-"`
57+
ConfigFileFlagMap map[string]string `json:"-"`
58+
TokenServerIdentityProvider string `json:"-"`
5959
}
6060

6161
var prometheusPort = 62990
@@ -171,7 +171,7 @@ func (mc *MountConfig) prepareMountArgs() {
171171
invalidArgs := []string{}
172172

173173
for _, arg := range mc.Options {
174-
if strings.Contains(arg, ":") {
174+
if strings.Contains(arg, ":") && !strings.Contains(arg, "https") {
175175
i := strings.LastIndex(arg, ":")
176176
f, v := arg[:i], arg[i+1:]
177177

@@ -217,13 +217,8 @@ func (mc *MountConfig) prepareMountArgs() {
217217
value = argPair[1]
218218
}
219219

220-
if flag == tokenServerFlag {
221-
val, err := strconv.ParseBool(value)
222-
if err != nil {
223-
klog.Errorf("failed to parse start-token-server flag value: %v", err)
224-
} else {
225-
mc.PodShouldUseTokenServer = val
226-
}
220+
if flag == identityProviderFlag {
221+
mc.TokenServerIdentityProvider = value
227222

228223
continue
229224
}
@@ -290,7 +285,7 @@ func (mc *MountConfig) prepareConfigFile() error {
290285
}
291286
}
292287
}
293-
if mc.PodShouldUseTokenServer {
288+
if mc.TokenServerIdentityProvider != "" {
294289
configMap["gcs-auth"] = map[string]interface{}{
295290
"token-url": unixSocketBasePath + filepath.Join(mc.TempDir, TokenFileName),
296291
}

pkg/sidecar_mounter/sidecar_mounter_config_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ func TestPrepareMountArgs(t *testing.T) {
8888
BufferDir: "test-buffer-dir",
8989
CacheDir: "test-cache-dir",
9090
ConfigFile: "test-config-file",
91-
Options: []string{"uid=100", "gid=200", "debug_gcs", "max-conns-per-host=10", "implicit-dirs", "write:create-empty-file:false", "logging:severity:error", "write:create-empty-file:true"},
91+
Options: []string{"uid=100", "gid=200", "token-server-identity-provider=https://fakeresource", "debug_gcs", "max-conns-per-host=10", "implicit-dirs", "write:create-empty-file:false", "logging:severity:error", "write:create-empty-file:true"},
9292
},
9393
expectedArgs: map[string]string{
9494
"implicit-dirs": "",
@@ -327,7 +327,7 @@ func TestPrepareConfigFile(t *testing.T) {
327327
"metadata-cache:type-cache-max-size-mb": "-1",
328328
"cache-dir": "/gcsfuse-cache/.volumes/volume-name",
329329
},
330-
PodShouldUseTokenServer: true,
330+
TokenServerIdentityProvider: "https://container.googleapis.com/v1/projects/fake-project/locations/us-central1/clusters/fake-cluster",
331331
},
332332
expectedConfig: map[string]interface{}{
333333
"logging": map[string]interface{}{

0 commit comments

Comments
 (0)