Skip to content
Open
Original file line number Diff line number Diff line change
Expand Up @@ -39,18 +39,28 @@
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;
import java.nio.charset.StandardCharsets;
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;

Expand Down Expand Up @@ -149,14 +159,28 @@ interface TimeService {
*
* <p>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.
*
* <p>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}. */
Expand All @@ -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. */
Expand Down Expand Up @@ -275,9 +307,9 @@ private static boolean hasWorkloadConfigOrGkeBundle(
*
* <p>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
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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.
*
* <p>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<Certificate> 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.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>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.
*
* <p>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));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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));
}

Expand Down Expand Up @@ -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.<String, Object>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);
}
}

Expand Down
Loading
Loading