Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
8 changes: 7 additions & 1 deletion internal/oidc/actions_oidc.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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{
Expand Down
4 changes: 2 additions & 2 deletions internal/oidc/actions_oidc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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,
Expand Down
8 changes: 7 additions & 1 deletion internal/oidc/oidc_credential.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
98 changes: 98 additions & 0 deletions internal/oidc/oidc_credential_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
"net/http"
"strings"
"testing"
"testing/synctest"
"time"

"github.com/jarcoal/httpmock"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -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")
Expand Down
Loading