From 0ca3bcf8d68013c1982ea6f8f6a5e94fc3c4bf07 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Tue, 1 Dec 2026 15:52:52 +0000 Subject: [PATCH 1/3] chore(auth): add _build_iam_endpoint helper in iam --- packages/google-auth/google/auth/iam.py | 64 ++++++++ packages/google-auth/tests/test_iam.py | 186 ++++++++++++++++++++++++ 2 files changed, 250 insertions(+) diff --git a/packages/google-auth/google/auth/iam.py b/packages/google-auth/google/auth/iam.py index 46ae558c5198..f85388f71ba7 100644 --- a/packages/google-auth/google/auth/iam.py +++ b/packages/google-auth/google/auth/iam.py @@ -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 @@ -56,6 +58,68 @@ _IAM_IDTOKEN_ENDPOINT = _IAM_BASE_URL + ":generateIdToken" +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.`` 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 ``:generateAccessToken`` URL 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}" + ) + if parsed.path.endswith(":generateAccessToken"): + path = parsed.path[: -len(":generateAccessToken")] + f":{action}" + else: + base_path = parsed.path.rstrip("/") + path = f"{base_path}/v1/projects/-/serviceAccounts/{target_principal}:{action}" + return urllib.parse.urlunsplit(parsed._replace(path=path)) + + class Signer(crypt.Signer): """Signs messages using the IAM `signBlob API`_. diff --git a/packages/google-auth/tests/test_iam.py b/packages/google-auth/tests/test_iam.py index 51e045e9864d..beed6dc7cb29 100644 --- a/packages/google-auth/tests/test_iam.py +++ b/packages/google-auth/tests/test_iam.py @@ -110,3 +110,189 @@ 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/sa@example.com:generateAccessToken", + id="default_universe", + ), + pytest.param( + "GOOGLEAPIS.COM", + None, + "generateIdToken", + "https://iamcredentials.googleapis.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateIdToken", + id="default_universe_uppercase", + ), + pytest.param( + "example.com", + None, + "signBlob", + "https://iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/sa@example.com:signBlob", + id="custom_universe_sign_blob", + ), + pytest.param( + "example.com", + None, + "signJwt", + "https://iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/sa@example.com:signJwt", + id="custom_universe_sign_jwt", + ), + pytest.param( + "example.com", + "https://us-east1-iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken?alt=json", + "generateIdToken", + "https://us-east1-iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateIdToken?alt=json", + id="override_rewrites_action_and_preserves_query", + ), + pytest.param( + "example.com", + "https://us-east1-iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken?alt=json", + "generateAccessToken", + "https://us-east1-iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken?alt=json", + id="override_preserves_generate_access_token", + ), + pytest.param( + "googleapis.com", + "https://proxy.example.com/iam/", + "signBlob", + "https://proxy.example.com/iam/v1/projects/-" + "/serviceAccounts/sa@example.com: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/sa@example.com: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/sa@example.com: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("sa@example.com", 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/sa@example.com:signBlob", + id="default_universe_uses_mtls", + ), + pytest.param( + "GOOGLEAPIS.COM", + "https://iamcredentials.mtls.googleapis.com/v1/projects/-" + "/serviceAccounts/sa@example.com:signBlob", + id="default_universe_uppercase_uses_mtls", + ), + pytest.param( + "example.com", + "https://iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/sa@example.com: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( + "sa@example.com", + 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("sa@example.com") + == "https://iamcredentials.custom.universe.domain/v1/projects/-" + "/serviceAccounts/sa@example.com: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( + "sa@example.com", "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( + "sa@example.com", bad_universe_domain, None, "generateIdToken" + ) From 2699fb9e05c6ab4e3b1766952d2d642532c8c8ba Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Tue, 1 Dec 2026 15:59:19 +0000 Subject: [PATCH 2/3] chore(auth): rewrite all IAM action suffixes in _build_iam_endpoint --- packages/google-auth/google/auth/iam.py | 17 ++++++++++++---- packages/google-auth/tests/test_iam.py | 27 +++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/packages/google-auth/google/auth/iam.py b/packages/google-auth/google/auth/iam.py index f85388f71ba7..4bff0971b3ff 100644 --- a/packages/google-auth/google/auth/iam.py +++ b/packages/google-auth/google/auth/iam.py @@ -57,6 +57,13 @@ _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, @@ -75,8 +82,8 @@ def _build_iam_endpoint( 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 ``:generateAccessToken`` URL or a base origin / - path prefix). + 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"``). @@ -112,8 +119,10 @@ def _build_iam_endpoint( raise exceptions.InvalidValue( f"Invalid iam_endpoint_override: {iam_endpoint_override}" ) - if parsed.path.endswith(":generateAccessToken"): - path = parsed.path[: -len(":generateAccessToken")] + f":{action}" + 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}" diff --git a/packages/google-auth/tests/test_iam.py b/packages/google-auth/tests/test_iam.py index beed6dc7cb29..43bf1f1ac053 100644 --- a/packages/google-auth/tests/test_iam.py +++ b/packages/google-auth/tests/test_iam.py @@ -165,6 +165,33 @@ def test_sign_bytes_retryable_failure(self, mock_time): "/serviceAccounts/sa@example.com:generateAccessToken?alt=json", id="override_preserves_generate_access_token", ), + pytest.param( + "example.com", + "https://us-east1-iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/sa@example.com:signBlob", + "generateIdToken", + "https://us-east1-iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateIdToken", + id="override_rewrites_sign_blob", + ), + pytest.param( + "example.com", + "https://us-east1-iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/sa@example.com:signJwt", + "signBlob", + "https://us-east1-iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/sa@example.com:signBlob", + id="override_rewrites_sign_jwt", + ), + pytest.param( + "example.com", + "https://us-east1-iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateIdToken", + "generateAccessToken", + "https://us-east1-iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken", + id="override_rewrites_generate_id_token", + ), pytest.param( "googleapis.com", "https://proxy.example.com/iam/", From 5873a01527ccfe3a8676b08d1e35ce1a0f9a5599 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Wed, 2 Dec 2026 18:15:27 +0000 Subject: [PATCH 3/3] chore(auth): tighten iam_endpoint_override validation and strip trailing slash --- packages/google-auth/google/auth/iam.py | 34 +++++++++++--- packages/google-auth/tests/test_iam.py | 60 +++++++++++++++++++++++-- 2 files changed, 83 insertions(+), 11 deletions(-) diff --git a/packages/google-auth/google/auth/iam.py b/packages/google-auth/google/auth/iam.py index 4bff0971b3ff..4f906240db1e 100644 --- a/packages/google-auth/google/auth/iam.py +++ b/packages/google-auth/google/auth/iam.py @@ -94,9 +94,10 @@ def _build_iam_endpoint( 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. + ``iam_endpoint_override`` is not a valid HTTPS URL without + userinfo, fragments, whitespace, or control characters. """ - if not iam_endpoint_override: + if iam_endpoint_override is None or iam_endpoint_override == "": _helpers.validate_universe_domain(universe_domain) if universe_domain.lower() == credentials.DEFAULT_UNIVERSE_DOMAIN: domain = _IAM_DOMAIN @@ -107,25 +108,44 @@ def _build_iam_endpoint( f"serviceAccounts/{target_principal}:{action}" ) + if ( + not isinstance(iam_endpoint_override, str) + or "#" in iam_endpoint_override + or not iam_endpoint_override.isprintable() + or any(ch.isspace() for ch in iam_endpoint_override) + ): + raise exceptions.InvalidValue( + f"Invalid iam_endpoint_override: {iam_endpoint_override}" + ) + try: parsed = urllib.parse.urlsplit(iam_endpoint_override) hostname = parsed.hostname + _ = parsed.port except ValueError as exc: raise exceptions.InvalidValue( f"Invalid iam_endpoint_override: {iam_endpoint_override}" ) from exc - if not parsed.scheme or not hostname: + if ( + parsed.scheme != "https" + or not iam_endpoint_override[len(parsed.scheme) :].startswith("://") + or "@" in parsed.netloc + or not hostname + ): raise exceptions.InvalidValue( f"Invalid iam_endpoint_override: {iam_endpoint_override}" ) + + stripped_path = parsed.path.rstrip("/") for known_action in _IAM_ACTIONS: - if parsed.path.endswith(f":{known_action}"): - path = parsed.path[: -len(known_action)] + action + if stripped_path.endswith(f":{known_action}"): + path = stripped_path[: -len(known_action)] + action break else: - base_path = parsed.path.rstrip("/") - path = f"{base_path}/v1/projects/-/serviceAccounts/{target_principal}:{action}" + path = ( + f"{stripped_path}/v1/projects/-/serviceAccounts/{target_principal}:{action}" + ) return urllib.parse.urlunsplit(parsed._replace(path=path)) diff --git a/packages/google-auth/tests/test_iam.py b/packages/google-auth/tests/test_iam.py index 43bf1f1ac053..3eef2212362d 100644 --- a/packages/google-auth/tests/test_iam.py +++ b/packages/google-auth/tests/test_iam.py @@ -216,6 +216,31 @@ def test_sign_bytes_retryable_failure(self, mock_time): "/serviceAccounts/sa@example.com:signBlob", id="override_origin_with_trailing_slash", ), + pytest.param( + "googleapis.com", + "", + "signBlob", + "https://iamcredentials.googleapis.com/v1/projects/-" + "/serviceAccounts/sa@example.com:signBlob", + id="empty_override_uses_default", + ), + pytest.param( + "example.com", + "https://us-east1-iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken/", + "signBlob", + "https://us-east1-iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/sa@example.com:signBlob", + id="override_rewrites_action_with_trailing_slash", + ), + pytest.param( + "googleapis.com", + "https://proxy.example.com:8443/iam/", + "signBlob", + "https://proxy.example.com:8443/iam/v1/projects/-" + "/serviceAccounts/sa@example.com:signBlob", + id="override_with_explicit_port", + ), ], ) def test_build_iam_endpoint(universe_domain, override, action, expected_url): @@ -293,10 +318,37 @@ def test_build_iam_endpoint_template_placeholder(): @pytest.mark.parametrize( "bad_override", [ - "us-east1-iamcredentials.googleapis.com", - "https://", - "https://:443/path", - "https://[invalid", + pytest.param("us-east1-iamcredentials.googleapis.com", id="schemeless"), + pytest.param("http://us-east1-iamcredentials.example.com", id="plaintext_http"), + pytest.param("ftp://us-east1-iamcredentials.example.com", id="ftp_scheme"), + pytest.param("https:us-east1-iamcredentials.example.com", id="missing_slashes"), + pytest.param("https://", id="missing_host"), + pytest.param("https://:443/path", id="missing_host_with_port"), + pytest.param("https://[invalid", id="malformed_ipv6"), + pytest.param("https://iamcredentials.example.com:abc", id="non_numeric_port"), + pytest.param( + "https://iamcredentials.example.com:99999", id="out_of_range_port" + ), + pytest.param( + "https://user@iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken", + id="userinfo_in_netloc", + ), + pytest.param( + "https://iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/sa@example.com:generateAccessToken#frag", + id="fragment", + ), + pytest.param( + "https://iamcredentials.example.com/path with space", id="inner_space" + ), + pytest.param(" https://iamcredentials.example.com", id="leading_space"), + pytest.param("https://iamcredentials.example.com/\tpath", id="tab_char"), + pytest.param("https://iamcredentials.example.com/\x00path", id="control_char"), + pytest.param(123, id="non_str_int"), + pytest.param(0, id="non_str_falsy_int"), + pytest.param([], id="non_str_empty_list"), + pytest.param(b"https://iamcredentials.example.com", id="non_str_bytes"), ], ) def test_build_iam_endpoint_invalid_override(bad_override):