Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,10 @@ public class DefaultMtlsProviderFactory {

/**
* Creates an instance of {@link MtlsProvider}. It first attempts to create an {@link
* com.google.auth.mtls.X509Provider}. If the certificate source is unavailable, it falls back to
* creating a {@link SecureConnectProvider}. If the secure connect provider also fails, it throws
* a {@link com.google.auth.mtls.CertificateSourceUnavailableException}.
* com.google.auth.mtls.X509Provider}, which also falls back to the GKE credential bundle when no
* certificate configuration is present. If the certificate source is unavailable, it falls back
* to creating a {@link SecureConnectProvider}. If the secure connect provider also fails, it
* throws a {@link com.google.auth.mtls.CertificateSourceUnavailableException}.
*
* @return an instance of {@link MtlsProvider}.
* @throws com.google.auth.mtls.CertificateSourceUnavailableException if neither provider can be
Expand All @@ -53,7 +54,7 @@ public static MtlsProvider create() throws IOException {
// Note: The caller should handle CertificateSourceUnavailableException gracefully, since
// it is an expected error case. All other IOExceptions are unexpected and should be surfaced
// up the call stack.
MtlsProvider mtlsProvider = new X509Provider();
MtlsProvider mtlsProvider = X509Provider.createForTransport();
if (mtlsProvider.isAvailable()) {
return mtlsProvider;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
/*
* Copyright 2026 Google LLC
*
* 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 LLC 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.mtls;

import com.google.api.client.util.PemReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;

/**
* Builds the mTLS {@link KeyStore} from PEM-encoded certificates and a private key.
*
* <p>This replaces {@code com.google.api.client.util.SecurityUtils#createMtlsKeyStore}, which keeps
* only the first certificate. Here the key entry holds every certificate in the input, so the
* intermediate certificates are presented too. Some peers (for example, another workload that
* trusts only a root CA) need them to verify the client certificate.
*
* <p>Everything else matches the upstream method: key store type (JKS), alias, empty password,
* accepted key format (PKCS#8 {@code PRIVATE KEY}), which private key is chosen, and error
* messages. Any input that the upstream method accepted is still accepted, even though more of it
* is now used: once a certificate and a private key have been found (the point where the upstream
* method stopped reading), a malformed or unreadable later section ends the input instead of
* failing, and an extra certificate that cannot be parsed is left out of the chain. Unlike the
* upstream method, the input is decoded as UTF-8 rather than the platform default charset, and it
* is read to the end.
*/
@NullMarked
final class MtlsKeyStoreUtils {

private MtlsKeyStoreUtils() {}

/**
* Creates a key store holding one private key entry.
*
* @param certAndKey PEM input containing one or more {@code CERTIFICATE} sections and a PKCS#8
* {@code PRIVATE KEY} section, in any order. The first certificate must be the one that
* matches the private key (the leaf); the remaining certificates are kept in input order as
* the rest of the chain. If there are several private keys, the one used is the same as
* upstream: the last one before the first certificate, or else the first one after it. The
* stream is read to the end and is not closed.
* @throws IllegalArgumentException if the input has no certificate or no private key, or if a PEM
* section before that point is malformed
* @throws GeneralSecurityException if the first certificate or the private key cannot be parsed,
* or the key store cannot be created
* @throws IOException if the input cannot be read before a certificate and a private key are
* found
*/
static KeyStore createMtlsKeyStore(InputStream certAndKey)
throws GeneralSecurityException, IOException {
List<byte[]> certificates = new ArrayList<>();
byte @Nullable [] privateKey = null;
PemReader reader = new PemReader(new InputStreamReader(certAndKey, StandardCharsets.UTF_8));
while (true) {
PemReader.Section section;
try {
section = reader.readNextSection();
} catch (IllegalArgumentException | IOException e) {
if (!certificates.isEmpty() && privateKey != null) {
// Malformed or unreadable trailing content after a usable certificate and key: stop
// here, as the upstream method (which stopped reading at this point) would have.
break;
}
throw e;
}
if (section == null) {
break;
}
if ("CERTIFICATE".equals(section.getTitle())) {
certificates.add(section.getBase64DecodedBytes());
} else if ("PRIVATE KEY".equals(section.getTitle())
&& (privateKey == null || certificates.isEmpty())) {
// Same choice as upstream: a later key replaces an earlier one until the first certificate
// has been seen.
privateKey = section.getBase64DecodedBytes();
}
}
if (certificates.isEmpty()) {
throw new IllegalArgumentException("certificate is missing from certAndKey string");
}
if (privateKey == null) {
throw new IllegalArgumentException("private key is missing from certAndKey string");
}

CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
List<X509Certificate> chain = new ArrayList<>(certificates.size());
chain.add(parseCertificate(certFactory, certificates.get(0)));
for (int i = 1; i < certificates.size(); i++) {
try {
chain.add(parseCertificate(certFactory, certificates.get(i)));
} catch (CertificateException | RuntimeException e) {
// The upstream method never parsed extra certificates; leave this one out rather than
// fail.
}
}
PrivateKey key =
KeyFactory.getInstance(chain.get(0).getPublicKey().getAlgorithm())
.generatePrivate(new PKCS8EncodedKeySpec(privateKey));
Comment thread
macastelaz marked this conversation as resolved.

KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null);
Comment thread
macastelaz marked this conversation as resolved.
keyStore.setKeyEntry("alias", key, new char[] {}, chain.toArray(new X509Certificate[0]));
return keyStore;
}

private static X509Certificate parseCertificate(CertificateFactory certFactory, byte[] der)
throws CertificateException {
return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(der));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import com.google.api.core.InternalApi;
import com.google.auth.oauth2.EnvironmentProvider;
import com.google.auth.oauth2.PropertyProvider;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.io.BaseEncoding;
import java.io.File;
Expand All @@ -58,17 +59,75 @@
static final String WELL_KNOWN_CERTIFICATE_CONFIG_FILE = "certificate_config.json";
static final String CLOUDSDK_CONFIG_DIRECTORY = "gcloud";

/**
* Well-known path of the combined certificate chain and private key bundle that GKE delivers to
* pods with Agent Identity (Pod Certificates). Used as a fallback client certificate source when
* no certificate configuration file is configured or present.
*/
static final String GKE_CREDENTIAL_BUNDLE_PATH =
"/var/run/secrets/workload-spiffe-credentials/x509.credential-bundle.private-key.pem";

private static volatile String gkeCredentialBundlePath = GKE_CREDENTIAL_BUNDLE_PATH;

private MtlsUtils() {
// Prevent instantiation for Utility class
}

/**
* Returns {@code true} if a certificate configuration is configured or present: either {@code
* GOOGLE_API_CERTIFICATE_CONFIG} is set, or the well-known gcloud {@code certificate_config.json}
* file exists. When this returns {@code true}, the GKE credential bundle fallback is not used, so
* the certificate used for mTLS and the certificate bound to tokens always come from the same
* source.
*/
public static boolean hasCertificateConfiguration(

Check warning on line 83 in google-auth-library-java/oauth2_http/java/com/google/auth/mtls/MtlsUtils.java

View workflow job for this annotation

GitHub Actions / BomContentAssertionsTest (Test for assertion logic in BomContentTest)

Check warning on line 83 in google-auth-library-java/oauth2_http/java/com/google/auth/mtls/MtlsUtils.java

View workflow job for this annotation

GitHub Actions / BomContentAssertionsTest (Test for assertion logic in BomContentTest)

no @PARAM for propProvider

Check warning on line 83 in google-auth-library-java/oauth2_http/java/com/google/auth/mtls/MtlsUtils.java

View workflow job for this annotation

GitHub Actions / BomContentAssertionsTest (Test for assertion logic in BomContentTest)

no @PARAM for envProvider

Check warning on line 83 in google-auth-library-java/oauth2_http/java/com/google/auth/mtls/MtlsUtils.java

View workflow job for this annotation

GitHub Actions / bom-content-test

Check warning on line 83 in google-auth-library-java/oauth2_http/java/com/google/auth/mtls/MtlsUtils.java

View workflow job for this annotation

GitHub Actions / bom-content-test

no @PARAM for propProvider

Check warning on line 83 in google-auth-library-java/oauth2_http/java/com/google/auth/mtls/MtlsUtils.java

View workflow job for this annotation

GitHub Actions / bom-content-test

no @PARAM for envProvider
EnvironmentProvider envProvider, PropertyProvider propProvider) {
if (!Strings.isNullOrEmpty(envProvider.getEnv(CERTIFICATE_CONFIGURATION_ENV_VARIABLE))) {
return true;
}
try {
return getWellKnownCertificateConfigFile(envProvider, propProvider).exists();
} catch (IOException e) {
// APPDATA missing on Windows, etc. No well-known configuration file.
return false;
}
}

/**
* Returns the GKE credential bundle path if no certificate configuration is configured or present
* (see {@link #hasCertificateConfiguration}) and the bundle exists and is readable; otherwise
* returns {@code null}.
*/
static @Nullable String getGkeCredentialBundlePath(
EnvironmentProvider envProvider, PropertyProvider propProvider) {
if (hasCertificateConfiguration(envProvider, propProvider)) {
return null;
}
return findGkeCredentialBundle();
}

/**
* Returns the GKE credential bundle path if it is a readable, non-empty regular file, otherwise
* null.
*/
private static @Nullable String findGkeCredentialBundle() {
File bundle = new File(gkeCredentialBundlePath);
return bundle.isFile() && bundle.canRead() && bundle.length() > 0 ? bundle.getPath() : null;
}

/** Overrides the GKE credential bundle path for testing; {@code null} restores the default. */
@VisibleForTesting
static void setGkeCredentialBundlePathForTesting(@Nullable String path) {
gkeCredentialBundlePath = path != null ? path : GKE_CREDENTIAL_BUNDLE_PATH;
}

/**
* Returns if mutual TLS client certificate should be used. Returns true if valid workload
* certificates are configured or if GOOGLE_API_USE_CLIENT_CERTIFICATE is explicitly set to true
* (e.g. for Enterprise Certificate Proxy or custom MtlsProviders), unless explicitly disabled via
* GOOGLE_API_USE_CLIENT_CERTIFICATE=false.
*/
public static boolean useMtlsClientCertificate(

Check warning on line 130 in google-auth-library-java/oauth2_http/java/com/google/auth/mtls/MtlsUtils.java

View workflow job for this annotation

GitHub Actions / BomContentAssertionsTest (Test for assertion logic in BomContentTest)

Check warning on line 130 in google-auth-library-java/oauth2_http/java/com/google/auth/mtls/MtlsUtils.java

View workflow job for this annotation

GitHub Actions / BomContentAssertionsTest (Test for assertion logic in BomContentTest)

no @PARAM for propProvider

Check warning on line 130 in google-auth-library-java/oauth2_http/java/com/google/auth/mtls/MtlsUtils.java

View workflow job for this annotation

GitHub Actions / BomContentAssertionsTest (Test for assertion logic in BomContentTest)

no @PARAM for envProvider

Check warning on line 130 in google-auth-library-java/oauth2_http/java/com/google/auth/mtls/MtlsUtils.java

View workflow job for this annotation

GitHub Actions / bom-content-test

Check warning on line 130 in google-auth-library-java/oauth2_http/java/com/google/auth/mtls/MtlsUtils.java

View workflow job for this annotation

GitHub Actions / bom-content-test

no @PARAM for propProvider

Check warning on line 130 in google-auth-library-java/oauth2_http/java/com/google/auth/mtls/MtlsUtils.java

View workflow job for this annotation

GitHub Actions / bom-content-test

no @PARAM for envProvider
EnvironmentProvider envProvider, PropertyProvider propProvider) {
String useClientCertificate = envProvider.getEnv("GOOGLE_API_USE_CLIENT_CERTIFICATE");
if ("false".equalsIgnoreCase(useClientCertificate)) {
Expand All @@ -89,16 +148,20 @@
* <ol>
* <li><b>Non-null {@link String} (Valid happy path):</b> A valid workload certificate
* configuration was found and both the certificate and private key files exist and are
* readable.
* readable; or no certificate configuration is set or present and the GKE credential bundle
* ({@code /var/run/secrets/workload-spiffe-credentials/
* x509.credential-bundle.private-key.pem}) exists and is readable, in which case the bundle
* path is returned.
* <li><b>{@link IllegalStateException} (Invalid state - fail closed):</b> An explicit {@code
* GOOGLE_API_CERTIFICATE_CONFIG} path or an existing default well-known certificate
* configuration file is missing, unreadable, malformed, or references missing/unreadable
* certificate or private key files. This is treated as an unrecoverable misconfiguration.
* <li><b>{@code null} (Safe fallback / fail open):</b> Client certificates are explicitly
* disabled via {@code GOOGLE_API_USE_CLIENT_CERTIFICATE=false}, no explicit configuration
* is set and the default well-known configuration file does not exist on disk, or the
* configuration specifies an non-workload source (e.g., ECP/PKCS11 without a {@code
* workload} section). Callers can proceed without workload certificate file polling.
* is set and neither the default well-known configuration file nor a readable GKE
* credential bundle exists on disk, or the configuration specifies an non-workload source
* (e.g., ECP/PKCS11 without a {@code workload} section). Callers can proceed without
* workload certificate file polling.
* </ol>
*/
public static @Nullable String getWorkloadCertPath(
Expand Down Expand Up @@ -175,9 +238,14 @@
checkCertAndKeyFilesReadable(config, defaultConfigFile.getAbsolutePath(), true);
return config.getCertPath();
}
// A default configuration file exists without a workload section (e.g. ECP); it takes
// precedence over the GKE credential bundle.
return null;
}

return null;
// 3. GKE credential bundle (Pod Certificates), used only when no certificate configuration
// file is configured or present. The combined bundle serves as both certificate and key.
return findGkeCredentialBundle();
}

private static void checkCertAndKeyFilesReadable(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@

import com.google.api.client.json.JsonParser;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.SecurityUtils;
import com.google.api.core.InternalApi;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
Expand Down Expand Up @@ -148,7 +147,7 @@ static KeyStore getKeyStore(InputStream metadata, ProcessProvider processProvide
}

// Create mTLS key store with the input certificates from shell command.
return SecurityUtils.createMtlsKeyStore(process.getInputStream());
return MtlsKeyStoreUtils.createMtlsKeyStore(process.getInputStream());
}

@VisibleForTesting
Expand Down
Loading
Loading