GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing github.com — feat(oauth2): Extract actor tokens for cert-bound OAuth2 STS exchange by macastelaz · Pull Request #13955 · googleapis/google-cloud-java Conversation
|
|
Before we launch lets make sure to add integration tests for each supported transport and certificate rotation scenario to make sure that bound tokens work e2e. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
Summary of changes: - Comment 1: Fix Javadoc referencing package-private API - Comment 2: Replace instanceof with isMtlsConfigured() check - Comment 3: Per-cycle cert pinning with KeyStore snapshot, 401 retry - Comment 4: Atomic subject+actor token read via readTokens() - Comment 5: Make setActorTokenSupplier/Type package-private - Comment 6: Add Javadocs to builder setter methods - Comment 7: Fix Builder copy constructor (always copy actorTokenType) - Comment 8: Annotate no-arg MtlsHttpTransportFactory with @internalapi - Comment 9: Revert class rename to FileIdentityPoolSubjectTokenSupplier - Comment 10: Remove CachedFile/volatile caching mechanism - Comment 11: Add actorTokenFieldName validation - Comment 12: Integration tests noted for follow-up PR Added overload exchangeExternalCredentialForAccessToken(request, factory) for per-cycle transport factory threading. Added 12 new unit tests covering readTokens(), validation, and mTLS. All 982 existing + new tests pass.
- Fix copyright year (2024 -> 2026) in FileIdentityPoolSubjectTokenSupplier - Add Javadoc explaining class name retained for serialization compatibility - Add hasKeyStore() to MtlsHttpTransportFactory for watertight mTLS validation - Update isMtlsConfigured() to verify KeyStore is non-null via hasKeyStore() - Update no-arg constructor Javadoc to explain serialization requirement - Add comment to Builder copy constructor explaining supplier reconstruction - Add 3 unit tests for hasKeyStore() and no-arg factory validation
|
Note that as a result of this latest iteration, I've identified and captured some additional future work to explore in subsequent PRs which I've captured here: https://paste.googleplex.com/5973231872901120 |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
| /** Functional interface for supplying an actor token for IdentityPool credentials. */ | ||
| @NullMarked | ||
| @FunctionalInterface | ||
| interface IdentityPoolActorTokenSupplier extends java.io.Serializable { |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Some thoughts about the hierarchy (not a blocker on this PR as the interface is package-private and the methods added are internal), but wanted to get your thoughts:
From reading the docs, I believe this is a deliberate design choice as not all general ExternalAccount types may have the concept of an actor_token. I have a slight worry that we may be tying the interface a little too closely to the class itself. (SubjectToken interface and now a new ActorToken interface). Expanding this in the future may result in something like PluggableActorTokenSupplier and AwsActorTokenSupplier interfaces or new interfaces for a new token type.
What do you think about having something like ExternalAccountTokenSupplier (generalized for subject and actor tokens now and can work for any new token in the future). I see the two token methods below take in ExternalAccountSupplierContext param so it may be a bit harder to generalize for more types.
public interface ExternalAccountTokenSupplier {
String getSubjectToken(ExternalAccountSupplierContext context);
String getActorToken(ExternalAccountSupplierContext context);
}
IdentityPoolSubjectTokenSupplier would extend from ExternalAccountTokenSupplier and throw an exception or return null for getActorToken.
IdentityPoolSubjectTokenSupplier interface would be marked as obsolete and we would use the more general ExternalAccountTokenSupplier. Widening the class type should be fine.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for flagging this! I definitely agree we will want to avoid a future where we would have something like "PluggableActorTokenSupplier" and "AwsActorTokenSupplier" interfaces.
With that said, I think we may hit a problem if trying to combine them into a single ExternalAccountTokenSupplier which is that I believe java limits @FunctionalInterface to having only a single abstract method and then whenever a lambda expression is provided it is used for that single abstract method.
I think if/when we expand the actor token support beyond IdentityPoolCredentials we can evaluate other options (which we won't be limited to given the package-private nature of this current solution as you called out), such as having a single ExternalAccountActorTokenSupplier (keeping it separate from the subject token but generalizing beyond cred type).
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| URI uri = URI.create(url); | ||
| String host = uri.getHost(); | ||
| if (host != null | ||
| && host.endsWith("googleapis.com") | ||
| && !host.contains(".mtls.") | ||
| && !host.contains(".p.")) { | ||
| throw new IllegalArgumentException( | ||
| "The " | ||
| + fieldName | ||
| + " endpoint (" | ||
| + url | ||
| + ") cannot be used with actor tokens because it is a plain public Google API" | ||
| + " endpoint. Please use an mTLS endpoint (e.g. containing '.mtls.') or Private" | ||
| + " Service Connect (containing '.p.')."); | ||
| } |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
One general question: Tracing through the tokenUrl flow, I see that we have a default TOKEN_URL set to be https://sts.{UNIVERSE_DOMAIN}/v1/token which then gets replaced with the proper universe domain. Can you double check that this wouldn't result in accidental IllegalArgumentException errors from this?
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Double checked this shouldn't lead to any accidental IllegalArgumentException errors. The constructor of the base ExternalAccountCredentials checks if the tokenUrl is null and if so uses the default token URL that replaces the universe domain ("https://sts.{UNIVERSE_DOMAIN}/v1/token"). That means getTokenUrl never contains the unreplaced universe domain. The only time we'd get an IllegalArgumentException is if the user doesn't specify the mtls token url while specifying an actor token requiring the mtls endpoint - but this is WAI. There is a possible world in the future, from what I've heard, where we may be able to do a token exchange on a non-mtls endpoint so leaving that door open for now seems to make the most sense to me (though we still plan to validate the user config has the mtls token url if they include the actor token).
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
…token suppliers
…nd add @nullable to getActorTokenType
There was an error while loading. Please reload this page.
| @Nullable private final IdentityPoolActorTokenSupplier actorTokenSupplier; | ||
| @Nullable private final String actorTokenType; | ||
| // Transient: not serialized directly. Reconstructed in readObject() from the credentialSource | ||
| // certificate config so deserialized credentials remain usable for mTLS and refresh. | ||
| @Nullable private transient X509Provider x509Provider; |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
nit: annotation is type-use so it should be on the type
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Shoot - sorry about that. Fixed!
Sorry, something went wrong.
There was an error while loading. Please reload this page.
# Conflicts: # google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IdentityPoolCredentials.java
There was an error while loading. Please reload this page.
No region tags are edited in this PR.This comment is generated by snippet-bot.
|
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| if (builder.transportFactory == null | ||
| || builder.transportFactory == OAuth2Utils.HTTP_TRANSPORT_FACTORY | ||
| || builder.transportFactory instanceof OAuth2Utils.DefaultHttpTransportFactory) { | ||
| this.transportFactory = new MtlsHttpTransportFactory(mtlsKeyStore); | ||
| } |
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
IIUC, since this upgrades the transportFactory to the mtls variant when there is the default transportFactory, what are the consequences when users set a custom HttpTransportFactory?
If it may not work, should we add a debug level statement? Or would it be better to throw an exception for an invalid state
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Added an else block to log at the debug level to inform users that they need to ensure that mtls is supported in their custom transport factory if mtls is required by the token endpoint.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| HttpTransportFactory cycleTransportFactory = this.transportFactory; | ||
| if (this.x509Provider != null) { | ||
| KeyStore pinnedKeyStore = this.x509Provider.getKeyStore(); | ||
| cycleTransportFactory = new MtlsHttpTransportFactory(pinnedKeyStore); |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
qq, do we need the same default transport check here as well to avoid overriding any custom transport?
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for flagging this gap - this definitely needed the same check to avoid overriding any custom transport and added a test to ensure the custom transport gets preserved across refreshes
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| if (host != null | ||
| && host.endsWith("googleapis.com") | ||
| && !host.contains(".mtls.") | ||
| && !host.contains(".p.")) { |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
nit: Can you add a small comment to explain the conditions as it was a bit hard for me to figure out immediately.
IIUC, this checks that GDU cannot work unless it's configured with PSC or MTLS right? We do allow for non-GDU, but don't explicitly check for PSC/ mTLS in those cases.
I'm sure there probably are some weird edge cases that we may not be validating here and I'm assuming that we don't intend to cover every possible case.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Added a comment clarifying the intent for GDU but not enforcing non-GDU universes.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| } catch (IllegalArgumentException e) { | ||
| throw e; |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
qq, why throw this exception again?
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
The original reason for this (keeping the desired IAE that resulted from reasons not related to URL validity) is actually no longer relevant (it's handled in the constructor of ExternalAccountCredentials which already validates the tokenUrl and serviceAccountImpersonationUrl anyways) so I was able to remove the try/catch and simplify this a bit! Thanks for flagging!
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| if (actorTokenFieldName != null) { | ||
| if (actorTokenFieldName.trim().isEmpty()) { | ||
| throw new IllegalArgumentException("The actor_token_field_name must not be empty."); | ||
| } | ||
| if (actorTokenFieldName.equals(subjectTokenFieldName)) { | ||
| throw new IllegalArgumentException( | ||
| "The actor_token_field_name must differ from the subject_token_field_name."); | ||
| } | ||
| } |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
just a general question for my curiosity (nothing wrong with validation): How often/ realistic do you think something like this would end up being the case. IIUC, these values will be generated initially by gcloud but I believe a user can simply modify the file themselves if they want. Is this something we've seen customers do in the past?
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
This check was added from an earlier review suggestion by @lsirac (comment #13955 (comment)) to fail fast on obvious misconfigurations.
You're right that when users generate the credential config directly via gcloud iam workload-identity-pools create-cred-config, gcloud outputs well-formed field names automatically. However, in practice we do see customers authoring or templating these JSON config files outside of gcloud—for example, via Terraform/IaC templates, Kubernetes ConfigMaps/Helm charts, or by copy-pasting and hand-editing an existing config file when setting up custom token suppliers.
If someone accidentally copy-pastes the same JSON key for both subject_token_field_name and actor_token_field_name (or leaves it blank in a template), failing immediately at config load time with a clear IllegalArgumentException is much easier to diagnose than sending duplicate tokens to STS and getting a generic 400 invalid_grant error during runtime token exchange.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
… add debug log, and simplify validateMtlsEndpoint
…d and avoid spurious custom transport log
1fed6d4
into
googleapis:oauth2-bound-tokens
There was an error while loading. Please reload this page.
… IdentityPoolCredentials (#14430) ## Summary Allows `actor_token` and `actor_token_type` to be used in `IdentityPoolCredentials` with standard (non-mTLS) STS and IAM impersonation endpoints and without requiring client certificate (`certificate_config`) configuration. ## Context & Rationale In #13955, client-side guardrails (`isMtlsConfigured()` and `validateMtlsEndpoint()`) were enforced in the `IdentityPoolCredentials` constructor because Google STS initially required actor tokens to be paired with certificate-bound tokens over mTLS. Per the original design discussion, this was intentionally designed as a one-way door that could be loosened in a non-breaking manner once backend support for non-mTLS actor token exchanges was ready. ## Changes 1. **Removed Constructor mTLS Restrictions:** - Removed `isMtlsConfigured()` check in `IdentityPoolCredentials(Builder)` so actor tokens can be configured with standard `HttpTransportFactory` instances and without a `certificate` block. - Removed `validateMtlsEndpoint()` checks on `tokenUrl` and `serviceAccountImpersonationUrl`, allowing standard public endpoints (e.g., `https://sts.googleapis.com/v1/token`) to be used with actor tokens. - Preserved strict pairing validation between `actorTokenSupplier` and `actorTokenType`, as well as JSON format checks for file-based actor token extraction. 2. **401 Handling & Cert Rotation:** - When `x509Provider == null` (non-mTLS credentials), `refreshAccessToken()` uses standard transport without snapshotting a `KeyStore`, and `401 Unauthorized` errors propagate immediately without retry. - When `x509Provider != null && transportFactory instanceof MtlsHttpTransportFactory` (mTLS credentials), per-cycle certificate pinning and single-retry cert reload on `401` remain unchanged. 3. **Javadoc & Test Coverage:** - Updated class-level and builder Javadocs on `IdentityPoolCredentials`. - Updated negative constructor tests to positive verification tests (`*_succeeds`). - Added `refreshAccessToken_401WithActorTokenAndNonMtlsTransport_bubblesUpWithoutRetry` and `fromStream_fileCredentialSource_withoutCertificateConfig_andActorToken_withNonMtlsUrl_refreshesSuccessfully` to verify end-to-end non-mTLS actor token exchanges. ## Verification - All **1,035** unit tests passing in `oauth2_http` module (including all **88** tests in `IdentityPoolCredentialsTest`). - 100% compliant with `fmt-maven-plugin:2.25:check`. --------- Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
…on for Workload Identity Federation (#14781) ### Summary Merges the `oauth2-bound-tokens` feature branch into `main`, adding end-to-end support for certificate-bound OAuth 2.0 tokens and automatic mTLS certificate rotation in Workload Identity Federation (`IdentityPoolCredentials` and `ImpersonatedCredentials`). #### Included Feature Branch PRs - #13955 — `feat(oauth2): Extract actor tokens for cert-bound OAuth2 STS exchange` - #14212 — `feat(oauth2): implement IAM impersonation mTLS transport pinning and 401 recovery` - #14220 — `test(oauth2): add mTLS in-process socket tests and live GCP WIF integration tests` - #14430 — `feat(oauth2): support non-mTLS token URLs and unbound actor tokens in IdentityPoolCredentials` - #14554 — `test(auth): enable mTLS and actor_token WIF integration tests by default` #### Key Capabilities - **Actor Token Support for Hybrid Certificate-Bound WIF (`IdentityPoolActorTokenSupplier`, `FileIdentityPoolSubjectTokenSupplier`)**: - Supports extracting both a primary X.509 leaf certificate subject token and a secondary file-sourced `actor_token` (text or JSON via `actor_token_field_name` and `actor_token_type`) for STS token exchange. - Caches file-sourced tokens using file metadata (`mtime`, size, file key) and JWT `exp` claims with a 5-minute expiration margin to avoid redundant disk reads. - **Per-Cycle mTLS Transport Pinning & Certificate Rotation (`IdentityPoolCredentials`, `ImpersonatedCredentials`, `MtlsHttpTransportFactory`)**: - Snapshots the `KeyStore` once per refresh cycle so leaf certificate extraction, the STS token exchange, and downstream IAM Service Account impersonation (`generateAccessToken` / `generateIdToken`) share the exact same certificate and private key snapshot. - Automatically recovers from `401 Unauthorized`, OAuth `invalid_grant`, and transient TLS/KeyStore load failures during non-atomic split cert/key writes by reloading the `KeyStore` once and retrying when a certificate change is detected (`OAuth2Utils.hasCertificateChanged`). - Supports standalone `ImpersonatedCredentials` configured with `MtlsProvider` as well as delegated `ImpersonatedCredentials` chains. - **Test Coverage**: - Comprehensive unit tests across `IdentityPoolCredentialsTest`, `ImpersonatedCredentialsTest`, `FileIdentityPoolSubjectTokenSupplierTest`, `MtlsHttpTransportFactoryTest`, `OAuth2UtilsTest`, and `OAuthExceptionTest`. - In-process mTLS socket tests (`MtlsPipelineLocalTest`) and live GCP Workload Identity Federation integration tests (`ITWorkloadIdentityFederationTest`). ### Manual & Live Verification End-to-end live GCP and real-TLS socket fault-injection testing was executed against `oauth2-bound-tokens` (`65d592bd783`): - **Full verification report, logs, and test harness**: https://paste.googleplex.com/6755399436525184 - **Scenarios verified (15 / 15 passed)**: 1. **Live Direct mTLS STS Exchange (`sts.mtls.googleapis.com`)**: File-based JSON `subject_token` + `actor_token` with RFC 8705 `cnf.x5t#S256` certificate binding and atomic single-supplier file reads. 2. **Serialization Round-Trip (`readObject`) + `createScoped()`**: Deserialization of `IdentityPoolCredentials` with mTLS state reconstruction across multiple live STS refresh cycles. 3. **Full 3-Hop Live mTLS Chain (`STS mTLS` -> `IAM Impersonation mTLS` -> `GCS mTLS`)**: Cert-bound workload + actor token exchange at `sts.mtls.googleapis.com`, service account impersonation at `iamcredentials.mtls.googleapis.com`, and bucket access at `storage.mtls.googleapis.com` (`HTTP 200`). 4. **Programmatic Builder (`Suppliers` + `MtlsHttpTransportFactory`) Live 3-Hop mTLS**: End-to-end `STS mTLS` -> `IAM mTLS` -> `GCS mTLS` (`HTTP 200`) and verification of `OAuth2Utils` mTLS helpers (`hasMtlsKeyStore`, `isKeylessMtlsTransportFactory`, `isDefaultOrMtlsTransportFactory`). 5. **Non-mTLS Unbound Actor Token over Public Endpoints**: Unbound `subject_token` + `actor_token` exchange over public `sts.googleapis.com` -> `iamcredentials.googleapis.com` -> `storage.googleapis.com` (`HTTP 200`). 6. **X.509 Certificate Workload Identity Federation**: Leaf certificate extraction and `trust_chain` handshake against `sts.mtls.googleapis.com` via `CertificateIdentityPoolSubjectTokenSupplier`. 7. **`PluggableAuthCredentials` Impersonation Transport Reconciliation**: Rebuilding `PluggableAuthCredentials` with a custom `HttpTransportFactory` and verifying both STS and `ImpersonatedCredentials` use the reconciled transport against live STS, IAM, and GCS (`HTTP 200`). 8. **Review Feedback Edge Cases**: `FileIdentityPoolSubjectTokenSupplier` TEXT format subject/actor token handling and `OAuthException.createFromJsonErrorResponse` parsing across live STS 400 errors, nested `google.rpc.Status` JSON, and empty-body HTTP error fallbacks. 9. **Real-TLS Socket Fault Injection**: Mid-cycle cert rotation pinning between STS and IAM, `401 Unauthorized` IAM recovery (both fresh and cached STS token eviction), `400 invalid_grant` STS cert rotation recovery, and 8-thread concurrent mTLS refresh. --------- Co-authored-by: Jin Seop Kim <[email protected]> Co-authored-by: Blake Li <[email protected]> Co-authored-by: Sakthivel Subramanian <[email protected]> Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
There was an error while loading. Please reload this page.
Successfully merging this pull request may close these issues.
There was an error while loading. Please reload this page.