diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/AgentIdentityUtils.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/AgentIdentityUtils.java index 86d403b57049..39b7cbc7a4d1 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/AgentIdentityUtils.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/AgentIdentityUtils.java @@ -39,6 +39,7 @@ import com.google.auth.oauth2.AgentIdentityCertificateValidationUtils.UnsupportedKeyAlgorithmException; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; +import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -46,11 +47,20 @@ import java.nio.file.AccessDeniedException; import java.nio.file.Files; import java.nio.file.Paths; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.KeyStoreException; import java.security.PrivateKey; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; +import java.util.ArrayList; import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.logging.Level; +import java.util.regex.Matcher; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @@ -149,14 +159,28 @@ interface TimeService { * *

This class intentionally stores in-memory certificate content rather than file paths to * prevent redundant filesystem reads and race conditions when binding tokens to requests. + * + *

When the private key was loaded and verified together with the certificate, it also holds a + * {@link KeyStore} with that key and the certificate chain. Callers that present the certificate + * over mTLS use it so the TLS client certificate is exactly the certificate a token was bound to, + * without reading the files again. */ static class CertInfo { private final X509Certificate certificate; private final String certContent; + private final @Nullable KeyStore keyStore; CertInfo(final X509Certificate certificate, final String certContent) { + this(certificate, certContent, null); + } + + CertInfo( + final X509Certificate certificate, + final String certContent, + final @Nullable KeyStore keyStore) { this.certificate = certificate; this.certContent = certContent; + this.keyStore = keyStore; } /** Returns the parsed {@link X509Certificate}. */ @@ -168,6 +192,14 @@ X509Certificate getCertificate() { String getCertContent() { return certContent; } + + /** + * Returns a {@link KeyStore} with the verified private key and certificate chain, or {@code + * null} if it isn't available. + */ + @Nullable KeyStore getKeyStore() { + return keyStore; + } } /** Holds the resolved filesystem paths for the certificate and private key. */ @@ -275,9 +307,9 @@ private static boolean hasWorkloadConfigOrGkeBundle( * *

To handle transient race conditions during certificate rotation on disk, this method employs * a retry mechanism with backoff when reading the configuration and certificate files. Note that - * callers such as {@link ComputeEngineCredentials#refreshAccessToken()} invoke this method via - * {@link #getBoundTokenPayload()} under {@link OAuth2Credentials}'s token refresh coalescing, - * which already serializes concurrent token refreshes to mitigate thundering herd contention. + * callers such as {@link ComputeEngineCredentials#refreshAccessToken()} invoke this method under + * {@link OAuth2Credentials}'s token refresh coalescing, which already serializes concurrent token + * refreshes to mitigate thundering herd contention. * * @return A {@link CertInfo} object containing the parsed {@link X509Certificate} and its raw PEM * chain content, or {@code null} if the agent identity features are disabled, opted out, or @@ -412,7 +444,8 @@ private static ResolvedCertAndKeyPaths resolveCertAndKeyPaths( keyPath, cert.getPublicKey().getAlgorithm()); if (AgentIdentityCertificateValidationUtils.verifyKeyPair(cert, privateKey)) { - CertInfo info = new CertInfo(cert, certContent); + CertInfo info = + new CertInfo(cert, certContent, buildKeyStoreOrNull(cert, certContent, privateKey)); if (AgentIdentityCacheUtils.tryUpdateCache( configMetaBefore, certMeta, keyMeta, true, info)) { return info; @@ -486,6 +519,71 @@ private static ResolvedCertAndKeyPaths resolveCertAndKeyPaths( lastException); } + /** + * Builds an in-memory {@link KeyStore} with the private key and the certificate chain, or returns + * {@code null} if it can't be built. + * + *

The key and {@code leaf} have already been verified to match, so a failure here must not + * fail token binding: without a {@link KeyStore}, IAM Credentials calls keep using the default + * endpoint and transport. + */ + private static @Nullable KeyStore buildKeyStoreOrNull( + final X509Certificate leaf, final String certContent, final PrivateKey privateKey) { + try { + return buildKeyStore(leaf, certContent, privateKey); + } catch (GeneralSecurityException | IOException | RuntimeException e) { + LoggingUtils.log( + LOGGER_PROVIDER, + Level.FINE, + Collections.emptyMap(), + "Could not build an mTLS key store from the Agent Identity certificate and key: " + + e.getMessage()); + return null; + } + } + + /** + * Builds an in-memory {@link KeyStore} with the private key, the verified {@code leaf} and any + * other certificates in {@code certContent}. Like {@code MtlsKeyStoreUtils}, it skips duplicate + * and unparsable additional certificates rather than failing, because the leaf alone is enough to + * present the client certificate. + */ + private static KeyStore buildKeyStore( + final X509Certificate leaf, final String certContent, final PrivateKey privateKey) + throws IOException, GeneralSecurityException { + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + List chain = new ArrayList<>(); + chain.add(leaf); + Matcher matcher = OAuth2Utils.PEM_CERT_PATTERN.matcher(certContent); + while (matcher.find()) { + Certificate certificate; + try { + certificate = + certificateFactory.generateCertificate( + new ByteArrayInputStream(matcher.group().getBytes(StandardCharsets.UTF_8))); + } catch (CertificateException | RuntimeException e) { + LoggingUtils.log( + LOGGER_PROVIDER, + Level.FINE, + Collections.emptyMap(), + "Skipping an unparsable certificate in the Agent Identity certificate chain."); + continue; + } + if (certificate != null && !chain.contains(certificate)) { + chain.add(certificate); + } + } + KeyStore keyStore; + try { + keyStore = KeyStore.getInstance("JKS"); + } catch (KeyStoreException e) { + keyStore = KeyStore.getInstance("PKCS12"); + } + keyStore.load(null); + keyStore.setKeyEntry("alias", privateKey, new char[] {}, chain.toArray(new Certificate[0])); + return keyStore; + } + /** * Checks if runtime token binding is enabled. * diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/BoundAccessToken.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/BoundAccessToken.java new file mode 100644 index 000000000000..e22ef6baccf2 --- /dev/null +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/BoundAccessToken.java @@ -0,0 +1,76 @@ +/* + * Copyright 2026, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.google.auth.oauth2; + +import com.google.auth.oauth2.AgentIdentityUtils.CertInfo; +import java.io.InvalidObjectException; +import java.io.ObjectInputStream; +import java.io.ObjectStreamException; +import java.util.Date; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; + +/** + * An {@link AccessToken} that is bound to an agent identity certificate. + * + *

Keeps the {@link CertInfo} that the token was bound to when it was minted, so callers that + * send the token over mTLS present exactly that certificate, even if the certificate on disk has + * rotated since then. + * + *

The certificate isn't serialized. {@link #writeReplace()} writes a plain {@link AccessToken} + * that is already expired, so serialized credentials stay readable by versions of the library + * without this class, and deserialized credentials mint a new token (bound to the certificate + * available where they run) on first use instead of sending a bound token without its certificate. + */ +@NullMarked +final class BoundAccessToken extends AccessToken { + private static final long serialVersionUID = 1L; + + private final transient CertInfo certInfo; + + BoundAccessToken(String tokenValue, @Nullable Date expirationTime, CertInfo certInfo) { + super(tokenValue, expirationTime); + this.certInfo = certInfo; + } + + /** Returns the certificate this token is bound to. */ + CertInfo getCertInfo() { + return certInfo; + } + + private Object writeReplace() throws ObjectStreamException { + return new AccessToken(getTokenValue(), new Date(0)); + } + + private void readObject(ObjectInputStream in) throws InvalidObjectException { + throw new InvalidObjectException("BoundAccessToken cannot be deserialized directly"); + } +} diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ComputeEngineCredentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ComputeEngineCredentials.java index c7595556d009..40c15fc1fa11 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ComputeEngineCredentials.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ComputeEngineCredentials.java @@ -433,7 +433,10 @@ private String getUniverseDomainFromMetadata() throws IOException { @Override public AccessToken refreshAccessToken() throws IOException { String tokenUrl = createTokenUrlWithScopes(); - String boundTokenPayload = AgentIdentityUtils.getBoundTokenPayload(); + // Keep the CertInfo (not only its PEM payload) so the returned token records the certificate + // it is bound to. Callers that send the token over mTLS present exactly that certificate. + AgentIdentityUtils.CertInfo boundCertInfo = AgentIdentityUtils.getAgentIdentityCertInfo(); + String boundTokenPayload = boundCertInfo != null ? boundCertInfo.getCertContent() : null; HttpRequest request = boundTokenPayload != null ? buildBoundTokenRequest(tokenUrl, boundTokenPayload) @@ -481,6 +484,9 @@ public AccessToken refreshAccessToken() throws IOException { OAuth2Utils.validateInt32(responseData, "expires_in", PARSE_ERROR_PREFIX); long expiresAtMilliseconds = clock.currentTimeMillis() + expiresInSeconds * 1000; + if (boundCertInfo != null) { + return new BoundAccessToken(accessToken, new Date(expiresAtMilliseconds), boundCertInfo); + } return new AccessToken(accessToken, new Date(expiresAtMilliseconds)); } @@ -880,18 +886,28 @@ public String getAccount() { public byte[] sign(byte[] toSign) { try { String account = getAccount(); + String universeDomain; + try { + universeDomain = this.getUniverseDomain(); + } catch (IOException ex) { + throw new SigningException("Failed to sign: Error obtaining universe domain", ex); + } + IamUtils.IamCallTarget target; + try { + target = IamUtils.resolveCallTarget(this, transportFactory, universeDomain); + } catch (IOException ex) { + throw new SigningException("Failed to sign: Error refreshing credentials", ex); + } return IamUtils.sign( - String.format(IamUtils.IAM_SIGN_BLOB_ENDPOINT_FORMAT, this.getUniverseDomain(), account), - this, - transportFactory.create(), + String.format(IamUtils.IAM_SIGN_BLOB_ENDPOINT_FORMAT, target.endpointDomain, account), + target.credentials, + target.transportFactory.create(), toSign, Collections.emptyMap()); } catch (SigningException ex) { throw ex; } catch (RuntimeException ex) { throw new SigningException("Signing failed", ex); - } catch (IOException ex) { - throw new SigningException("Failed to sign: Error obtaining universe domain", ex); } } diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java index f47505069a30..342567a030a7 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java @@ -48,16 +48,29 @@ import com.google.auth.Credentials; import com.google.auth.ServiceAccountSigner; import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.http.HttpTransportFactory; +import com.google.auth.mtls.MtlsHttpTransportFactory; import com.google.auth.oauth2.MetricsUtils.RequestType; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.io.BaseEncoding; import java.io.IOException; import java.io.InputStream; +import java.io.InvalidObjectException; +import java.io.NotSerializableException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.security.KeyStore; import java.util.Arrays; +import java.util.Collections; import java.util.HashSet; import java.util.Map; +import java.util.Objects; import java.util.Set; +import java.util.function.Function; +import java.util.logging.Level; import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * This internal class provides shared utilities for interacting with the IAM API for common @@ -82,6 +95,209 @@ class IamUtils { static final Set IAM_RETRYABLE_STATUS_CODES = new HashSet<>(Arrays.asList(500, 502, 503, 504)); + // Prefix that turns a universe domain into the mTLS domain in the IAM_*_ENDPOINT_FORMAT URLs, + // for example iamcredentials.mtls.googleapis.com. + private static final String MTLS_DOMAIN_PREFIX = "mtls."; + + // Creates the mTLS transport factory for a bound token's key store. Replaced only in tests. + private static volatile Function mtlsTransportFactoryProvider = + MtlsHttpTransportFactory::new; + + /** + * The credentials, transport and endpoint domain to use for one IAM Credentials call. + * + *

{@link #endpointDomain} is the value to substitute into the {@code IAM_*_ENDPOINT_FORMAT} + * templates: the universe domain, or {@code mtls.} for the mTLS endpoint. + */ + static final class IamCallTarget { + final Credentials credentials; + final HttpTransportFactory transportFactory; + final String endpointDomain; + private final boolean usesMtls; + + IamCallTarget( + Credentials credentials, + HttpTransportFactory transportFactory, + String endpointDomain, + boolean usesMtls) { + this.credentials = credentials; + this.transportFactory = transportFactory; + this.endpointDomain = endpointDomain; + this.usesMtls = usesMtls; + } + + boolean usesMtls() { + return usesMtls; + } + } + + /** + * A {@link GoogleCredentials} pinned to a single already-minted {@link BoundAccessToken}, so the + * request header always uses the token bound to the presented mTLS certificate even if the source + * credential refreshes concurrently. + */ + private static final class PinnedTokenCredentials extends GoogleCredentials { + private static final long serialVersionUID = 1L; + private final transient BoundAccessToken token; + + PinnedTokenCredentials( + BoundAccessToken token, @Nullable String quotaProjectId, String universeDomain) { + super( + GoogleCredentials.newBuilder() + .setQuotaProjectId(quotaProjectId) + .setUniverseDomain(universeDomain)); + this.token = token; + } + + @Override + public AccessToken refreshAccessToken() { + return token; + } + + private void writeObject(ObjectOutputStream out) throws IOException { + throw new NotSerializableException("PinnedTokenCredentials cannot be serialized"); + } + + private void readObject(ObjectInputStream in) throws IOException { + throw new InvalidObjectException("PinnedTokenCredentials cannot be deserialized"); + } + } + + /** + * Returns where and how to send an IAM Credentials call that is authenticated with {@code + * authCredentials}. + * + *

When {@code authCredentials} is a {@link ComputeEngineCredentials} whose current access + * token is bound to an agent identity certificate, a bound token is accepted only over mTLS, + * presenting that certificate, to the mTLS endpoint. In that case the call goes to {@code + * iamcredentials.mtls.} over an mTLS transport that presents the certificate the + * token was bound to, authenticated with that same token. + * + *

Otherwise, and whenever the caller customized the transport or the universe domain isn't the + * default one, the call goes to {@code iamcredentials.} with {@code + * authCredentials} and {@code transportFactory}, as before. + */ + static IamCallTarget resolveCallTarget( + Credentials authCredentials, HttpTransportFactory transportFactory, String universeDomain) + throws IOException { + if (!(transportFactory instanceof OAuth2Utils.DefaultHttpTransportFactory)) { + return new IamCallTarget( + authCredentials, transportFactory, universeDomain, /* usesMtls= */ false); + } + return resolveBoundTokenCallTarget( + authCredentials, transportFactory, universeDomain, mtlsTransportFactoryProvider); + } + + /** + * Refreshes {@code authCredentials} after a 401 response on a bound-token mTLS call and resolves + * a fresh {@link IamCallTarget} for a single retry. + * + *

Skips forcing a refresh when another thread has already refreshed {@code authCredentials} to + * a different token or certificate. Returns {@code null} if the refresh fails or produces the + * same bound token value and certificate as {@code previousTarget}, so the caller surfaces the + * original 401 instead of resending an identical rejected request. + */ + static @Nullable IamCallTarget refreshAndResolveRetryTarget( + Credentials authCredentials, + HttpTransportFactory transportFactory, + String universeDomain, + IamCallTarget previousTarget) { + if (!previousTarget.usesMtls() + || !(previousTarget.credentials instanceof PinnedTokenCredentials) + || !(authCredentials instanceof ComputeEngineCredentials)) { + return null; + } + BoundAccessToken previousToken = ((PinnedTokenCredentials) previousTarget.credentials).token; + ComputeEngineCredentials computeEngineCredentials = (ComputeEngineCredentials) authCredentials; + try { + AccessToken currentToken = computeEngineCredentials.getAccessToken(); + if (currentToken == null || isSameBoundToken(previousToken, currentToken)) { + computeEngineCredentials.refresh(); + } + IamCallTarget retryTarget = + resolveCallTarget(authCredentials, transportFactory, universeDomain); + if (retryTarget.credentials instanceof PinnedTokenCredentials + && isSameBoundToken( + previousToken, ((PinnedTokenCredentials) retryTarget.credentials).token)) { + return null; + } + return retryTarget; + } catch (IOException e) { + LoggingUtils.log( + LOGGER_PROVIDER, + Level.WARNING, + Collections.emptyMap(), + "Unable to refresh credentials after 401 response: " + e.getMessage()); + return null; + } + } + + private static boolean isSameBoundToken( + BoundAccessToken previousToken, @Nullable AccessToken candidateToken) { + if (!(candidateToken instanceof BoundAccessToken)) { + return false; + } + BoundAccessToken candidate = (BoundAccessToken) candidateToken; + return Objects.equals(previousToken.getTokenValue(), candidate.getTokenValue()) + && !OAuth2Utils.hasCertificateChanged( + previousToken.getCertInfo().getKeyStore(), candidate.getCertInfo().getKeyStore()); + } + + @VisibleForTesting + static void setMtlsTransportFactoryProvider(Function provider) { + mtlsTransportFactoryProvider = provider; + } + + @VisibleForTesting + static void resetForTest() { + mtlsTransportFactoryProvider = MtlsHttpTransportFactory::new; + } + + /** + * Like {@link #resolveCallTarget}, without the transport check, and with the mTLS transport + * factory supplied by the caller. + */ + @VisibleForTesting + static IamCallTarget resolveBoundTokenCallTarget( + Credentials authCredentials, + HttpTransportFactory transportFactory, + String universeDomain, + Function mtlsTransportFactory) + throws IOException { + IamCallTarget defaultTarget = + new IamCallTarget(authCredentials, transportFactory, universeDomain, /* usesMtls= */ false); + if (!(authCredentials instanceof ComputeEngineCredentials) + || !Credentials.GOOGLE_DEFAULT_UNIVERSE.equals(universeDomain)) { + return defaultTarget; + } + ComputeEngineCredentials computeEngineCredentials = (ComputeEngineCredentials) authCredentials; + computeEngineCredentials.refreshIfExpired(); + // The token object carries the certificate it was bound to, so the token and the certificate + // presented below always match, even if another thread refreshes the credentials meanwhile. + final AccessToken token = computeEngineCredentials.getAccessToken(); + if (!(token instanceof BoundAccessToken)) { + return defaultTarget; + } + BoundAccessToken boundToken = (BoundAccessToken) token; + KeyStore keyStore = boundToken.getCertInfo().getKeyStore(); + if (keyStore == null) { + return defaultTarget; + } + // Authenticate with exactly this token: the source credentials could otherwise refresh and + // attach a token bound to a different certificate. Calling refresh() populates OAuthValue in + // memory via getAdditionalHeaders() after quotaProjectId is initialized, so x-goog-user-project + // is preserved while getAccessToken() and getRequestMetadata() start ready without extra I/O. + PinnedTokenCredentials pinnedTokenCredentials = + new PinnedTokenCredentials( + boundToken, computeEngineCredentials.getQuotaProjectId(), universeDomain); + pinnedTokenCredentials.refresh(); + return new IamCallTarget( + pinnedTokenCredentials, + mtlsTransportFactory.apply(keyStore), + MTLS_DOMAIN_PREFIX + universeDomain, + /* usesMtls= */ true); + } + /** * Returns a signature for the provided bytes. * @@ -224,6 +440,57 @@ private static String getStatusMessageOrDefault(HttpResponse response) { : statusMessage; } + /** + * Resolves the IAM call target (routing bound agent-identity tokens over mTLS) and requests an ID + * token, performing a single source-credential refresh and retry if IAM rejects a bound token + * with HTTP 401. + */ + static IdToken getIdToken( + String serviceAccountEmail, + Credentials authCredentials, + HttpTransportFactory transportFactory, + String targetAudience, + boolean includeEmail, + Map additionalFields, + CredentialTypeForMetrics credentialTypeForMetrics, + String universeDomain) + throws IOException { + IamCallTarget target = resolveCallTarget(authCredentials, transportFactory, universeDomain); + HttpResponse response = + executeIdTokenRequest( + String.format(IAM_ID_TOKEN_ENDPOINT_FORMAT, target.endpointDomain, serviceAccountEmail), + target.credentials, + target.transportFactory.create(), + targetAudience, + includeEmail, + additionalFields, + credentialTypeForMetrics, + /* disableAdapterRetry= */ target.usesMtls()); + if (target.usesMtls() && response.getStatusCode() == HttpStatusCodes.STATUS_CODE_UNAUTHORIZED) { + IamCallTarget retryTarget = + refreshAndResolveRetryTarget(authCredentials, transportFactory, universeDomain, target); + if (retryTarget != null) { + try { + response.ignore(); + } catch (IOException ignored) { + // Best-effort cleanup of the rejected 401 response before retrying. + } + response = + executeIdTokenRequest( + String.format( + IAM_ID_TOKEN_ENDPOINT_FORMAT, retryTarget.endpointDomain, serviceAccountEmail), + retryTarget.credentials, + retryTarget.transportFactory.create(), + targetAudience, + includeEmail, + additionalFields, + credentialTypeForMetrics, + /* disableAdapterRetry= */ true); + } + } + return parseIdTokenResponse(response); + } + /** * Returns an IdToken issued to the serviceAccount with a specified targetAudience * @@ -248,6 +515,29 @@ static IdToken getIdToken( Map additionalFields, CredentialTypeForMetrics credentialTypeForMetrics) throws IOException { + HttpResponse response = + executeIdTokenRequest( + idTokenUrl, + credentials, + transport, + targetAudience, + includeEmail, + additionalFields, + credentialTypeForMetrics, + /* disableAdapterRetry= */ credentials instanceof PinnedTokenCredentials); + return parseIdTokenResponse(response); + } + + private static HttpResponse executeIdTokenRequest( + String idTokenUrl, + Credentials credentials, + HttpTransport transport, + String targetAudience, + boolean includeEmail, + Map additionalFields, + CredentialTypeForMetrics credentialTypeForMetrics, + boolean disableAdapterRetry) + throws IOException { GenericUrl genericUrl = new GenericUrl(idTokenUrl); GenericData idTokenRequest = new GenericData(); @@ -261,6 +551,12 @@ static IdToken getIdToken( HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(credentials); HttpRequest request = transport.createRequestFactory(adapter).buildPostRequest(genericUrl, idTokenContent); + if (disableAdapterRetry) { + // PinnedTokenCredentials always returns the same token on refresh(), so disable + // HttpCredentialsAdapter's 401 retry to avoid resending a rejected token 10 times; the + // caller performs at most one outer refresh-and-retry pairing the new token and certificate. + request.setUnsuccessfulResponseHandler(null); + } // Disable automatic logging by google-http-java-client to prevent leakage of sensitive tokens. // Client Library Debug Logging via LoggingUtils is used instead. @@ -279,6 +575,10 @@ static IdToken getIdToken( HttpResponse response = request.execute(); LoggingUtils.logResponse(response, LOGGER_PROVIDER, "Received response for ID token request"); + return response; + } + + private static IdToken parseIdTokenResponse(HttpResponse response) throws IOException { int statusCode = response.getStatusCode(); if (statusCode >= 400 && statusCode < HttpStatusCodes.STATUS_CODE_SERVER_ERROR) { String errorMessage = parseErrorMessage(response); diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ImpersonatedCredentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ImpersonatedCredentials.java index cf3dedffa9d6..79d7bda717b8 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ImpersonatedCredentials.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ImpersonatedCredentials.java @@ -46,6 +46,7 @@ import com.google.api.client.util.GenericData; import com.google.api.core.ObsoleteApi; import com.google.auth.CredentialTypeForMetrics; +import com.google.auth.Credentials; import com.google.auth.ServiceAccountSigner; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.http.HttpTransportFactory; @@ -368,17 +369,42 @@ public void setTransportFactory(HttpTransportFactory httpTransportFactory) { */ @Override public byte[] sign(byte[] toSign) { - try { - return IamUtils.sign( - getIamEndpoint(IamUtils.IAM_SIGN_BLOB_ENDPOINT_FORMAT, SIGN_BLOB_ACTION), - sourceCredentials, - transportFactory.create(), - toSign, - ImmutableMap.of("delegates", this.delegates)); - } catch (IOException ex) { - // Throwing an IOException would be a breaking change, so wrap it here. - throw new SigningException("Failed to sign: Error obtaining IAM endpoint", ex); + String signBlobUrl; + Credentials authCredentials = sourceCredentials; + HttpTransportFactory effectiveTransportFactory = transportFactory; + if (this.iamEndpointOverride != null) { + try { + signBlobUrl = getIamEndpoint(IamUtils.IAM_SIGN_BLOB_ENDPOINT_FORMAT, SIGN_BLOB_ACTION); + } catch (IOException ex) { + // Throwing an IOException would be a breaking change, so wrap it here. + throw new SigningException("Failed to sign: Error obtaining IAM endpoint", ex); + } + } else { + String universeDomain; + try { + universeDomain = getUniverseDomain(); + } catch (IOException ex) { + // Throwing an IOException would be a breaking change, so wrap it here. + throw new SigningException("Failed to sign: Error obtaining IAM endpoint", ex); + } + IamUtils.IamCallTarget target; + try { + target = IamUtils.resolveCallTarget(sourceCredentials, transportFactory, universeDomain); + } catch (IOException ex) { + throw new SigningException("Failed to sign: Error refreshing source credentials", ex); + } + signBlobUrl = + String.format( + IamUtils.IAM_SIGN_BLOB_ENDPOINT_FORMAT, target.endpointDomain, getAccount()); + authCredentials = target.credentials; + effectiveTransportFactory = target.transportFactory; } + return IamUtils.sign( + signBlobUrl, + authCredentials, + effectiveTransportFactory.create(), + toSign, + ImmutableMap.of("delegates", this.delegates)); } private String getIamEndpoint(String endpointFormat, String action) throws IOException { @@ -738,9 +764,15 @@ AccessToken refreshAccessToken( this.transportFactory = cycleTransportFactory; } } - HttpTransportFactory effectiveTransportFactory = + HttpTransportFactory baseTransportFactory = firstNonNull(cycleTransportFactory, this.transportFactory); + HttpTransportFactory effectiveTransportFactory = baseTransportFactory; HttpCredentialsAdapter adapter; + // Set only when the IAM endpoint domain differs from getUniverseDomain() (mTLS) or after a + // bound-token retry re-resolves the target. + String iamEndpointDomain = null; + IamUtils.IamCallTarget boundTokenTarget = null; + String boundTokenUniverseDomain = null; AccessToken intermediateAccessTokenForCache = null; boolean usedCachedStsToken = false; if (this.sourceCredentials instanceof ExternalAccountCredentials) { @@ -805,63 +837,114 @@ public AccessToken refreshAccessToken() { } } adapter = new HttpCredentialsAdapter(sourceCredentials); + if (this.iamEndpointOverride == null) { + // A certificate-bound agent identity token must be sent over mTLS to the mTLS endpoint. + boundTokenUniverseDomain = getUniverseDomain(); + try { + boundTokenTarget = + IamUtils.resolveCallTarget( + this.sourceCredentials, baseTransportFactory, boundTokenUniverseDomain); + } catch (IOException e) { + throw new IOException("Unable to refresh sourceCredentials", e); + } + if (boundTokenTarget.usesMtls()) { + adapter = new HttpCredentialsAdapter(boundTokenTarget.credentials); + effectiveTransportFactory = boundTokenTarget.transportFactory; + iamEndpointDomain = boundTokenTarget.endpointDomain; + } + } } - HttpTransport httpTransport = effectiveTransportFactory.create(); JsonObjectParser parser = new JsonObjectParser(OAuth2Utils.JSON_FACTORY); - - HttpRequestFactory requestFactory = httpTransport.createRequestFactory(); - - String endpointUrl = - this.iamEndpointOverride != null - ? this.iamEndpointOverride - : String.format( - IamUtils.IAM_ACCESS_TOKEN_ENDPOINT_FORMAT, - getUniverseDomain(), - this.targetPrincipal); - - GenericUrl url = new GenericUrl(endpointUrl); - Map body = ImmutableMap.of( "delegates", this.delegates, "scope", this.scopes, "lifetime", this.lifetime + "s"); - HttpContent requestContent = new JsonHttpContent(parser.getJsonFactory(), body); - HttpRequest request = requestFactory.buildPostRequest(url, requestContent); - // Disable automatic logging by google-http-java-client to prevent leakage of sensitive tokens. - // Client Library Debug Logging via LoggingUtils is used instead. - request.setLoggingEnabled(false); - adapter.initialize(request); - if (cycleTransportFactory != null - && this.sourceCredentials instanceof ExternalAccountCredentials) { - // Disable HttpCredentialsAdapter's default 401 retry so 401 responses propagate to the - // caller (e.g. IdentityPoolCredentials) to re-snapshot the certificate and retry the full - // cycle with a newly pinned transport. - request.setUnsuccessfulResponseHandler(null); - } - request.setParser(parser); - MetricsUtils.setMetricsHeader( - request, - MetricsUtils.getGoogleCredentialsMetricsHeader( - RequestType.ACCESS_TOKEN_REQUEST, getMetricsCredentialType())); - HttpResponse response = null; - try { - LoggingUtils.logRequest(request, LOGGER_PROVIDER, "Sending request to refresh access token"); - response = request.execute(); - } catch (IOException e) { - if (cycleTransportFactory != null) { - synchronized (this) { - if (usedCachedStsToken && this.cachedStsAccessToken == intermediateAccessTokenForCache) { - this.cachedStsAccessToken = null; - this.cachedStsKeyStore = null; + IOException firstAttemptException = null; + boolean disableAdapterRetry = + (cycleTransportFactory != null + && this.sourceCredentials instanceof ExternalAccountCredentials) + || iamEndpointDomain != null; + for (int attempt = 0; ; attempt++) { + HttpTransport httpTransport = effectiveTransportFactory.create(); + HttpRequestFactory requestFactory = httpTransport.createRequestFactory(); + + String endpointUrl = + this.iamEndpointOverride != null + ? this.iamEndpointOverride + : String.format( + IamUtils.IAM_ACCESS_TOKEN_ENDPOINT_FORMAT, + iamEndpointDomain != null ? iamEndpointDomain : getUniverseDomain(), + this.targetPrincipal); + + GenericUrl url = new GenericUrl(endpointUrl); + + HttpContent requestContent = new JsonHttpContent(parser.getJsonFactory(), body); + HttpRequest request = requestFactory.buildPostRequest(url, requestContent); + // Disable automatic logging by google-http-java-client to prevent leakage of sensitive + // tokens. Client Library Debug Logging via LoggingUtils is used instead. + request.setLoggingEnabled(false); + adapter.initialize(request); + if (disableAdapterRetry) { + // Disable HttpCredentialsAdapter's default 401 retry when the request uses a pinned + // single-token credential (whose refresh() is a no-op): for ExternalAccountCredentials so + // 401 responses propagate to IdentityPoolCredentials to re-snapshot the certificate and + // retry the full cycle, and for bound agent-identity tokens so an outer single refresh + // re-pairs the new token with its certificate instead of resending the rejected token + // 10 times. + request.setUnsuccessfulResponseHandler(null); + } + request.setParser(parser); + MetricsUtils.setMetricsHeader( + request, + MetricsUtils.getGoogleCredentialsMetricsHeader( + RequestType.ACCESS_TOKEN_REQUEST, getMetricsCredentialType())); + + try { + LoggingUtils.logRequest( + request, LOGGER_PROVIDER, "Sending request to refresh access token"); + response = request.execute(); + break; + } catch (IOException e) { + if (attempt == 0 + && boundTokenTarget != null + && boundTokenTarget.usesMtls() + && boundTokenUniverseDomain != null + && OAuth2Utils.isUnauthorizedException(e)) { + IamUtils.IamCallTarget retryTarget = + IamUtils.refreshAndResolveRetryTarget( + this.sourceCredentials, + baseTransportFactory, + boundTokenUniverseDomain, + boundTokenTarget); + if (retryTarget != null) { + firstAttemptException = e; + adapter = new HttpCredentialsAdapter(retryTarget.credentials); + effectiveTransportFactory = retryTarget.transportFactory; + iamEndpointDomain = retryTarget.endpointDomain; + disableAdapterRetry = true; + continue; } } - if (usedCachedStsToken && OAuth2Utils.isUnauthorizedException(e)) { - throw new CachedStsTokenRejectedException("Error requesting access token", e); + if (cycleTransportFactory != null) { + synchronized (this) { + if (usedCachedStsToken + && this.cachedStsAccessToken == intermediateAccessTokenForCache) { + this.cachedStsAccessToken = null; + this.cachedStsKeyStore = null; + } + } + if (usedCachedStsToken && OAuth2Utils.isUnauthorizedException(e)) { + throw new CachedStsTokenRejectedException("Error requesting access token", e); + } } + IOException error = new IOException("Error requesting access token", e); + if (firstAttemptException != null) { + error.addSuppressed(firstAttemptException); + } + throw error; } - throw new IOException("Error requesting access token", e); } if (cycleTransportFactory != null @@ -931,14 +1014,25 @@ public IdToken idTokenWithAudience( String targetAudience, @Nullable List options) throws IOException { boolean includeEmail = options != null && options.contains(IdTokenProvider.Option.INCLUDE_EMAIL); + if (this.iamEndpointOverride != null) { + return IamUtils.getIdToken( + getIamEndpoint(IamUtils.IAM_ID_TOKEN_ENDPOINT_FORMAT, GENERATE_ID_TOKEN_ACTION), + sourceCredentials, + transportFactory.create(), + targetAudience, + includeEmail, + ImmutableMap.of("delegates", this.delegates), + getMetricsCredentialType()); + } return IamUtils.getIdToken( - getIamEndpoint(IamUtils.IAM_ID_TOKEN_ENDPOINT_FORMAT, GENERATE_ID_TOKEN_ACTION), + getAccount(), sourceCredentials, - transportFactory.create(), + transportFactory, targetAudience, includeEmail, ImmutableMap.of("delegates", this.delegates), - getMetricsCredentialType()); + getMetricsCredentialType(), + getUniverseDomain()); } @Override diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java index bc589082af2b..e1a9a01ac14c 100644 --- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java @@ -71,10 +71,15 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; +import java.security.KeyStore; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -1359,6 +1364,134 @@ void refreshAccessToken_withValidCertAndKey_requestsBoundToken() throws IOExcept assertEquals(expectedCert, ((String) bodyJson.get("certificate_chain")).trim()); } + @Test + void refreshAccessToken_withValidCertAndKey_returnsTokenWithBoundCertificateAndKey() + throws Exception { + setupCertAndKeyConfig(); + envProvider.setEnv(AgentIdentityUtils.GOOGLE_API_ENABLE_RUNTIME_BOUND_TOKEN, "true"); + MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); + transportFactory.transport.setServiceAccountEmail(SA_CLIENT_EMAIL); + ComputeEngineCredentials credentials = + ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); + + AccessToken token = credentials.refreshAccessToken(); + + assertTrue(token instanceof BoundAccessToken); + AgentIdentityUtils.CertInfo certInfo = ((BoundAccessToken) token).getCertInfo(); + X509Certificate expectedLeaf; + try (InputStream in = Files.newInputStream(tempDir.resolve("certificates.pem"))) { + expectedLeaf = + (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(in); + } + assertEquals(expectedLeaf, certInfo.getCertificate()); + KeyStore keyStore = certInfo.getKeyStore(); + assertNotNull(keyStore); + String alias = keyStore.aliases().nextElement(); + assertTrue(keyStore.isKeyEntry(alias)); + // MtlsHttpTransportFactory unlocks the key with an empty password. + assertNotNull(keyStore.getKey(alias, new char[0])); + assertEquals(expectedLeaf, keyStore.getCertificateChain(alias)[0]); + } + + @Test + void refreshAccessToken_extraCertificatesInChain_retainsValidAndSkipsUnparsableAndDuplicates() + throws Exception { + setupCertAndKeyConfig(); + envProvider.setEnv(AgentIdentityUtils.GOOGLE_API_ENABLE_RUNTIME_BOUND_TOKEN, "true"); + Path certPath = tempDir.resolve("certificates.pem"); + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + X509Certificate expectedLeaf; + try (InputStream in = Files.newInputStream(certPath)) { + expectedLeaf = (X509Certificate) certificateFactory.generateCertificate(in); + } + Path extraCertPath = + Paths.get( + ComputeEngineCredentialsTest.class + .getResource("/x509_intermediate_certificate.pem") + .toURI()); + X509Certificate expectedExtra; + try (InputStream in = Files.newInputStream(extraCertPath)) { + expectedExtra = (X509Certificate) certificateFactory.generateCertificate(in); + } + String leafPem = new String(Files.readAllBytes(certPath), StandardCharsets.UTF_8).trim(); + String extraPem = new String(Files.readAllBytes(extraCertPath), StandardCharsets.UTF_8).trim(); + String chainPem = + leafPem + + "\n" + + leafPem + + "\n-----BEGIN CERTIFICATE----------END CERTIFICATE-----\n" + + extraPem + + "\n-----BEGIN CERTIFICATE-----\nbm90IGEgY2VydGlmaWNhdGU=\n-----END CERTIFICATE-----\n"; + Files.write(certPath, chainPem.getBytes(StandardCharsets.UTF_8)); + MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); + transportFactory.transport.setServiceAccountEmail(SA_CLIENT_EMAIL); + ComputeEngineCredentials credentials = + ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); + + AccessToken token = credentials.refreshAccessToken(); + + assertTrue(token instanceof BoundAccessToken); + KeyStore keyStore = ((BoundAccessToken) token).getCertInfo().getKeyStore(); + assertNotNull(keyStore); + String alias = keyStore.aliases().nextElement(); + Certificate[] chain = keyStore.getCertificateChain(alias); + assertEquals(2, chain.length); + assertEquals(expectedLeaf, chain[0]); + assertEquals(expectedExtra, chain[1]); + } + + @Test + void refreshAccessToken_boundTokensOptedOut_returnsPlainAccessToken() throws IOException { + setupCertAndKeyConfig(); + envProvider.setEnv(AgentIdentityUtils.GOOGLE_API_ENABLE_RUNTIME_BOUND_TOKEN, "false"); + MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); + ComputeEngineCredentials credentials = + ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); + + AccessToken token = credentials.refreshAccessToken(); + + assertFalse(token instanceof BoundAccessToken); + assertEquals("GET", transportFactory.transport.getRequestMethod()); + } + + @Test + void boundAccessToken_serializesAsPlainAccessToken() throws Exception { + setupCertAndKeyConfig(); + envProvider.setEnv(AgentIdentityUtils.GOOGLE_API_ENABLE_RUNTIME_BOUND_TOKEN, "true"); + MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); + transportFactory.transport.setServiceAccountEmail(SA_CLIENT_EMAIL); + ComputeEngineCredentials credentials = + ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); + AccessToken token = credentials.refreshAccessToken(); + assertTrue(token instanceof BoundAccessToken); + + AccessToken deserialized = serializeAndDeserialize(token); + + assertEquals(AccessToken.class, deserialized.getClass()); + assertEquals(token.getTokenValue(), deserialized.getTokenValue()); + // Serialized as expired, so deserialized credentials mint a new bound token on first use. + assertEquals(new Date(0), deserialized.getExpirationTime()); + } + + @Test + void deserializedCredentialsWithBoundToken_mintNewBoundTokenOnFirstUse() throws Exception { + setupCertAndKeyConfig(); + envProvider.setEnv(AgentIdentityUtils.GOOGLE_API_ENABLE_RUNTIME_BOUND_TOKEN, "true"); + MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); + transportFactory.transport.setServiceAccountEmail(SA_CLIENT_EMAIL); + ComputeEngineCredentials credentials = + ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); + credentials.refresh(); + assertTrue(credentials.getAccessToken() instanceof BoundAccessToken); + + ComputeEngineCredentials deserialized = serializeAndDeserialize(credentials); + assertFalse(deserialized.getAccessToken() instanceof BoundAccessToken); + + deserialized.getRequestMetadata(CALL_URI); + + assertTrue(deserialized.getAccessToken() instanceof BoundAccessToken); + } + @Test void idTokenWithAudience_withValidCertAndKey_requestsBoundToken() throws IOException { setupCertAndKeyConfig(); diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamMtlsRoutingTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamMtlsRoutingTest.java new file mode 100644 index 000000000000..8eb2277a5bf8 --- /dev/null +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamMtlsRoutingTest.java @@ -0,0 +1,619 @@ +/* + * Copyright 2026, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.google.auth.oauth2; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.google.api.client.http.HttpResponseException; +import com.google.api.client.http.HttpStatusCodes; +import com.google.api.client.http.HttpTransport; +import com.google.api.client.http.LowLevelHttpRequest; +import com.google.api.client.http.LowLevelHttpResponse; +import com.google.api.client.json.GenericJson; +import com.google.api.client.json.Json; +import com.google.api.client.testing.http.MockHttpTransport; +import com.google.api.client.testing.http.MockLowLevelHttpRequest; +import com.google.api.client.testing.http.MockLowLevelHttpResponse; +import com.google.auth.Credentials; +import com.google.auth.ServiceAccountSigner.SigningException; +import com.google.auth.http.HttpTransportFactory; +import com.google.auth.mtls.MtlsHttpTransportFactory; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.KeyStore; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; +import java.util.Date; +import java.util.Deque; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * Tests that IAM Credentials calls authenticated with a certificate-bound agent identity token go + * to the mTLS endpoint, over a transport built from the certificate the token was bound to, with + * that token. + */ +class IamMtlsRoutingTest { + + private static final String TARGET = "target@project.iam.gserviceaccount.com"; + private static final String SOURCE_ACCOUNT = "agent@project.iam.gserviceaccount.com"; + private static final String BOUND_TOKEN = "bound-token"; + private static final String MTLS_BASE = + "https://iamcredentials.mtls.googleapis.com/v1/projects/-/serviceAccounts/"; + + @TempDir Path tempDir; + + private final List requestUrls = new ArrayList<>(); + private final List authorizationHeaders = new ArrayList<>(); + private final List quotaProjectHeaders = new ArrayList<>(); + // KeyStore of the transport that actually executed each IAM request (null for default transport). + private final List requestKeyStores = new ArrayList<>(); + private final Deque queuedIamResponses = new ArrayDeque<>(); + private final AtomicInteger metadataTokenRequests = new AtomicInteger(); + private String nextMetadataAccessToken = "refreshed-bound-token"; + private int metadataTokenStatusCode = HttpStatusCodes.STATUS_CODE_OK; + private AgentIdentityUtils.CertInfo certInfo; + + // Subclasses DefaultHttpTransportFactory so IamUtils.resolveCallTarget treats it as the default + // transport factory while still keeping metadata and non-mTLS IAM requests in memory. + private final HttpTransportFactory defaultRecordingTransportFactory = + new OAuth2Utils.DefaultHttpTransportFactory() { + @Override + public HttpTransport create() { + return newDefaultTransport(); + } + }; + + @BeforeEach + void setUp() throws Exception { + String certPath = resourcePath("/agent/agent_spiffe_cert.pem"); + String keyPath = resourcePath("/agent/agent_spiffe_key.pem"); + AgentIdentityUtils.resetForTest(); + certInfo = AgentIdentityUtils.loadAndVerifyCredentials(certPath, keyPath); + AgentIdentityUtils.resetForTest(); + AgentIdentityUtils.setEnvironmentProvider(new TestEnvironmentProvider()); + AgentIdentityUtils.setPropertyProvider(new TestPropertyProvider()); + AgentIdentityUtils.setWellKnownDir(tempDir.resolve("no-spiffe").toString()); + assertNotNull(certInfo.getKeyStore()); + + // Record keyStore only when a request actually executes on the returned mTLS transport, not + // when the factory is created. + IamUtils.setMtlsTransportFactoryProvider( + keyStore -> (HttpTransportFactory) () -> newRecordingIamTransport(keyStore)); + } + + @AfterEach + void tearDown() { + IamUtils.resetForTest(); + AgentIdentityUtils.resetForTest(); + } + + private static String resourcePath(String resource) throws Exception { + return Paths.get(IamMtlsRoutingTest.class.getResource(resource).toURI()).toString(); + } + + private void configureAgentCertConfig(String certResource, String keyResource) throws Exception { + Path configPath = tempDir.resolve("certificate_config.json"); + Map workload = new HashMap<>(); + workload.put("cert_path", resourcePath(certResource)); + workload.put("key_path", resourcePath(keyResource)); + Map certConfigs = new HashMap<>(); + certConfigs.put("workload", workload); + Map config = new HashMap<>(); + config.put("cert_configs", certConfigs); + Files.write( + configPath, OAuth2Utils.JSON_FACTORY.toString(config).getBytes(StandardCharsets.UTF_8)); + + TestEnvironmentProvider envProvider = new TestEnvironmentProvider(); + envProvider.setEnv(AgentIdentityUtils.GOOGLE_API_CERTIFICATE_CONFIG, configPath.toString()); + AgentIdentityUtils.resetForTest(); + AgentIdentityUtils.setEnvironmentProvider(envProvider); + AgentIdentityUtils.setPropertyProvider(new TestPropertyProvider()); + AgentIdentityUtils.setWellKnownDir(tempDir.resolve("no-spiffe").toString()); + } + + private void resetRecordedRequests() { + requestUrls.clear(); + authorizationHeaders.clear(); + quotaProjectHeaders.clear(); + requestKeyStores.clear(); + queuedIamResponses.clear(); + metadataTokenRequests.set(0); + } + + private void enqueueIamError(int statusCode, String reasonPhrase, String wwwAuthenticateHeader) { + MockLowLevelHttpResponse errorResponse = + new MockLowLevelHttpResponse().setStatusCode(statusCode).setReasonPhrase(reasonPhrase); + if (wwwAuthenticateHeader != null) { + errorResponse.addHeader("WWW-Authenticate", wwwAuthenticateHeader); + } + queuedIamResponses.add(errorResponse); + } + + private MockHttpTransport newDefaultTransport() { + MockHttpTransport nonMtlsIamTransport = newRecordingIamTransport(/* mtlsKeyStore= */ null); + return new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { + if (url.equals(ComputeEngineCredentials.getDefaultServiceAccountUrl())) { + return new MockLowLevelHttpRequest(url) { + @Override + public LowLevelHttpResponse execute() { + return new MockLowLevelHttpResponse() + .setContentType(Json.MEDIA_TYPE) + .setContent(SOURCE_ACCOUNT); + } + }; + } + if (url.startsWith(ComputeEngineCredentials.getTokenServerEncodedUrl())) { + return new MockLowLevelHttpRequest(url) { + @Override + public LowLevelHttpResponse execute() throws IOException { + metadataTokenRequests.incrementAndGet(); + if (metadataTokenStatusCode != HttpStatusCodes.STATUS_CODE_OK) { + return new MockLowLevelHttpResponse() + .setStatusCode(metadataTokenStatusCode) + .setContent("Metadata token error"); + } + GenericJson refreshContents = new GenericJson(); + refreshContents.setFactory(OAuth2Utils.JSON_FACTORY); + refreshContents.put("access_token", nextMetadataAccessToken); + refreshContents.put("expires_in", 3600); + refreshContents.put("token_type", "Bearer"); + return new MockLowLevelHttpResponse() + .setContentType(Json.MEDIA_TYPE) + .setStatusCode(HttpStatusCodes.STATUS_CODE_OK) + .setContent(refreshContents.toPrettyString()); + } + }; + } + return nonMtlsIamTransport.buildRequest(method, url); + } + }; + } + + private MockHttpTransport newRecordingIamTransport(KeyStore mtlsKeyStore) { + return new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) { + return new MockLowLevelHttpRequest(url) { + @Override + public LowLevelHttpResponse execute() { + requestUrls.add(url); + requestKeyStores.add(mtlsKeyStore); + List authorization = getHeaderValues("Authorization"); + authorizationHeaders.add(authorization.isEmpty() ? null : authorization.get(0)); + List quotaProject = getHeaderValues("x-goog-user-project"); + quotaProjectHeaders.add(quotaProject.isEmpty() ? null : quotaProject.get(0)); + MockLowLevelHttpResponse queued = queuedIamResponses.poll(); + if (queued != null) { + return queued; + } + String content; + if (url.endsWith(":generateAccessToken")) { + content = + "{\"accessToken\": \"impersonated\", \"expireTime\": \"2099-01-01T00:00:00Z\"}"; + } else if (url.endsWith(":signBlob")) { + content = + "{\"signedBlob\": \"" + + Base64.getEncoder() + .encodeToString("signature".getBytes(StandardCharsets.UTF_8)) + + "\"}"; + } else { + content = "{\"token\": \"" + ComputeEngineCredentialsTest.STANDARD_ID_TOKEN + "\"}"; + } + return new MockLowLevelHttpResponse() + .setContentType(Json.MEDIA_TYPE) + .setContent(content); + } + }; + } + }; + } + + private ComputeEngineCredentials boundSource(String quotaProjectId) { + ComputeEngineCredentials.Builder builder = + ComputeEngineCredentials.newBuilder() + .setHttpTransportFactory(defaultRecordingTransportFactory) + .setQuotaProjectId(quotaProjectId) + .setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE); + builder.setAccessToken( + new BoundAccessToken( + BOUND_TOKEN, new Date(System.currentTimeMillis() + 3_600_000L), certInfo)); + return builder.build(); + } + + private ImpersonatedCredentials impersonated(String iamEndpointOverride) { + return impersonated(iamEndpointOverride, null); + } + + private ImpersonatedCredentials impersonated(String iamEndpointOverride, String quotaProjectId) { + return ImpersonatedCredentials.newBuilder() + .setSourceCredentials(boundSource(quotaProjectId)) + .setTargetPrincipal(TARGET) + .setScopes(Collections.singletonList(OAuth2Utils.CLOUD_PLATFORM_SCOPE)) + .setLifetime(300) + .setHttpTransportFactory(defaultRecordingTransportFactory) + .setIamEndpointOverride(iamEndpointOverride) + .build(); + } + + private void assertSentOverMtlsWithBoundToken(String expectedUrl) { + assertEquals(Collections.singletonList(expectedUrl), requestUrls); + assertEquals(Collections.singletonList("Bearer " + BOUND_TOKEN), authorizationHeaders); + assertEquals(1, requestKeyStores.size()); + assertSame(certInfo.getKeyStore(), requestKeyStores.get(0)); + } + + @Test + void impersonatedRefreshAccessToken_boundSource_usesMtlsEndpoint() throws Exception { + AccessToken token = impersonated(null).refreshAccessToken(); + + assertEquals("impersonated", token.getTokenValue()); + assertSentOverMtlsWithBoundToken(MTLS_BASE + TARGET + ":generateAccessToken"); + } + + @Test + void impersonatedSign_boundSource_usesMtlsEndpoint() { + byte[] signature = impersonated(null).sign("data".getBytes(StandardCharsets.UTF_8)); + + assertEquals("signature", new String(signature, StandardCharsets.UTF_8)); + assertSentOverMtlsWithBoundToken(MTLS_BASE + TARGET + ":signBlob"); + } + + @Test + void impersonatedIdTokenWithAudience_boundSource_usesMtlsEndpoint() throws Exception { + IdToken idToken = impersonated(null).idTokenWithAudience("https://example.com", null); + + assertNotNull(idToken); + assertSentOverMtlsWithBoundToken(MTLS_BASE + TARGET + ":generateIdToken"); + } + + @Test + void impersonatedWithEndpointOverride_allIamCallsUseOverrideWithoutMtls() throws Exception { + String overrideBase = + "https://us-east1-iamcredentials.example.com/v1/projects/-/serviceAccounts/" + TARGET; + String override = overrideBase + ":generateAccessToken"; + ImpersonatedCredentials credentials = impersonated(override); + + credentials.sign("data".getBytes(StandardCharsets.UTF_8)); + assertEquals(Collections.singletonList(overrideBase + ":signBlob"), requestUrls); + assertEquals(Collections.singletonList("Bearer " + BOUND_TOKEN), authorizationHeaders); + assertEquals(Collections.singletonList(null), requestKeyStores); + + resetRecordedRequests(); + credentials.idTokenWithAudience("https://example.com", null); + assertEquals(Collections.singletonList(overrideBase + ":generateIdToken"), requestUrls); + assertEquals(Collections.singletonList("Bearer " + BOUND_TOKEN), authorizationHeaders); + assertEquals(Collections.singletonList(null), requestKeyStores); + + resetRecordedRequests(); + credentials.refreshAccessToken(); + assertEquals(Collections.singletonList(override), requestUrls); + assertEquals(Collections.singletonList("Bearer " + BOUND_TOKEN), authorizationHeaders); + assertEquals(Collections.singletonList(null), requestKeyStores); + } + + @Test + void impersonatedWithInvalidEndpointOverride_signAndIdTokenFailWithoutNetworkCall() { + ImpersonatedCredentials credentials = + impersonated("https://us-east1-iamcredentials.example.com"); + + assertThrows( + SigningException.class, () -> credentials.sign("data".getBytes(StandardCharsets.UTF_8))); + assertThrows( + IOException.class, () -> credentials.idTokenWithAudience("https://example.com", null)); + assertEquals(Collections.emptyList(), requestUrls); + assertEquals(Collections.emptyList(), requestKeyStores); + } + + @Test + void computeEngineSign_boundToken_usesMtlsEndpoint() { + byte[] signature = boundSource(null).sign("data".getBytes(StandardCharsets.UTF_8)); + + assertEquals("signature", new String(signature, StandardCharsets.UTF_8)); + assertSentOverMtlsWithBoundToken(MTLS_BASE + SOURCE_ACCOUNT + ":signBlob"); + } + + @Test + void allMtlsIamCalls_boundSourceWithQuotaProject_preserveQuotaProjectHeader() throws Exception { + String quotaProject = "agent-quota-project"; + ImpersonatedCredentials credentials = impersonated(null, quotaProject); + + credentials.refreshAccessToken(); + assertSentOverMtlsWithBoundToken(MTLS_BASE + TARGET + ":generateAccessToken"); + assertEquals(Collections.singletonList(quotaProject), quotaProjectHeaders); + + resetRecordedRequests(); + credentials.sign("data".getBytes(StandardCharsets.UTF_8)); + assertSentOverMtlsWithBoundToken(MTLS_BASE + TARGET + ":signBlob"); + assertEquals(Collections.singletonList(quotaProject), quotaProjectHeaders); + + resetRecordedRequests(); + credentials.idTokenWithAudience("https://example.com", null); + assertSentOverMtlsWithBoundToken(MTLS_BASE + TARGET + ":generateIdToken"); + assertEquals(Collections.singletonList(quotaProject), quotaProjectHeaders); + + resetRecordedRequests(); + boundSource(quotaProject).sign("data".getBytes(StandardCharsets.UTF_8)); + assertSentOverMtlsWithBoundToken(MTLS_BASE + SOURCE_ACCOUNT + ":signBlob"); + assertEquals(Collections.singletonList(quotaProject), quotaProjectHeaders); + } + + @Test + void refreshAccessToken_boundSource401_refreshesAndRetriesOnceOverRotatedCert() throws Exception { + configureAgentCertConfig("/agent/agent_spiffe_cert_chain.pem", "/agent/agent_spiffe_key.pem"); + enqueueIamError( + HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, "Unauthorized", "Bearer error=\"invalid_token\""); + + AccessToken token = impersonated(null).refreshAccessToken(); + + assertEquals("impersonated", token.getTokenValue()); + assertEquals(1, metadataTokenRequests.get()); + String expectedUrl = MTLS_BASE + TARGET + ":generateAccessToken"; + assertEquals(Arrays.asList(expectedUrl, expectedUrl), requestUrls); + assertEquals( + Arrays.asList("Bearer " + BOUND_TOKEN, "Bearer " + nextMetadataAccessToken), + authorizationHeaders); + assertEquals(2, requestKeyStores.size()); + assertSame(certInfo.getKeyStore(), requestKeyStores.get(0)); + assertNotNull(requestKeyStores.get(1)); + assertNotSame(certInfo.getKeyStore(), requestKeyStores.get(1)); + assertEquals(2, requestKeyStores.get(1).getCertificateChain("alias").length); + } + + @Test + void idTokenWithAudience_boundSource401_refreshesAndRetriesOnceOverRotatedCert() + throws Exception { + configureAgentCertConfig("/agent/agent_spiffe_cert_chain.pem", "/agent/agent_spiffe_key.pem"); + enqueueIamError( + HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, + "Unauthorized", + "Bearer realm=\"https://accounts.google.com/\""); + + IdToken idToken = impersonated(null).idTokenWithAudience("https://example.com", null); + + assertNotNull(idToken); + assertEquals(1, metadataTokenRequests.get()); + String expectedUrl = MTLS_BASE + TARGET + ":generateIdToken"; + assertEquals(Arrays.asList(expectedUrl, expectedUrl), requestUrls); + assertEquals( + Arrays.asList("Bearer " + BOUND_TOKEN, "Bearer " + nextMetadataAccessToken), + authorizationHeaders); + assertEquals(2, requestKeyStores.size()); + assertSame(certInfo.getKeyStore(), requestKeyStores.get(0)); + assertNotNull(requestKeyStores.get(1)); + assertNotSame(certInfo.getKeyStore(), requestKeyStores.get(1)); + assertEquals(2, requestKeyStores.get(1).getCertificateChain("alias").length); + } + + @Test + void refreshAccessTokenAndIdToken_boundSource401WithUnchangedToken_failsFastAfterSingleRefresh() + throws Exception { + configureAgentCertConfig("/agent/agent_spiffe_cert.pem", "/agent/agent_spiffe_key.pem"); + nextMetadataAccessToken = BOUND_TOKEN; + enqueueIamError( + HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, "Unauthorized", "Bearer error=\"invalid_token\""); + + IOException refreshEx = + assertThrows(IOException.class, () -> impersonated(null).refreshAccessToken()); + assertTrue(refreshEx.getCause() instanceof HttpResponseException); + assertEquals(1, metadataTokenRequests.get()); + assertSentOverMtlsWithBoundToken(MTLS_BASE + TARGET + ":generateAccessToken"); + + resetRecordedRequests(); + enqueueIamError(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, "Unauthorized", null); + IOException idTokenEx = + assertThrows( + IOException.class, + () -> impersonated(null).idTokenWithAudience("https://example.com", null)); + assertEquals("Error code 401 trying to getIDToken: Unauthorized", idTokenEx.getMessage()); + assertEquals(1, metadataTokenRequests.get()); + assertSentOverMtlsWithBoundToken(MTLS_BASE + TARGET + ":generateIdToken"); + } + + @Test + void refreshAccessTokenAndIdToken_boundSource403_doesNotRefreshOrRetry() { + enqueueIamError(HttpStatusCodes.STATUS_CODE_FORBIDDEN, "Forbidden", null); + + assertThrows(IOException.class, () -> impersonated(null).refreshAccessToken()); + assertEquals(0, metadataTokenRequests.get()); + assertSentOverMtlsWithBoundToken(MTLS_BASE + TARGET + ":generateAccessToken"); + + resetRecordedRequests(); + enqueueIamError(HttpStatusCodes.STATUS_CODE_FORBIDDEN, "Forbidden", null); + IOException idTokenEx = + assertThrows( + IOException.class, + () -> impersonated(null).idTokenWithAudience("https://example.com", null)); + assertEquals("Error code 403 trying to getIDToken: Forbidden", idTokenEx.getMessage()); + assertEquals(0, metadataTokenRequests.get()); + assertSentOverMtlsWithBoundToken(MTLS_BASE + TARGET + ":generateIdToken"); + } + + @Test + void refreshAccessTokenAndIdToken_boundSource401Twice_retriesAtMostOnce() throws Exception { + configureAgentCertConfig("/agent/agent_spiffe_cert.pem", "/agent/agent_spiffe_key.pem"); + enqueueIamError( + HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, "Unauthorized", "Bearer error=\"invalid_token\""); + enqueueIamError( + HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, "Unauthorized", "Bearer error=\"invalid_token\""); + + IOException refreshEx = + assertThrows(IOException.class, () -> impersonated(null).refreshAccessToken()); + assertTrue(refreshEx.getCause() instanceof HttpResponseException); + assertEquals( + HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, + ((HttpResponseException) refreshEx.getCause()).getStatusCode()); + assertEquals(1, refreshEx.getSuppressed().length); + assertEquals(1, metadataTokenRequests.get()); + String refreshUrl = MTLS_BASE + TARGET + ":generateAccessToken"; + assertEquals(Arrays.asList(refreshUrl, refreshUrl), requestUrls); + assertEquals( + Arrays.asList("Bearer " + BOUND_TOKEN, "Bearer " + nextMetadataAccessToken), + authorizationHeaders); + assertEquals(2, requestKeyStores.size()); + assertSame(certInfo.getKeyStore(), requestKeyStores.get(0)); + assertNotNull(requestKeyStores.get(1)); + + resetRecordedRequests(); + enqueueIamError(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, "Unauthorized", null); + enqueueIamError(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, "Unauthorized", null); + IOException idTokenEx = + assertThrows( + IOException.class, + () -> impersonated(null).idTokenWithAudience("https://example.com", null)); + assertEquals("Error code 401 trying to getIDToken: Unauthorized", idTokenEx.getMessage()); + assertEquals(1, metadataTokenRequests.get()); + String idTokenUrl = MTLS_BASE + TARGET + ":generateIdToken"; + assertEquals(Arrays.asList(idTokenUrl, idTokenUrl), requestUrls); + assertEquals( + Arrays.asList("Bearer " + BOUND_TOKEN, "Bearer " + nextMetadataAccessToken), + authorizationHeaders); + assertEquals(2, requestKeyStores.size()); + assertSame(certInfo.getKeyStore(), requestKeyStores.get(0)); + assertNotNull(requestKeyStores.get(1)); + } + + @Test + void refreshAccessTokenAndIdToken_boundSource401ToUnboundToken_retriesOnceOnDefaultEndpoint() { + // setUp leaves agent cert configuration absent, so source.refresh() mints an unbound token. + String defaultBase = "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/"; + enqueueIamError( + HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, "Unauthorized", "Bearer error=\"invalid_token\""); + enqueueIamError( + HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, "Unauthorized", "Bearer error=\"invalid_token\""); + + assertThrows(IOException.class, () -> impersonated(null).refreshAccessToken()); + assertEquals(1, metadataTokenRequests.get()); + assertEquals( + Arrays.asList( + MTLS_BASE + TARGET + ":generateAccessToken", + defaultBase + TARGET + ":generateAccessToken"), + requestUrls); + assertEquals( + Arrays.asList("Bearer " + BOUND_TOKEN, "Bearer " + nextMetadataAccessToken), + authorizationHeaders); + assertEquals(2, requestKeyStores.size()); + assertSame(certInfo.getKeyStore(), requestKeyStores.get(0)); + assertNull(requestKeyStores.get(1)); + + resetRecordedRequests(); + enqueueIamError(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, "Unauthorized", null); + enqueueIamError(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, "Unauthorized", null); + IOException idTokenEx = + assertThrows( + IOException.class, + () -> impersonated(null).idTokenWithAudience("https://example.com", null)); + assertEquals("Error code 401 trying to getIDToken: Unauthorized", idTokenEx.getMessage()); + assertEquals(1, metadataTokenRequests.get()); + assertEquals( + Arrays.asList( + MTLS_BASE + TARGET + ":generateIdToken", defaultBase + TARGET + ":generateIdToken"), + requestUrls); + assertEquals( + Arrays.asList("Bearer " + BOUND_TOKEN, "Bearer " + nextMetadataAccessToken), + authorizationHeaders); + assertEquals(2, requestKeyStores.size()); + assertSame(certInfo.getKeyStore(), requestKeyStores.get(0)); + assertNull(requestKeyStores.get(1)); + } + + @Test + void refreshAccessTokenAndIdToken_boundSource401WhenRefreshFails_surfacesOriginal401() + throws Exception { + configureAgentCertConfig("/agent/agent_spiffe_cert.pem", "/agent/agent_spiffe_key.pem"); + metadataTokenStatusCode = HttpStatusCodes.STATUS_CODE_SERVER_ERROR; + enqueueIamError( + HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, "Unauthorized", "Bearer error=\"invalid_token\""); + + IOException refreshEx = + assertThrows(IOException.class, () -> impersonated(null).refreshAccessToken()); + assertTrue(refreshEx.getCause() instanceof HttpResponseException); + assertEquals( + HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, + ((HttpResponseException) refreshEx.getCause()).getStatusCode()); + assertEquals(1, metadataTokenRequests.get()); + assertSentOverMtlsWithBoundToken(MTLS_BASE + TARGET + ":generateAccessToken"); + + resetRecordedRequests(); + enqueueIamError(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, "Unauthorized", null); + IOException idTokenEx = + assertThrows( + IOException.class, + () -> impersonated(null).idTokenWithAudience("https://example.com", null)); + assertEquals("Error code 401 trying to getIDToken: Unauthorized", idTokenEx.getMessage()); + assertEquals(1, metadataTokenRequests.get()); + assertSentOverMtlsWithBoundToken(MTLS_BASE + TARGET + ":generateIdToken"); + } + + @Test + void sign_boundSource401_doesNotRetryPinnedToken() { + enqueueIamError( + HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, "Unauthorized", "Bearer error=\"invalid_token\""); + assertThrows( + SigningException.class, + () -> impersonated(null).sign("data".getBytes(StandardCharsets.UTF_8))); + assertEquals(0, metadataTokenRequests.get()); + assertSentOverMtlsWithBoundToken(MTLS_BASE + TARGET + ":signBlob"); + + resetRecordedRequests(); + enqueueIamError(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, "Unauthorized", null); + assertThrows( + SigningException.class, + () -> boundSource(null).sign("data".getBytes(StandardCharsets.UTF_8))); + assertEquals(0, metadataTokenRequests.get()); + assertSentOverMtlsWithBoundToken(MTLS_BASE + SOURCE_ACCOUNT + ":signBlob"); + } + + @Test + void mtlsTransportFactory_fromBoundTokenKeyStore_createsTransport() { + assertNotNull(new MtlsHttpTransportFactory(certInfo.getKeyStore()).create()); + } +} diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java index 303d4f6720dc..99f0b78c6f2e 100644 --- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java @@ -32,19 +32,50 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.api.client.http.HttpStatusCodes; +import com.google.api.client.http.LowLevelHttpRequest; +import com.google.api.client.http.LowLevelHttpResponse; +import com.google.api.client.json.GenericJson; +import com.google.api.client.json.Json; import com.google.api.client.testing.http.MockHttpTransport; +import com.google.api.client.testing.http.MockLowLevelHttpRequest; import com.google.api.client.testing.http.MockLowLevelHttpResponse; import com.google.auth.CredentialTypeForMetrics; import com.google.auth.Credentials; +import com.google.auth.RequestMetadataCallback; import com.google.auth.ServiceAccountSigner; +import com.google.auth.http.HttpTransportFactory; +import com.google.auth.mtls.MtlsHttpTransportFactory; import com.google.common.collect.ImmutableMap; +import com.google.common.util.concurrent.MoreExecutors; +import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.NotSerializableException; +import java.io.ObjectOutputStream; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.KeyStore; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.mockito.Mockito; class IamUtilsTest { @@ -600,4 +631,471 @@ void getIdToken_4xxErrorWithJsonEmptyMessage_usesStatusMessage() { CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT)); assertEquals("Error code 403 trying to getIDToken: Forbidden", exception.getMessage()); } + + private static AgentIdentityUtils.CertInfo loadAgentCertInfo() throws Exception { + String certPath = + Paths.get(IamUtilsTest.class.getResource("/agent/agent_spiffe_cert.pem").toURI()) + .toString(); + String keyPath = + Paths.get(IamUtilsTest.class.getResource("/agent/agent_spiffe_key.pem").toURI()).toString(); + AgentIdentityUtils.resetForTest(); + try { + return AgentIdentityUtils.loadAndVerifyCredentials(certPath, keyPath); + } finally { + AgentIdentityUtils.resetForTest(); + } + } + + private static ComputeEngineCredentials computeEngineCredentialsWithToken(AccessToken token) { + ComputeEngineCredentials.Builder builder = + ComputeEngineCredentials.newBuilder() + .setHttpTransportFactory(MockMetadataServerTransport::new); + builder.setAccessToken(token); + return builder.build(); + } + + private static Date oneHourFromNow() { + return new Date(System.currentTimeMillis() + 3_600_000L); + } + + @Test + void resolveBoundTokenCallTarget_boundToken_usesMtlsEndpointCertificateAndToken() + throws Exception { + AgentIdentityUtils.CertInfo certInfo = loadAgentCertInfo(); + assertNotNull(certInfo.getKeyStore()); + ComputeEngineCredentials source = + computeEngineCredentialsWithToken( + new BoundAccessToken("bound-token", oneHourFromNow(), certInfo)); + HttpTransportFactory defaultFactory = MockHttpTransport::new; + HttpTransportFactory mtlsFactory = MockHttpTransport::new; + AtomicReference keyStoreUsed = new AtomicReference<>(); + + IamUtils.IamCallTarget target = + IamUtils.resolveBoundTokenCallTarget( + source, + defaultFactory, + Credentials.GOOGLE_DEFAULT_UNIVERSE, + keyStore -> { + keyStoreUsed.set(keyStore); + return mtlsFactory; + }); + + assertTrue(target.usesMtls()); + assertEquals("mtls.googleapis.com", target.endpointDomain); + assertSame(mtlsFactory, target.transportFactory); + assertSame(certInfo.getKeyStore(), keyStoreUsed.get()); + Map> metadata = + target.credentials.getRequestMetadata( + URI.create("https://iamcredentials.mtls.googleapis.com")); + assertEquals(Collections.singletonList("Bearer bound-token"), metadata.get("Authorization")); + } + + @Test + void resolveBoundTokenCallTarget_boundToken_pinnedCredentialsStartWithTokenAndKeepIt() + throws Exception { + AgentIdentityUtils.CertInfo certInfo = loadAgentCertInfo(); + BoundAccessToken token = new BoundAccessToken("bound-token", oneHourFromNow(), certInfo); + ComputeEngineCredentials source = computeEngineCredentialsWithToken(token); + + IamUtils.IamCallTarget target = + IamUtils.resolveBoundTokenCallTarget( + source, + MockHttpTransport::new, + Credentials.GOOGLE_DEFAULT_UNIVERSE, + keyStore -> MockHttpTransport::new); + + GoogleCredentials pinned = (GoogleCredentials) target.credentials; + assertNotSame(source, pinned); + // Seeded with the bound token, so the first use doesn't go through a refresh. + assertSame(token, pinned.getAccessToken()); + // A refresh (for example when the token becomes stale) keeps the same bound token. + pinned.refresh(); + assertSame(token, pinned.getAccessToken()); + } + + @Test + void resolveBoundTokenCallTarget_boundTokenWithQuotaProject_preservesQuotaProjectHeader() + throws Exception { + AgentIdentityUtils.CertInfo certInfo = loadAgentCertInfo(); + ComputeEngineCredentials.Builder builder = + ComputeEngineCredentials.newBuilder() + .setHttpTransportFactory(MockMetadataServerTransport::new) + .setQuotaProjectId("quota-project"); + builder.setAccessToken(new BoundAccessToken("bound-token", oneHourFromNow(), certInfo)); + ComputeEngineCredentials source = builder.build(); + + IamUtils.IamCallTarget target = + IamUtils.resolveBoundTokenCallTarget( + source, + MockHttpTransport::new, + Credentials.GOOGLE_DEFAULT_UNIVERSE, + keyStore -> MockHttpTransport::new); + + URI uri = URI.create("https://iamcredentials.mtls.googleapis.com"); + Map> syncMetadata = target.credentials.getRequestMetadata(uri); + assertEquals( + Collections.singletonList("Bearer bound-token"), syncMetadata.get("Authorization")); + assertEquals( + Collections.singletonList("quota-project"), syncMetadata.get("x-goog-user-project")); + + AtomicReference>> asyncMetadata = new AtomicReference<>(); + target.credentials.getRequestMetadata( + uri, + MoreExecutors.directExecutor(), + new RequestMetadataCallback() { + @Override + public void onSuccess(Map> metadata) { + asyncMetadata.set(metadata); + } + + @Override + public void onFailure(Throwable exception) { + throw new AssertionError("Unexpected failure", exception); + } + }); + assertNotNull(asyncMetadata.get()); + assertEquals( + Collections.singletonList("Bearer bound-token"), asyncMetadata.get().get("Authorization")); + assertEquals( + Collections.singletonList("quota-project"), asyncMetadata.get().get("x-goog-user-project")); + } + + private static String writeAgentCertConfig(Path tempDir, String certResource, String keyResource) + throws Exception { + Path configPath = tempDir.resolve("certificate_config.json"); + Map workload = new HashMap<>(); + workload.put( + "cert_path", Paths.get(IamUtilsTest.class.getResource(certResource).toURI()).toString()); + workload.put( + "key_path", Paths.get(IamUtilsTest.class.getResource(keyResource).toURI()).toString()); + Map certConfigs = new HashMap<>(); + certConfigs.put("workload", workload); + Map config = new HashMap<>(); + config.put("cert_configs", certConfigs); + Files.write( + configPath, OAuth2Utils.JSON_FACTORY.toString(config).getBytes(StandardCharsets.UTF_8)); + return configPath.toString(); + } + + private static void configureAgentCertEnv(Path tempDir, String certResource, String keyResource) + throws Exception { + String configPath = writeAgentCertConfig(tempDir, certResource, keyResource); + TestEnvironmentProvider envProvider = new TestEnvironmentProvider(); + envProvider.setEnv(AgentIdentityUtils.GOOGLE_API_CERTIFICATE_CONFIG, configPath); + AgentIdentityUtils.resetForTest(); + AgentIdentityUtils.setEnvironmentProvider(envProvider); + AgentIdentityUtils.setPropertyProvider(new TestPropertyProvider()); + AgentIdentityUtils.setWellKnownDir(tempDir.resolve("no-spiffe").toString()); + } + + private static MockHttpTransport newMetadataTokenTransport( + AtomicReference nextToken, AtomicInteger requestCount) { + return new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) { + return new MockLowLevelHttpRequest(url) { + @Override + public LowLevelHttpResponse execute() throws IOException { + requestCount.incrementAndGet(); + GenericJson refreshContents = new GenericJson(); + refreshContents.setFactory(OAuth2Utils.JSON_FACTORY); + refreshContents.put("access_token", nextToken.get()); + refreshContents.put("expires_in", 3600); + refreshContents.put("token_type", "Bearer"); + return new MockLowLevelHttpResponse() + .setContentType(Json.MEDIA_TYPE) + .setStatusCode(HttpStatusCodes.STATUS_CODE_OK) + .setContent(refreshContents.toPrettyString()); + } + }; + } + }; + } + + @Test + void resolveBoundTokenCallTarget_nullInitialToken_refreshesAndUsesMtls(@TempDir Path tempDir) + throws Exception { + configureAgentCertEnv(tempDir, "/agent/agent_spiffe_cert.pem", "/agent/agent_spiffe_key.pem"); + try { + AtomicInteger metadataRequests = new AtomicInteger(); + MockHttpTransport metadataTransport = + newMetadataTokenTransport(new AtomicReference<>("minted-bound-token"), metadataRequests); + ComputeEngineCredentials source = + ComputeEngineCredentials.newBuilder() + .setHttpTransportFactory(() -> metadataTransport) + .setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE) + .build(); + assertNull(source.getAccessToken()); + AtomicReference keyStoreUsed = new AtomicReference<>(); + + IamUtils.IamCallTarget target = + IamUtils.resolveBoundTokenCallTarget( + source, + MockHttpTransport::new, + Credentials.GOOGLE_DEFAULT_UNIVERSE, + keyStore -> { + keyStoreUsed.set(keyStore); + return MockHttpTransport::new; + }); + + assertEquals(1, metadataRequests.get()); + assertTrue(target.usesMtls()); + assertNotNull(keyStoreUsed.get()); + assertSame( + ((BoundAccessToken) source.getAccessToken()).getCertInfo().getKeyStore(), + keyStoreUsed.get()); + Map> metadata = + target.credentials.getRequestMetadata( + URI.create("https://iamcredentials.mtls.googleapis.com")); + assertEquals( + Collections.singletonList("Bearer minted-bound-token"), metadata.get("Authorization")); + } finally { + AgentIdentityUtils.resetForTest(); + } + } + + @Test + void resolveBoundTokenCallTarget_certificateRotation_isolatesInFlightTargetAndSwitchesNextCall( + @TempDir Path tempDir) throws Exception { + configureAgentCertEnv(tempDir, "/agent/agent_spiffe_cert.pem", "/agent/agent_spiffe_key.pem"); + try { + AtomicReference nextToken = new AtomicReference<>("bound-token-a"); + AtomicInteger metadataRequests = new AtomicInteger(); + MockHttpTransport metadataTransport = newMetadataTokenTransport(nextToken, metadataRequests); + ComputeEngineCredentials source = + ComputeEngineCredentials.newBuilder() + .setHttpTransportFactory(() -> metadataTransport) + .setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE) + .build(); + AtomicReference keyStoreUsed = new AtomicReference<>(); + + IamUtils.IamCallTarget targetA = + IamUtils.resolveBoundTokenCallTarget( + source, + MockHttpTransport::new, + Credentials.GOOGLE_DEFAULT_UNIVERSE, + keyStore -> { + keyStoreUsed.set(keyStore); + return MockHttpTransport::new; + }); + KeyStore keyStoreA = keyStoreUsed.get(); + assertNotNull(keyStoreA); + assertEquals(1, keyStoreA.getCertificateChain("alias").length); + assertEquals(1, metadataRequests.get()); + + // Rotate the certificate on disk and simulate a concurrent refresh on source before targetA + // sends its request. + configureAgentCertEnv( + tempDir, "/agent/agent_spiffe_cert_chain.pem", "/agent/agent_spiffe_key.pem"); + nextToken.set("bound-token-b"); + source.refresh(); + assertEquals("bound-token-b", source.getAccessToken().getTokenValue()); + assertEquals(2, metadataRequests.get()); + + URI uri = URI.create("https://iamcredentials.mtls.googleapis.com"); + assertEquals( + Collections.singletonList("Bearer bound-token-a"), + targetA.credentials.getRequestMetadata(uri).get("Authorization")); + + // Subsequent IAM calls pick up Cert B and token B together without extra refreshes. + IamUtils.IamCallTarget targetB = + IamUtils.resolveBoundTokenCallTarget( + source, + MockHttpTransport::new, + Credentials.GOOGLE_DEFAULT_UNIVERSE, + keyStore -> { + keyStoreUsed.set(keyStore); + return MockHttpTransport::new; + }); + assertEquals(2, metadataRequests.get()); + KeyStore keyStoreB = keyStoreUsed.get(); + assertNotNull(keyStoreB); + assertNotSame(keyStoreA, keyStoreB); + assertEquals(2, keyStoreB.getCertificateChain("alias").length); + assertEquals( + Collections.singletonList("Bearer bound-token-b"), + targetB.credentials.getRequestMetadata(uri).get("Authorization")); + } finally { + AgentIdentityUtils.resetForTest(); + } + } + + @Test + void refreshAndResolveRetryTarget_concurrentRefreshAlreadyCompleted_reusesRefreshedToken( + @TempDir Path tempDir) throws Exception { + configureAgentCertEnv(tempDir, "/agent/agent_spiffe_cert.pem", "/agent/agent_spiffe_key.pem"); + try { + AtomicReference nextToken = new AtomicReference<>("bound-token-a"); + AtomicInteger metadataRequests = new AtomicInteger(); + MockHttpTransport metadataTransport = newMetadataTokenTransport(nextToken, metadataRequests); + ComputeEngineCredentials source = + ComputeEngineCredentials.newBuilder() + .setHttpTransportFactory(() -> metadataTransport) + .setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE) + .build(); + + IamUtils.IamCallTarget targetA = + IamUtils.resolveCallTarget( + source, OAuth2Utils.HTTP_TRANSPORT_FACTORY, Credentials.GOOGLE_DEFAULT_UNIVERSE); + assertTrue(targetA.usesMtls()); + assertEquals(1, metadataRequests.get()); + + // Another thread rotates and refreshes source to token B before this thread enters 401 retry. + configureAgentCertEnv( + tempDir, "/agent/agent_spiffe_cert_chain.pem", "/agent/agent_spiffe_key.pem"); + nextToken.set("bound-token-b"); + source.refresh(); + assertEquals(2, metadataRequests.get()); + + IamUtils.IamCallTarget retryTarget = + IamUtils.refreshAndResolveRetryTarget( + source, + OAuth2Utils.HTTP_TRANSPORT_FACTORY, + Credentials.GOOGLE_DEFAULT_UNIVERSE, + targetA); + + assertNotNull(retryTarget); + assertTrue(retryTarget.usesMtls()); + // Reused the already-refreshed token without making a third metadata request. + assertEquals(2, metadataRequests.get()); + assertEquals( + Collections.singletonList("Bearer bound-token-b"), + retryTarget + .credentials + .getRequestMetadata(URI.create("https://iamcredentials.mtls.googleapis.com")) + .get("Authorization")); + assertEquals( + 2, + ((MtlsHttpTransportFactory) retryTarget.transportFactory) + .getKeyStore() + .getCertificateChain("alias") + .length); + } finally { + AgentIdentityUtils.resetForTest(); + } + } + + @Test + void resolveBoundTokenCallTarget_unboundToken_usesDefaultTarget() throws Exception { + ComputeEngineCredentials source = + computeEngineCredentialsWithToken(new AccessToken("unbound-token", oneHourFromNow())); + HttpTransportFactory defaultFactory = MockHttpTransport::new; + + IamUtils.IamCallTarget target = + IamUtils.resolveBoundTokenCallTarget( + source, + defaultFactory, + Credentials.GOOGLE_DEFAULT_UNIVERSE, + keyStore -> { + throw new AssertionError("mTLS transport must not be created"); + }); + + assertFalse(target.usesMtls()); + assertSame(source, target.credentials); + assertSame(defaultFactory, target.transportFactory); + assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, target.endpointDomain); + } + + @Test + void resolveBoundTokenCallTarget_boundTokenWithoutKeyStore_usesDefaultTarget() throws Exception { + AgentIdentityUtils.CertInfo loaded = loadAgentCertInfo(); + AgentIdentityUtils.CertInfo withoutKey = + new AgentIdentityUtils.CertInfo(loaded.getCertificate(), loaded.getCertContent()); + ComputeEngineCredentials source = + computeEngineCredentialsWithToken( + new BoundAccessToken("bound-token", oneHourFromNow(), withoutKey)); + + IamUtils.IamCallTarget target = + IamUtils.resolveBoundTokenCallTarget( + source, + MockHttpTransport::new, + Credentials.GOOGLE_DEFAULT_UNIVERSE, + keyStore -> { + throw new AssertionError("mTLS transport must not be created"); + }); + + assertFalse(target.usesMtls()); + assertSame(source, target.credentials); + } + + @Test + void resolveBoundTokenCallTarget_nonDefaultUniverse_usesDefaultTarget() throws Exception { + ComputeEngineCredentials source = + computeEngineCredentialsWithToken( + new BoundAccessToken("bound-token", oneHourFromNow(), loadAgentCertInfo())); + + IamUtils.IamCallTarget target = + IamUtils.resolveBoundTokenCallTarget( + source, + MockHttpTransport::new, + "example.com", + keyStore -> { + throw new AssertionError("mTLS transport must not be created"); + }); + + assertFalse(target.usesMtls()); + assertEquals("example.com", target.endpointDomain); + } + + @Test + void resolveBoundTokenCallTarget_notComputeEngineCredentials_usesDefaultTarget() + throws Exception { + IamUtils.IamCallTarget target = + IamUtils.resolveBoundTokenCallTarget( + credentials, + MockHttpTransport::new, + Credentials.GOOGLE_DEFAULT_UNIVERSE, + keyStore -> { + throw new AssertionError("mTLS transport must not be created"); + }); + + assertFalse(target.usesMtls()); + assertSame(credentials, target.credentials); + } + + @Test + void resolveCallTarget_defaultTransportAndBoundToken_usesMtlsTransportFactory() throws Exception { + AgentIdentityUtils.CertInfo certInfo = loadAgentCertInfo(); + ComputeEngineCredentials source = + computeEngineCredentialsWithToken( + new BoundAccessToken("bound-token", oneHourFromNow(), certInfo)); + + IamUtils.IamCallTarget target = + IamUtils.resolveCallTarget( + source, OAuth2Utils.HTTP_TRANSPORT_FACTORY, Credentials.GOOGLE_DEFAULT_UNIVERSE); + + assertTrue(target.usesMtls()); + assertTrue(target.transportFactory instanceof MtlsHttpTransportFactory); + assertSame( + certInfo.getKeyStore(), ((MtlsHttpTransportFactory) target.transportFactory).getKeyStore()); + } + + @Test + void resolveCallTarget_customTransportFactory_usesDefaultTarget() throws Exception { + ComputeEngineCredentials source = + computeEngineCredentialsWithToken( + new BoundAccessToken("bound-token", oneHourFromNow(), loadAgentCertInfo())); + HttpTransportFactory customFactory = MockHttpTransport::new; + + IamUtils.IamCallTarget target = + IamUtils.resolveCallTarget(source, customFactory, Credentials.GOOGLE_DEFAULT_UNIVERSE); + + assertFalse(target.usesMtls()); + assertSame(customFactory, target.transportFactory); + } + + @Test + void resolveCallTarget_pinnedTokenCredentials_isNotSerializable() throws Exception { + ComputeEngineCredentials source = + computeEngineCredentialsWithToken( + new BoundAccessToken("bound-token", oneHourFromNow(), loadAgentCertInfo())); + + IamUtils.IamCallTarget target = + IamUtils.resolveCallTarget( + source, OAuth2Utils.HTTP_TRANSPORT_FACTORY, Credentials.GOOGLE_DEFAULT_UNIVERSE); + + try (ObjectOutputStream out = new ObjectOutputStream(new ByteArrayOutputStream())) { + assertThrows(NotSerializableException.class, () -> out.writeObject(target.credentials)); + } + } }