-
Notifications
You must be signed in to change notification settings - Fork 128
[googleapis_auth] Support external_account credentials for Workload Identity Federation #727
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
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,209 @@ | ||
| // Copyright 2026 Google LLC | ||
| // | ||
| // Use of this source code is governed by a BSD-style | ||
| // license that can be found in the LICENSE file or at | ||
| // https://developers.google.com/open-source/licenses/bsd | ||
|
|
||
| import 'dart:convert'; | ||
| import 'dart:io'; | ||
|
|
||
| import 'package:http/http.dart' as http; | ||
|
|
||
| import 'auth_http_utils.dart'; | ||
| import 'service_account_credentials.dart'; | ||
| import 'utils.dart'; | ||
|
|
||
| /// An authenticated HTTP client that exchanges an external credential for a | ||
| /// Google access token using the Google Security Token Service (STS) API. | ||
| /// | ||
| /// This client allows external workloads (like AWS, Azure, OIDC) to access | ||
| /// Google Cloud resources using Workload Identity Federation. | ||
| class StsAuthClient extends AutoRefreshDelegatingClient { | ||
| final Map<String, dynamic> _credentialSource; | ||
| final String _audience; | ||
| final String _subjectTokenType; | ||
| final String _tokenUrl; | ||
| final List<String> _scopes; | ||
| final String? _quotaProject; | ||
|
|
||
| AccessCredentials _credentials; | ||
| http.Client? _authClient; | ||
|
|
||
| /// Creates an [StsAuthClient] instance. | ||
| /// | ||
| /// [credentialSource] is a map describing how to retrieve the external token. | ||
| /// It typically contains a 'file' or 'url' key. | ||
| /// | ||
| /// [audience] is the audience for the token exchange. | ||
| /// | ||
| /// [subjectTokenType] specifies the type of the external token (e.g., | ||
| /// `urn:ietf:params:oauth:token-type:jwt`). | ||
| /// | ||
| /// [tokenUrl] is the endpoint for the token exchange, usually | ||
| /// `https://sts.googleapis.com/v1/token`. | ||
| /// | ||
| /// [scopes] are the OAuth2 scopes to request. | ||
| /// | ||
| /// [baseClient] is an optional [http.Client] that will be used for | ||
| /// the returned client's authenticated requests and for retrieving external | ||
| /// tokens. | ||
| StsAuthClient({ | ||
| required Map<String, dynamic> credentialSource, | ||
| required String audience, | ||
| required String subjectTokenType, | ||
| required String tokenUrl, | ||
| required List<String> scopes, | ||
| String? quotaProject, | ||
| http.Client? baseClient, | ||
| }) : _credentialSource = credentialSource, | ||
| _audience = audience, | ||
| _subjectTokenType = subjectTokenType, | ||
| _tokenUrl = tokenUrl, | ||
| _scopes = List.unmodifiable(scopes), | ||
| _quotaProject = quotaProject, | ||
| _credentials = AccessCredentials( | ||
| AccessToken('Bearer', '', DateTime.now().toUtc()), | ||
| null, | ||
| scopes, | ||
| ), | ||
| super( | ||
| baseClient ?? http.Client(), | ||
| closeUnderlyingClient: baseClient == null, | ||
| ); | ||
|
|
||
| @override | ||
| AccessCredentials get credentials => _credentials; | ||
|
|
||
| /// Injects the generated credentials. Set internally during initialization. | ||
| set initialCredentials(AccessCredentials credentials) { | ||
| _credentials = credentials; | ||
| } | ||
|
|
||
| /// Generates a new access token via STS token exchange. | ||
| /// | ||
| /// This retrieves the subject token and exchanges it for a federated access | ||
| /// token via the STS API. | ||
| Future<AccessCredentials> generateAccessToken() async { | ||
| final subjectToken = await _getSubjectToken(); | ||
|
|
||
| final responseJson = await baseClient.requestJson( | ||
| 'POST', | ||
| Uri.parse(_tokenUrl), | ||
| 'Failed to exchange external account credential for access token.', | ||
| headers: {'Content-Type': 'application/json'}, | ||
| body: jsonEncode({ | ||
| 'audience': _audience, | ||
| 'grantType': 'urn:ietf:params:oauth:grant-type:token-exchange', | ||
| 'requestedTokenType': 'urn:ietf:params:oauth:token-type:access_token', | ||
| 'subjectTokenType': _subjectTokenType, | ||
| 'subjectToken': subjectToken, | ||
| 'scope': _scopes.join(' '), | ||
| }), | ||
| ); | ||
|
|
||
| final (accessToken, expiresIn) = switch (responseJson) { | ||
| {'access_token': final String t, 'expires_in': final int e} => (t, e), | ||
| _ => throw ServerRequestFailedException( | ||
| 'STS generateAccessToken response missing required fields.', | ||
| responseContent: responseJson, | ||
| ), | ||
| }; | ||
|
|
||
| return AccessCredentials( | ||
| AccessToken('Bearer', accessToken, expiryDate(expiresIn)), | ||
| null, | ||
| _scopes, | ||
| ); | ||
| } | ||
|
|
||
| Future<String> _getSubjectToken() async { | ||
| if (_credentialSource.containsKey('file')) { | ||
| final fileField = _credentialSource['file'] as String; | ||
| return await File(fileField).readAsString(); | ||
| } else if (_credentialSource.containsKey('url')) { | ||
| final url = _credentialSource['url'] as String; | ||
| final headers = _credentialSource['headers'] as Map<String, dynamic>?; | ||
| final format = _credentialSource['format'] as Map<String, dynamic>?; | ||
|
|
||
| final parsedHeaders = headers?.map( | ||
| (key, value) => MapEntry(key, value.toString()), | ||
| ); | ||
|
|
||
| final response = await baseClient.get( | ||
| Uri.parse(url), | ||
| headers: parsedHeaders, | ||
| ); | ||
|
|
||
| if (response.statusCode != 200) { | ||
| throw Exception( | ||
| 'Failed to retrieve subject token from URL: $url. ' | ||
| 'Status code: ${response.statusCode}, Body: ${response.body}', | ||
| ); | ||
| } | ||
|
|
||
| var token = response.body; | ||
|
|
||
| if (format != null && format['type'] == 'json') { | ||
| final json = jsonDecode(token) as Map<String, dynamic>; | ||
| final subjectTokenFieldName = | ||
| format['subject_token_field_name'] as String; | ||
| token = json[subjectTokenFieldName] as String; | ||
| } | ||
| return token; | ||
| } | ||
| throw UnsupportedError( | ||
| 'Unsupported credential source type. Must provide file or url.', | ||
| ); | ||
| } | ||
|
|
||
| @override | ||
| Future<http.StreamedResponse> send(http.BaseRequest request) async { | ||
| if (_credentials.accessToken.hasExpired) { | ||
| final newCredentials = await generateAccessToken(); | ||
| notifyAboutNewCredentials(newCredentials); | ||
| _credentials = newCredentials; | ||
| _authClient = AuthenticatedClient( | ||
| baseClient, | ||
| _credentials, | ||
| quotaProject: _quotaProject, | ||
| ); | ||
| } | ||
|
|
||
| _authClient ??= AuthenticatedClient( | ||
| baseClient, | ||
| _credentials, | ||
| quotaProject: _quotaProject, | ||
| ); | ||
| return _authClient!.send(request); | ||
| } | ||
| } | ||
|
|
||
| /// Obtains oauth2 credentials by exchanging an external credential for a | ||
| /// Google access token. | ||
| Future<StsAuthClient> clientViaStsTokenExchange({ | ||
| required Map<String, dynamic> credentialSource, | ||
| required String audience, | ||
| required String subjectTokenType, | ||
| required String tokenUrl, | ||
| required List<String> scopes, | ||
| String? quotaProject, | ||
| http.Client? baseClient, | ||
| }) async { | ||
| final stsClient = StsAuthClient( | ||
| credentialSource: credentialSource, | ||
| audience: audience, | ||
| subjectTokenType: subjectTokenType, | ||
| tokenUrl: tokenUrl, | ||
| scopes: scopes, | ||
| quotaProject: quotaProject, | ||
| baseClient: baseClient, | ||
| ); | ||
|
|
||
| try { | ||
| stsClient.initialCredentials = await stsClient.generateAccessToken(); | ||
| return stsClient; | ||
| } catch (e) { | ||
| stsClient.close(); | ||
| rethrow; | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
The
_getSubjectTokenmethod uses unsafe casts (as) which can lead to runtime errors if thecredential_sourcemap has an unexpected structure. It would be more robust to use pattern matching to safely access and cast values from the map. Additionally, throwing a genericExceptionfor HTTP failures is not ideal; a more specific exception likeServerRequestFailedExceptionwould be more consistent with the rest of the codebase and provide better error handling for consumers.