From 4234369799259bd645508214c96ab668327dc04e Mon Sep 17 00:00:00 2001 From: v-thavaahariharangit <164553783+v-thavaahariharangit@users.noreply.github.com> Date: Tue, 27 Oct 2026 15:05:05 +0000 Subject: [PATCH] Lower the direct GCP WIF token lifetime threshold to four minutes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/copilot-instructions.md | 2 +- internal/oidc/actions_oidc.go | 8 ++- internal/oidc/actions_oidc_test.go | 4 +- internal/oidc/oidc_credential.go | 8 ++- internal/oidc/oidc_credential_test.go | 98 +++++++++++++++++++++++++++ 5 files changed, 115 insertions(+), 5 deletions(-) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 9d3a471d..a4a02651 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -73,7 +73,7 @@ Handlers can support OIDC token exchange for Azure, JFrog, or AWS. See [oidc_cre - Check `oidc.CreateOIDCCredential(cred)` to detect OIDC config - Use `oidc.GetOrRefreshOIDCToken(cred, ctx)` for cached token retrieval -- Tokens are cached with 5-minute expiry buffer +- Tokens are cached with a 5-minute expiry buffer (4 minutes for direct GCP Workload Identity Federation without service-account impersonation) ## Environment Variables diff --git a/internal/oidc/actions_oidc.go b/internal/oidc/actions_oidc.go index f37a9570..4f5c11fb 100644 --- a/internal/oidc/actions_oidc.go +++ b/internal/oidc/actions_oidc.go @@ -32,6 +32,12 @@ const ( awsCodeArtifactDateFormat = "20060102T150405Z" awsCodeArtifactSTSRequestUrl = "https://sts.amazonaws.com" awsCodeArtifactTokenURLPath = "/v1/authorization-token" //nolint:gosec // URL path, not a credential + + // GitHub OIDC tokens last five minutes, and direct WIF inherits their expiry. + // Leave room for exchange latency; a five-minute minimum rejects fresh tokens. + // https://github.com/google-github-actions/auth#inputs-workload-identity-federation + // https://github.com/dependabot/proxy/issues/262 + gcpDirectWIFExpiryBuffer = 4 * time.Minute ) // tokenResponse represents the response from GitHub's OIDC provider @@ -758,7 +764,7 @@ func GetGCPAccessToken(ctx context.Context, params GCPOIDCParameters, githubToke // If no service account, return the federated token directly (direct WIF) if params.ServiceAccount == "" { stsExpiry := time.Duration(stsTokenResp.ExpiresIn) * time.Second - if stsExpiry <= 5*time.Minute { + if stsExpiry <= gcpDirectWIFExpiryBuffer { return nil, fmt.Errorf("GCP STS token expires too soon (%v remaining)", stsExpiry) } return &OIDCAccessToken{ diff --git a/internal/oidc/actions_oidc_test.go b/internal/oidc/actions_oidc_test.go index 77d7a829..f1698d73 100644 --- a/internal/oidc/actions_oidc_test.go +++ b/internal/oidc/actions_oidc_test.go @@ -1269,7 +1269,7 @@ func TestGetGCPAccessToken(t *testing.T) { expectError: true, }, { - name: "STS token at exactly 5 minutes (direct WIF)", + name: "STS token at exactly 4 minutes (direct WIF)", params: GCPOIDCParameters{ WorkloadIdentityProvider: "projects/123/locations/global/workloadIdentityPools/pool/providers/prov", Audience: "//iam.googleapis.com/projects/123/locations/global/workloadIdentityPools/pool/providers/prov", @@ -1279,7 +1279,7 @@ func TestGetGCPAccessToken(t *testing.T) { w.Header().Set("Content-Type", "application/json") encodeJSONResponse(t, w, gcpSTSTokenResponse{ AccessToken: "federated-access-token", - ExpiresIn: 300, + ExpiresIn: 240, }) }, expectError: true, diff --git a/internal/oidc/oidc_credential.go b/internal/oidc/oidc_credential.go index b51cb2d7..dd8e6e20 100644 --- a/internal/oidc/oidc_credential.go +++ b/internal/oidc/oidc_credential.go @@ -225,8 +225,14 @@ func GetOrRefreshOIDCToken(cred *OIDCCredential, ctx context.Context) (string, e return "", fmt.Errorf("failed to get %s access token: %w", cred.Provider(), err) } + refreshBuffer := 5 * time.Minute + if params, ok := cred.parameters.(*GCPOIDCParameters); ok && params.ServiceAccount == "" { + // A five-minute buffer would mark fresh direct WIF tokens expired in the cache. + refreshBuffer = gcpDirectWIFExpiryBuffer + } + cred.cachedToken = oidcAccessToken.Token - cred.tokenExpiry = time.Now().Add(oidcAccessToken.ExpiresIn).Add(-time.Minute * 5) // refresh 5 minutes before expiry + cred.tokenExpiry = time.Now().Add(oidcAccessToken.ExpiresIn).Add(-refreshBuffer) return oidcAccessToken.Token, nil } diff --git a/internal/oidc/oidc_credential_test.go b/internal/oidc/oidc_credential_test.go index 2fd4a42a..3b066047 100644 --- a/internal/oidc/oidc_credential_test.go +++ b/internal/oidc/oidc_credential_test.go @@ -9,6 +9,8 @@ import ( "net/http" "strings" "testing" + "testing/synctest" + "time" "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" @@ -79,6 +81,102 @@ func TestSuccessfulAuthenticationDoesNotMakeARepeatedRequest(t *testing.T) { assert.Equal(t, 1, requestsReceived, "expected only one token request due to successful authentication being cached") } +func TestGetOrRefreshGCPToken(t *testing.T) { + tests := []struct { + name string + expiresIn int + serviceAccount string + refreshAfter time.Duration + wantError string + }{ + {name: "nearly five minutes", expiresIn: 298, refreshAfter: 58 * time.Second}, + {name: "five minutes", expiresIn: 300, refreshAfter: time.Minute}, + {name: "just over four minutes", expiresIn: 241, refreshAfter: time.Second}, + {name: "exactly four minutes", expiresIn: 240, wantError: "GCP STS token expires too soon"}, + {name: "under four minutes", expiresIn: 239, wantError: "GCP STS token expires too soon"}, + {name: "expired", expiresIn: 0, wantError: "GCP STS token expires too soon"}, + {name: "negative lifetime", expiresIn: -1, wantError: "GCP STS token expires too soon"}, + {name: "long-lived direct WIF", expiresIn: 3600, refreshAfter: 56 * time.Minute}, + { + name: "impersonation retains five-minute minimum", + expiresIn: 298, + serviceAccount: "my-sa@my-project.iam.gserviceaccount.com", + wantError: "GCP IAM token expires too soon", + }, + { + name: "impersonation retains five-minute refresh buffer", + expiresIn: 3600, + serviceAccount: "my-sa@my-project.iam.gserviceaccount.com", + refreshAfter: 55 * time.Minute, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + t.Setenv(envActionsIDTokenRequestURL, "https://example.com/token") + t.Setenv(envActionsIDTokenRequestToken, "test-token") + + creds, err := CreateOIDCCredential(config.Credential{ + "workload-identity-provider": "projects/123/locations/global/workloadIdentityPools/pool/providers/prov", + "service-account": tt.serviceAccount, + }, testHTTPClient) + require.NoError(t, err) + + httpmock.Activate() + defer httpmock.DeactivateAndReset() + httpmock.RegisterResponder("GET", "https://example.com/token", + httpmock.NewStringResponder(200, `{"count":1,"value":"test-assertion"}`)) + + requestsReceived := 0 + httpmock.RegisterResponder("POST", "https://sts.googleapis.com/v1/token", func(req *http.Request) (*http.Response, error) { + requestsReceived++ + return httpmock.NewJsonResponse(200, gcpSTSTokenResponse{ + AccessToken: fmt.Sprintf("gcp-token-%d", requestsReceived), + ExpiresIn: tt.expiresIn, + }) + }) + if tt.serviceAccount != "" { + iamURL := fmt.Sprintf("https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/%s:generateAccessToken", tt.serviceAccount) + httpmock.RegisterResponder("POST", iamURL, func(req *http.Request) (*http.Response, error) { + return httpmock.NewJsonResponse(200, gcpIAMGenerateAccessTokenResponse{ + AccessToken: fmt.Sprintf("gcp-token-%d", requestsReceived), + ExpireTime: time.Now().Add(time.Duration(tt.expiresIn) * time.Second).Format(time.RFC3339Nano), + }) + }) + } + + token, err := GetOrRefreshOIDCToken(creds, t.Context()) + if tt.wantError != "" { + require.ErrorContains(t, err, tt.wantError) + assert.Empty(t, token) + assert.Empty(t, creds.cachedToken) + + _, err = GetOrRefreshOIDCToken(creds, t.Context()) + require.ErrorContains(t, err, "credential has been rejected due to previous authentication failure") + assert.Equal(t, 1, requestsReceived) + return + } + require.NoError(t, err) + assert.Equal(t, "gcp-token-1", token) + assert.Equal(t, time.Now().Add(tt.refreshAfter), creds.tokenExpiry) + + time.Sleep(tt.refreshAfter - time.Second) + token, err = GetOrRefreshOIDCToken(creds, t.Context()) + require.NoError(t, err) + assert.Equal(t, "gcp-token-1", token) + assert.Equal(t, 1, requestsReceived, "token should be reused before the refresh boundary") + + time.Sleep(time.Second) + token, err = GetOrRefreshOIDCToken(creds, t.Context()) + require.NoError(t, err) + assert.Equal(t, "gcp-token-2", token) + assert.Equal(t, 2, requestsReceived, "token should be refreshed at the refresh boundary") + }) + }) + } +} + func TestFailedAuthenticationIsNotRetried(t *testing.T) { // these variables are necessary t.Setenv(envActionsIDTokenRequestURL, "https://example.com/token")