Skip to content

feat: add GCP authentication support - #2051

Merged
Andriy Knysh (aknysh) merged 44 commits into
cloudposse:mainfrom
shirkevich:google-auth
Feb 17, 2026
Merged

Andriy Knysh (aknysh) merged 44 commits into
cloudposse:mainfrom
shirkevich:google-auth

Conversation

@shirkevich

@shirkevich Mikhail Shirkov (shirkevich) commented Feb 3, 2026 •

Copy link
Copy Markdown
Collaborator

what

  • Add GCP auth providers:
    • gcp/adc (Application Default Credentials)
    • gcp/workload-identity-federation (OIDC WIF for CI/CD)
  • Add GCP identities:
    • gcp/service-account (impersonation via IAM Credentials API, delegates supported)
    • gcp/project (project/region/zone context only)
  • Add GCP auth context support in schema and environment export (GOOGLE_OAUTH_ACCESS_TOKEN, GOOGLE_CLOUD_PROJECT, etc.)
  • Implement AWS-style file isolation for GCP:
    • New path layout: ~/.config/atmos/gcp/<provider-name>/...
    • Provider-scoped ADC and gcloud config directories
  • Extend auth factory/identity wiring to support new GCP kinds
  • Add IAM credentials service injection for testability
  • Fix auth whoami validation fallback for non-validated credentials (GCP)

why

  • Extend the existing multi-cloud auth framework to GCP, matching AWS/Azure patterns.
  • Provide secure CI/CD via WIF (no long-lived keys).
  • Enforce consistent, provider-scoped file isolation aligned with the universal pattern (AWS reference).
  • Ensure auth whoami works for GCP credential types that don’t implement validation yet.

references

  • Universal auth file isolation pattern: docs/prd/auth-file-isolation-pattern.md
  • AWS reference implementation: docs/prd/aws-auth-file-isolation.md
  • Azure isolation plan (consistency target): docs/prd/azure-auth-file-isolation.md
  • GCP provider/identity docs updated in website/docs/cli/configuration/auth/*

p.s. tested locally and in GitHub with WIF

Summary by CodeRabbit

  • New Features

    • First-class GCP auth: ADC and Workload Identity Federation providers, Service Account and Project identities, GCPCredentials type, provider-scoped credential files, env helpers, static token via GOOGLE_OAUTH_ACCESS_TOKEN, auth-realm resolution, and pluggable provider/identity factory; keyring now stores GCP creds.
  • Bug Fixes

    • Validate fallback for NotImplemented to accept unexpired creds; clearer whoami error guidance for GCP reauthentication scenarios.
  • Documentation

    • New GCP docs, examples, blog post and roadmap update.
  • Tests

    • Extensive unit tests for GCP flows, files, factories, providers, identities and credentials.

Add Google Cloud Platform authentication to the Atmos auth system with support for:

## Providers
- `gcp-adc`: Application Default Credentials (local development with gcloud)
- `gcp-wif`: Workload Identity Federation (CI/CD with GitHub Actions)

## Identities
- `gcp/service-account`: Service account impersonation via IAM Credentials API
- `gcp/project`: Project context without authentication (sets project/region/zone)

## Features
- Credential isolation per identity (files stored in ~/.config/atmos/gcp/)
- Environment variable management (GOOGLE_OAUTH_ACCESS_TOKEN, GOOGLE_CLOUD_PROJECT, etc.)
- Token caching and expiry checking
- Integration with Google Secret Manager store
- Support for custom scopes and token lifetime

## Configuration Example
```yaml
auth:
  providers:
    gcp-adc:
      kind: gcp/adc
    gcp-wif:
      kind: gcp/workload-identity-federation
      project_number: "123456789"
      workload_identity_pool_id: "my-pool"
      workload_identity_provider_id: "github"
      service_account_email: "[email protected]"
      token_source:
        type: url
  identities:
    terraform:
      kind: gcp/service-account
      provider: gcp-adc
      principal:
        service_account_email: "[email protected]"
```

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Add comprehensive documentation for GCP authentication support:

- GCP Application Default Credentials (ADC) provider for local development
- GCP Workload Identity Federation (WIF) provider for CI/CD pipelines
- GCP Service Account identity for service account impersonation
- GCP Project identity for project context targeting

Documentation follows the same structure and patterns as existing
AWS and Azure authentication documentation.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Fixes the following PR review findings:

1. Provider resolution for GCP identities in whoami/reporting paths
   - Added config storage to GCP identities (gcp/service-account, gcp/project)
   - GetProviderName() now returns config.Via.Provider for proper reporting
   - Factory calls SetConfig() after identity creation via ConfigSetter interface

2. Missing test for PrepareEnvironment error path
   - Added TestPrepareEnvironment_NoCredentials to verify error when no
     credentials exist and user is guided to run 'atmos auth login'

3. Documentation gap for token_source.request_token
   - Added documentation for request_token field used by non-GitHub OIDC
     providers when fetching tokens from URL endpoints

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@shirkevich
Mikhail Shirkov (shirkevich) requested a review from a team as a code owner February 3, 2026 10:13
@github-actions github-actions Bot added the size/xl Extra large size PR label Feb 3, 2026
@mergify

mergify Bot commented Feb 3, 2026

Copy link
Copy Markdown
Contributor

Warning

This PR exceeds the recommended limit of 1,000 lines.

Large PRs are difficult to review and may be rejected due to their size.

Please verify that this PR does not address multiple issues.
Consider refactoring it into smaller, more focused PRs to facilitate a smoother review process.

@coderabbitai

coderabbitai Bot commented Feb 3, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds comprehensive GCP authentication: new GCP providers (ADC, WIF), identities (service-account, project), GCPCredentials and specs, provider-scoped file/env helpers and setup/cleanup, factory registration for GCP, auth-realm resolution, keyring GCP support, docs/tests, and whoami error handling tweaks.

Changes

Cohort / File(s) Summary
Auth CLI
cmd/auth_whoami.go, cmd/auth_whoami_test.go
Adjust whoami error handling to wrap Google reauth scenarios; propagate errors through helper that suggests reauth; treat ErrNotImplemented from credential Validate as fallback to expiry-check; add test.
Internal GCP client options
internal/gcp/auth.go
Add support for static GOOGLE_OAUTH_ACCESS_TOKEN token source (preferred before ADC); create oauth2 static token source when env var present.
GCP cloud package — env & files
pkg/auth/cloud/gcp/doc.go, pkg/auth/cloud/gcp/env.go, pkg/auth/cloud/gcp/files.go, pkg/auth/cloud/gcp/*_test.go
New package docs; env var lifecycle (prepare/get/set/restore); file helpers for ADC/properties/token files, path helpers, write/cleanup utilities and tests.
GCP cloud package — setup
pkg/auth/cloud/gcp/setup.go, pkg/auth/cloud/gcp/setup_test.go
Orchestrates writing/loading ADC, properties, access token files; SetAuthContext, Setup/Cleanup, LoadCredentials/CredentialsExist, token expiry formatting and client-credential resolution; extensive tests.
Factory core & GCP registrations
pkg/auth/factory/factory.go, pkg/auth/factory/gcp_providers.go, pkg/auth/factory/gcp_identities.go, pkg/auth/factory/*_test.go
Introduce pluggable Factory for providers/identities with registration/lookup; register GCP providers and identities; NewProvider/NewIdentity delegate to factory when present; add ConfigSetter hook.
GCP providers
pkg/auth/providers/gcp_adc/provider.go, pkg/auth/providers/gcp_wif/provider.go, pkg/auth/providers/.../*_test.go, pkg/auth/providers/*/doc.go
Add GCP ADC and Workload Identity Federation providers: ADC discovery, STS exchange, optional SA impersonation, token/email resolution, env handling, and tests/docs.
GCP identities
pkg/auth/identities/gcp_service_account/..., pkg/auth/identities/gcp_project/...
Add gcp/service-account and gcp/project identities with full lifecycle methods (Validate/Authenticate/Environment/LoadCredentials/PostAuthenticate/Logout) and tests/docs.
Types & specs
pkg/auth/types/constants.go, pkg/auth/types/gcp_credentials.go, pkg/auth/types/gcp_specs.go, pkg/auth/types/*_test.go
New GCP kind constants, GCPCredentials type and methods, provider/identity spec structs and parsers, and unit tests.
Keyring / credential stores
pkg/auth/credentials/keyring_*.go, pkg/auth/credentials/suite_test.go
Extend file/memory/system keyrings to store/restore GCPCredentials; add store/retrieve tests.
Schema & auth realm
pkg/schema/schema.go, pkg/schema/schema_auth.go, pkg/config/auth_realm.go, pkg/config/config.go
Add GCPAuthContext to AuthContext; add AuthConfig Realm/RealmSource; implement realm precedence (env > config > path-hash > default) and wire into InitCliConfig.
Errors
errors/errors.go
Add ADC/file-write error sentinels (ErrInvalidADCContent, ErrWriteADCFile, ErrWritePropertiesFile, ErrWriteAccessTokenFile).
Manager misc
pkg/auth/manager.go, pkg/auth/manager_chain.go, pkg/auth/manager_test.go
Set realm on identities that implement realmSetter; add conditional suppression of auth-error printing via context flag; adjust tests to updated error messages.
Context helpers
pkg/auth/types/context.go, pkg/auth/types/context_test.go
Add WithSuppressAuthErrors / SuppressAuthErrors context helpers and tests.
Docs & website
website/docs/..., website/blog/..., website/blog/authors.yml, website/src/data/roadmap.js
Add/extend docs for GCP providers/identities, CLI/provider docs, blog post, author entry, and roadmap update.

Sequence Diagram(s)

sequenceDiagram
    participant CLI as CLI
    participant Factory as Factory
    participant Provider as Provider
    participant Files as Files
    participant Env as Env

    CLI->>Factory: CreateProvider(kind="gcp/adc"|"gcp/wif", spec)
    Factory->>Provider: constructor(spec)
    Provider-->>Factory: instance
    Factory-->>CLI: provider

    CLI->>Provider: Authenticate(ctx)
    Provider->>Env: Check GOOGLE_OAUTH_ACCESS_TOKEN
    alt static token present
        Env-->>Provider: static token source (oauth2.TokenSource)
    else
        Provider->>Files: Read provider-scoped ADC/token/config files
        Files-->>Provider: ADC data or access token or config paths
    end
    Provider->>Provider: Exchange/obtain token (ADC / STS / IAM impersonation)
    Provider-->>CLI: GCPCredentials (AccessToken, Expiry, ProjectID, SA email, Scopes)
Loading
sequenceDiagram
    participant Setup as Setup
    participant Files as Files
    participant Env as Env
    participant AuthCtx as AuthCtx

    Setup->>Files: WriteADCFile(provider, identity, creds)
    Files-->>Setup: adc.json path
    Setup->>Files: WritePropertiesFile(provider, identity, project/region)
    Files-->>Setup: properties path
    Setup->>Files: WriteAccessTokenFile(provider, identity, token)
    Files-->>Setup: token path

    Setup->>Env: SetEnvironmentVariables(ctx, config, provider, identity)
    Env-->>Setup: env vars set (GOOGLE_OAUTH_ACCESS_TOKEN or GOOGLE_APPLICATION_CREDENTIALS)

    Setup->>AuthCtx: SetAuthContext(authCtx, provider, identity, creds)
    AuthCtx-->>Setup: populated GCPAuthContext
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

Suggested reviewers

  • aknysh
🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 26.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: add GCP authentication support' clearly and concisely summarizes the main change—introducing GCP authentication capabilities to the codebase.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 14

🤖 Fix all issues with AI agents
In `@pkg/auth/cloud/gcp/setup.go`:
- Around line 15-26: The comment block for the SetupFiles function is missing
trailing periods on the list and parameter lines; update the doc comment above
SetupFiles in setup.go so every sentence and each bullet ends with a period —
e.g., add periods to the lines for "ADC JSON file
(application_default_credentials.json).", "gcloud properties file (for
project/region defaults).", "Access token file (for tools that read tokens
directly).", and the parameter descriptions for ctx, atmosConfig, identityName,
and creds — leaving the function signature and behavior unchanged.
- Around line 148-151: The code silently ignores errors from GetADCFilePath and
GetConfigDir when setting gcpAuth.CredentialsFile and gcpAuth.ConfigDir; change
this to check and propagate/handle those errors the same way SetAuthContext
does: call GetADCFilePath and GetConfigDir, capture their returned errors,
return or wrap the errors if non-nil before assigning to gcpAuth.CredentialsFile
and gcpAuth.ConfigDir so empty paths are not used when resolution fails.
- Around line 38-40: Replace direct error returns with the static sentinel
ErrInvalidAuthConfig wrapped with contextual text in the three places: in
SetupFiles when creds == nil, in SetAuthContext when creds == nil, and in
LoadCreds for file read and JSON parse failures; import the errors package that
exposes ErrInvalidAuthConfig and wrap errors using fmt.Errorf with %w so each
returned error is like fmt.Errorf("%w: <brief context>",
errors.ErrInvalidAuthConfig) and when you have an underlying err include it as
fmt.Errorf("%w: <brief context>: %v", errors.ErrInvalidAuthConfig, err) while
referencing the functions SetupFiles, SetAuthContext, and LoadCreds to locate
the changes.

In `@pkg/auth/factory/gcp_providers.go`:
- Around line 21-24: The error wrapping for parse failures should preserve both
the invalid-config sentinel and the underlying parse error: replace the current
fmt.Errorf usage around types.ParseGCPADCProviderSpec(spec) (and the similar
block for types.ParseGCPProviderSpec(spec)) to join the errors with
errors.Join(errUtils.ErrInvalidProviderConfig, err) and then wrap that join with
a single %w (e.g. fmt.Errorf("parse gcp/adc spec: %w",
errors.Join(errUtils.ErrInvalidProviderConfig, err))); ensure you add the errors
import if missing and apply the same pattern for the other parse block
(ParseGCPProviderSpec) so callers can unwrap/inspect both errors.

In `@pkg/auth/identities/gcp_project/identity.go`:
- Around line 151-176: In PostAuthenticate (Identity.PostAuthenticate) populate
the missing Location by copying i.principal.Location into
params.AuthContext.GCP.Location when building the GCPAuthContext, and change
error handling around os.Setenv (in the loop using Environment()) to wrap
returned errors with the ErrAuthenticationFailed sentinel per guidelines (i.e.,
return a wrapped error that includes ErrAuthenticationFailed plus context about
which environment variable failed to set). Ensure references are to
Identity.PostAuthenticate, Environment(), i.principal, params.AuthContext.GCP
(GCPAuthContext), os.Setenv and ErrAuthenticationFailed.

In `@pkg/auth/identities/gcp_service_account/identity.go`:
- Around line 27-28: Update inline comments in
pkg/auth/identities/gcp_service_account/identity.go to end with periods to
satisfy the godot linter: add a trailing period to the comment for
DefaultLifetime and any other inline/helper comments referenced in the file
(including the block around the helper docs noted in the review). Locate
comments near the DefaultLifetime constant and the helper functions/blocks (the
helper docs mentioned in the review) and append a period to each comment
sentence so every comment ends with a period.
- Around line 130-133: The error returned after calling
impersonateServiceAccount (accessToken, expiry, err :=
i.impersonateServiceAccount(...)) is being wrapped with fmt.Errorf using "%v",
which prevents proper unwrapping; change the wrapping to use "%w" so the
original err is preserved for errors.Is/errors.As (replace fmt.Errorf("%w:
impersonation failed: %v", errUtils.ErrAuthenticationFailed, err) with
fmt.Errorf("%w: impersonation failed: %w", errUtils.ErrAuthenticationFailed,
err)).
- Around line 150-167: The impersonateServiceAccount method currently calls
iamcredentials.NewService directly (coupling to external API); refactor by
introducing an IAMCredentialsService interface (with the GenerateAccessToken
method matching
Projects.ServiceAccounts.GenerateAccessToken(...).Context(...).Do() semantics),
add a constructor or field on Identity to accept an implementation (inject the
service) and replace the iamcredentials.NewService call with the injected
service usage inside impersonateServiceAccount; update Identity to accept the
interface (and preserve existing behavior by providing a production
implementation that wraps iamcredentials.NewService) and add unit tests for
Identity.impersonateServiceAccount covering successful token generation and
error paths (mock the interface to return both valid GenerateAccessToken
responses and errors) following the same injection pattern used in
pkg/auth/providers/gcp_wif/provider.go.
- Around line 253-262: Add an expiration check after loading GCP creds: after
calling gcp.LoadCredentialsFromFiles, detect if creds is nil or
creds.AccessToken == "" or creds.IsExpired() and return an
authentication-failure error consistent with Azure handling by wrapping the
condition with errUtils.ErrAuthenticationFailed (use the same error wrapping
pattern used elsewhere); reference LoadCredentialsFromFiles, creds.IsExpired(),
and i.Name() to locate where to add the check and replace the current "no
credentials found" / load error returns with the wrapped
errUtils.ErrAuthenticationFailed response.

In `@pkg/auth/providers/gcp_adc/provider_test.go`:
- Around line 40-79: The test TestAuthenticate_NoCredentials constructs adcPath
using string concatenation with "/" which is platform-unsafe; change the adcPath
construction to use filepath.Join(home, ".config", "gcloud",
"application_default_credentials.json") and add "path/filepath" to the imports;
update the check that uses adcPath (the os.Stat call and the t.Skip message) to
use the new adcPath variable created via filepath.Join so the test works
correctly on Windows and POSIX systems.

In `@pkg/auth/providers/gcp_adc/provider.go`:
- Around line 65-72: Add the same validation guard used in the WIF provider by
calling p.Validate() at the start of Provider.Authenticate to ensure p.spec is
present before accessing p.spec.Scopes; update Authenticate (method name:
Authenticate on type Provider) to return the validation error if p.Validate()
fails (same behavior as WIF provider) so direct instantiation or nil spec in
tests won't cause a nil deref—mirror the pattern used in the WIF provider and
keep existing behavior of falling back to DefaultScope when scopes are empty.

In `@pkg/auth/providers/gcp_wif/provider.go`:
- Around line 227-243: The outbound HTTP calls in getTokenFromURL and
exchangeToken use http.DefaultClient (no timeout) which can hang; replace those
uses with an http.Client instance that sets a sensible Timeout (matching other
providers) and use that client to perform Do(req) for both getTokenFromURL and
exchangeToken (or reference a shared client variable used by Azure/GitHub
providers) so the requests cannot block indefinitely; update calls that
currently call http.DefaultClient.Do to use the new client.
- Around line 157-200: Update getOIDCToken, getTokenFromEnv, getTokenFromFile,
and getTokenFromURL to return wrapped sentinel errors and validate empty tokens:
treat configuration problems (p.spec.TokenSource == nil, missing FilePath/URL,
unknown token source type) as errUtils.ErrInvalidProviderConfig by wrapping the
original fmt.Errorf with fmt.Errorf("%w: <message>",
errUtils.ErrInvalidProviderConfig), and treat runtime retrieval failures (empty
env var, os.ReadFile errors, HTTP fetch errors, or trimmed token == "") as
errUtils.ErrAuthenticationFailed by wrapping the underlying error with
fmt.Errorf("%w: %v", errUtils.ErrAuthenticationFailed, err) or fmt.Errorf("%w:
token is empty", errUtils.ErrAuthenticationFailed) for empty-token checks; make
these changes in getOIDCToken (unknown type and nil source), getTokenFromEnv
(empty/missing env), getTokenFromFile (missing FilePath, file read error, and
empty file -> empty token check), and getTokenFromURL (ensure URL configured,
wrap fetch/parsing errors and verify trimmed token is non-empty).

In `@pkg/auth/types/gcp_specs.go`:
- Around line 109-120: The error wrapping in the mapstructure decoder creation
and Decode calls for GCPWorkloadIdentityFederationProviderSpec and
GCPWorkloadIdentityFederationPrincipalSpec uses "%v", which breaks error chains;
change the fmt.Errorf calls that currently look like fmt.Errorf("%w: ...: %v",
errUtils.ErrInvalidAuthConfig, err) to use "%w" for the wrapped error
(fmt.Errorf("%w: ...: %w", errUtils.ErrInvalidAuthConfig, err)) for all
instances around mapstructure.NewDecoder and decoder.Decode so errors.Is/As can
inspect the original error.
🧹 Nitpick comments (16)
pkg/auth/cloud/gcp/files.go (1)

147-224: Write and cleanup functions look good.

Proper file permissions (0o600), nil content check in WriteADCFile, and CleanupIdentityFiles handles missing directories gracefully. The error wrapping with %w is consistent.

Consider using static errors from errors/errors.go for the error messages (e.g., ErrFailedToWriteFile) if you want consistency with the rest of the codebase. Not blocking.

,

pkg/auth/factory/gcp_providers_test.go (2)

38-52: Test behavior could be more explicit.

The test accepts both success and failure outcomes, which might mask regressions. If the parser should reject integer project_id, consider asserting require.Error(t, err). If weak typing is intentional, document this in a comment and skip the error check.

♻️ Option: Make assertion explicit
 func TestCreateGCPADCProvider_InvalidSpec(t *testing.T) {
 	f := NewFactory()
 
-	// Invalid spec (e.g., wrong type for a field).
+	// Invalid spec - project_id should be string, not int.
+	// Parser uses mapstructure with WeaklyTypedInput, so this may coerce.
 	spec := map[string]any{
 		"project_id": 123, // Should be string.
 	}
 
 	_, err := f.CreateProvider(types.ProviderKindGCPADC, "bad-adc", spec)
-	// Depending on parser strictness, this may or may not error.
-	// If weak typing is disabled, expect an error.
-	if err != nil {
-		assert.Contains(t, err.Error(), "parse")
-	}
+	// With WeaklyTypedInput enabled, mapstructure coerces 123 to "123".
+	// If strict typing is enforced, uncomment:
+	// require.Error(t, err)
+	// assert.Contains(t, err.Error(), "parse")
+	_ = err // Currently accepts coercion.
 }

76-91: Consider using require.Error for clearer test intent.

The conditional logic makes it unclear whether creation or validation should fail. If incomplete specs should fail at creation, use require.Error(t, err). If validation is deferred, that's fine—just clarify with a comment.

♻️ Option: Clarify expected behavior
 func TestCreateGCPWIFProvider_MissingRequired(t *testing.T) {
 	f := NewFactory()
 
-	// Missing project_number, pool_id, provider_id.
+	// Missing required fields: project_number, pool_id, provider_id.
+	// WIF constructor defers validation, so creation succeeds but Validate() fails.
 	spec := map[string]any{
 		"project_id": "incomplete",
 	}
 
 	provider, err := f.CreateProvider(types.ProviderKindGCPWorkloadIdentityFederation, "incomplete-wif", spec)
-	// Provider is created but Validate() will fail later.
-	// Or if constructor validates, expect error here.
-	if err == nil && provider != nil {
-		err = provider.Validate()
-		require.Error(t, err)
-	}
+	require.NoError(t, err, "creation should succeed; validation is deferred")
+	require.NotNil(t, provider)
+	require.Error(t, provider.Validate(), "Validate() should fail with missing required fields")
 }
pkg/auth/factory/gcp_identities.go (1)

21-24: Consider using %w for inner error to preserve the error chain.

Currently using %v for the inner error loses the ability to unwrap it. If callers need to inspect the parse error, use %w.

♻️ Preserve error chain
 		parsed, err := types.ParseGCPServiceAccountIdentityPrincipal(principal)
 		if err != nil {
-			return nil, fmt.Errorf("%w: parse gcp/service-account principal: %v", errUtils.ErrInvalidIdentityConfig, err)
+			return nil, fmt.Errorf("%w: parse gcp/service-account principal: %w", errUtils.ErrInvalidIdentityConfig, err)
 		}
 		parsed, err := types.ParseGCPProjectIdentityPrincipal(principal)
 		if err != nil {
-			return nil, fmt.Errorf("%w: parse gcp/project principal: %v", errUtils.ErrInvalidIdentityConfig, err)
+			return nil, fmt.Errorf("%w: parse gcp/project principal: %w", errUtils.ErrInvalidIdentityConfig, err)
 		}

Also applies to: 37-40

pkg/auth/types/gcp_specs_test.go (1)

12-23: Consider a table-driven structure for parser cases.
These parser tests are a good fit for a table-driven pattern to reduce duplication and align with the test guidelines.

As per coding guidelines “Use table-driven tests for testing multiple scenarios in Go.”

pkg/auth/factory/gcp_identities_test.go (1)

12-20: Consider table-driven tests for identity cases.
Multiple scenarios here could be collapsed into a table to reduce repetition and align with test guidelines.

As per coding guidelines “Use table-driven tests for comprehensive coverage.”

pkg/auth/identities/gcp_service_account/identity_test.go (1)

119-139: Consider using generated mocks for better maintainability.

The manual MockProvider works but guidelines recommend using go.uber.org/mock/mockgen with //go:generate directives. For a simple test double like this, it's acceptable, but as the interface evolves, generated mocks will track changes automatically.

pkg/auth/cloud/gcp/env_test.go (4)

14-34: Prefer t.Setenv for automatic cleanup.

The test sets environment variables with os.Setenv and manual defer cleanup. Using t.Setenv provides automatic restoration after the test completes.

♻️ Suggested refactor
 func TestPrepareEnvironment_ClearsGCPVars(t *testing.T) {
 	ctx := context.Background()
-	os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", "/path/to/creds.json")
-	os.Setenv("GOOGLE_CLOUD_PROJECT", "my-project")
-	os.Setenv("CLOUDSDK_CONFIG", "/path/to/config")
-	defer func() {
-		os.Unsetenv("GOOGLE_APPLICATION_CREDENTIALS")
-		os.Unsetenv("GOOGLE_CLOUD_PROJECT")
-		os.Unsetenv("CLOUDSDK_CONFIG")
-	}()
+	t.Setenv("GOOGLE_APPLICATION_CREDENTIALS", "/path/to/creds.json")
+	t.Setenv("GOOGLE_CLOUD_PROJECT", "my-project")
+	t.Setenv("CLOUDSDK_CONFIG", "/path/to/config")
 
 	err := PrepareEnvironment(ctx, nil)

Based on learnings: "tests should prefer t.Setenv for environment variable setup/teardown instead of os.Setenv/Unsetenv to ensure test-scoped isolation."


36-47: Same pattern here—use t.Setenv for cleaner tests.

♻️ Suggested refactor
 func TestGetCurrentGCPEnvironment(t *testing.T) {
-	os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", "/tmp/creds.json")
-	os.Setenv("GOOGLE_CLOUD_PROJECT", "test-project")
-	defer func() {
-		os.Unsetenv("GOOGLE_APPLICATION_CREDENTIALS")
-		os.Unsetenv("GOOGLE_CLOUD_PROJECT")
-	}()
+	t.Setenv("GOOGLE_APPLICATION_CREDENTIALS", "/tmp/creds.json")
+	t.Setenv("GOOGLE_CLOUD_PROJECT", "test-project")
 
 	env := GetCurrentGCPEnvironment()

84-96: Environment variable manipulation needs cleanup via t.Setenv.

Lines 86, 90, 95 use os.Setenv/os.Unsetenv. The test verifies restore behavior, but setup/teardown should still use t.Setenv for isolation.

♻️ Suggested refactor
 func TestRestoreEnvironment(t *testing.T) {
 	ctx := context.Background()
-	os.Setenv("GOOGLE_CLOUD_PROJECT", "original-project")
+	t.Setenv("GOOGLE_CLOUD_PROJECT", "original-project")
 	saved := GetCurrentGCPEnvironment()
 	require.NotEmpty(t, saved["GOOGLE_CLOUD_PROJECT"])
 
 	os.Unsetenv("GOOGLE_CLOUD_PROJECT")
 	err := RestoreEnvironment(ctx, saved)
 	require.NoError(t, err)
 	assert.Equal(t, "original-project", os.Getenv("GOOGLE_CLOUD_PROJECT"))
-
-	os.Unsetenv("GOOGLE_CLOUD_PROJECT")
 }

98-117: Manual cleanup loop can be avoided with t.Setenv.

The cleanup loop at lines 114-116 wouldn't be needed if using t.Setenv for the variables that SetEnvironmentVariables modifies.

pkg/auth/providers/gcp_wif/provider_test.go (1)

126-149: Use t.Setenv for environment variable manipulation.

Lines 137 and 143-144 use os.Unsetenv/os.Setenv. Switch to t.Setenv for automatic cleanup.

♻️ Suggested refactor
 func TestGetTokenFromEnv(t *testing.T) {
 	p := &Provider{
 		spec: &types.GCPWorkloadIdentityFederationProviderSpec{
 			TokenSource: &types.WIFTokenSource{
 				Type:                TokenSourceTypeEnvironment,
 				EnvironmentVariable: "TEST_OIDC_TOKEN",
 			},
 		},
 	}
 
-	// Test missing env var.
-	os.Unsetenv("TEST_OIDC_TOKEN")
-	_, err := p.getTokenFromEnv()
-	require.Error(t, err)
-	assert.Contains(t, err.Error(), "empty")
-
-	// Test with env var set.
-	os.Setenv("TEST_OIDC_TOKEN", "my-oidc-token")
-	defer os.Unsetenv("TEST_OIDC_TOKEN")
-
-	token, err := p.getTokenFromEnv()
-	require.NoError(t, err)
-	assert.Equal(t, "my-oidc-token", token)
+	// Test missing env var - ensure it's unset for this subtest.
+	t.Run("missing env var", func(t *testing.T) {
+		_, err := p.getTokenFromEnv()
+		require.Error(t, err)
+		assert.Contains(t, err.Error(), "empty")
+	})
+
+	// Test with env var set.
+	t.Run("with env var", func(t *testing.T) {
+		t.Setenv("TEST_OIDC_TOKEN", "my-oidc-token")
+		token, err := p.getTokenFromEnv()
+		require.NoError(t, err)
+		assert.Equal(t, "my-oidc-token", token)
+	})
 }

Based on learnings: "tests should prefer t.Setenv for environment variable setup/teardown."

pkg/auth/cloud/gcp/setup_test.go (1)

88-119: Use t.Setenv to avoid manual cleanup.

Lines 93-94 and 116-118 use os.Setenv/os.Unsetenv. The test modifies environment state that should be isolated.

♻️ Suggested refactor
 func TestSetup(t *testing.T) {
 	tmp := t.TempDir()
 	t.Setenv("XDG_CONFIG_HOME", tmp)
 	ctx := context.Background()
 
-	os.Setenv("GOOGLE_CLOUD_PROJECT", "old-project")
-	defer os.Unsetenv("GOOGLE_CLOUD_PROJECT")
+	t.Setenv("GOOGLE_CLOUD_PROJECT", "old-project")
 
 	creds := &types.GCPCredentials{
 		AccessToken: "ya29.setup-token",
 		TokenExpiry: time.Now().Add(1 * time.Hour),
 		ProjectID:   "new-project",
 	}
 	err := Setup(ctx, nil, "setup-full-identity", creds)
 	require.NoError(t, err)
 
 	assert.Equal(t, "new-project", os.Getenv("GOOGLE_CLOUD_PROJECT"))
 	// ... assertions ...
-
-	for _, key := range GCPEnvironmentVariables {
-		os.Unsetenv(key)
-	}
 }

Note: The cleanup loop may still be needed since Setup sets additional env vars. Consider wrapping in a subtest or using t.Cleanup for deterministic restoration.

pkg/auth/identities/gcp_project/identity_test.go (1)

280-314: Use t.Setenv for environment variable setup.

Lines 281-286 use os.Unsetenv with defer. Since PostAuthenticate sets these variables, use t.Setenv at the start to ensure they're restored after the test.

♻️ Suggested refactor
 func TestPostAuthenticate(t *testing.T) {
-	os.Unsetenv("GOOGLE_CLOUD_PROJECT")
-	os.Unsetenv("GOOGLE_CLOUD_REGION")
-	defer func() {
-		os.Unsetenv("GOOGLE_CLOUD_PROJECT")
-		os.Unsetenv("GOOGLE_CLOUD_REGION")
-	}()
+	// t.Setenv ensures restoration even if test sets these vars
+	t.Setenv("GOOGLE_CLOUD_PROJECT", "")
+	t.Setenv("GOOGLE_CLOUD_REGION", "")
 
 	id := &Identity{
pkg/auth/cloud/gcp/env.go (1)

30-35: Use atmosConfig in perf.Track for GCP env helpers.

These public helpers already accept atmosConfig, but perf tracking currently passes nil, which drops config context in traces.

♻️ Suggested change
-	defer perf.Track(nil, "gcp.PrepareEnvironment")()
+	defer perf.Track(atmosConfig, "gcp.PrepareEnvironment")()
...
-	defer perf.Track(nil, "gcp.SetEnvironmentVariables")()
+	defer perf.Track(atmosConfig, "gcp.SetEnvironmentVariables")()
...
-	defer perf.Track(nil, "gcp.GetEnvironmentVariables")()
+	defer perf.Track(atmosConfig, "gcp.GetEnvironmentVariables")()

As per coding guidelines: Add defer perf.Track(atmosConfig, "pkg.FuncName")() + blank line to all public functions, except trivial getters/setters, command constructors, simple factories, and functions that only delegate to another tracked function.

Also applies to: 61-65, 95-100

pkg/auth/cloud/gcp/setup.go (1)

28-35: Pass atmosConfig into perf.Track for setup helpers.

These public functions accept atmosConfig but pass nil to perf tracking, which loses config context.

♻️ Suggested change
-	defer perf.Track(nil, "gcp.SetupFiles")()
+	defer perf.Track(atmosConfig, "gcp.SetupFiles")()
...
-	defer perf.Track(nil, "gcp.Setup")()
+	defer perf.Track(atmosConfig, "gcp.Setup")()
...
-	defer perf.Track(nil, "gcp.Cleanup")()
+	defer perf.Track(atmosConfig, "gcp.Cleanup")()
...
-	defer perf.Track(nil, "gcp.LoadCredentialsFromFiles")()
+	defer perf.Track(atmosConfig, "gcp.LoadCredentialsFromFiles")()
...
-	defer perf.Track(nil, "gcp.CredentialsExist")()
+	defer perf.Track(atmosConfig, "gcp.CredentialsExist")()

As per coding guidelines: Add defer perf.Track(atmosConfig, "pkg.FuncName")() + blank line to all public functions, except trivial getters/setters, command constructors, simple factories, and functions that only delegate to another tracked function.

Also applies to: 128-135, 157-160, 174-180, 216-223

Comment thread pkg/auth/cloud/gcp/setup.go Resolved
Comment thread pkg/auth/cloud/gcp/setup.go Resolved
Comment thread pkg/auth/cloud/gcp/setup.go Resolved
Comment thread pkg/auth/factory/gcp_providers.go Resolved
Comment thread pkg/auth/providers/gcp_adc/provider.go Resolved
Comment thread pkg/auth/providers/gcp_wif/provider.go Resolved
Comment thread pkg/auth/providers/gcp_wif/provider.go Resolved
Comment thread pkg/auth/types/gcp_specs.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Fix all issues with AI agents
In `@pkg/auth/cloud/gcp/setup.go`:
- Around line 122-126: Update the top-of-function doc comment for the Setup
function so each list item ends with a period; locate the comment block that
begins with "Setup performs the complete setup for a GCP identity:" and append a
trailing period to each bullet line ("Prepares the environment (clears
conflicting vars)", "Writes credential files", and "Sets environment variables
(including project/region from creds)") so the godot linter no longer fails.

In `@pkg/auth/identities/gcp_service_account/identity.go`:
- Around line 285-314: The PrepareEnvironment error handling currently discards
the original error chain and misses the authentication sentinel; update the two
fmt.Errorf returns so they both include errUtils.ErrAuthenticationFailed as the
sentinel while preserving the wrapped error chain by nesting fmt.Errorf calls.
Specifically, replace the load credentials return around
gcp.LoadCredentialsFromFiles (currently fmt.Errorf("%w: load credentials: %v",
... , err)) with a nested wrap that preserves the original err (e.g.,
fmt.Errorf("%w: %v", errUtils.ErrAuthenticationFailed, fmt.Errorf("load
credentials: %w", err))) and similarly update the
GetEnvironmentVariablesForIdentity error return (currently fmt.Errorf("get GCP
environment variables: %w", err)) to include the ErrAuthenticationFailed
sentinel while preserving chaining (e.g., fmt.Errorf("%w: %v",
errUtils.ErrAuthenticationFailed, fmt.Errorf("get GCP environment variables:
%w", err))). Ensure changes are made inside PrepareEnvironment and reference
gcp.LoadCredentialsFromFiles and gcp.GetEnvironmentVariablesForIdentity.

In `@pkg/auth/providers/gcp_wif/provider.go`:
- Around line 274-358: Both exchangeToken and impersonateServiceAccount return
raw fmt.Errorf errors; update each error return to wrap the underlying error
with the static sentinel error (errUtils.ErrAuthenticationFailed or the shared
sentinel from errors/errors.go) using errors.Join for combination and %w for
context so callers can use errors.Is; specifically modify error returns in
exchangeToken (create STS request, STS request, STS error decode) and in
impersonateServiceAccount (create IAM credentials service, generate access
token, parse expiry fallback) to join the sentinel with the underlying error
while preserving the existing contextual message and %w wrapping where
appropriate.
🧹 Nitpick comments (4)
pkg/auth/cloud/gcp/setup.go (1)

29-36: Pass atmosConfig into perf.Track for public helpers.
These public functions accept atmosConfig but trace with nil, which drops context.

Suggested fix
-	defer perf.Track(nil, "gcp.SetupFiles")()
+	defer perf.Track(atmosConfig, "gcp.SetupFiles")()
...
-	defer perf.Track(nil, "gcp.Setup")()
+	defer perf.Track(atmosConfig, "gcp.Setup")()
...
-	defer perf.Track(nil, "gcp.Cleanup")()
+	defer perf.Track(atmosConfig, "gcp.Cleanup")()
...
-	defer perf.Track(nil, "gcp.LoadCredentialsFromFiles")()
+	defer perf.Track(atmosConfig, "gcp.LoadCredentialsFromFiles")()
...
-	defer perf.Track(nil, "gcp.CredentialsExist")()
+	defer perf.Track(atmosConfig, "gcp.CredentialsExist")()

As per coding guidelines: Add defer perf.Track(atmosConfig, "pkg.FuncName")() + blank line to all public functions, except trivial getters/setters, command constructors, simple factories, and functions that only delegate to another tracked function.

Also applies to: 129-136, 164-166, 181-187, 224-230

pkg/auth/identities/gcp_service_account/identity_test.go (1)

121-142: Use mockgen-generated mocks instead of manual mocks.
This keeps tests consistent with repo-wide mocking policy.

As per coding guidelines: Use interfaces and dependency injection for testability - Generate mocks with go.uber.org/mock/mockgen using //go:generate directives, never manual mocks.

Also applies to: 265-276

pkg/auth/providers/gcp_wif/provider_test.go (1)

127-150: Prefer t.Setenv for env var setup/teardown in tests.
This avoids cross-test leakage and is the repo convention.

Suggested fix
-	os.Unsetenv("TEST_OIDC_TOKEN")
-	_, err := p.getTokenFromEnv()
+	t.Setenv("TEST_OIDC_TOKEN", "")
+	_, err := p.getTokenFromEnv()
 ...
-	os.Setenv("TEST_OIDC_TOKEN", "my-oidc-token")
-	defer os.Unsetenv("TEST_OIDC_TOKEN")
+	t.Setenv("TEST_OIDC_TOKEN", "my-oidc-token")

Based on learnings: In the cloudposse/atmos repo, tests that manipulate environment variables should use testing.T.Setenv for automatic setup/teardown instead of os.Setenv/Unsetenv.

pkg/auth/providers/gcp_wif/provider.go (1)

95-115: Add perf tracking to public validation hooks.
Validate (and PreAuthenticate, if you want uniform tracing) are public and non-trivial enough to track.

🧭 Suggested update
 func (p *Provider) Validate() error {
+	defer perf.Track(nil, "gcp_wif.Validate")()
+
 	if p.spec == nil {
 		return fmt.Errorf("%w: spec is nil", errUtils.ErrInvalidProviderConfig)
 	}
@@
 func (p *Provider) PreAuthenticate(_ types.AuthManager) error {
+	defer perf.Track(nil, "gcp_wif.PreAuthenticate")()
+
 	return nil
 }
As per coding guidelines, Add `defer perf.Track(atmosConfig, "pkg.FuncName")()` + blank line to all public functions, except trivial getters/setters, command constructors, simple factories, and functions that only delegate to another tracked function.

Comment thread pkg/auth/cloud/gcp/setup.go Resolved
Comment thread pkg/auth/providers/gcp_wif/provider.go Resolved
Add GCPCredentials type support to all credential store implementations
(system keyring, file keyring, and memory keyring). This enables proper
caching and retrieval of GCP credentials, fixing the whoami command
showing "Credentials may be expired or invalid" after successful login.

Changes:
- Add GCP credential case to Store() methods in all keyring stores
- Add GCP credential case to Retrieve() methods in all keyring stores
- Add debug logging for GCP credential operations in system keyring
- Add testStoreAndRetrieveGCP test to verify GCP credential operations

Co-Authored-By: Claude Opus 4.5 <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🤖 Fix all issues with AI agents
In `@pkg/auth/cloud/gcp/files.go`:
- Around line 83-142: The MkdirAll errors returned in GetProviderDir, GetADCDir,
and GetConfigDir must be wrapped with the project's static sentinel error (e.g.,
errUtils.ErrInvalidAuthConfig or a more specific sentinel from errors/errors.go)
using fmt.Errorf("%s: %w", "<context message>", err) so callers can use
errors.Is; update the error returns in the MkdirAll failure branches of
GetProviderDir, GetADCDir, and GetConfigDir to wrap the original err with that
sentinel and a brief context message (e.g., "failed to create provider
directory", "failed to create ADC directory", "failed to create config
directory").
- Around line 73-130: The doc comments for GetGCPBaseDir, GetProviderDir,
GetADCDir, GetADCFilePath (and the following GetConfigDir block) have "Returns:"
lines missing a trailing period; update each Returns: sentence to end with a
period so they comply with godot. Locate the doc comment above the functions
GetGCPBaseDir, GetProviderDir, GetADCDir, GetADCFilePath and the GetConfigDir
header and add a period at the end of each "Returns:" line (e.g., change
"Returns: ~/.config/atmos/gcp/" to "Returns: ~/.config/atmos/gcp/."). Ensure no
other punctuation changes.
- Around line 168-226: The file write functions return raw errors and the
nil-content check lacks a sentinel; update WriteADCFile, WritePropertiesFile,
and WriteAccessTokenFile to wrap all returned errors with the package static
sentinels from errors/errors.go (e.g. use errors.ErrInvalidADCContent for the
nil content check in WriteADCFile, and errors.ErrWriteADCFile,
errors.ErrWritePropertiesFile, errors.ErrWriteAccessTokenFile for file-write
failures and path errors), preserving chaining via fmt.Errorf("%w: ...",
errors.ErrX, err) and import the errors package; ensure every returned error
from Get*Path and os.WriteFile is wrapped this way and keep the original error
with %w.

In `@pkg/auth/cloud/gcp/setup_test.go`:
- Around line 101-126: Replace the os.Setenv/os.Unsetenv usage with t.Setenv and
remove the manual cleanup loop: change os.Setenv("GOOGLE_CLOUD_PROJECT",
"old-project") (and any other os.Setenv calls in this test) to
t.Setenv("GOOGLE_CLOUD_PROJECT", "old-project") and delete the defer os.Unsetenv
call; for the final loop that calls os.Unsetenv over GCPEnvironmentVariables,
instead call t.Setenv(key, "") for each key (or register t.Cleanup to unset
them) so the test restores environment state via the testing.T helpers; keep the
rest of the test (Setup, creds, assertions, adcPath checks) unchanged.

In `@pkg/auth/cloud/gcp/setup.go`:
- Around line 51-57: The ADCFileContent initialization currently hardcodes a
client secret in the ClientSecret field which triggered a gitleaks finding;
remove the literal and instead source the client secret from a secure
configuration (e.g., environment variable, secret manager, or existing config
loader) and set ADCFileContent.ClientSecret to that value, or if this exact
value is an intentionally public, documented Google client ID/secret, add the
repository's approved gitleaks allowlist annotation for the ClientSecret
assignment so CI will not fail; update the code paths that construct
ADCFileContent to use the new config key (look for ADCFileContent and
ClientSecret in setup.go) and ensure tests/config docs reflect the change.
- Around line 198-208: The read/parse ADC error messages are currently wrapping
the original errors with "%v", which breaks error chaining; update the two
fmt.Errorf calls around os.ReadFile(adcPath) and json.Unmarshal(data, &adc) to
use "%w" and wrap the original err with errUtils.ErrInvalidAuthConfig (e.g.,
fmt.Errorf("%w: read ADC file: %w", errUtils.ErrInvalidAuthConfig, err)) so
consumers using errors.Is(err, errUtils.ErrInvalidAuthConfig) will work; look
for the block that reads adcPath, the ADCFileContent unmarshalling, and the
references to errUtils.ErrInvalidAuthConfig to apply the change.
- Around line 58-77: Wrap each returned error from WriteADCFile,
WritePropertiesFile, and WriteAccessTokenFile with the static sentinel defined
in errors/errors.go (import the package and use fmt.Errorf with %w) so callers
can reliably errors.Is against that sentinel; e.g., replace direct returns like
`fmt.Errorf("write ADC file: %w", err)` with a wrapped error that includes the
sentinel (fmt.Errorf("%w: write ADC file: %v", errors.<sentinel>, err)) and do
the same for WritePropertiesFile and WriteAccessTokenFile returns.
🧹 Nitpick comments (4)
pkg/auth/cloud/gcp/env.go (1)

27-101: Pass atmosConfig into perf tracking for public APIs.
PrepareEnvironment, SetEnvironmentVariables, and GetEnvironmentVariables accept atmosConfig but call perf.Track(nil, ...). Use the provided config to follow the tracing guideline.

🔧 Suggested adjustment
-func PrepareEnvironment(ctx context.Context, atmosConfig *schema.AtmosConfiguration) error {
-	defer perf.Track(nil, "gcp.PrepareEnvironment")()
+func PrepareEnvironment(ctx context.Context, atmosConfig *schema.AtmosConfiguration) error {
+	defer perf.Track(atmosConfig, "gcp.PrepareEnvironment")()
-func SetEnvironmentVariables(ctx context.Context, atmosConfig *schema.AtmosConfiguration, providerName, identityName string) error {
-	defer perf.Track(nil, "gcp.SetEnvironmentVariables")()
+func SetEnvironmentVariables(ctx context.Context, atmosConfig *schema.AtmosConfiguration, providerName, identityName string) error {
+	defer perf.Track(atmosConfig, "gcp.SetEnvironmentVariables")()
-func GetEnvironmentVariables(atmosConfig *schema.AtmosConfiguration, providerName, identityName string) (map[string]string, error) {
-	defer perf.Track(nil, "gcp.GetEnvironmentVariables")()
+func GetEnvironmentVariables(atmosConfig *schema.AtmosConfiguration, providerName, identityName string) (map[string]string, error) {
+	defer perf.Track(atmosConfig, "gcp.GetEnvironmentVariables")()
As per coding guidelines: Add `defer perf.Track(atmosConfig, "pkg.FuncName")()` + blank line to all public functions, except trivial getters/setters, command constructors, simple factories, and functions that only delegate to another tracked function.
pkg/auth/cloud/gcp/env_test.go (1)

14-33: Use t.Setenv for env isolation in tests.
These tests should use t.Setenv instead of os.Setenv/os.Unsetenv to prevent cross-test leakage (same applies to the other env-setting tests in this file).

🔧 Example adjustment
-	os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", "/path/to/creds.json")
-	os.Setenv("GOOGLE_CLOUD_PROJECT", "my-project")
-	os.Setenv("CLOUDSDK_CONFIG", "/path/to/config")
-	defer func() {
-		os.Unsetenv("GOOGLE_APPLICATION_CREDENTIALS")
-		os.Unsetenv("GOOGLE_CLOUD_PROJECT")
-		os.Unsetenv("CLOUDSDK_CONFIG")
-	}()
+	t.Setenv("GOOGLE_APPLICATION_CREDENTIALS", "/path/to/creds.json")
+	t.Setenv("GOOGLE_CLOUD_PROJECT", "my-project")
+	t.Setenv("CLOUDSDK_CONFIG", "/path/to/config")
Based on learnings: In the cloudposse/atmos repo, tests that manipulate environment variables should use testing.T.Setenv for automatic setup/teardown instead of os.Setenv/Unsetenv.
pkg/auth/identities/gcp_service_account/identity_test.go (1)

121-276: Use generated mocks from pkg/auth/types for Provider and ICredentials; add mockgen for IAMCredentialsService.

The manual MockProvider and mockNonGCPCreds duplicate already-generated mocks in pkg/auth/types/mock_interfaces.go. Replace them with types.MockProvider and types.MockICredentials.

For mockIAMService, add a //go:generate directive to the IAMCredentialsService interface in identity.go and use the generated mock instead. This aligns with the codebase pattern and enables proper mock expectations via EXPECT() chains.

pkg/auth/cloud/gcp/setup_test.go (1)

150-220: Consider table-driven tests for the multi-scenario cases.
LoadCredentialsFromFiles and CredentialsExist each cover multiple variants; a table-driven layout would reduce duplication.

As per coding guidelines: Use table-driven tests for testing multiple scenarios in Go.

Comment thread pkg/auth/cloud/gcp/files.go Resolved
Comment thread pkg/auth/cloud/gcp/files.go Resolved
Comment thread pkg/auth/cloud/gcp/files.go Resolved
Comment thread pkg/auth/cloud/gcp/setup_test.go Resolved
Comment thread pkg/auth/cloud/gcp/setup.go Resolved
Comment thread pkg/auth/cloud/gcp/setup.go Resolved
Comment thread pkg/auth/cloud/gcp/setup.go Resolved
@aknysh Andriy Knysh (aknysh) added the minor New features that do not break anything label Feb 3, 2026
@aknysh

Copy link
Copy Markdown
Member

@coderabbital full review please

@coderabbitai

coderabbitai Bot commented Feb 3, 2026

Copy link
Copy Markdown
Contributor

@aknysh: I'll perform a full review of the PR.

✅ Actions performed

Full review triggered.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@pkg/auth/cloud/gcp/files.go`:
- Around line 144-157: Update the doc comments for GetPropertiesFilePath and
GetAccessTokenFilePath to end the "Returns:" path description sentences with a
trailing period; locate the `Returns:` lines in the comment above the
GetPropertiesFilePath function and the comment above GetAccessTokenFilePath and
add a period at the end of each path description to satisfy the godot linter.

In `@pkg/auth/cloud/gcp/setup_test.go`:
- Around line 114-116: The comment immediately above the
assert.Equal(os.Getenv("GOOGLE_OAUTH_ACCESS_TOKEN")) line ends without a period;
update that comment text ("When we have an access token, we use
GOOGLE_OAUTH_ACCESS_TOKEN instead of GOOGLE_APPLICATION_CREDENTIALS (to avoid
refresh token requirement in ADC file).") so it ends with a period to satisfy
the godot linter—i.e., add the missing trailing period to the comment above the
assert.Equal call in setup_test.go.
🧹 Nitpick comments (4)
pkg/auth/factory/gcp_providers_test.go (2)

38-52: Test assertion is non-deterministic.

The conditional if err != nil means this test passes regardless of whether an error occurs. Consider making the expected behavior explicit:

  1. If the parser should reject type mismatches, use require.Error(t, err).
  2. If weak typing is intentional, document why and verify the provider was created correctly.

Also, the comment on line 43 needs a period per godot linter requirements.

♻️ Suggested fix for deterministic behavior
 func TestCreateGCPADCProvider_InvalidSpec(t *testing.T) {
 	f := NewFactory()
 
-	// Invalid spec (e.g., wrong type for a field).
+	// Invalid spec (e.g., wrong type for a field).
 	spec := map[string]any{
-		"project_id": 123, // Should be string.
+		"project_id": 123, // Should be string.
 	}
 
 	_, err := f.CreateProvider(types.ProviderKindGCPADC, "bad-adc", spec)
-	// Depending on parser strictness, this may or may not error.
-	// If weak typing is disabled, expect an error.
-	if err != nil {
-		assert.Contains(t, err.Error(), "parse")
-	}
+	// If weak typing is disabled, this should error.
+	// If the system uses weak typing and coerces 123 to "123", verify creation succeeds.
+	require.Error(t, err, "Expected error for invalid spec type")
+	assert.Contains(t, err.Error(), "parse")
 }

76-91: Test silently passes if both creation and validation paths fail unexpectedly.

The conditional structure means if err != nil (unexpected creation failure), the test passes without verification. Consider asserting the expected behavior path:

 func TestCreateGCPWIFProvider_MissingRequired(t *testing.T) {
 	f := NewFactory()

-	// Missing project_number, pool_id, provider_id.
+	// Missing project_number, pool_id, provider_id.
 	spec := map[string]any{
 		"project_id": "incomplete",
 	}

 	provider, err := f.CreateProvider(types.ProviderKindGCPWorkloadIdentityFederation, "incomplete-wif", spec)
-	// Provider is created but Validate() will fail later.
-	// Or if constructor validates, expect error here.
-	if err == nil && provider != nil {
-		err = provider.Validate()
-		require.Error(t, err)
-	}
+	// Provider is created but Validate() will fail later.
+	// Or if constructor validates, expect error here.
+	if err != nil {
+		// Constructor validated - verify error.
+		require.Error(t, err)
+		return
+	}
+	require.NotNil(t, provider)
+	err = provider.Validate()
+	require.Error(t, err, "Expected validation to fail for incomplete WIF spec")
 }

Also, comments on lines 85-86 need periods per godot linter.

pkg/auth/cloud/gcp/files.go (2)

100-114: Consider validating identityName parameter.

GetProviderDir validates that providerName is not empty, but GetADCDir (and similarly GetConfigDir) doesn't validate identityName. An empty identityName would create an odd path structure.

Optional validation
 func GetADCDir(providerName, identityName string) (string, error) {
 	defer perf.Track(nil, "gcp.GetADCDir")()

+	if identityName == "" {
+		return "", fmt.Errorf("%w: identity name is required", errUtils.ErrInvalidAuthConfig)
+	}
 	providerDir, err := GetProviderDir(providerName)

229-245: Consider wrapping cleanup error with static sentinel.

Line 241's error isn't wrapped with a static sentinel from errors/errors.go. For consistency, consider adding a cleanup-specific sentinel or using an existing one.

-		return fmt.Errorf("failed to remove %s: %w", dir, err)
+		return fmt.Errorf("%w: failed to remove %s: %w", errUtils.ErrInvalidAuthConfig, dir, err)

If cleanup failures should be distinguishable, a dedicated ErrCleanupFailed sentinel could be added to errors/errors.go.

As per coding guidelines: All errors MUST be wrapped using static errors defined in errors/errors.go.

Comment thread pkg/auth/cloud/gcp/files.go Resolved
Comment thread pkg/auth/cloud/gcp/setup_test.go Resolved
@codecov

codecov Bot commented Feb 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.17557% with 271 lines in your changes missing coverage. Please review.
✅ Project coverage is 76.43%. Comparing base (082335d) to head (ea0e37a).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
pkg/auth/cloud/gcp/files.go 60.33% 37 Missing and 34 partials ⚠️
...kg/auth/identities/gcp_service_account/identity.go 80.48% 29 Missing and 11 partials ⚠️
pkg/auth/cloud/gcp/setup.go 78.94% 17 Missing and 15 partials ⚠️
pkg/auth/providers/gcp_wif/provider.go 92.85% 10 Missing and 8 partials ⚠️
pkg/auth/types/gcp_specs.go 78.94% 6 Missing and 6 partials ⚠️
cmd/auth_whoami.go 28.57% 10 Missing ⚠️
pkg/auth/credentials/keyring_system.go 62.96% 7 Missing and 3 partials ⚠️
pkg/auth/identities/gcp_project/identity.go 90.09% 5 Missing and 5 partials ⚠️
pkg/auth/providers/gcp_adc/provider.go 89.13% 10 Missing ⚠️
pkg/config/auth_realm.go 57.14% 6 Missing and 3 partials ⚠️
... and 10 more
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2051      +/-   ##
==========================================
+ Coverage   76.33%   76.43%   +0.09%     
==========================================
  Files         803      816      +13     
  Lines       75574    76934    +1360     
==========================================
+ Hits        57692    58804    +1112     
- Misses      14299    14457     +158     
- Partials     3583     3673      +90     
Flag Coverage Δ
unittests 76.43% <80.17%> (+0.09%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
errors/errors.go 100.00% <ø> (ø)
pkg/auth/manager_chain.go 89.58% <100.00%> (+0.10%) ⬆️
pkg/auth/types/gcp_credentials.go 100.00% <100.00%> (ø)
pkg/config/config.go 73.36% <100.00%> (+0.12%) ⬆️
pkg/schema/schema.go 88.98% <ø> (ø)
pkg/schema/schema_auth.go 100.00% <ø> (ø)
pkg/auth/credentials/keyring_memory.go 82.14% <75.00%> (-0.55%) ⬇️
pkg/auth/manager.go 80.72% <75.00%> (-0.30%) ⬇️
pkg/auth/types/context.go 90.00% <80.00%> (-10.00%) ⬇️
pkg/auth/factory/gcp_identities.go 81.81% <81.81%> (ø)
... and 16 more

... and 9 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Fix all issues with AI agents
In `@pkg/auth/cloud/gcp/setup.go`:
- Around line 47-58: The SetupFiles function currently reads
ATMOS_GCP_ADC_CLIENT_ID and ATMOS_GCP_ADC_CLIENT_SECRET directly from the
environment; change it to first read these keys from the provided
*schema.AtmosConfiguration (use atmosConfig.Settings["ATMOS_GCP_ADC_CLIENT_ID"]
/ ["ATMOS_GCP_ADC_CLIENT_SECRET"] or Viper-bound Settings access) and only fall
back to os.Getenv if the settings entry is empty; ensure the same default client
ID is applied when Settings doesn't contain the client ID and retain the
existing error behavior for missing client secret
(errUtils.ErrInvalidAuthConfig) so tests and config precedence use
atmosConfig.Settings instead of env-only access in SetupFiles.

In `@pkg/auth/factory/gcp_providers_test.go`:
- Around line 38-51: Update TestCreateGCPADCProvider_InvalidSpec to be
deterministic: add the errUtils import, construct spec using an unconvertible
type for "project_id" (e.g., a struct or slice) so parsing must fail, call
f.CreateProvider(types.ProviderKindGCPADC, "bad-adc", spec) and replace the
current conditional check with require.Error(t, err) and assert.ErrorIs(t, err,
errUtils.ErrInvalidAuthConfig) to assert the specific ErrInvalidAuthConfig; keep
references to NewFactory and CreateProvider intact.

In `@pkg/auth/providers/gcp_wif/provider_test.go`:
- Around line 127-150: Update TestGetTokenFromEnv to use t.Setenv instead of
os.Setenv/os.Unsetenv to avoid leaking environment changes: in the "missing env
var" case call t.Setenv("TEST_OIDC_TOKEN", "") before p.getTokenFromEnv(), and
in the "with env var set" case call t.Setenv("TEST_OIDC_TOKEN", "my-oidc-token")
(remove defer/unset), leaving the rest of the test logic around
TestGetTokenFromEnv and p.getTokenFromEnv unchanged.
🧹 Nitpick comments (3)
pkg/auth/identities/gcp_service_account/identity_test.go (3)

3-16: Import order: move google.golang.org/api to 3rd-party group.

The iamcredentials import belongs in group 2 (3rd-party) rather than group 3 (Atmos packages).

📦 Suggested import reordering
 import (
 	"context"
 	"errors"
 	"testing"
 	"time"

 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/require"
+	"google.golang.org/api/iamcredentials/v1"

 	errUtils "github.com/cloudposse/atmos/errors"
 	"github.com/cloudposse/atmos/pkg/auth/types"
 	"github.com/cloudposse/atmos/pkg/schema"
-	"google.golang.org/api/iamcredentials/v1"
 )

As per coding guidelines, imports should be organized: 1) Go stdlib, 2) 3rd-party, 3) Atmos packages.


107-119: Minor: Consider using require.NoError for the constructor.

Line 111 ignores the error with _. While acceptable here since the input is known-valid, explicit assertion is cleaner.

✨ Optional improvement
-	id, _ := New(principal)
+	id, err := New(principal)
+	require.NoError(t, err)

121-141: Consider generated mocks for consistency.

Guidelines prefer mockgen-generated mocks. This manual mock is simple and works fine for this test file—just flagging for awareness.

As per coding guidelines: "Generate mocks with go.uber.org/mock/mockgen using //go:generate directives."

Comment thread pkg/auth/cloud/gcp/setup.go Resolved
Comment thread pkg/auth/factory/gcp_providers_test.go Resolved
@coderabbitai

coderabbitai Bot commented Feb 3, 2026

Copy link
Copy Markdown
Contributor

@aknysh On it—starting a full review now.


🧠 Learnings used
Learnt from: aknysh
Repo: cloudposse/atmos PR: 1327
File: internal/exec/describe_affected_utils_2.go:248-248
Timestamp: 2025-06-23T18:50:33.614Z
Learning: When aknysh mentions that a suggestion is not related to the current PR and needs separate tests to be reviewed in a separate PR, this indicates their preference for maintaining focused PR scope and proper test coverage for each change.
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Fix all issues with AI agents
In `@pkg/auth/identities/gcp_service_account/identity.go`:
- Around line 384-400: The error wrapping in Identity.LoadCredentials uses
fmt.Errorf("%w: resolve provider name: %v", errUtils.ErrInvalidIdentityConfig,
err) which mixes %w and %v; change it to use %w for the wrapped error (e.g.,
fmt.Errorf("%w: resolve provider name: %w", errUtils.ErrInvalidIdentityConfig,
err)) so the original error is wrapped correctly; update the error creation in
LoadCredentials (and any identical pattern in that function) to use %w for
wrapping the underlying error returned by i.GetProviderName().
- Around line 370-382: In Identity.CredentialsExist replace the fmt.Errorf call
that uses "%v" to wrap the resolved provider name error with "%w" for proper
error wrapping (the call that returns fmt.Errorf("%w: resolve provider name:
%v", errUtils.ErrInvalidIdentityConfig, err)), so update it to use "%w" and pass
err as the wrapped error; keep the surrounding logic (providerName,
ErrInvalidIdentityConfig, i.Name(), and final call to gcp.CredentialsExist)
unchanged.
- Around line 356-368: In Identity.Logout, replace the fmt.Errorf that uses "%v"
for the wrapped error with "%w" so the error returned by GetProviderName is
wrapped correctly (change fmt.Errorf("%w: resolve provider name: %v",
errUtils.ErrInvalidIdentityConfig, err) to use "%w" for the err); keep the other
fmt.Errorf that reports empty providerName as-is and ensure references to
GetProviderName, Identity.Logout and gcp.Cleanup remain unchanged.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@pkg/auth/identities/gcp_service_account/identity.go`:
- Around line 384-399: LoadCredentials currently can return (nil, nil) and
doesn't check token expiry; update Identity.LoadCredentials to treat a nil creds
result from gcp.LoadCredentialsFromFiles as an error (wrap with the static error
from errors/errors.go using fmt.Errorf("%w: missing credentials for %s",
errStaticName, i.Name()) or errors.Join as appropriate) and additionally
validate the returned credentials' expiry/validity (call the credential's
Expiry/Valid method or field and return a wrapped error like fmt.Errorf("%w:
expired credentials for %s", errStaticName, i.Name()) when expired). Ensure any
existing errors from gcp.LoadCredentialsFromFiles are wrapped with %w or
combined with errors.Join and continue returning a non-nil error in all failure
cases; reference Identity.LoadCredentials and gcp.LoadCredentialsFromFiles when
locating the change and use the static errors defined in errors/errors.go for
wrapping.

…m field

- Add SetRealm method to gcp_adc.Provider, gcp_wif.Provider, and gcp_project.Identity
  to satisfy updated Provider/Identity interfaces from realm isolation feature
- Remove duplicate Realm field in AuthConfig struct (merge artifact)
- Add SetRealm to MockProvider in gcp_service_account tests
- Regenerate golden snapshots after merge

Co-Authored-By: Claude Opus 4.6 <[email protected]>
coderabbitai[bot]
coderabbitai Bot previously approved these changes Feb 11, 2026
Comment thread pkg/auth/providers/gcp_wif/doc.go Fixed
@aknysh

Copy link
Copy Markdown
Member

Mikhail Shirkov (@shirkevich) thanks, we are almost there

please fix these errors:

Error: pkg/auth/identities/gcp_service_account/identity.go:35:24: undefined: gcp.IAMCredentialsServiceFactory
Error: pkg/auth/identities/gcp_service_account/identity.go:48:26: undefined: gcp.NewIAMCredentialsService
Error: pkg/auth/identities/gcp_service_account/identity.go:171:17: undefined: gcp.NewIAMCredentialsService
Error: pkg/auth/identities/gcp_service_account/identity.go:178:13: undefined: gcp.ImpersonateServiceAccount
github.com/cloudposse/atmos/pkg/auth/providers/gcp_wif
# github.com/cloudposse/atmos/pkg/auth/providers/gcp_wif
Error: pkg/auth/providers/gcp_wif/provider.go:43:75: undefined: gcp.IAMCredentialsService
Error: pkg/auth/providers/gcp_wif/provider.go:66:26: undefined: gcp.NewIAMCredentialsService
Error: pkg/auth/providers/gcp_wif/provider.go:388:17: undefined: gcp.NewIAMCredentialsService
Error: pkg/auth/providers/gcp_wif/provider.go:395:34: undefined: gcp.ImpersonateServiceAccount

… of silent fallback

- Add ErrEmptyRealm sentinel error for credential isolation enforcement
- Replace realmOrDefault() with requireRealm() in gcp_service_account — all
  file operations (PrepareEnvironment, PostAuthenticate, Logout,
  CredentialsExist, LoadCredentials) now fail fast on empty realm
- Remove default realm ("default") from gcp_service_account constructor
- Add centralized empty-realm validation in auth manager after realm computation
- Remove redundant realm-setting in initializeIdentities() that used raw
  config.Realm instead of computed m.realm.Value
- Remove unused realmSetter interface from manager
- Document SetRealm as realm-independent no-op on ADC, WIF, and project types
- Add comprehensive tests: empty realm rejection, realm isolation, realm-
  independent behavior verification

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@osterman

Copy link
Copy Markdown
Member

Code RabBit (@CodeRabbit) please review file path, temp file usage, and XDG implementation. Also review ini file generation, I think it could be redundant with other ini handling from AWS.

@coderabbitai

coderabbitai Bot commented Feb 12, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

I'll review the file path handling, XDG implementation, temp file usage, and INI generation in the GCP auth code.


🏁 Script executed:

#!/bin/bash
# Examine GCP file path and XDG implementation
echo "=== GCP files.go - Path construction and XDG usage ==="
cat pkg/auth/cloud/gcp/files.go | head -100

echo -e "\n=== Check XDG usage in GCP files ==="
rg -n "XDG" pkg/auth/cloud/gcp/

echo -e "\n=== Check temp file usage in GCP ==="
rg -n "ioutil.TempFile|os.CreateTemp|TempDir" pkg/auth/cloud/gcp/

echo -e "\n=== GCP WritePropertiesFile - INI generation ==="
ast-grep --pattern 'func WritePropertiesFile($$$) {
  $$$
}'

Length of output: 7676


🏁 Script executed:

#!/bin/bash
# Check AWS INI handling for comparison
echo "=== Search for AWS INI file handling ==="
rg -n "WriteFile.*properties|\.ini|gopkg.in/ini" pkg/auth/cloud/aws/ --type go -A 3 -B 3

echo -e "\n=== Check if there's shared INI utility ==="
fd -e go -x grep -l "ini\|properties" {} \; | head -20

echo -e "\n=== Look for existing INI packages/utilities ==="
rg -n "gopkg.in/ini|github.com.*ini" go.mod

Length of output: 4423


🏁 Script executed:

#!/bin/bash
# Detailed examination of path construction
echo "=== GetGCPBaseDir implementation ==="
ast-grep --pattern 'func GetGCPBaseDir() ($$$) {
  $$$
}'

echo -e "\n=== Check XDG_CONFIG_HOME usage vs XDG_CACHE_HOME ==="
rg -n "XDG_CONFIG_HOME|XDG_CACHE_HOME" pkg/auth/cloud/gcp/ -A 2 -B 2

echo -e "\n=== Compare with AWS path handling ==="
rg -n "GetAWSBaseDir|AWS.*BaseDir" pkg/auth/cloud/aws/ --type go -A 5

Length of output: 11750


🏁 Script executed:

#!/bin/bash
# Check the INI generation implementation in detail
echo "=== Full WritePropertiesFile implementation ==="
sed -n '/func WritePropertiesFile/,/^}/p' pkg/auth/cloud/gcp/files.go

echo -e "\n=== Check for hardcoded paths ==="
rg -n "\.cache|\.config|~/\." pkg/auth/cloud/gcp/files.go

Length of output: 922


🏁 Script executed:

#!/bin/bash
# Check AWS file manager for locking and advanced features
echo "=== AWS file locking implementation ==="
rg -n "flock|Lock|Unlock" pkg/auth/cloud/aws/files.go -A 3 -B 1

echo -e "\n=== AWS INI library usage patterns ==="
sed -n '/func.*INI/,/^}/p' pkg/auth/cloud/aws/files.go | head -50

echo -e "\n=== Check if GCP needs similar file management ==="
rg -n "WriteFile|os\.Create" pkg/auth/cloud/gcp/files.go -B 2 -A 2

Length of output: 3893


🏁 Script executed:

#!/bin/bash
# Compare INI usage between AWS and what GCP could use
echo "=== How AWS uses gopkg.in/ini.v1 ==="
rg -n "ini\.(Empty|Load|NewSection|NewKey|SaveTo)" pkg/auth/cloud/aws/ --type go -A 2 -B 1 | head -60

echo -e "\n=== GCP properties file structure ==="
cat pkg/auth/cloud/gcp/files.go | grep -A 20 "func WritePropertiesFile"

Length of output: 4209


🏁 Script executed:

#!/bin/bash
# Check for any potential race conditions or concurrent access patterns
echo "=== Check for concurrent file operations in GCP ==="
rg -n "sync\.|mutex|lock" pkg/auth/cloud/gcp/ --type go

echo -e "\n=== Check AWS concurrent patterns ==="
rg -n "type.*Manager|struct.*Manager" pkg/auth/cloud/aws/files.go -A 10 | head -30

Length of output: 648


@osterman, I've reviewed the file path handling, XDG implementation, temp file usage, and INI generation in the GCP auth code. Here are my findings:

✅ Good: File Paths & XDG Implementation

The path implementation is correctly using XDG_CONFIG_HOME:

  • Uses xdg.GetXDGConfigDir() which returns ~/.config/atmos/
  • Path structure: ~/.config/atmos/{realm}/gcp/{provider}/...
  • Proper realm-based isolation for multi-config scenarios
  • Path segment validation to prevent directory traversal
  • No hardcoded paths in production code

This is correct because credentials and config files belong in XDG_CONFIG_HOME (not XDG_CACHE_HOME which is for toolchain caching).

✅ Good: Temp File Usage

No temp files are used in production code—all GCP credential files are written directly with os.WriteFile(). The only TempDir() usage is in tests (which is correct).

⚠️ Issue 1: Redundant INI Generation

The WritePropertiesFile function manually generates INI content using string concatenation, while AWS uses the gopkg.in/ini.v1 library which is already in go.mod.

Current GCP approach:

b := []byte("[core]\n")
if projectID != "" {
    b = append(b, []byte("project = "+projectID+"\n")...)
}
b = append(b, []byte("\n[compute]\n")...)

AWS approach (using ini.v1):

cfg := ini.Empty()
sec, _ := cfg.NewSection("core")
sec.NewKey("project", projectID)
// ...handles escaping, special chars, etc.

Recommendation: Refactor GCP to use the same ini.v1 library for consistency, maintainability, and proper handling of special characters.

⚠️ Issue 2: Missing File Locking

AWS implements file locking with github.com/gofrs/flock including timeout and retry logic. GCP has no file locking, which could cause race conditions if:

  • Multiple Atmos processes authenticate concurrently
  • Parallel Terraform runs with the same identity
  • Concurrent CI/CD jobs

Recommendation: Add file locking to GCP file operations similar to AWS, especially for:

  • WriteADCFile
  • WritePropertiesFile
  • CleanupIdentityFiles

Summary

Aspect Status Notes
XDG Implementation ✅ Correct Uses XDG_CONFIG_HOME appropriately
File Paths ✅ Good Realm-based isolation, proper validation
Temp Files ✅ N/A Not used (which is fine)
INI Generation ⚠️ Redundant Should use ini.v1 library like AWS
File Locking ❌ Missing No concurrency protection

Would you like me to create an issue to track the refactoring of INI generation and addition of file locking?


🧠 Learnings used
Learnt from: osterman
Repo: cloudposse/atmos PR: 808
File: pkg/config/config.go:478-483
Timestamp: 2024-12-02T21:26:32.337Z
Learning: In the 'atmos' project, when reviewing Go code like `pkg/config/config.go`, avoid suggesting file size checks after downloading remote configs if such checks aren't implemented elsewhere in the codebase.

Learnt from: aknysh
Repo: cloudposse/atmos PR: 944
File: go.mod:206-206
Timestamp: 2025-01-17T00:18:57.769Z
Learning: For indirect dependencies with license compliance issues in the cloudposse/atmos repository, the team prefers to handle them in follow-up PRs rather than blocking the current changes, as these issues often require deeper investigation of the dependency tree.

Learnt from: osterman
Repo: cloudposse/atmos PR: 1686
File: errors/errors.go:184-203
Timestamp: 2025-12-13T06:10:13.688Z
Learning: cloudposse/atmos: For toolchain work, duplicate/unused error sentinels in errors/errors.go should be cleaned up in a separate refactor PR and not block feature PRs; canonical toolchain sentinels live under toolchain/registry with re-exports in toolchain/errors.go.

Learnt from: osterman
Repo: cloudposse/atmos PR: 1686
File: docs/prd/tool-dependencies-integration.md:58-64
Timestamp: 2025-12-13T06:07:37.766Z
Learning: cloudposse/atmos: For PRD docs (docs/prd/*.md), markdownlint issues like MD040/MD010/MD034 can be handled in a separate documentation cleanup commit and should not block the current PR.

Learnt from: Listener430
Repo: cloudposse/atmos PR: 934
File: tests/fixtures/scenarios/docs-generate/README.md.gotmpl:99-118
Timestamp: 2025-01-25T03:51:57.689Z
Learning: For the cloudposse/atmos repository, changes to template contents should be handled in dedicated PRs and are typically considered out of scope for PRs focused on other objectives.

Learnt from: osterman
Repo: cloudposse/atmos PR: 1466
File: website/docs/cli/commands/toolchain/usage.mdx:117-121
Timestamp: 2025-09-08T01:25:44.958Z
Learning: XDG Base Directory Specification compliance implementation for atmos toolchain is complete: created toolchain/xdg_cache.go with GetXDGCacheDir() and GetXDGTempCacheDir() functions, updated toolchain/installer.go and cmd/toolchain_clean.go to use these XDG helpers, and changed all cache paths from hardcoded ~/.cache/tools-cache to XDG-compliant ${XDG_CACHE_HOME}/atmos-toolchain (or ~/.cache/atmos-toolchain fallback).

Learnt from: osterman
Repo: cloudposse/atmos PR: 1466
File: website/docs/cli/commands/toolchain/usage.mdx:117-121
Timestamp: 2025-09-08T01:25:44.958Z
Learning: Final XDG Base Directory Specification implementation for atmos toolchain is complete and verified: toolchain/xdg_cache.go provides GetXDGCacheDir() and GetXDGTempCacheDir() functions, all hardcoded ~/.cache/tools-cache paths have been replaced with XDG-compliant paths using ${XDG_CACHE_HOME}/atmos-toolchain (or ~/.cache/atmos-toolchain fallback), and tests have been updated to expect the new path structure.

Learnt from: osterman
Repo: cloudposse/atmos PR: 1697
File: internal/exec/oci_utils.go:0-0
Timestamp: 2025-11-08T19:56:18.660Z
Learning: In the Atmos codebase, when a function receives an `*schema.AtmosConfiguration` parameter, it should read configuration values from `atmosConfig.Settings` fields rather than using direct `os.Getenv()` or `viper.GetString()` calls. The Atmos pattern is: viper.BindEnv in cmd/root.go binds environment variables → Viper unmarshals into atmosConfig.Settings via mapstructure → business logic reads from the Settings struct. This provides centralized config management, respects precedence, and enables testability. Example: `atmosConfig.Settings.AtmosGithubToken` instead of `os.Getenv("ATMOS_GITHUB_TOKEN")` in functions like `getGHCRAuth` in internal/exec/oci_utils.go.

Learnt from: osterman
Repo: cloudposse/atmos PR: 740
File: cmd/cmd_utils.go:340-359
Timestamp: 2024-10-23T21:36:40.262Z
Learning: In the Go codebase for Atmos, when reviewing functions like `checkAtmosConfig` in `cmd/cmd_utils.go`, avoid suggesting refactoring to return errors instead of calling `os.Exit` if such changes would significantly increase the scope due to the need to update multiple call sites.

Learnt from: osterman
Repo: cloudposse/atmos PR: 1466
File: website/docs/cli/commands/toolchain/usage.mdx:117-121
Timestamp: 2025-09-08T01:25:44.958Z
Learning: The atmos toolchain XDG compliance implementation is complete with GetXDGCacheDir() and GetXDGTempCacheDir() functions in toolchain/xdg_cache.go, updated installer.go and toolchain_clean.go to use these helpers, and changed cache paths from ~/.cache/tools-cache to ${XDG_CACHE_HOME}/atmos-toolchain (or ~/.cache/atmos-toolchain when XDG_CACHE_HOME is not set).

Learnt from: osterman
Repo: cloudposse/atmos PR: 1466
File: website/docs/cli/commands/toolchain/usage.mdx:117-121
Timestamp: 2025-09-08T01:25:44.958Z
Learning: The atmos toolchain should follow XDG Base Directory Specification like the rest of atmos core, using XDG_CACHE_HOME environment variable when available and falling back to ~/.cache when not set, instead of hardcoding ~/.cache/tools-cache paths.

Learnt from: osterman
Repo: cloudposse/atmos PR: 1466
File: website/docs/cli/commands/toolchain/usage.mdx:117-121
Timestamp: 2025-09-08T01:25:44.958Z
Learning: The atmos toolchain has been updated to follow XDG Base Directory Specification with helper functions GetXDGCacheDir() and GetXDGTempCacheDir() in toolchain/xdg_cache.go, using XDG_CACHE_HOME when set and falling back to ~/.cache/atmos-toolchain, making it consistent with atmos core's XDG compliance.

Refactor GCP credential file operations for consistency with AWS/Azure:
- Replace manual string concatenation in WritePropertiesFile with ini.v1
  library for proper escaping and consistent INI generation
- Add flock-based file locking (10s timeout, 50ms retry) to WriteADCFile,
  WritePropertiesFile, WriteAccessTokenFile, and CleanupIdentityFiles to
  prevent race conditions during concurrent authentication

Co-Authored-By: Claude Opus 4.6 <[email protected]>
The impersonate.go and impersonate_test.go files were never committed,
causing CI failures with undefined references to IAMCredentialsService,
NewIAMCredentialsService, and ImpersonateServiceAccount.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Add tests for previously uncovered functions and paths:
- SetEnvironmentVariablesFromStackInfo (0% → 100%)
- ProjectEnvVars/ZoneEnvVars empty branches (66% → 100%)
- formatTokenExpiry zero time (66% → 100%)
- adcCredentialsPath fallback paths (25% → 87.5%)
- validatePathSegment all branches (85% → 100%)
- WriteAccessTokenFile empty token and zero expiry
- WritePropertiesFile special chars and permissions
- WriteADCFile overwrite behavior
- GetConfigDir error paths
- LoadCredentialsFromFiles invalid JSON and empty token
- resolveADCClientCredentials env var paths

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@aknysh

Copy link
Copy Markdown
Member

Mikhail Shirkov (@shirkevich) can you please check the failing tests? Sorry it takes too long, let's finish it today

Tests that call PostAuthenticate → Setup → resolveADCClientCredentials()
require the ADC client secret env var which CI environments don't have.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
After commit 0848941 enforced non-empty realm in NewAuthManager(),
tests creating AuthConfig without Realm field fail with "realm
computation produced an empty value". Add Realm: "test-realm" to all
AuthConfig structs that flow through NewAuthManager() across 9 test
files in cmd/, cmd/devcontainer/, and pkg/auth/ packages.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@aknysh
Andriy Knysh (aknysh) merged commit e62868b into cloudposse:main Feb 17, 2026
56 checks passed
@github-actions

Copy link
Copy Markdown

These changes were released in v1.206.3-rc.1.

@github-actions

Copy link
Copy Markdown

These changes were released in v1.207.0.

@github-actions

Copy link
Copy Markdown

These changes were released in v1.208.0-rc.0.

@github-actions

Copy link
Copy Markdown

These changes were released in v1.208.0-test.15.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

minor New features that do not break anything size/xl Extra large size PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants