Repository navigation
fix(auth): validate and use service_account_impersonation_url host #19224
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
+463
−14
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
7a30b38
fix(auth): propagate top-level universe_domain in impersonated creds
ohmayr 69f91b9
fix(auth): validate and use service_account_impersonation_url host
ohmayr e9f028f
fix(auth): validate missing source_credentials in impersonated loader
ohmayr a1df949
chore(auth): merge main and resolve impersonated_credentials conflicts
ohmayr 0da9ff0
fix(auth): reject backslash in service_account_impersonation_url
ohmayr aa2344a
fix(auth): normalize default-universe subdomains and update docs
ohmayr 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 |
|---|---|---|
|
|
@@ -26,12 +26,15 @@ | |
| """ | ||
|
|
||
| import base64 | ||
| import collections.abc | ||
| import copy | ||
| import http.client as http_client | ||
| import json | ||
| import logging | ||
| import re | ||
| import urllib.parse | ||
| from datetime import datetime | ||
| from typing import TYPE_CHECKING, Optional | ||
| from typing import TYPE_CHECKING, Any, Optional, Tuple | ||
|
|
||
| from google.auth import ( | ||
| _exponential_backoff, | ||
|
|
@@ -63,6 +66,72 @@ | |
| "external_account_authorized_user" | ||
| ) | ||
|
|
||
| _DNS_LABEL = r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?" | ||
| _IAM_HOST_PATTERN = re.compile( | ||
| rf"^(?:{_DNS_LABEL}[.-])?iamcredentials" | ||
| rf"(?:-{_DNS_LABEL}\.p|\.p|\.{_DNS_LABEL}\.rep(?:\.mtls)?|\.mtls)?" | ||
| rf"\.({_DNS_LABEL}(?:\.{_DNS_LABEL})+)$" | ||
| ) | ||
|
|
||
|
|
||
| def _extract_universe_from_iam_host(hostname: str) -> Optional[str]: | ||
| """Extracts the universe domain from a Google IAM Credentials hostname. | ||
|
|
||
| Recognizes standard global, regional (``<region>-iamcredentials.<u_d>`` or | ||
| ``<region>.iamcredentials.<u_d>``), REP | ||
| (``iamcredentials.<region>.rep[.mtls].<u_d>``), PSC | ||
| (``iamcredentials[-<ep>].p.<u_d>``), and mTLS | ||
| (``iamcredentials.mtls.<u_d>``) hostnames. Returns ``None`` for custom | ||
| proxy hostnames. | ||
| """ | ||
| match = _IAM_HOST_PATTERN.fullmatch(hostname.lower()) | ||
| if not match: | ||
| return None | ||
| universe = match.group(1) | ||
| if universe.endswith(f".{credentials.DEFAULT_UNIVERSE_DOMAIN}"): | ||
| return credentials.DEFAULT_UNIVERSE_DOMAIN | ||
| return universe | ||
|
|
||
|
|
||
| def _parse_impersonation_url(impersonation_url: Any) -> Tuple[str, str]: | ||
| """Validates an impersonation URL and extracts ``(target_principal, hostname)``. | ||
|
|
||
| Raises: | ||
| google.auth.exceptions.InvalidValue: If ``impersonation_url`` is not a | ||
| valid HTTPS ``:generateAccessToken`` URL with a non-empty target | ||
| principal. | ||
| """ | ||
| error_msg = f"Cannot extract target principal from {impersonation_url}" | ||
| if ( | ||
| not isinstance(impersonation_url, str) | ||
| or "#" in impersonation_url | ||
| or "\\" in impersonation_url | ||
| or any(ch.isspace() or ord(ch) < 0x20 for ch in impersonation_url) | ||
| ): | ||
| raise exceptions.InvalidValue(error_msg) | ||
| try: | ||
| parsed = urllib.parse.urlsplit(impersonation_url) | ||
| hostname = (parsed.hostname or "").removesuffix(".") | ||
| _ = parsed.port | ||
| except ValueError as exc: | ||
| raise exceptions.InvalidValue(error_msg) from exc | ||
|
|
||
| start_index = parsed.path.rfind("/") | ||
| if ( | ||
| parsed.scheme != "https" | ||
| or not hostname | ||
| or "@" in parsed.netloc | ||
| or not parsed.path.endswith(":generateAccessToken") | ||
| or start_index == -1 | ||
| ): | ||
| raise exceptions.InvalidValue(error_msg) | ||
|
|
||
| target_principal = parsed.path[start_index + 1 : -len(":generateAccessToken")] | ||
| if not target_principal: | ||
| raise exceptions.InvalidValue(error_msg) | ||
|
|
||
| return target_principal, hostname | ||
|
|
||
|
|
||
| def _make_iam_token_request( | ||
| request, | ||
|
|
@@ -500,7 +569,7 @@ def from_impersonated_service_account_info(cls, info, scopes=None): | |
| Refer https://cloud.google.com/docs/authentication/external/externally-sourced-credentials for more details. | ||
|
|
||
| Args: | ||
| info (Mapping[str, str]): The impersonated service account credentials info in Google | ||
| info (Mapping[str, Any]): The impersonated service account credentials info in Google | ||
| format. | ||
| scopes (Sequence[str]): Optional list of scopes to include in the | ||
| credentials. | ||
|
|
@@ -517,22 +586,53 @@ def from_impersonated_service_account_info(cls, info, scopes=None): | |
| """ | ||
|
|
||
| source_credentials_info = info.get("source_credentials") | ||
|
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. This seems to contradict the docstrings:
Contributor
Author
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. Updated the |
||
| if not isinstance(source_credentials_info, collections.abc.Mapping): | ||
| raise exceptions.InvalidValue( | ||
| "The 'source_credentials' field is required in the impersonated service account info." | ||
| ) | ||
| impersonation_url = info.get("service_account_impersonation_url") | ||
| target_principal, url_host = _parse_impersonation_url(impersonation_url) | ||
| url_universe = _extract_universe_from_iam_host(url_host) | ||
|
|
||
| universe_domain = info.get("universe_domain") | ||
| source_universe_domain = source_credentials_info.get("universe_domain") | ||
| if source_universe_domain is not None: | ||
| _helpers.validate_universe_domain(source_universe_domain) | ||
| elif universe_domain is not None: | ||
| explicit_universe = ( | ||
| universe_domain if universe_domain is not None else source_universe_domain | ||
| ) | ||
| if explicit_universe is not None: | ||
| _helpers.validate_universe_domain(explicit_universe) | ||
| if url_universe is not None: | ||
| _helpers.compare_universe_domains(explicit_universe, url_universe) | ||
| elif ( | ||
| explicit_universe.lower() != credentials.DEFAULT_UNIVERSE_DOMAIN | ||
| and _helpers.has_default_universe_host(f"https://{url_host}") | ||
| ): | ||
| raise exceptions.InvalidValue( | ||
| f"Non-default universe domain ({explicit_universe}) cannot " | ||
| f"use default-universe impersonation URL host ({url_host})." | ||
| ) | ||
| elif ( | ||
| url_universe is not None | ||
| and url_universe != credentials.DEFAULT_UNIVERSE_DOMAIN | ||
| ): | ||
| universe_domain = url_universe | ||
|
|
||
| if source_universe_domain is None and universe_domain is not None: | ||
| source_credentials_info = { | ||
| **source_credentials_info, | ||
| "universe_domain": universe_domain, | ||
| } | ||
|
|
||
| source_credentials_type = source_credentials_info.get("type") | ||
| if source_credentials_type == _SOURCE_CREDENTIAL_AUTHORIZED_USER_TYPE: | ||
| from google.oauth2 import credentials | ||
| from google.oauth2 import credentials as oauth2_credentials | ||
|
|
||
| source_credentials = credentials.Credentials.from_authorized_user_info( | ||
| source_credentials_info | ||
| source_credentials = ( | ||
| oauth2_credentials.Credentials.from_authorized_user_info( | ||
| source_credentials_info | ||
| ) | ||
| ) | ||
| elif source_credentials_type == _SOURCE_CREDENTIAL_SERVICE_ACCOUNT_TYPE: | ||
| from google.oauth2 import service_account | ||
|
|
@@ -556,25 +656,31 @@ def from_impersonated_service_account_info(cls, info, scopes=None): | |
| ) | ||
| ) | ||
|
|
||
| impersonation_url = info.get("service_account_impersonation_url") | ||
| start_index = impersonation_url.rfind("/") | ||
| end_index = impersonation_url.find(":generateAccessToken") | ||
| if start_index == -1 or end_index == -1 or start_index > end_index: | ||
| raise exceptions.InvalidValue( | ||
| "Cannot extract target principal from {}".format(impersonation_url) | ||
| ) | ||
| target_principal = impersonation_url[start_index + 1 : end_index] | ||
| delegates = info.get("delegates") | ||
| quota_project_id = info.get("quota_project_id") | ||
| scopes = scopes or info.get("scopes") | ||
| trust_boundary = info.get("trust_boundary") | ||
|
|
||
| # Leave iam_endpoint_override unset for the exact standard default URL | ||
| # so mTLS endpoint selection via iam._IAM_ENDPOINT stays intact; keep | ||
| # the override for regional, custom-universe, and proxy URLs. | ||
| default_impersonation_url = ( | ||
| "https://iamcredentials.{}/v1/projects/-/serviceAccounts/{}" | ||
| ":generateAccessToken" | ||
| ).format(credentials.DEFAULT_UNIVERSE_DOMAIN, target_principal) | ||
| iam_endpoint_override = ( | ||
| None | ||
| if impersonation_url == default_impersonation_url | ||
| else impersonation_url | ||
| ) | ||
|
|
||
| return cls( | ||
| source_credentials, | ||
| target_principal, | ||
| scopes, | ||
| delegates, | ||
| quota_project_id=quota_project_id, | ||
| iam_endpoint_override=iam_endpoint_override, | ||
| trust_boundary=trust_boundary, | ||
| universe_domain=universe_domain, | ||
| ) | ||
|
|
||
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.
If
source_credentialsis missing from theinfodictionary,source_credentials_infowill beNone. This will lead to a crypticAttributeErrorwhen trying to access.get("universe_domain")or.get("type")on it later in the method. It is highly recommended to validate thatsource_credentials_infois notNoneand raise a clearexceptions.InvalidValueexception if it is missing.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.
Added an explicit Mapping check for source_credentials in commit be24566 so missing or non-mapping values raise InvalidValue instead of AttributeError, along with unit tests.