-
Notifications
You must be signed in to change notification settings - Fork 1.2k
feat(oauth2): Extract actor tokens for cert-bound OAuth2 STS exchange #13955
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: oauth2-bound-tokens
Are you sure you want to change the base?
Changes from all commits
a4813a2
c739b37
1a32e6f
c42bd53
803dd53
cbcce28
745d26b
48c29d2
178d71d
c22c521
1aa5036
474f0d7
62b8bd5
3288350
8dbaa6f
48ee795
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
|
@@ -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. | ||
|
|
@@ -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() { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think this can break callers compiled against the old signature. Can we keep the NetHttpTransport return type and use composition / test-specific abstraction instead? |
||
| try { | ||
| // Build the mTLS transport using the provided KeyStore. | ||
| return new NetHttpTransport.Builder().trustCertificates(null, mtlsKeyStore, "").build(); | ||
|
|
||
| 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 | ||
|
|
@@ -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; | ||
|
|
@@ -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; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Before this PR, private final long serialVersionUID = ...Java serialization did not treat it as the class UID as it was not static. This PR changes it to: private static final long serialVersionUID = ...I think existing serialized credentials will fail with Also, the |
||
|
|
||
| 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); | ||
| } | ||
| } | ||
|
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; | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
should we check mtlsKeyStore.size() > 0?