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..86c2d78dbe96 --- /dev/null +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/BoundAccessToken.java @@ -0,0 +1,70 @@ +/* + * 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.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)); + } +} 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 6c150079271f..ac3b8871b2e8 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,19 +886,31 @@ 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, /* endpointOverridden= */ false); + } catch (IOException ex) { + throw new SigningException("Failed to sign: Error refreshing credentials", ex); + } return IamUtils.sign( account, - this, - this.getUniverseDomain(), - transportFactory.create(), + target.credentials, + target.endpointDomain, + 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 3111bef92402..624f9e4208d1 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,22 @@ 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.security.KeyStore; import java.util.Arrays; import java.util.HashSet; import java.util.Map; import java.util.Set; +import java.util.function.Function; 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 +88,150 @@ 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 (and to pass as the universe domain argument of {@link #sign} and {@link + * #getIdToken}): 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 AccessToken}, 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 AccessToken token; + + PinnedTokenCredentials( + AccessToken token, @Nullable String quotaProjectId, String universeDomain) { + super( + GoogleCredentials.newBuilder() + .setQuotaProjectId(quotaProjectId) + .setUniverseDomain(universeDomain)); + this.token = token; + } + + @Override + public AccessToken refreshAccessToken() { + return token; + } + } + + /** + * 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 endpoint or 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, + boolean endpointOverridden) + throws IOException { + if (endpointOverridden + || !(transportFactory instanceof OAuth2Utils.DefaultHttpTransportFactory)) { + return new IamCallTarget( + authCredentials, transportFactory, universeDomain, /* usesMtls= */ false); + } + return resolveBoundTokenCallTarget( + authCredentials, transportFactory, universeDomain, mtlsTransportFactoryProvider); + } + + @VisibleForTesting + static void setMtlsTransportFactoryProvider(Function provider) { + mtlsTransportFactoryProvider = provider; + } + + @VisibleForTesting + static void resetForTest() { + mtlsTransportFactoryProvider = MtlsHttpTransportFactory::new; + } + + /** + * Like {@link #resolveCallTarget}, without the endpoint and transport checks, 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; + } + KeyStore keyStore = ((BoundAccessToken) token).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( + token, 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. * @@ -277,6 +427,11 @@ static IdToken getIdToken( HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(credentials); HttpRequest request = transport.createRequestFactory(adapter).buildPostRequest(genericUrl, idTokenContent); + if (credentials instanceof PinnedTokenCredentials) { + // PinnedTokenCredentials always returns the same token on refresh(), so disable + // HttpCredentialsAdapter's 401 retry to avoid resending a rejected token 10 times. + 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. 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 64a8e202f989..64afdff83943 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 @@ -365,19 +365,34 @@ public void setTransportFactory(HttpTransportFactory httpTransportFactory) { */ @Override public byte[] sign(byte[] toSign) { + String universeDomain; try { - return IamUtils.sign( - getAccount(), - sourceCredentials, - getUniverseDomain(), - transportFactory.create(), - toSign, - ImmutableMap.of("delegates", this.delegates)); + universeDomain = getUniverseDomain(); } catch (IOException ex) { // Throwing an IOException would be a breaking change, so wrap it here. // This should not happen for this credential type. throw new SigningException("Failed to sign: Error obtaining universe domain", ex); } + IamUtils.IamCallTarget target; + try { + target = + IamUtils.resolveCallTarget( + sourceCredentials, + transportFactory, + universeDomain, + // iamEndpointOverride only applies to generateAccessToken; signBlob always uses the + // IAM Credentials endpoint. + /* endpointOverridden= */ false); + } catch (IOException ex) { + throw new SigningException("Failed to sign: Error refreshing source credentials", ex); + } + return IamUtils.sign( + getAccount(), + target.credentials, + target.endpointDomain, + target.transportFactory.create(), + toSign, + ImmutableMap.of("delegates", this.delegates)); } /** @@ -709,6 +724,8 @@ AccessToken refreshAccessToken( HttpTransportFactory effectiveTransportFactory = firstNonNull(cycleTransportFactory, this.transportFactory); HttpCredentialsAdapter adapter; + // Set only when the IAM endpoint domain differs from getUniverseDomain() (mTLS). + @Nullable String iamEndpointDomain = null; AccessToken intermediateAccessTokenForCache = null; boolean usedCachedStsToken = false; if (this.sourceCredentials instanceof ExternalAccountCredentials) { @@ -773,6 +790,26 @@ 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. + String universeDomain = getUniverseDomain(); + IamUtils.IamCallTarget target; + try { + target = + IamUtils.resolveCallTarget( + this.sourceCredentials, + effectiveTransportFactory, + universeDomain, + /* endpointOverridden= */ false); + } catch (IOException e) { + throw new IOException("Unable to refresh sourceCredentials", e); + } + if (target.usesMtls()) { + adapter = new HttpCredentialsAdapter(target.credentials); + effectiveTransportFactory = target.transportFactory; + iamEndpointDomain = target.endpointDomain; + } + } } HttpTransport httpTransport = effectiveTransportFactory.create(); @@ -785,7 +822,7 @@ public AccessToken refreshAccessToken() { ? this.iamEndpointOverride : String.format( IamUtils.IAM_ACCESS_TOKEN_ENDPOINT_FORMAT, - getUniverseDomain(), + iamEndpointDomain != null ? iamEndpointDomain : getUniverseDomain(), this.targetPrincipal); GenericUrl url = new GenericUrl(endpointUrl); @@ -800,11 +837,14 @@ public AccessToken refreshAccessToken() { // 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. + if ((cycleTransportFactory != null + && this.sourceCredentials instanceof ExternalAccountCredentials) + || iamEndpointDomain != null) { + // 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 a 401 doesn't resend the same + // rejected token 10 times. request.setUnsuccessfulResponseHandler(null); } request.setParser(parser); @@ -899,15 +939,23 @@ public IdToken idTokenWithAudience( String targetAudience, @Nullable List options) throws IOException { boolean includeEmail = options != null && options.contains(IdTokenProvider.Option.INCLUDE_EMAIL); + IamUtils.IamCallTarget target = + IamUtils.resolveCallTarget( + sourceCredentials, + transportFactory, + getUniverseDomain(), + // iamEndpointOverride only applies to generateAccessToken; generateIdToken always uses + // the IAM Credentials endpoint. + /* endpointOverridden= */ false); return IamUtils.getIdToken( getAccount(), - sourceCredentials, - transportFactory.create(), + target.credentials, + target.transportFactory.create(), targetAudience, includeEmail, ImmutableMap.of("delegates", this.delegates), getMetricsCredentialType(), - getUniverseDomain()); + target.endpointDomain); } @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..77170b9f8414 --- /dev/null +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamMtlsRoutingTest.java @@ -0,0 +1,324 @@ +/* + * 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.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + +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.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.Paths; +import java.security.KeyStore; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +/** + * 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/"; + + private final List requestUrls = new ArrayList<>(); + private final List authorizationHeaders = new ArrayList<>(); + private final List quotaProjectHeaders = new ArrayList<>(); + private final AtomicReference keyStoreUsed = new AtomicReference<>(); + private int responseStatusCode = HttpStatusCodes.STATUS_CODE_OK; + private String responseWwwAuthenticateHeader = null; + private AgentIdentityUtils.CertInfo certInfo; + + // Subclasses DefaultHttpTransportFactory so IamUtils.resolveCallTarget treats it as the default + // transport factory while still keeping any non-mTLS request in memory. + private final HttpTransportFactory defaultRecordingTransportFactory = + new OAuth2Utils.DefaultHttpTransportFactory() { + @Override + public HttpTransport create() { + return newRecordingIamTransport(); + } + }; + + @BeforeEach + void setUp() throws Exception { + String certPath = + Paths.get(IamMtlsRoutingTest.class.getResource("/agent/agent_spiffe_cert.pem").toURI()) + .toString(); + String keyPath = + Paths.get(IamMtlsRoutingTest.class.getResource("/agent/agent_spiffe_key.pem").toURI()) + .toString(); + AgentIdentityUtils.resetForTest(); + certInfo = AgentIdentityUtils.loadAndVerifyCredentials(certPath, keyPath); + AgentIdentityUtils.resetForTest(); + assertNotNull(certInfo.getKeyStore()); + + IamUtils.setMtlsTransportFactoryProvider( + keyStore -> { + keyStoreUsed.set(keyStore); + return (HttpTransportFactory) this::newRecordingIamTransport; + }); + } + + @AfterEach + void tearDown() { + IamUtils.resetForTest(); + AgentIdentityUtils.resetForTest(); + } + + private void resetRecordedRequests() { + requestUrls.clear(); + authorizationHeaders.clear(); + quotaProjectHeaders.clear(); + keyStoreUsed.set(null); + } + + private MockHttpTransport newRecordingIamTransport() { + return new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) { + requestUrls.add(url); + return new MockLowLevelHttpRequest(url) { + @Override + public LowLevelHttpResponse execute() { + 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)); + if (responseStatusCode != HttpStatusCodes.STATUS_CODE_OK) { + MockLowLevelHttpResponse errorResponse = + new MockLowLevelHttpResponse() + .setStatusCode(responseStatusCode) + .setReasonPhrase("Unauthorized"); + if (responseWwwAuthenticateHeader != null) { + errorResponse.addHeader("WWW-Authenticate", responseWwwAuthenticateHeader); + } + return errorResponse; + } + 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); + assertSame(certInfo.getKeyStore(), keyStoreUsed.get()); + } + + @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_refreshUsesOverrideAndSignAndIdTokenUseMtlsEndpoint() + throws Exception { + String override = + "https://us-east1-iamcredentials.example.com/v1/projects/-/serviceAccounts/" + + TARGET + + ":generateAccessToken"; + ImpersonatedCredentials credentials = impersonated(override); + + credentials.sign("data".getBytes(StandardCharsets.UTF_8)); + assertSentOverMtlsWithBoundToken(MTLS_BASE + TARGET + ":signBlob"); + + resetRecordedRequests(); + credentials.idTokenWithAudience("https://example.com", null); + assertSentOverMtlsWithBoundToken(MTLS_BASE + TARGET + ":generateIdToken"); + + // refreshAccessToken() keeps using the override and the default-typed transport, not mTLS. + resetRecordedRequests(); + credentials.refreshAccessToken(); + assertEquals(Collections.singletonList(override), requestUrls); + assertEquals(Collections.singletonList("Bearer " + BOUND_TOKEN), authorizationHeaders); + assertNull(keyStoreUsed.get()); + } + + @Test + void computeEngineSign_boundToken_usesMtlsEndpoint() { + ComputeEngineCredentials source = Mockito.spy(boundSource(null)); + Mockito.doReturn(SOURCE_ACCOUNT).when(source).getAccount(); + + byte[] signature = source.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(); + assertEquals(Collections.singletonList(quotaProject), quotaProjectHeaders); + + resetRecordedRequests(); + credentials.sign("data".getBytes(StandardCharsets.UTF_8)); + assertEquals(Collections.singletonList(quotaProject), quotaProjectHeaders); + + resetRecordedRequests(); + credentials.idTokenWithAudience("https://example.com", null); + assertEquals(Collections.singletonList(quotaProject), quotaProjectHeaders); + + resetRecordedRequests(); + ComputeEngineCredentials source = Mockito.spy(boundSource(quotaProject)); + Mockito.doReturn(SOURCE_ACCOUNT).when(source).getAccount(); + source.sign("data".getBytes(StandardCharsets.UTF_8)); + assertEquals(Collections.singletonList(quotaProject), quotaProjectHeaders); + } + + @Test + void allMtlsIamCalls_boundSource401_doNotRetryPinnedToken() { + responseStatusCode = HttpStatusCodes.STATUS_CODE_UNAUTHORIZED; + responseWwwAuthenticateHeader = "Bearer error=\"invalid_token\""; + + assertThrows(IOException.class, () -> impersonated(null).refreshAccessToken()); + assertEquals(1, requestUrls.size()); + + resetRecordedRequests(); + assertThrows( + SigningException.class, + () -> impersonated(null).sign("data".getBytes(StandardCharsets.UTF_8))); + assertEquals(1, requestUrls.size()); + + resetRecordedRequests(); + responseWwwAuthenticateHeader = 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, requestUrls.size()); + + resetRecordedRequests(); + ComputeEngineCredentials source = Mockito.spy(boundSource(null)); + Mockito.doReturn(SOURCE_ACCOUNT).when(source).getAccount(); + assertThrows( + SigningException.class, () -> source.sign("data".getBytes(StandardCharsets.UTF_8))); + assertEquals(1, requestUrls.size()); + } + + @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 b136f264f998..f4c6726f4819 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,6 +32,11 @@ 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; @@ -40,9 +45,22 @@ 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.IOException; +import java.net.URI; +import java.nio.file.Paths; +import java.security.KeyStore; +import java.util.Collections; +import java.util.Date; +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.mockito.Mockito; @@ -610,4 +628,370 @@ void getIdToken_4xxErrorWithJsonEmptyMessage_usesStatusMessage() { Credentials.GOOGLE_DEFAULT_UNIVERSE)); 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")); + } + + @Test + void resolveBoundTokenCallTarget_nullInitialToken_refreshesAndUsesMtls() throws Exception { + AgentIdentityUtils.CertInfo certInfo = loadAgentCertInfo(); + BoundAccessToken mintedToken = + new BoundAccessToken("minted-bound-token", oneHourFromNow(), certInfo); + ComputeEngineCredentials source = + Mockito.spy( + ComputeEngineCredentials.newBuilder() + .setHttpTransportFactory(MockMetadataServerTransport::new) + .setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE) + .build()); + AtomicInteger refreshCount = new AtomicInteger(); + Mockito.doAnswer( + invocation -> { + refreshCount.incrementAndGet(); + return mintedToken; + }) + .when(source) + .refreshAccessToken(); + 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, refreshCount.get()); + assertTrue(target.usesMtls()); + assertSame(certInfo.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")); + } + + @Test + void resolveBoundTokenCallTarget_certificateRotation_isolatesInFlightTargetAndSwitchesNextCall() + throws Exception { + AgentIdentityUtils.CertInfo certInfoA = loadAgentCertInfo(); + KeyStore keyStoreA = certInfoA.getKeyStore(); + assertNotNull(keyStoreA); + KeyStore keyStoreB = KeyStore.getInstance(keyStoreA.getType()); + keyStoreB.load(null); + assertNotSame(keyStoreA, keyStoreB); + AgentIdentityUtils.CertInfo certInfoB = + new AgentIdentityUtils.CertInfo( + certInfoA.getCertificate(), certInfoA.getCertContent(), keyStoreB); + BoundAccessToken tokenA = new BoundAccessToken("bound-token-a", oneHourFromNow(), certInfoA); + BoundAccessToken tokenB = new BoundAccessToken("bound-token-b", oneHourFromNow(), certInfoB); + + ComputeEngineCredentials source = + Mockito.spy( + ComputeEngineCredentials.newBuilder() + .setHttpTransportFactory(MockMetadataServerTransport::new) + .setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE) + .build()); + AtomicInteger refreshCount = new AtomicInteger(); + Mockito.doAnswer(invocation -> refreshCount.incrementAndGet() == 1 ? tokenA : tokenB) + .when(source) + .refreshAccessToken(); + AtomicReference keyStoreUsed = new AtomicReference<>(); + + IamUtils.IamCallTarget targetA = + IamUtils.resolveBoundTokenCallTarget( + source, + MockHttpTransport::new, + Credentials.GOOGLE_DEFAULT_UNIVERSE, + keyStore -> { + keyStoreUsed.set(keyStore); + return MockHttpTransport::new; + }); + assertSame(keyStoreA, keyStoreUsed.get()); + + // Simulate a concurrent refresh on source rotating to Cert B before targetA sends its request. + source.refresh(); + assertSame(tokenB, source.getAccessToken()); + + 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. + IamUtils.IamCallTarget targetB = + IamUtils.resolveBoundTokenCallTarget( + source, + MockHttpTransport::new, + Credentials.GOOGLE_DEFAULT_UNIVERSE, + keyStore -> { + keyStoreUsed.set(keyStore); + return MockHttpTransport::new; + }); + assertSame(keyStoreB, keyStoreUsed.get()); + assertEquals( + Collections.singletonList("Bearer bound-token-b"), + targetB.credentials.getRequestMetadata(uri).get("Authorization")); + } + + @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, + /* endpointOverridden= */ false); + + assertTrue(target.usesMtls()); + assertTrue(target.transportFactory instanceof MtlsHttpTransportFactory); + assertSame( + certInfo.getKeyStore(), ((MtlsHttpTransportFactory) target.transportFactory).getKeyStore()); + } + + @Test + void resolveCallTarget_endpointOverridden_usesDefaultTarget() 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, + /* endpointOverridden= */ true); + + assertFalse(target.usesMtls()); + assertSame(source, target.credentials); + } + + @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, + /* endpointOverridden= */ false); + + assertFalse(target.usesMtls()); + assertSame(customFactory, target.transportFactory); + } }