From 402ff22627225cffe92a0c3f53eed9654aef8c77 Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Thu, 3 Dec 2026 16:29:35 +0000 Subject: [PATCH] docs(auth): document token lifecycle, refresh margins, and listener behavior --- .../com/google/auth/oauth2/AccessToken.java | 28 +++- .../auth/oauth2/CloudShellCredentials.java | 20 ++- .../google/auth/oauth2/OAuth2Credentials.java | 140 ++++++++++++++---- .../oauth2/OAuth2CredentialsWithRefresh.java | 52 ++++++- 4 files changed, 202 insertions(+), 38 deletions(-) diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/AccessToken.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/AccessToken.java index e3ff2ccbf002..b9d7fc9f47f0 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/AccessToken.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/AccessToken.java @@ -53,8 +53,16 @@ public class AccessToken implements Serializable { private final List scopes; /** - * @param tokenValue String representation of the access token. - * @param expirationTime Time when access token will expire. + * Creates an {@code AccessToken} with the given raw token string and optional expiration time. + * + *

Passing {@code null} for {@code expirationTime} indicates that the expiration time is + * unknown or managed externally. {@link OAuth2Credentials} treats tokens with a {@code null} + * expiration time as non-expiring and will not automatically refresh them on {@link + * OAuth2Credentials#refreshIfExpired()} or {@link + * OAuth2Credentials#getRequestMetadata(java.net.URI)}. + * + * @param tokenValue string representation of the access token + * @param expirationTime time when the access token will expire, or {@code null} if unknown */ public AccessToken(String tokenValue, @Nullable Date expirationTime) { this.tokenValue = tokenValue; @@ -97,9 +105,14 @@ public String getTokenValue() { } /** - * Time when access token will expire. + * Returns a copy of the time when this access token will expire, or {@code null} if no expiration + * time was set. + * + *

When this method returns {@code null}, {@link OAuth2Credentials} treats the token as fresh + * and does not trigger automatic expiration-based refreshes. Call {@link + * OAuth2Credentials#refresh()} explicitly if a new token is needed. * - * @return The expiration time as a {@link Date}. + * @return a defensive copy of the expiration {@link Date}, or {@code null} if none is set */ public @Nullable Date getExpirationTime() { if (expirationTimeMillis == null) { @@ -194,6 +207,13 @@ public Builder setScopes(@Nullable List scopes) { return this; } + /** + * Sets the time when the access token will expire, or {@code null} if unknown (which disables + * automatic expiration-based refreshes in {@link OAuth2Credentials}). + * + * @param expirationTime the expiration time, or {@code null} + * @return this builder + */ @CanIgnoreReturnValue public Builder setExpirationTime(@Nullable Date expirationTime) { this.expirationTime = expirationTime; diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/CloudShellCredentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/CloudShellCredentials.java index 4f00696623d0..f8de7cd02eb0 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/CloudShellCredentials.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/CloudShellCredentials.java @@ -46,7 +46,16 @@ import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; -/** OAuth2 credentials representing the built-in service account for Google Cloud Shell. */ +/** + * OAuth2 credentials representing the built-in user account for Google Cloud Shell. + * + *

The local Cloud Shell authorization channel returns access tokens without an expiration time + * ({@link AccessToken#getExpirationTime()} is {@code null}). As a result, {@link OAuth2Credentials} + * treats a cached token as non-expiring after the first fetch, and {@link + * OAuth2Credentials#refreshIfExpired()} will not automatically refresh it. Call {@link + * OAuth2Credentials#refresh()} explicitly (or rely on an HTTP 401 retry handler such as {@link + * com.google.auth.http.HttpCredentialsAdapter}) when a fresh token is required. + */ @NullMarked public class CloudShellCredentials extends GoogleCredentials { @@ -80,6 +89,15 @@ protected int getAuthPort() { return this.authPort; } + /** + * Fetches a fresh access token from the local Cloud Shell authorization proxy. + * + *

The returned {@link AccessToken} has a {@code null} expiration time, so {@link + * OAuth2Credentials} will not refresh it automatically after caching. + * + * @return a new access token with a {@code null} expiration time + * @throws IOException if communicating with the local Cloud Shell auth port fails + */ @Override public AccessToken refreshAccessToken() throws IOException { Socket socket = new Socket("localhost", this.getAuthPort()); diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2Credentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2Credentials.java index 3646f75a45e9..7a36505df032 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2Credentials.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2Credentials.java @@ -91,14 +91,22 @@ public class OAuth2Credentials extends Credentials { transient Clock clock = Clock.SYSTEM; /** - * Returns the credentials instance from the given access token. + * Returns a non-refreshable credentials instance wrapping the given static {@link AccessToken}. + * + *

Instances created by this method cannot refresh tokens. Calling {@link #refresh()} always + * throws {@link IllegalStateException}, even while the token is unexpired or has a {@code null} + * expiration time. Calling {@link #getRequestMetadata(URI)} or {@link #refreshIfExpired()} + * succeeds while the token is valid and throws {@link IllegalStateException} once the token + * expires or enters the expiration margin (a {@code null} expiration time is treated as + * non-expiring and never triggers automatic refresh). For custom automatic token refresh, use + * {@link OAuth2CredentialsWithRefresh}. * *

The returned credentials default to {@link Credentials#GOOGLE_DEFAULT_UNIVERSE}. To create * access-token credentials for a custom universe domain, use {@link * GoogleCredentials#create(String, AccessToken)}. * - * @param accessToken the access token - * @return the credentials instance + * @param accessToken the temporary access token to send as a bearer token + * @return a non-refreshable credentials instance */ public static OAuth2Credentials create(AccessToken accessToken) { return OAuth2Credentials.newBuilder().setAccessToken(accessToken).build(); @@ -147,11 +155,12 @@ public boolean hasRequestMetadataOnly() { } /** - * Returns the cached access token. + * Returns the currently cached access token, or {@code null} if no token has been fetched yet. * - *

If not set, you should call {@link #refresh()} to fetch and cache an access token. + *

This method does not perform network I/O or check expiration. Call {@link + * #refreshIfExpired()} before calling this method to ensure a valid, unexpired token is cached. * - * @return The cached access token. + * @return the cached access token, or {@code null} before the first refresh */ public final @Nullable AccessToken getAccessToken() { OAuthValue localState = value; @@ -173,6 +182,24 @@ Duration getExpirationMargin() { return this.expirationMargin; } + /** + * Asynchronously provides request metadata containing an {@code Authorization} bearer token and + * any additional headers. + * + *

Cached tokens are evaluated in three states relative to the configured refresh and + * expiration margins: + * + *

+ */ @Override public void getRequestMetadata( final URI uri, Executor executor, final RequestMetadataCallback callback) { @@ -184,8 +211,21 @@ public void getRequestMetadata( } /** - * Provide the request metadata by ensuring there is a current access token and providing it as an - * authorization bearer token. + * Synchronously provides request metadata containing an {@code Authorization} bearer token and + * any additional headers, refreshing the cached token when missing, stale, or expired. + * + *

Unlike the asynchronous overload, if the cached token is stale (within the refresh margin + * but outside the expiration margin), this method executes the refresh synchronously on the + * calling thread before returning. If that refresh fails while the cached token is still outside + * the expiration margin, the still-valid cached metadata is returned. Once expired, refresh + * failures propagate as {@link IOException} (or {@link IllegalStateException} for non-refreshable + * credentials). + * + * @param uri the target request URI, or {@code null} if not applicable + * @return request metadata headers including the bearer {@code Authorization} header + * @throws IOException if token refresh fails when no unexpired token is available + * @throws IllegalStateException if a refresh is required and this credential does not support + * refreshing */ @Override public Map> getRequestMetadata(@Nullable URI uri) throws IOException { @@ -193,8 +233,16 @@ public Map> getRequestMetadata(@Nullable URI uri) throws IO } /** - * Request a new token regardless of the current token state. If the current token is not expired, - * it will still be returned during the refresh. + * Unconditionally requests a new access token regardless of the current token state. + * + *

Prefer {@link #refreshIfExpired()} in application code so valid cached tokens are reused. + * Concurrent calls coalesce onto a single in-flight refresh, and while the refresh is running, + * other callers continue to receive the existing token if it is not yet expired. + * + * @throws IOException if token refresh fails + * @throws IllegalStateException if this credential type does not support refreshing (for example, + * instances returned by {@link #create(AccessToken)}), even if the cached token is unexpired + * or has a {@code null} expiration time */ @Override public void refresh() throws IOException { @@ -204,9 +252,19 @@ public void refresh() throws IOException { } /** - * Refresh these credentials only if they have expired or are expiring imminently. + * Refreshes the cached access token if none is cached, if it has expired, or if it is within the + * configured refresh margin. * - * @throws IOException during token refresh. + *

Prefer this method over {@link #refresh()} in application code so valid cached tokens are + * reused. Tokens with a {@code null} expiration time are treated as fresh and never trigger an + * automatic refresh. Concurrent callers share a single in-flight refresh. When the cached token + * is stale (within the refresh margin but outside the expiration margin), this method runs the + * refresh synchronously on the calling thread and falls back to the still-valid cached token if + * that refresh fails. + * + * @throws IOException if token refresh fails when no unexpired token is available + * @throws IllegalStateException if a refresh is required and this credential type does not + * support refreshing */ public void refreshIfExpired() throws IOException { // asyncFetch will ensure that the token is refreshed @@ -364,13 +422,19 @@ private CacheState getState() { /** * Method to refresh the access token according to the specific type of credentials. * - *

Throws IllegalStateException if not overridden since direct use of OAuth2Credentials is only - * for temporary or non-refreshing access tokens. + *

Subclasses override this method to fetch a new access token. Callers should normally use + * {@link #refreshIfExpired()} or {@link #refresh()} instead of calling this method directly, + * because this method does not update the cached token, coordinate concurrent refreshes, or + * notify registered change listeners. + * + *

Throws {@link IllegalStateException} if not overridden, since direct use of {@code + * OAuth2Credentials} is only for temporary or non-refreshing access tokens. * - * @return never - * @throws IllegalStateException always. OAuth2Credentials does not support refreshing the access - * token. An instance with a new access token or a derived type that supports refreshing - * should be used instead. + * @return the newly fetched access token (never returns on the base implementation) + * @throws IOException if fetching a new access token fails in a subclass + * @throws IllegalStateException always on the base implementation, because {@code + * OAuth2Credentials} does not support refreshing the access token. Use an instance with a new + * access token or a refreshable subclass such as {@link OAuth2CredentialsWithRefresh}. */ public AccessToken refreshAccessToken() throws IOException { throw new IllegalStateException( @@ -389,10 +453,13 @@ protected Map> getAdditionalHeaders() { } /** - * Adds a listener that is notified when the Credentials data changes. + * Adds a listener that is notified when the credentials data changes. * - *

This is called when token content changes, such as when the access token is refreshed. This - * is typically used by code caching the access token. + *

Listeners are invoked synchronously while holding the credential's internal lock immediately + * after a token refresh completes, so listeners should remain fast and non-blocking. Any {@link + * IOException} or {@link RuntimeException} thrown by a listener is caught and suppressed without + * failing the refresh, and stops notification of any remaining listeners for that refresh. + * Registered listeners are transient and are not preserved across Java serialization. * * @param listener the listener to be added */ @@ -429,11 +496,13 @@ public interface CredentialsChangedListener { /** * Notifies that the credentials have changed. * - *

This is called when token content changes, such as when the access token is refreshed. - * This is typically used by code caching the access token. + *

Called synchronously while holding the credential's internal lock after the cached token + * is updated. Exceptions thrown by this method are caught and suppressed (they do not fail the + * refresh), and prevent subsequent registered listeners from being notified for that refresh. * - * @param credentials The updated credentials instance - * @throws IOException May be thrown by listeners if saving credentials fails. + * @param credentials the updated credentials instance + * @throws IOException may be thrown by listeners if saving credentials fails (caught and + * suppressed by {@code OAuth2Credentials}) */ void onChanged(OAuth2Credentials credentials) throws IOException; } @@ -738,22 +807,43 @@ public Builder setAccessToken(@Nullable AccessToken token) { return this; } + /** + * Sets how far before token expiration a cached token is considered stale, triggering a + * proactive refresh while still allowing callers to use the cached token. + * + *

Must be non-null and non-negative, and should be greater than or equal to the expiration + * margin so proactive refreshes occur before the token is treated as expired. + * + * @param refreshMargin the non-negative proactive refresh margin + * @return this builder + */ @CanIgnoreReturnValue public Builder setRefreshMargin(Duration refreshMargin) { this.refreshMargin = refreshMargin; return this; } + /** Returns the refresh margin configured via {@link #setRefreshMargin(Duration)}. */ public Duration getRefreshMargin() { return refreshMargin; } + /** + * Sets how far before token expiration a cached token is considered expired, requiring callers + * to wait for a refresh before proceeding. + * + *

Must be non-null and non-negative. + * + * @param expirationMargin the non-negative expiration margin + * @return this builder + */ @CanIgnoreReturnValue public Builder setExpirationMargin(Duration expirationMargin) { this.expirationMargin = expirationMargin; return this; } + /** Returns the expiration margin configured via {@link #setExpirationMargin(Duration)}. */ public Duration getExpirationMargin() { return expirationMargin; } diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2CredentialsWithRefresh.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2CredentialsWithRefresh.java index 3e3665111d18..c8bc9b7fa8bd 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2CredentialsWithRefresh.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2CredentialsWithRefresh.java @@ -43,17 +43,40 @@ import org.jspecify.annotations.Nullable; /** - * A refreshable alternative to {@link OAuth2Credentials}. - * - *

To enable automatic token refreshes, you must provide an {@link + * A refreshable alternative to {@link OAuth2Credentials} backed by a caller-supplied {@link * OAuth2CredentialsWithRefresh.OAuth2RefreshHandler}. * + *

Use this class instead of non-refreshing {@link OAuth2Credentials#create(AccessToken)} when + * you have custom token-acquisition logic and want thread-safe caching, single-flight refresh + * coordination, and margin-based refreshing. + * + *

Providing an initial {@link AccessToken} on the builder is optional. When omitted, the first + * {@link OAuth2Credentials#refreshIfExpired()} or {@link + * OAuth2Credentials#getRequestMetadata(java.net.URI)} call fetches a token lazily from the handler. + * If an initial token is provided, it must include a non-null expiration time or {@link + * OAuth2CredentialsWithRefresh.Builder#build()} throws {@link IllegalArgumentException}. If + * instances will be Java-serialized, the provided refresh handler must also implement {@link + * java.io.Serializable}. + * *

Because {@link OAuth2CredentialsWithRefresh.OAuth2RefreshHandler} returns {@link AccessToken} * values without universe domain metadata, credentials default to {@link * Credentials#GOOGLE_DEFAULT_UNIVERSE}. Callers refreshing tokens for a custom universe domain * should configure it explicitly via {@link * OAuth2CredentialsWithRefresh.Builder#setUniverseDomain}. If lazy or delegated universe domain * resolution is needed, subclass this class and override {@link #getUniverseDomain()}. + * + *

{@code
+ * OAuth2CredentialsWithRefresh credentials =
+ *     OAuth2CredentialsWithRefresh.newBuilder()
+ *         .setRefreshHandler(
+ *             () ->
+ *                 new AccessToken(
+ *                     fetchTokenFromCustomProvider(),
+ *                     Date.from(Instant.now().plusSeconds(3600))))
+ *         .build();
+ * credentials.refreshIfExpired();
+ * AccessToken token = credentials.getAccessToken();
+ * }
*/ @NullMarked public class OAuth2CredentialsWithRefresh extends OAuth2Credentials { @@ -61,8 +84,20 @@ public class OAuth2CredentialsWithRefresh extends OAuth2Credentials { // Matches the computed serialVersionUID prior to adding universeDomain. private static final long serialVersionUID = -5362111100740719676L; - /** Interface for the refresh handler. */ + /** + * Callback interface used by {@link OAuth2CredentialsWithRefresh} to obtain fresh access tokens. + * + *

Returned tokens should include a non-null expiration time so {@link OAuth2Credentials} can + * schedule subsequent automatic refreshes. If a returned token has a {@code null} expiration + * time, it is treated as non-expiring and will not refresh automatically. + */ public interface OAuth2RefreshHandler { + /** + * Fetches and returns a fresh {@link AccessToken}. + * + * @return a fresh access token with an expiration time + * @throws IOException if fetching a new token fails + */ AccessToken refreshAccessToken() throws IOException; } @@ -157,8 +192,9 @@ public static class Builder extends OAuth2Credentials.Builder { private Builder() {} /** - * Sets the {@link AccessToken} to be consumed. It must contain an expiration time otherwise an - * {@link IllegalArgumentException} will be thrown. + * Sets the optional initial {@link AccessToken} to be consumed. If provided, it must contain a + * non-null expiration time or {@link #build()} throws {@link IllegalArgumentException}. When + * omitted, the first refresh fetches a token lazily from the configured refresh handler. */ @Override @CanIgnoreReturnValue @@ -168,8 +204,8 @@ public Builder setAccessToken(AccessToken token) { } /** - * Sets the {@link OAuth2CredentialsWithRefresh.OAuth2RefreshHandler} to be used for token - * refreshes. + * Sets the required {@link OAuth2CredentialsWithRefresh.OAuth2RefreshHandler} used for token + * refreshes. Must be non-null or {@link #build()} throws {@link NullPointerException}. */ @CanIgnoreReturnValue public Builder setRefreshHandler(OAuth2RefreshHandler handler) {