Repository navigation
chore(auth): add _build_iam_endpoint helper #19298
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
Open
parthea
wants to merge
2
commits into
main
Choose a base branch
from
chore/auth-build-iam-endpoint
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+286
−0
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -22,6 +22,8 @@ | |
| import base64 | ||
| import http.client as http_client | ||
| import json | ||
| import urllib.parse | ||
| from typing import Optional | ||
|
|
||
| from google.auth import _exponential_backoff, _helpers, credentials, crypt, exceptions | ||
| from google.auth.transport import _mtls_helper | ||
|
|
@@ -55,6 +57,77 @@ | |
| _IAM_SIGNJWT_ENDPOINT = _IAM_BASE_URL + ":signJwt" | ||
| _IAM_IDTOKEN_ENDPOINT = _IAM_BASE_URL + ":generateIdToken" | ||
|
|
||
| _IAM_ACTIONS = ( | ||
| "generateAccessToken", | ||
| "generateIdToken", | ||
| "signBlob", | ||
| "signJwt", | ||
| ) | ||
|
|
||
|
|
||
| def _build_iam_endpoint( | ||
| target_principal: str, | ||
| universe_domain: str, | ||
| iam_endpoint_override: Optional[str], | ||
| action: str, | ||
| ) -> str: | ||
| """Builds an IAM Credentials API URL, using ``iam_endpoint_override`` when set. | ||
|
|
||
| When ``iam_endpoint_override`` is not set, uses ``_IAM_DOMAIN`` (which | ||
| respects mTLS configuration) for the default universe domain and | ||
| ``iamcredentials.<universe_domain>`` for non-default universe domains. | ||
|
|
||
| Args: | ||
| target_principal (str): The target service account email (or ``"{}"`` | ||
| to produce a format template). | ||
| universe_domain (str): The configured universe domain. | ||
| iam_endpoint_override (Optional[str]): Optional IAM endpoint override | ||
| URL (either a full IAM Credentials RPC URL such as | ||
| ``:generateAccessToken`` or a base origin / path prefix). | ||
| action (str): The IAM Credentials API RPC suffix (for example, | ||
| ``"generateAccessToken"``, ``"signBlob"``, ``"signJwt"``, or | ||
| ``"generateIdToken"``). | ||
|
|
||
| Returns: | ||
| str: The resolved IAM Credentials API endpoint URL. | ||
|
|
||
| Raises: | ||
| google.auth.exceptions.InvalidValue: If ``universe_domain`` is invalid | ||
| when ``iam_endpoint_override`` is unset, or if | ||
| ``iam_endpoint_override`` is missing a URL scheme or host. | ||
| """ | ||
| if not iam_endpoint_override: | ||
| _helpers.validate_universe_domain(universe_domain) | ||
| if universe_domain.lower() == credentials.DEFAULT_UNIVERSE_DOMAIN: | ||
| domain = _IAM_DOMAIN | ||
| else: | ||
| domain = f"iamcredentials.{universe_domain}" | ||
| return ( | ||
| f"https://{domain}/v1/projects/-/" | ||
| f"serviceAccounts/{target_principal}:{action}" | ||
| ) | ||
|
|
||
| try: | ||
| parsed = urllib.parse.urlsplit(iam_endpoint_override) | ||
| hostname = parsed.hostname | ||
| except ValueError as exc: | ||
| raise exceptions.InvalidValue( | ||
| f"Invalid iam_endpoint_override: {iam_endpoint_override}" | ||
| ) from exc | ||
|
|
||
| if not parsed.scheme or not hostname: | ||
| raise exceptions.InvalidValue( | ||
| f"Invalid iam_endpoint_override: {iam_endpoint_override}" | ||
| ) | ||
| for known_action in _IAM_ACTIONS: | ||
| if parsed.path.endswith(f":{known_action}"): | ||
| path = parsed.path[: -len(known_action)] + action | ||
| break | ||
| else: | ||
| base_path = parsed.path.rstrip("/") | ||
| path = f"{base_path}/v1/projects/-/serviceAccounts/{target_principal}:{action}" | ||
| return urllib.parse.urlunsplit(parsed._replace(path=path)) | ||
|
Comment on lines
+122
to
+129
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. If |
||
|
|
||
|
|
||
| class Signer(crypt.Signer): | ||
| """Signs messages using the IAM `signBlob API`_. | ||
|
|
||
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 |
|---|---|---|
|
|
@@ -110,3 +110,216 @@ def test_sign_bytes_retryable_failure(self, mock_time): | |
| with pytest.raises(exceptions.TransportError): | ||
| signer.sign("123") | ||
| request.call_count == 3 | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "universe_domain,override,action,expected_url", | ||
| [ | ||
| pytest.param( | ||
| "googleapis.com", | ||
| None, | ||
| "generateAccessToken", | ||
| "https://iamcredentials.googleapis.com/v1/projects/-" | ||
| "/serviceAccounts/[email protected]:generateAccessToken", | ||
| id="default_universe", | ||
| ), | ||
| pytest.param( | ||
| "GOOGLEAPIS.COM", | ||
| None, | ||
| "generateIdToken", | ||
| "https://iamcredentials.googleapis.com/v1/projects/-" | ||
| "/serviceAccounts/[email protected]:generateIdToken", | ||
| id="default_universe_uppercase", | ||
| ), | ||
| pytest.param( | ||
| "example.com", | ||
| None, | ||
| "signBlob", | ||
| "https://iamcredentials.example.com/v1/projects/-" | ||
| "/serviceAccounts/[email protected]:signBlob", | ||
| id="custom_universe_sign_blob", | ||
| ), | ||
| pytest.param( | ||
| "example.com", | ||
| None, | ||
| "signJwt", | ||
| "https://iamcredentials.example.com/v1/projects/-" | ||
| "/serviceAccounts/[email protected]:signJwt", | ||
| id="custom_universe_sign_jwt", | ||
| ), | ||
| pytest.param( | ||
| "example.com", | ||
| "https://us-east1-iamcredentials.example.com/v1/projects/-" | ||
| "/serviceAccounts/[email protected]:generateAccessToken?alt=json", | ||
| "generateIdToken", | ||
| "https://us-east1-iamcredentials.example.com/v1/projects/-" | ||
| "/serviceAccounts/[email protected]:generateIdToken?alt=json", | ||
| id="override_rewrites_action_and_preserves_query", | ||
| ), | ||
| pytest.param( | ||
| "example.com", | ||
| "https://us-east1-iamcredentials.example.com/v1/projects/-" | ||
| "/serviceAccounts/[email protected]:generateAccessToken?alt=json", | ||
| "generateAccessToken", | ||
| "https://us-east1-iamcredentials.example.com/v1/projects/-" | ||
| "/serviceAccounts/[email protected]:generateAccessToken?alt=json", | ||
| id="override_preserves_generate_access_token", | ||
| ), | ||
| pytest.param( | ||
| "example.com", | ||
| "https://us-east1-iamcredentials.example.com/v1/projects/-" | ||
| "/serviceAccounts/[email protected]:signBlob", | ||
| "generateIdToken", | ||
| "https://us-east1-iamcredentials.example.com/v1/projects/-" | ||
| "/serviceAccounts/[email protected]:generateIdToken", | ||
| id="override_rewrites_sign_blob", | ||
| ), | ||
| pytest.param( | ||
| "example.com", | ||
| "https://us-east1-iamcredentials.example.com/v1/projects/-" | ||
| "/serviceAccounts/[email protected]:signJwt", | ||
| "signBlob", | ||
| "https://us-east1-iamcredentials.example.com/v1/projects/-" | ||
| "/serviceAccounts/[email protected]:signBlob", | ||
| id="override_rewrites_sign_jwt", | ||
| ), | ||
| pytest.param( | ||
| "example.com", | ||
| "https://us-east1-iamcredentials.example.com/v1/projects/-" | ||
| "/serviceAccounts/[email protected]:generateIdToken", | ||
| "generateAccessToken", | ||
| "https://us-east1-iamcredentials.example.com/v1/projects/-" | ||
| "/serviceAccounts/[email protected]:generateAccessToken", | ||
| id="override_rewrites_generate_id_token", | ||
| ), | ||
| pytest.param( | ||
| "googleapis.com", | ||
| "https://proxy.example.com/iam/", | ||
| "signBlob", | ||
| "https://proxy.example.com/iam/v1/projects/-" | ||
| "/serviceAccounts/[email protected]:signBlob", | ||
| id="override_proxy_path_prefix", | ||
| ), | ||
| pytest.param( | ||
| "googleapis.com", | ||
| "https://us-east1-iamcredentials.googleapis.com", | ||
| "signBlob", | ||
| "https://us-east1-iamcredentials.googleapis.com/v1/projects/-" | ||
| "/serviceAccounts/[email protected]:signBlob", | ||
| id="override_origin_only", | ||
| ), | ||
| pytest.param( | ||
| "googleapis.com", | ||
| "https://us-east1-iamcredentials.googleapis.com/", | ||
| "signBlob", | ||
| "https://us-east1-iamcredentials.googleapis.com/v1/projects/-" | ||
| "/serviceAccounts/[email protected]:signBlob", | ||
| id="override_origin_with_trailing_slash", | ||
| ), | ||
| ], | ||
| ) | ||
| def test_build_iam_endpoint(universe_domain, override, action, expected_url): | ||
| with mock.patch("google.auth.iam._IAM_DOMAIN", "iamcredentials.googleapis.com"): | ||
| assert ( | ||
| iam._build_iam_endpoint("[email protected]", universe_domain, override, action) | ||
| == expected_url | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "universe_domain,expected_url", | ||
| [ | ||
| pytest.param( | ||
| "googleapis.com", | ||
| "https://iamcredentials.mtls.googleapis.com/v1/projects/-" | ||
| "/serviceAccounts/[email protected]:signBlob", | ||
| id="default_universe_uses_mtls", | ||
| ), | ||
| pytest.param( | ||
| "GOOGLEAPIS.COM", | ||
| "https://iamcredentials.mtls.googleapis.com/v1/projects/-" | ||
| "/serviceAccounts/[email protected]:signBlob", | ||
| id="default_universe_uppercase_uses_mtls", | ||
| ), | ||
| pytest.param( | ||
| "example.com", | ||
| "https://iamcredentials.example.com/v1/projects/-" | ||
| "/serviceAccounts/[email protected]:signBlob", | ||
| id="non_default_universe_omits_mtls", | ||
| ), | ||
| ], | ||
| ) | ||
| def test_build_iam_endpoint_mtls_scoped_to_default_universe( | ||
| universe_domain, expected_url | ||
| ): | ||
| with mock.patch( | ||
| "google.auth.iam._IAM_DOMAIN", "iamcredentials.mtls.googleapis.com" | ||
| ): | ||
| url = iam._build_iam_endpoint( | ||
| "[email protected]", | ||
| universe_domain, | ||
| None, | ||
| "signBlob", | ||
| ) | ||
| assert url == expected_url | ||
|
|
||
|
|
||
| def test_build_iam_endpoint_template_placeholder(): | ||
| default_template = iam._build_iam_endpoint( | ||
| "{}", | ||
| google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN, | ||
| None, | ||
| "generateIdToken", | ||
| ) | ||
| assert default_template == iam._IAM_IDTOKEN_ENDPOINT | ||
|
|
||
| custom_template = iam._build_iam_endpoint( | ||
| "{}", | ||
| "custom.universe.domain", | ||
| None, | ||
| "generateIdToken", | ||
| ) | ||
| assert ( | ||
| custom_template == "https://iamcredentials.custom.universe.domain/v1/projects/-" | ||
| "/serviceAccounts/{}:generateIdToken" | ||
| ) | ||
| assert ( | ||
| custom_template.format("[email protected]") | ||
| == "https://iamcredentials.custom.universe.domain/v1/projects/-" | ||
| "/serviceAccounts/[email protected]:generateIdToken" | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "bad_override", | ||
| [ | ||
| "us-east1-iamcredentials.googleapis.com", | ||
| "https://", | ||
| "https://:443/path", | ||
| "https://[invalid", | ||
| ], | ||
| ) | ||
| def test_build_iam_endpoint_invalid_override(bad_override): | ||
| with pytest.raises(exceptions.InvalidValue, match="Invalid iam_endpoint_override"): | ||
| iam._build_iam_endpoint( | ||
| "[email protected]", "googleapis.com", bad_override, "signBlob" | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "bad_universe_domain", | ||
| [ | ||
| None, | ||
| "", | ||
| " ", | ||
| "example.com/path", | ||
| ], | ||
| ) | ||
| def test_build_iam_endpoint_invalid_universe_domain(bad_universe_domain): | ||
| with pytest.raises( | ||
| exceptions.InvalidValue, | ||
| match="Universe domain must be a valid non-empty domain string.", | ||
| ): | ||
| iam._build_iam_endpoint( | ||
| "[email protected]", bad_universe_domain, None, "generateIdToken" | ||
| ) | ||
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.
Could we tighten the
iam_endpoint_overridecheck a bit? Right now it accepts non-HTTPS schemes (likeftp://orhttp://), invalid ports (likehttps://host:abcsinceparsed.portis not checked), userinfo (@in netloc), fragments (#), and whitespace/control chars, and non-str inputs raiseAttributeError/TypeErrorinstead ofInvalidValue. Checkingisinstance(..., str), rejecting whitespace/control chars,#, and@, touchingparsed.port, and restricting tohttpswould match the rest ofgoogle-auth.