From 4abfd87339731bbbde108264890e9636453bf0f9 Mon Sep 17 00:00:00 2001 From: Cody Oss Date: Tue, 28 Mar 2023 15:45:12 -0500 Subject: [PATCH] google: add CredentialsParams.EarlyTokenRefresh This option is a followup to to cl/479676 where an option was added to configure the preemptive token refresh. Currently the option in this package is only being used by compute credentials. In the future we can support more/all auth flows but that would require a lot of new surfaces to be added. Compute credentials are currently the only case where we are expirencing the need to configure this setting. Change-Id: Ib78ca4beec44d0fe030ae81e84c8fcc4924793ba Reviewed-on: https://go-review.googlesource.com/c/oauth2/+/479956 Run-TryBot: Cody Oss TryBot-Result: Gopher Robot Reviewed-by: Roland Shoemaker --- google/default.go | 11 ++++++++++- google/google.go | 6 +++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/google/default.go b/google/default.go index 91b538b..b3e8783 100644 --- a/google/default.go +++ b/google/default.go @@ -13,6 +13,7 @@ import ( "os" "path/filepath" "runtime" + "time" "cloud.google.com/go/compute/metadata" "golang.org/x/oauth2" @@ -68,6 +69,14 @@ type CredentialsParams struct { // The OAuth2 TokenURL default override. This value overrides the default TokenURL, // unless explicitly specified by the credentials config file. Optional. TokenURL string + + // EarlyTokenRefresh is the amount of time before a token expires that a new + // token will be preemptively fetched. If unset the default value is 10 + // seconds. + // + // Note: This option is currently only respected when using credentials + // fetched from the GCE metadata server. + EarlyTokenRefresh time.Duration } func (params CredentialsParams) deepCopy() CredentialsParams { @@ -155,7 +164,7 @@ func FindDefaultCredentialsWithParams(ctx context.Context, params CredentialsPar id, _ := metadata.ProjectID() return &Credentials{ ProjectID: id, - TokenSource: ComputeTokenSource("", params.Scopes...), + TokenSource: computeTokenSource("", params.EarlyTokenRefresh, params.Scopes...), }, nil } diff --git a/google/google.go b/google/google.go index a1b629a..cc12238 100644 --- a/google/google.go +++ b/google/google.go @@ -231,7 +231,11 @@ func (f *credentialsFile) tokenSource(ctx context.Context, params CredentialsPar // Further information about retrieving access tokens from the GCE metadata // server can be found at https://cloud.google.com/compute/docs/authentication. func ComputeTokenSource(account string, scope ...string) oauth2.TokenSource { - return oauth2.ReuseTokenSource(nil, computeSource{account: account, scopes: scope}) + return computeTokenSource(account, 0, scope...) +} + +func computeTokenSource(account string, earlyExpiry time.Duration, scope ...string) oauth2.TokenSource { + return oauth2.ReuseTokenSourceWithExpiry(nil, computeSource{account: account, scopes: scope}, earlyExpiry) } type computeSource struct {