Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
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 @@ -31,13 +31,15 @@

package com.google.auth.mtls;

import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.core.InternalApi;
import com.google.auth.http.HttpTransportFactory;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.util.Objects;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;

/**
* An HttpTransportFactory that creates {@link NetHttpTransport} instances configured for mTLS
Expand All @@ -50,7 +52,17 @@
@NullMarked
@InternalApi
public class MtlsHttpTransportFactory implements HttpTransportFactory {
private final KeyStore mtlsKeyStore;
@Nullable private final KeyStore mtlsKeyStore;

/**
* No-arg constructor required for Java serialization. {@link IdentityPoolCredentials} stores this
* factory in its serializable {@code transportFactory} field, and {@link
* java.io.ObjectInputStream} needs a no-arg constructor to reconstruct it during deserialization.
* Not intended for direct use; callers should use {@link #MtlsHttpTransportFactory(KeyStore)}.
*/
public MtlsHttpTransportFactory() {
this.mtlsKeyStore = null;
}

/**
* Constructs a factory for mTLS transports.
Expand All @@ -63,8 +75,17 @@ public MtlsHttpTransportFactory(KeyStore mtlsKeyStore) {
this.mtlsKeyStore = Objects.requireNonNull(mtlsKeyStore, "mtlsKeyStore cannot be null");
}

/**
* Returns whether this factory was constructed with a non-null {@link KeyStore} containing client
* certificates for mTLS. A factory created via the no-arg constructor (e.g. during
* deserialization) will return {@code false}.
*/
public boolean hasKeyStore() {
return this.mtlsKeyStore != null;
}

@Override
public NetHttpTransport create() {
public HttpTransport create() {
try {
// Build the mTLS transport using the provided KeyStore.
return new NetHttpTransport.Builder().trustCertificates(null, mtlsKeyStore, "").build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,8 @@ protected ExternalAccountCredentials(ExternalAccountCredentials.Builder builder)
this.workforcePoolUserProject = builder.workforcePoolUserProject;
if (workforcePoolUserProject != null && !isWorkforcePoolConfiguration()) {
throw new IllegalArgumentException(
"The workforce_pool_user_project parameter should only be provided for a Workforce Pool configuration.");
"The workforce_pool_user_project parameter should only be provided for a Workforce Pool"
+ " configuration.");
}

validateTokenUrl(tokenUrl);
Expand Down Expand Up @@ -431,6 +432,7 @@ static ExternalAccountCredentials fromJson(
Map<String, Object> json, HttpTransportFactory transportFactory) {
String audience = (String) json.get("audience");
String subjectTokenType = (String) json.get("subject_token_type");
String actorTokenType = (String) json.get("actor_token_type");
String tokenUrl = (String) json.get("token_url");

Map<String, Object> credentialSourceMap = (Map<String, Object>) json.get("credential_source");
Expand Down Expand Up @@ -487,6 +489,7 @@ static ExternalAccountCredentials fromJson(
.setHttpTransportFactory(transportFactory)
.setAudience(audience)
.setSubjectTokenType(subjectTokenType)
.setActorTokenType(actorTokenType)
.setTokenUrl(tokenUrl)
.setTokenInfoUrl(tokenInfoUrl)
.setCredentialSource(new IdentityPoolCredentialSource(credentialSourceMap))
Expand Down Expand Up @@ -531,6 +534,22 @@ private boolean shouldBuildImpersonatedCredential() {
*/
protected AccessToken exchangeExternalCredentialForAccessToken(
StsTokenExchangeRequest stsTokenExchangeRequest) throws IOException {
return exchangeExternalCredentialForAccessToken(stsTokenExchangeRequest, this.transportFactory);
}

/**
* Exchanges the external credential for a Google Cloud access token using the specified transport
* factory. This overload allows callers to provide a per-cycle transport factory, for example one
* pinned to a specific mTLS certificate.
*
* @param stsTokenExchangeRequest the Security Token Service token exchange request
* @param cycleTransportFactory the HTTP transport factory to use for this exchange
* @return the access token returned by the Security Token Service
* @throws OAuthException if the call to the Security Token Service fails
*/
protected AccessToken exchangeExternalCredentialForAccessToken(
StsTokenExchangeRequest stsTokenExchangeRequest, HttpTransportFactory cycleTransportFactory)
throws IOException {
// Handle service account impersonation if necessary.
if (this.shouldBuildImpersonatedCredential()) {
this.impersonatedCredentials = this.buildImpersonatedCredentials();
Expand All @@ -541,7 +560,9 @@ protected AccessToken exchangeExternalCredentialForAccessToken(

StsRequestHandler.Builder requestHandler =
StsRequestHandler.newBuilder(
tokenUrl, stsTokenExchangeRequest, transportFactory.create().createRequestFactory());
tokenUrl,
stsTokenExchangeRequest,
cycleTransportFactory.create().createRequestFactory());

// If this credential was initialized with a Workforce configuration then the
// workforcePoolUserProject must be passed to the Security Token Service via the internal
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2024 Google LLC
* Copyright 2026 Google LLC
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
Expand Down Expand Up @@ -31,12 +31,14 @@

package com.google.auth.oauth2;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.util.Data;
import com.google.auth.oauth2.IdentityPoolCredentialSource.CredentialFormatType;
import com.google.common.io.CharStreams;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
Expand All @@ -45,59 +47,161 @@
import java.nio.file.LinkOption;
import java.nio.file.Paths;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;

/**
* Internal provider for retrieving the subject tokens for {@link IdentityPoolCredentials} to
* exchange for GCP access tokens via a local file.
* Internal provider for retrieving the subject and actor tokens for {@link IdentityPoolCredentials}
* to exchange for GCP access tokens via a local file.
*
* <p>Note: Despite the name, this class handles both subject <em>and</em> actor tokens. The class
* name retains "Subject" for serialization backward compatibility; renaming it would break
* deserialization of previously serialized credentials.
*/
@NullMarked
class FileIdentityPoolSubjectTokenSupplier implements IdentityPoolSubjectTokenSupplier {
class FileIdentityPoolSubjectTokenSupplier
implements IdentityPoolSubjectTokenSupplier, IdentityPoolActorTokenSupplier {

private final long serialVersionUID = 2475549052347431992L;
private static final long serialVersionUID = 2475549052347431992L;

private final IdentityPoolCredentialSource credentialSource;

/**
* Constructor for FileIdentitySubjectTokenProvider
*
* @param credentialSource the credential source to use.
*/
FileIdentityPoolSubjectTokenSupplier(IdentityPoolCredentialSource credentialSource) {
this.credentialSource = credentialSource;
this.credentialSource = checkNotNull(credentialSource, "credentialSource cannot be null");
}

@Override
public String getSubjectToken(ExternalAccountSupplierContext context) throws IOException {
String credentialFilePath = this.credentialSource.getCredentialLocation();
return getToken(credentialSource.subjectTokenFieldName);
}

@Override
public String getActorToken(ExternalAccountSupplierContext context) throws IOException {
if (credentialSource.credentialFormatType == CredentialFormatType.TEXT) {
throw new IllegalArgumentException(
"Actor tokens are only supported for JSON-formatted credential files with distinct field"
+ " names.");
}
return getToken(credentialSource.actorTokenFieldName);
}

/**
* Reads the credential file once and returns both the subject and actor tokens atomically.
*
* <p>This method ensures that both tokens are extracted from the same file read, avoiding
* potential race conditions when the file is being updated between reads.
*
* @param context the supplier context
* @return a {@link TokenPair} containing both the subject and actor tokens
* @throws IOException if the file cannot be read or the required fields are missing
*/
TokenPair readTokens(ExternalAccountSupplierContext context) throws IOException {
String credentialFilePath = credentialSource.getCredentialLocation();
if (!Files.exists(Paths.get(credentialFilePath), LinkOption.NOFOLLOW_LINKS)) {
throw new IOException(
String.format(
"Invalid credential location. The file at %s does not exist.", credentialFilePath));
}
try {
return parseToken(
Files.newInputStream(new File(credentialFilePath).toPath()), this.credentialSource);
} catch (IOException e) {

if (credentialSource.credentialFormatType != CredentialFormatType.JSON) {
throw new IOException(
"Error when attempting to read the subject token from the credential file.", e);
"readTokens() is only supported for JSON-formatted credential sources.");
}

GenericJson parsedJson = readAndParseJsonFile(credentialFilePath);

String subjectFieldName = credentialSource.subjectTokenFieldName;
if (subjectFieldName == null) {
throw new IOException("Subject token field name must be specified for JSON credentials.");
}
String subject = extractField(parsedJson, subjectFieldName);

String actor = null;
if (credentialSource.actorTokenFieldName != null) {
actor = extractField(parsedJson, credentialSource.actorTokenFieldName);
}

return new TokenPair(subject, actor);
}

static String parseToken(InputStream inputStream, IdentityPoolCredentialSource credentialSource)
throws IOException {
if (credentialSource.credentialFormatType == CredentialFormatType.TEXT) {
private String getToken(@Nullable String targetFieldName) throws IOException {
String credentialFilePath = credentialSource.getCredentialLocation();
if (!Files.exists(Paths.get(credentialFilePath), LinkOption.NOFOLLOW_LINKS)) {
throw new IOException(
String.format(
"Invalid credential location. The file at %s does not exist.", credentialFilePath));
}

if (credentialSource.credentialFormatType == CredentialFormatType.JSON) {
if (targetFieldName == null) {
throw new IOException("Target field name must be specified for JSON credentials.");
}
GenericJson parsedJson = readAndParseJsonFile(credentialFilePath);
return extractField(parsedJson, targetFieldName);
}

try (InputStream inputStream = Files.newInputStream(Paths.get(credentialFilePath))) {
BufferedReader reader =
new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
return CharStreams.toString(reader);
} catch (IOException e) {
throw new IOException("Error when attempting to read the token from the credential file.", e);
}
}
Comment thread
macastelaz marked this conversation as resolved.

private static GenericJson readAndParseJsonFile(String credentialFilePath) throws IOException {
try (InputStream inputStream = Files.newInputStream(Paths.get(credentialFilePath))) {
JsonObjectParser parser = new JsonObjectParser(OAuth2Utils.JSON_FACTORY);
return parser.parseAndClose(inputStream, StandardCharsets.UTF_8, GenericJson.class);
} catch (Exception e) {
throw new IOException("Error when attempting to read the token from the credential file.", e);
}
}

private static String extractField(GenericJson json, String fieldName) throws IOException {
Object value = json.get(fieldName);
if (value == null || Data.isNull(value)) {
throw new IOException("Invalid token field name. No token was found for field: " + fieldName);
}
return value.toString();
}

/** Used primarily for UrlIdentityPoolSubjectTokenSupplier */
static String parseToken(
InputStream inputStream,
IdentityPoolCredentialSource credentialSource,
@Nullable String targetFieldName)
throws IOException {
try (InputStream in = inputStream;
java.io.Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8)) {
if (credentialSource.credentialFormatType == CredentialFormatType.TEXT) {
return CharStreams.toString(new BufferedReader(reader));
}

if (targetFieldName == null) {
throw new IOException("Target field name must be specified for JSON credentials.");
}

JsonObjectParser parser = new JsonObjectParser(OAuth2Utils.JSON_FACTORY);
GenericJson fileContents =
parser.parseAndClose(in, StandardCharsets.UTF_8, GenericJson.class);

Object value = fileContents.get(targetFieldName);
if (value == null || Data.isNull(value)) {
throw new IOException(
"Invalid token field name. No token was found for field: " + targetFieldName);
}
return value.toString();
}
}

JsonObjectParser parser = new JsonObjectParser(OAuth2Utils.JSON_FACTORY);
GenericJson fileContents =
parser.parseAndClose(inputStream, StandardCharsets.UTF_8, GenericJson.class);
/** Holds a pair of subject and actor tokens read atomically from the same file. */
static class TokenPair {
final String subject;
@Nullable final String actor;

if (!fileContents.containsKey(credentialSource.subjectTokenFieldName)) {
throw new IOException("Invalid subject token field name. No subject token was found.");
TokenPair(String subject, @Nullable String actor) {
this.subject = subject;
this.actor = actor;
}
return (String) fileContents.get(credentialSource.subjectTokenFieldName);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* 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.oauth2;

import java.io.IOException;
import org.jspecify.annotations.NullMarked;

/** Functional interface for supplying an actor token for IdentityPool credentials. */
@NullMarked
@FunctionalInterface
interface IdentityPoolActorTokenSupplier extends java.io.Serializable {

/**
* Returns a valid actor token as a string.
*
* @param context the context to use to fetch the actor token
* @return the actor token string
* @throws IOException if there was an error retrieving the token
*/
String getActorToken(ExternalAccountSupplierContext context) throws IOException;
}
Loading
Loading