← Back to Pull requests

gke-gcloud-auth-plugin: invalidate cached tokens when gcloud config changes #1249

Merged
immanuwell merged 2 files (314 lines) on Jul 24, 2026 23:05 UTC
View on GitHub
immanuwell immanuwell commented on Jul 10, 2026 09:22 UTC
Author

Fixes #1122

The plugin can reuse a cached token after CLOUDSDK_CONFIG switches to another active account. Same kube context, wrong creds sneak through.

This stores the active gcloud config in the cache key, then refreshes the token when that config changes. Old cache gets invalidated once, then its all good.

Repro
1. export KUBECONFIG=$HOME/.config/gk8s/t/dev
2. export CLOUDSDK_CONFIG=$HOME/.config/gcloud-one
3. gcloud auth activate-service-account --key-file=keyfile-admin
4. kubectl get nodes
5. export CLOUDSDK_CONFIG=$HOME/.config/gcloud-two
6. gcloud auth activate-service-account --key-file=keyfile-restricted-user
7. kubectl get nodes

Before this PR, step 7 can still use the admin token. Kinda sneaky.

Tests

  • go test ./cmd/gke-gcloud-auth-plugin

  • go test ./cmd/...
  • Diff: 314 lines (+289 / -25) across 2 files Reviewer: hdp617 Review duration: 20982m
    All Vouch review confidence checks passed
    Residual risk 0.08 = Change Risk (0.62) × (1 − Review Confidence (0.87)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.62 · 314 lines diff across 2 files
    0.62
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.89 · 5 substantive comment(s)
    0.89
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    86%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.344
    Sensitive Paths sensitive_paths
    0.062
    Real PR Conversation Timeline
    18 items
    kubernetes-prow[bot] kubernetes-prow[bot] commented on Jul 10, 2026 09:23 UTC
    Bot

    This issue is currently awaiting triage.

    If the repository mantainers determine this is a relevant issue, they will accept it by applying the triage/accepted label and provide further guidance.

    The triage/accepted label can be added by org members by writing /triage accepted in a comment.

    <details>

    Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.
    </details>

    kubernetes-prow[bot] kubernetes-prow[bot] commented on Jul 10, 2026 09:23 UTC
    Bot

    Hi @immanuwell. Thanks for your PR.

    I'm waiting for a kubernetes member to verify that this patch is reasonable to test. If it is, they should reply with /ok-to-test on its own line. Until that is done, I will not automatically test new commits in this PR, but the usual testing commands by org members will still work.

    >[!TIP]
    >We noticed you've done this a few times! Consider joining the org to skip this step and gain /lgtm and other bot rights. We recommend asking approvers on your previous PRs to sponsor you.

    Once the patch is verified, the new status will be reflected by the ok-to-test label.

    I understand the commands that are listed here.

    <details>

    Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.
    </details>

    hdp617 hdp617 commented on Jul 10, 2026 15:07 UTC
    Contributor

    /ok-to-test

    hdp617 hdp617 commented on code on Jul 13, 2026 23:08 UTC
    Code Review
    cmd/gke-gcloud-auth-plugin/cred.go:1
    @@ -334,10 +348,61 @@ func (p *plugin) getCachedGcloudAccessToken() (string, *metav1.Time, error) {
     	if c.ExtraArgs != strings.Join(p.tokenProvider.getExtraArgs(), " ") {
     		return "", nil, fmt.Errorf("cache is invalid as the passed in args have changed")
     	}
    +	currentGcloudConfig, err := p.currentGcloudConfig()
    +	if err != nil {
    +		return "", nil, fmt.Errorf("error retrieving gcloud config: %w", err)
    +	}
    +	if !gcloudConfigsEqual(c.GcloudConfig, currentGcloudConfig) {
    +		return "", nil, fmt.Errorf("cache is invalid as the gcloud config changed")
    +	}
     
     	return c.AccessToken, &metav1.Time{Time: expiryTimeStamp}, nil
     }
     
    +func (p *plugin) currentGcloudConfig() (*gcloudConfig, error) {
    +	if _, ok := p.tokenProvider.(*gcloudTokenProvider); !ok {
    +		return nil, nil
    +	}
    +
    +	configDir := os.Getenv("CLOUDSDK_CONFIG")
    +	if configDir == "" {
    +		userConfigDir, err := os.UserConfigDir()

    This doesn't work on macOS because Go’s os.UserConfigDir() resolves to ~/Library/Application.

    https://pkg.go.dev/os#UserConfigDir

    hdp617 hdp617 commented on code on Jul 13, 2026 23:09 UTC
    Code Review
    cmd/gke-gcloud-auth-plugin/cred.go:1
    @@ -334,10 +348,61 @@ func (p *plugin) getCachedGcloudAccessToken() (string, *metav1.Time, error) {
     	if c.ExtraArgs != strings.Join(p.tokenProvider.getExtraArgs(), " ") {
     		return "", nil, fmt.Errorf("cache is invalid as the passed in args have changed")
     	}
    +	currentGcloudConfig, err := p.currentGcloudConfig()
    +	if err != nil {
    +		return "", nil, fmt.Errorf("error retrieving gcloud config: %w", err)

    Should this be treated as a cache invalidation/miss?

    hdp617 hdp617 commented on code on Jul 13, 2026 23:13 UTC
    Code Review
    cmd/gke-gcloud-auth-plugin/cred.go:1
    @@ -334,10 +348,61 @@ func (p *plugin) getCachedGcloudAccessToken() (string, *metav1.Time, error) {
     	if c.ExtraArgs != strings.Join(p.tokenProvider.getExtraArgs(), " ") {
     		return "", nil, fmt.Errorf("cache is invalid as the passed in args have changed")
     	}
    +	currentGcloudConfig, err := p.currentGcloudConfig()
    +	if err != nil {
    +		return "", nil, fmt.Errorf("error retrieving gcloud config: %w", err)
    +	}
    +	if !gcloudConfigsEqual(c.GcloudConfig, currentGcloudConfig) {
    +		return "", nil, fmt.Errorf("cache is invalid as the gcloud config changed")
    +	}
     
     	return c.AccessToken, &metav1.Time{Time: expiryTimeStamp}, nil
     }
     
    +func (p *plugin) currentGcloudConfig() (*gcloudConfig, error) {
    +	if _, ok := p.tokenProvider.(*gcloudTokenProvider); !ok {
    +		return nil, nil
    +	}
    +
    +	configDir := os.Getenv("CLOUDSDK_CONFIG")
    +	if configDir == "" {
    +		userConfigDir, err := os.UserConfigDir()
    +		if err != nil {
    +			return nil, err
    +		}
    +		configDir = filepath.Join(userConfigDir, "gcloud")
    +	}
    +
    +	activeConfigContents, err := p.readFile(filepath.Join(configDir, activeConfig))
    +	if err != nil {
    +		return nil, err
    +	}
    +	activeConfigName := strings.TrimSpace(string(activeConfigContents))
    +	if activeConfigName == "" {
    +		return nil, fmt.Errorf("active gcloud configuration is empty")
    +	}
    +
    +	configContents, err := p.readFile(filepath.Join(configDir, "configurations", "config_"+activeConfigName))
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	return &gcloudConfig{
    +		ConfigDir:            configDir,
    +		ActiveConfig:         activeConfigName,
    +		ActiveConfigContents: string(configContents),

    Let's avoid duplicate raw file contents into the kube cache. How about hashing this?

    hdp617 hdp617 commented on Jul 13, 2026 23:19 UTC
    Contributor

    Thanks for looking into this! Thinking about reliability, the blast radius of breaking kubectl authentication is huge. Let's take a step back and think about how to roll out this feature safely.

    I'd recommend the following:
    Add a feature gate e.g. an env var like GKE_AUTH_PLUGIN_STRICT_CACHE_INVALIDATION. This should be opt-in at first, and we can flip it to default-on in a future release once it has bake time.
    Ensure that any errors encountered while reading or parsing the gcloud config files do not bubble up and fail the kubectl command. If the file is unreadable, log a warning and gracefully fall back to the legacy caching behavior.

  • Add some debug logs when a cache miss is intentionally triggered by this new file-diffing logic so we can trace it if users report unexpected token refreshes."
  • hdp617 hdp617 commented on code on Jul 13, 2026 23:34 UTC
    Code Review
    cmd/gke-gcloud-auth-plugin/cred.go:1
    @@ -334,10 +348,61 @@ func (p *plugin) getCachedGcloudAccessToken() (string, *metav1.Time, error) {
     	if c.ExtraArgs != strings.Join(p.tokenProvider.getExtraArgs(), " ") {
     		return "", nil, fmt.Errorf("cache is invalid as the passed in args have changed")
     	}
    +	currentGcloudConfig, err := p.currentGcloudConfig()
    +	if err != nil {
    +		return "", nil, fmt.Errorf("error retrieving gcloud config: %w", err)
    +	}
    +	if !gcloudConfigsEqual(c.GcloudConfig, currentGcloudConfig) {
    +		return "", nil, fmt.Errorf("cache is invalid as the gcloud config changed")
    +	}
     
     	return c.AccessToken, &metav1.Time{Time: expiryTimeStamp}, nil
     }
     
    +func (p *plugin) currentGcloudConfig() (*gcloudConfig, error) {
    +	if _, ok := p.tokenProvider.(*gcloudTokenProvider); !ok {
    +		return nil, nil
    +	}
    +
    +	configDir := os.Getenv("CLOUDSDK_CONFIG")
    +	if configDir == "" {
    +		userConfigDir, err := os.UserConfigDir()
    +		if err != nil {
    +			return nil, err
    +		}
    +		configDir = filepath.Join(userConfigDir, "gcloud")
    +	}
    +
    +	activeConfigContents, err := p.readFile(filepath.Join(configDir, activeConfig))

    The gcloud CLI also supports CLOUDSDK_ACTIVE_CONFIG_NAME. What would be the behavior when it's set?

    https://docs.cloud.google.com/sdk/docs/configurations

    immanuwell immanuwell commented on code on Jul 17, 2026 08:12 UTC
    Code Review
    cmd/gke-gcloud-auth-plugin/cred.go:1
    @@ -334,10 +348,61 @@ func (p *plugin) getCachedGcloudAccessToken() (string, *metav1.Time, error) {
     	if c.ExtraArgs != strings.Join(p.tokenProvider.getExtraArgs(), " ") {
     		return "", nil, fmt.Errorf("cache is invalid as the passed in args have changed")
     	}
    +	currentGcloudConfig, err := p.currentGcloudConfig()
    +	if err != nil {
    +		return "", nil, fmt.Errorf("error retrieving gcloud config: %w", err)
    +	}
    +	if !gcloudConfigsEqual(c.GcloudConfig, currentGcloudConfig) {
    +		return "", nil, fmt.Errorf("cache is invalid as the gcloud config changed")
    +	}
     
     	return c.AccessToken, &metav1.Time{Time: expiryTimeStamp}, nil
     }
     
    +func (p *plugin) currentGcloudConfig() (*gcloudConfig, error) {
    +	if _, ok := p.tokenProvider.(*gcloudTokenProvider); !ok {
    +		return nil, nil
    +	}
    +
    +	configDir := os.Getenv("CLOUDSDK_CONFIG")
    +	if configDir == "" {
    +		userConfigDir, err := os.UserConfigDir()

    fixed, config location now follows gcloud's documented default (~/.config/gcloud on macOS and Linux; the platform config directory on Windows)

    immanuwell immanuwell commented on code on Jul 17, 2026 08:13 UTC
    Code Review
    cmd/gke-gcloud-auth-plugin/cred.go:1
    @@ -334,10 +348,61 @@ func (p *plugin) getCachedGcloudAccessToken() (string, *metav1.Time, error) {
     	if c.ExtraArgs != strings.Join(p.tokenProvider.getExtraArgs(), " ") {
     		return "", nil, fmt.Errorf("cache is invalid as the passed in args have changed")
     	}
    +	currentGcloudConfig, err := p.currentGcloudConfig()
    +	if err != nil {
    +		return "", nil, fmt.Errorf("error retrieving gcloud config: %w", err)
    +	}
    +	if !gcloudConfigsEqual(c.GcloudConfig, currentGcloudConfig) {
    +		return "", nil, fmt.Errorf("cache is invalid as the gcloud config changed")
    +	}
     
     	return c.AccessToken, &metav1.Time{Time: expiryTimeStamp}, nil
     }
     
    +func (p *plugin) currentGcloudConfig() (*gcloudConfig, error) {
    +	if _, ok := p.tokenProvider.(*gcloudTokenProvider); !ok {
    +		return nil, nil
    +	}
    +
    +	configDir := os.Getenv("CLOUDSDK_CONFIG")
    +	if configDir == "" {
    +		userConfigDir, err := os.UserConfigDir()
    +		if err != nil {
    +			return nil, err
    +		}
    +		configDir = filepath.Join(userConfigDir, "gcloud")
    +	}
    +
    +	activeConfigContents, err := p.readFile(filepath.Join(configDir, activeConfig))
    +	if err != nil {
    +		return nil, err
    +	}
    +	activeConfigName := strings.TrimSpace(string(activeConfigContents))
    +	if activeConfigName == "" {
    +		return nil, fmt.Errorf("active gcloud configuration is empty")
    +	}
    +
    +	configContents, err := p.readFile(filepath.Join(configDir, "configurations", "config_"+activeConfigName))
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	return &gcloudConfig{
    +		ConfigDir:            configDir,
    +		ActiveConfig:         activeConfigName,
    +		ActiveConfigContents: string(configContents),

    got it, cache now stores a SHA-256 hash of the active config file instead of its raw contents

    immanuwell immanuwell commented on code on Jul 17, 2026 08:14 UTC
    Code Review
    cmd/gke-gcloud-auth-plugin/cred.go:1
    @@ -334,10 +348,61 @@ func (p *plugin) getCachedGcloudAccessToken() (string, *metav1.Time, error) {
     	if c.ExtraArgs != strings.Join(p.tokenProvider.getExtraArgs(), " ") {
     		return "", nil, fmt.Errorf("cache is invalid as the passed in args have changed")
     	}
    +	currentGcloudConfig, err := p.currentGcloudConfig()
    +	if err != nil {
    +		return "", nil, fmt.Errorf("error retrieving gcloud config: %w", err)
    +	}
    +	if !gcloudConfigsEqual(c.GcloudConfig, currentGcloudConfig) {
    +		return "", nil, fmt.Errorf("cache is invalid as the gcloud config changed")
    +	}
     
     	return c.AccessToken, &metav1.Time{Time: expiryTimeStamp}, nil
     }
     
    +func (p *plugin) currentGcloudConfig() (*gcloudConfig, error) {
    +	if _, ok := p.tokenProvider.(*gcloudTokenProvider); !ok {
    +		return nil, nil
    +	}
    +
    +	configDir := os.Getenv("CLOUDSDK_CONFIG")
    +	if configDir == "" {
    +		userConfigDir, err := os.UserConfigDir()
    +		if err != nil {
    +			return nil, err
    +		}
    +		configDir = filepath.Join(userConfigDir, "gcloud")
    +	}
    +
    +	activeConfigContents, err := p.readFile(filepath.Join(configDir, activeConfig))

    CLOUDSDK_ACTIVE_CONFIG_NAME now takes precedence over active_config

    immanuwell immanuwell commented on code on Jul 17, 2026 08:16 UTC
    Code Review
    cmd/gke-gcloud-auth-plugin/cred.go:1
    @@ -334,10 +348,61 @@ func (p *plugin) getCachedGcloudAccessToken() (string, *metav1.Time, error) {
     	if c.ExtraArgs != strings.Join(p.tokenProvider.getExtraArgs(), " ") {
     		return "", nil, fmt.Errorf("cache is invalid as the passed in args have changed")
     	}
    +	currentGcloudConfig, err := p.currentGcloudConfig()
    +	if err != nil {
    +		return "", nil, fmt.Errorf("error retrieving gcloud config: %w", err)

    updated the implementation to make strict gcloud-config cache invalidation opt-in via GKE_AUTH_PLUGIN_STRICT_CACHE_INVALIDATION=true, with fail-open behavior

    immanuwell immanuwell commented on Jul 17, 2026 08:17 UTC
    Author

    @hdp617 addressed your suggestions, PTAL

    hdp617 hdp617 commented on Jul 22, 2026 21:50 UTC
    Contributor

    /assign LogicalShark

    Could you also take a look? I remember you were looking at this issue.

    LogicalShark LogicalShark commented on Jul 24, 2026 20:20 UTC
    Contributor

    /lgtm

    hdp617 hdp617 commented on Jul 24, 2026 22:42 UTC
    Contributor

    /approve

    @immanuwell Thank you for looking into this issue.

    kubernetes-prow[bot] kubernetes-prow[bot] commented on Jul 24, 2026 22:42 UTC
    Bot

    [APPROVALNOTIFIER] This PR is APPROVED

    This pull-request has been approved by: <a href="https://github.com/kubernetes/cloud-provider-gcp/pull/1249#issuecomment-5075169472" title="Approved">hdp617</a>, <a href="https://github.com/kubernetes/cloud-provider-gcp/pull/1249#" title="Author self-approved">immanuwell</a>

    The full list of commands accepted by this bot can be found here.

    The pull request process is described here

    <details >
    Needs approval from an approver in each of these files:

  • ~~cmd/gke-gcloud-auth-plugin/OWNERS~~ [hdp617]
  • Approvers can indicate their approval by writing /approve in a comment
    Approvers can cancel approval by writing /approve cancel in a comment
    </details>
    <!-- META={"approvers":[]} -->

    Reviewers
    Assignees
    immanuwell immanuwell
    Labels
    risk: low confidence: 86.9% reviewed sensitive_module
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 62.1% (MEDIUM) · Higher = larger blast radius
    62.1%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 86.9% · Lower = rushed or shallow review
    86.9%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 8.2% · Safe to merge
    8.2%