Skip to content
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,16 @@ public class AccessToken implements Serializable {
private final List<String> 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.
*
* <p>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;
Expand Down Expand Up @@ -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.
*
* <p>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) {
Expand Down Expand Up @@ -194,6 +207,13 @@ public Builder setScopes(@Nullable List<String> 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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
* <p>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 {

Expand Down Expand Up @@ -80,6 +89,15 @@ protected int getAuthPort() {
return this.authPort;
}

/**
* Fetches a fresh access token from the local Cloud Shell authorization proxy.
*
* <p>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());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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}.
*
* <p>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}.
*
* <p>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();
Expand Down Expand Up @@ -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.
*
* <p>If not set, you should call {@link #refresh()} to fetch and cache an access token.
* <p>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;
Expand All @@ -173,6 +182,24 @@ Duration getExpirationMargin() {
return this.expirationMargin;
}

/**
* Asynchronously provides request metadata containing an {@code Authorization} bearer token and
* any additional headers.
*
* <p>Cached tokens are evaluated in three states relative to the configured refresh and
* expiration margins:
*
* <ul>
* <li>Fresh (outside the refresh margin, or {@code null} expiration time): invokes {@code
* callback} immediately with cached metadata without refreshing.
* <li>Stale (within the refresh margin, outside the expiration margin): invokes {@code
* callback} immediately with the still-valid cached metadata while scheduling a single
* background refresh on {@code executor}.
* <li>Expired (no token cached, or within or past the expiration margin): runs a single-flight
* refresh on {@code executor} and delivers the refreshed metadata (or error) to {@code
* callback} when complete.
* </ul>
*/
@Override
public void getRequestMetadata(
final URI uri, Executor executor, final RequestMetadataCallback callback) {
Expand All @@ -184,17 +211,38 @@ 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.
*
* <p>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<String, List<String>> getRequestMetadata(@Nullable URI uri) throws IOException {
return unwrapDirectFuture(asyncFetch(MoreExecutors.directExecutor())).requestMetadata;
}

/**
* 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.
*
* <p>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 {
Expand All @@ -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.
* <p>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
Expand Down Expand Up @@ -364,13 +422,19 @@ private CacheState getState() {
/**
* Method to refresh the access token according to the specific type of credentials.
*
* <p>Throws IllegalStateException if not overridden since direct use of OAuth2Credentials is only
* for temporary or non-refreshing access tokens.
* <p>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.
*
* <p>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(
Expand All @@ -389,10 +453,13 @@ protected Map<String, List<String>> getAdditionalHeaders() {
}

/**
* Adds a listener that is notified when the Credentials data changes.
* Adds a listener that is notified when the credentials data changes.
*
* <p>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.
* <p>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
*/
Expand Down Expand Up @@ -429,11 +496,13 @@ public interface CredentialsChangedListener {
/**
* Notifies that the credentials have changed.
*
* <p>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.
* <p>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;
}
Expand Down Expand Up @@ -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.
*
* <p>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.
*
* <p>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;
}
Expand Down
Loading
Loading