Skip to content

Commit 678b9b3

Browse files
Cherrypick #9385 to v1.85.x (#9504)
Original PR : #9385 RELEASE NOTES: N/A
1 parent 705f9b9 commit 678b9b3

12 files changed

Lines changed: 502 additions & 1320 deletions

File tree

‎credentials/google/gcp_service_account_identity_credentials.go‎

Lines changed: 20 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -20,19 +20,14 @@ package google
2020

2121
import (
2222
"context"
23-
"errors"
2423
"fmt"
2524
"sync"
2625
"time"
2726

28-
"cloud.google.com/go/auth"
29-
"cloud.google.com/go/auth/credentials/idtoken"
30-
"cloud.google.com/go/compute/metadata"
3127
"google.golang.org/grpc/codes"
3228
"google.golang.org/grpc/credentials"
3329
"google.golang.org/grpc/credentials/google/internal"
3430
"google.golang.org/grpc/internal/backoff"
35-
"google.golang.org/grpc/internal/transport"
3631
"google.golang.org/grpc/status"
3732
)
3833

@@ -53,14 +48,14 @@ const (
5348
type gcpServiceAccountIdentityCallCreds struct {
5449
// The following fields are initialized at creation time and are read-only
5550
// after that.
56-
ctx context.Context
57-
audience string
58-
creds *auth.Credentials
59-
backoff backoff.Strategy
51+
ctx context.Context
52+
audience string
53+
backoff backoff.Strategy
54+
fetchIDToken func(context.Context, string) (string, time.Time, error)
6055

6156
// The following fields are protected by mu.
6257
mu sync.Mutex
63-
token *auth.Token
58+
token string // cached raw JWT token value
6459
tokenExpiry time.Time // timestamp after which the cached token is considered invalid
6560
preemptiveTokenRefresh time.Time // timestamp after which background preemptive refresh is triggered
6661
fetching chan struct{} // used to ensure a single in-progress background token fetch
@@ -71,8 +66,8 @@ type gcpServiceAccountIdentityCallCreds struct {
7166

7267
func init() {
7368
internal.BackoffStrategy = backoff.DefaultExponential
74-
internal.NewIDTokenCredentials = func(opts *idtoken.Options) (*auth.Credentials, error) {
75-
return idtoken.NewCredentials(opts)
69+
internal.IDTokenFetcher = func() func(context.Context, string) (string, time.Time, error) {
70+
return newIDTokenFetcher().fetchIDToken
7671
}
7772
}
7873

@@ -103,16 +98,11 @@ func NewServiceAccountIdentityCredentials(ctx context.Context, audience string)
10398
return nil, fmt.Errorf("credentials: audience cannot be empty")
10499
}
105100

106-
creds, err := internal.NewIDTokenCredentials(&idtoken.Options{Audience: audience})
107-
if err != nil {
108-
return nil, fmt.Errorf("credentials: failed to create ID token credentials: %v", err)
109-
}
110-
111101
return &gcpServiceAccountIdentityCallCreds{
112-
ctx: ctx,
113-
audience: audience,
114-
creds: creds,
115-
backoff: internal.BackoffStrategy,
102+
ctx: ctx,
103+
audience: audience,
104+
backoff: internal.BackoffStrategy,
105+
fetchIDToken: internal.IDTokenFetcher(),
116106
}, nil
117107
}
118108

@@ -183,13 +173,13 @@ func (c *gcpServiceAccountIdentityCallCreds) cachedRequestMetadata(attemptPreemp
183173
//
184174
// It must be called with mu locked.
185175
func (c *gcpServiceAccountIdentityCallCreds) cachedRequestMetadataLocked(attemptPreemptiveRefresh bool) (map[string]string, error) {
186-
if c.token != nil && c.isTokenValidLocked() {
176+
if c.token != "" && c.isTokenValidLocked() {
187177
if attemptPreemptiveRefresh && c.isTokenStaleLocked() && c.fetching == nil {
188178
c.fetching = make(chan struct{})
189179
go c.startFetch()
190180
}
191181

192-
return map[string]string{"authorization": "Bearer " + c.token.Value}, nil
182+
return map[string]string{"authorization": "Bearer " + c.token}, nil
193183
}
194184

195185
if c.lastErr != nil && time.Now().Before(c.nextRetryTime) {
@@ -222,46 +212,27 @@ func (c *gcpServiceAccountIdentityCallCreds) isTokenValidLocked() bool {
222212
func (c *gcpServiceAccountIdentityCallCreds) startFetch() {
223213
ctx, cancel := context.WithTimeout(c.ctx, metadataTimeout)
224214
defer cancel()
225-
token, err := c.creds.TokenProvider.Token(ctx)
215+
token, exp, err := c.fetchIDToken(ctx, c.audience)
226216

227217
c.mu.Lock()
228218
defer c.mu.Unlock()
229219

230220
close(c.fetching)
231221
c.fetching = nil
232-
c.updateStateLocked(token, err)
222+
c.updateStateLocked(token, exp, err)
233223
}
234224

235225
// updateStateLocked updates the credentials local token cache and
236226
// backoff state based on the outcome of a background fetch attempt.
237227
//
238228
// If the fetch succeeded, the cached token is updated, and the backoff timers
239-
// and error are reset.
240-
//
241-
// If the fetch failed, backoff attempts are calculated and the error is mapped
242-
// to a gRPC status.
243-
// - If the HTTP request fails with a status that maps to gRPC UNAVAILABLE
244-
// according to HTTP to gRPC status code mappings, it returns UNAVAILABLE.
245-
// - All other HTTP error status codes map to UNAUTHENTICATED.
246-
// - Non-HTTP request failures are mapped to UNAVAILABLE.
229+
// and error are reset. If the fetch failed, the error is cached and the next
230+
// retry time is calculated using the backoff strategy.
247231
//
248232
// It must be called with mu locked.
249-
func (c *gcpServiceAccountIdentityCallCreds) updateStateLocked(token *auth.Token, err error) {
233+
func (c *gcpServiceAccountIdentityCallCreds) updateStateLocked(token string, exp time.Time, err error) {
250234
if err != nil {
251-
var mappedErr error
252-
var metadataErr *metadata.Error
253-
if errors.As(err, &metadataErr) {
254-
switch transport.HTTPStatusConvTab[metadataErr.Code] {
255-
case codes.Unavailable:
256-
mappedErr = status.Errorf(codes.Unavailable, "credentials: failed to fetch token from metadata server: %v", err)
257-
default:
258-
mappedErr = status.Errorf(codes.Unauthenticated, "credentials: failed to fetch token from metadata server: %v", err)
259-
}
260-
} else {
261-
mappedErr = status.Errorf(codes.Unavailable, "credentials: failed to fetch ID token: %v", err)
262-
}
263-
264-
c.lastErr = mappedErr
235+
c.lastErr = err
265236
backoffDelay := c.backoff.Backoff(c.retryAttempt)
266237
c.retryAttempt++
267238
c.nextRetryTime = time.Now().Add(backoffDelay)
@@ -273,6 +244,6 @@ func (c *gcpServiceAccountIdentityCallCreds) updateStateLocked(token *auth.Token
273244
c.token = token
274245
// Per gRFC A83, the cached token is considered invalid 30 seconds before its
275246
// actual expiration time to accommodate for clock skew.
276-
c.tokenExpiry = token.Expiry.Add(-30 * time.Second)
247+
c.tokenExpiry = exp.Add(-30 * time.Second)
277248
c.preemptiveTokenRefresh = c.tokenExpiry.Add(-preemptiveRefresh)
278249
}

‎credentials/google/gcp_service_account_identity_credentials_test.go‎

Lines changed: 28 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,11 @@ package google_test
2121
import (
2222
"context"
2323
"errors"
24-
"fmt"
2524
"strings"
2625
"sync"
2726
"testing"
2827
"time"
2928

30-
"cloud.google.com/go/auth"
31-
"cloud.google.com/go/auth/credentials/idtoken"
32-
"cloud.google.com/go/compute/metadata"
3329
"google.golang.org/grpc/codes"
3430
"google.golang.org/grpc/credentials"
3531
"google.golang.org/grpc/credentials/google"
@@ -66,23 +62,25 @@ func (m *stubBackoff) Backoff(int) time.Duration {
6662
return m.backoffDelay
6763
}
6864

69-
// stubTokenProvider implements auth.TokenProvider for unit testing.
65+
// stubTokenProvider implements ID token fetching for unit testing.
7066
// It supplies mocked token payloads, simulates processing delay, and tracks
7167
// invocation frequency to verify caching and backoff behaviors.
7268
type stubTokenProvider struct {
7369
mu sync.Mutex
7470
err error
75-
token *auth.Token
71+
tokenVal string
72+
expiry time.Time
7673
callCount int // tracks fetch attempts to verify caching and backoff behaviors.
7774
}
7875

79-
func (c *stubTokenProvider) Token(context.Context) (*auth.Token, error) {
76+
func (c *stubTokenProvider) fetch(context.Context, string) (string, time.Time, error) {
8077
c.mu.Lock()
8178
c.callCount++
82-
token := c.token
79+
tokenVal := c.tokenVal
80+
expiry := c.expiry
8381
err := c.err
8482
c.mu.Unlock()
85-
return token, err
83+
return tokenVal, expiry, err
8684
}
8785

8886
func (c *stubTokenProvider) setErr(err error) {
@@ -91,10 +89,11 @@ func (c *stubTokenProvider) setErr(err error) {
9189
c.err = err
9290
}
9391

94-
func (c *stubTokenProvider) setToken(token *auth.Token) {
92+
func (c *stubTokenProvider) setToken(tokenVal string, expiry time.Time) {
9593
c.mu.Lock()
9694
defer c.mu.Unlock()
97-
c.token = token
95+
c.tokenVal = tokenVal
96+
c.expiry = expiry
9897
}
9998

10099
func (c *stubTokenProvider) getCallCount() int {
@@ -107,27 +106,23 @@ func (c *stubTokenProvider) getCallCount() int {
107106
// configured with the specified token value, token expiry, error and delay.
108107
func setupStubTokenProvider(token string, err error) *stubTokenProvider {
109108
return &stubTokenProvider{
110-
err: err,
111-
token: &auth.Token{
112-
Value: token,
113-
Expiry: time.Now().Add(1 * time.Hour), // idtoken package works with hardcoded 1 hour token expiry.
114-
},
109+
err: err,
110+
tokenVal: token,
111+
expiry: time.Now().Add(1 * time.Hour), // keep token valid and outside the preemptive refresh window
115112
}
116113
}
117114

118115
// setupTestGCPServiceAccountIdentityCreds constructs a GCP service account
119116
// identity credentials instance with an injected stub token provider.
120117
//
121-
// It overrides internal.NewIDTokenCredentials to use the stubTokenProvider,
118+
// It overrides internal.IDTokenFetcher to use the stubTokenProvider,
122119
// and registers a cleanup function to restore original hook after the test.
123120
func setupTestGCPServiceAccountIdentityCreds(ctx context.Context, t *testing.T, stubToken *stubTokenProvider) credentials.PerRPCCredentials {
124-
// Override the ID token credentials to use stub token provider.
125-
origNewIDTokenCredentials := internal.NewIDTokenCredentials
126-
internal.NewIDTokenCredentials = func(*idtoken.Options) (*auth.Credentials, error) {
127-
return auth.NewCredentials(&auth.CredentialsOptions{
128-
TokenProvider: auth.NewCachedTokenProvider(stubToken, &auth.CachedTokenProviderOptions{})}), nil
121+
origIDTokenFetcher := internal.IDTokenFetcher
122+
internal.IDTokenFetcher = func() func(context.Context, string) (string, time.Time, error) {
123+
return stubToken.fetch
129124
}
130-
t.Cleanup(func() { internal.NewIDTokenCredentials = origNewIDTokenCredentials })
125+
t.Cleanup(func() { internal.IDTokenFetcher = origIDTokenFetcher })
131126

132127
creds, err := google.NewServiceAccountIdentityCredentials(ctx, "audience")
133128
if err != nil {
@@ -432,13 +427,8 @@ func (s) TestGCPServiceAccountIdentityCallCreds_EarlyExpiry(t *testing.T) {
432427
secondToken = "token-B"
433428
)
434429
stubToken := setupStubTokenProvider(firstToken, nil)
435-
stubToken.setToken(
436-
&auth.Token{
437-
Value: firstToken,
438-
// Keeping it 1 minute as we subtract 30 seconds from the token expiry.
439-
Expiry: time.Now().Add(1 * time.Minute),
440-
},
441-
)
430+
// Keeping token expiry 1 minute as we subtract 30 seconds from it.
431+
stubToken.setToken(firstToken, time.Now().Add(1*time.Minute))
442432
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
443433
defer cancel()
444434
creds := setupTestGCPServiceAccountIdentityCreds(ctx, t, stubToken)
@@ -461,7 +451,7 @@ func (s) TestGCPServiceAccountIdentityCallCreds_EarlyExpiry(t *testing.T) {
461451
}
462452

463453
// Update stub token provider to return a new token
464-
stubToken.setToken(&auth.Token{Value: secondToken, Expiry: time.Now().Add(1 * time.Hour)})
454+
stubToken.setToken(secondToken, time.Now().Add(1*time.Hour))
465455

466456
// The cached token has not expired yet but is stale (the current time is
467457
// past the preemptiveTokenRefresh window). GetRequestMetadata should
@@ -495,33 +485,32 @@ func (s) TestGCPServiceAccountIdentityCallCreds_EarlyExpiry(t *testing.T) {
495485
}
496486
}
497487

498-
// Test verifies that different types of errors from the metadata server are
499-
// mapped to the correct gRPC status codes when returned through
500-
// GetRequestMetadata.
501-
func (s) TestGCPServiceAccountIdentityCallCreds_ErrorMapping(t *testing.T) {
488+
// Test verifies that errors returned by the underlying token fetcher function
489+
// are properly propagated to callers of GetRequestMetadata.
490+
func (s) TestGCPServiceAccountIdentityCallCreds_ErrorPropagation(t *testing.T) {
502491
tests := []struct {
503492
name string
504493
err error
505494
want codes.Code
506495
}{
507496
{
508497
name: "429_too_many_requests",
509-
err: &metadata.Error{Code: 429, Message: "too many requests"},
498+
err: status.Errorf(codes.Unavailable, "credentials: failed to fetch ID token: HTTP status 429"),
510499
want: codes.Unavailable,
511500
},
512501
{
513502
name: "503_service_unavailable",
514-
err: &metadata.Error{Code: 503, Message: "unavailable"},
503+
err: status.Errorf(codes.Unavailable, "credentials: failed to fetch ID token: HTTP status 503"),
515504
want: codes.Unavailable,
516505
},
517506
{
518507
name: "403_forbidden",
519-
err: &metadata.Error{Code: 403, Message: "forbidden"},
508+
err: status.Errorf(codes.Unauthenticated, "credentials: failed to fetch ID token: HTTP status 403"),
520509
want: codes.Unauthenticated,
521510
},
522511
{
523512
name: "generic_protocol_error",
524-
err: fmt.Errorf("generic connection error"),
513+
err: status.Errorf(codes.Unavailable, "generic connection error"),
525514
want: codes.Unavailable,
526515
},
527516
}

0 commit comments

Comments
 (0)