diff --git a/packages/google-auth/google/auth/iam.py b/packages/google-auth/google/auth/iam.py index 46ae558c5198..08add9399342 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 @@ -55,6 +57,81 @@ _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.`` 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, or has + an invalid port. + """ + 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 + _ = 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: + raise exceptions.InvalidValue( + f"Invalid iam_endpoint_override: {iam_endpoint_override}" + ) + stripped_path = parsed.path.rstrip("/") + for known_action in _IAM_ACTIONS: + if stripped_path.endswith(f":{known_action}"): + path = stripped_path[: -len(known_action)] + action + break + else: + path = ( + f"{stripped_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/google/auth/impersonated_credentials.py b/packages/google-auth/google/auth/impersonated_credentials.py index 76fbacf750c3..15199ce5894a 100644 --- a/packages/google-auth/google/auth/impersonated_credentials.py +++ b/packages/google-auth/google/auth/impersonated_credentials.py @@ -91,9 +91,9 @@ def _make_iam_token_request( `iamcredentials.googleapis.com` is not enabled or the `Service Account Token Creator` is not assigned """ - iam_endpoint = iam_endpoint_override or iam._IAM_ENDPOINT.replace( - credentials.DEFAULT_UNIVERSE_DOMAIN, universe_domain - ).format(principal) + iam_endpoint = iam._build_iam_endpoint( + principal, universe_domain, iam_endpoint_override, "generateAccessToken" + ) body = json.dumps(body).encode("utf-8") @@ -237,9 +237,12 @@ def __init__( quota_project_id (Optional[str]): The project ID used for quota and billing. This project may be different from the project used to create the credentials. - iam_endpoint_override (Optional[str]): The full IAM endpoint override - with the target_principal embedded. This is useful when supporting - impersonation with regional endpoints. + iam_endpoint_override (Optional[str]): Optional IAM endpoint override + URL (either a full ``:generateAccessToken`` URL with + ``target_principal`` embedded, or a base origin / path prefix). + Used for token refresh, ``sign_bytes``, and + ``IDTokenCredentials.refresh`` (useful for regional endpoints + and proxies). subject (Optional[str]): sub field of a JWT. This field should only be set if you wish to impersonate as a user. This feature is useful when using domain wide delegation. @@ -401,9 +404,12 @@ def _build_regional_access_boundary_lookup_url( def sign_bytes(self, message): from google.auth.transport.requests import AuthorizedSession - iam_sign_endpoint = iam._IAM_SIGN_ENDPOINT.replace( - credentials.DEFAULT_UNIVERSE_DOMAIN, self.universe_domain - ).format(self._target_principal) + iam_sign_endpoint = iam._build_iam_endpoint( + self._target_principal, + self.universe_domain, + self._iam_endpoint_override, + "signBlob", + ) body = { "payload": base64.b64encode(message).decode("utf-8"), @@ -647,10 +653,12 @@ def with_quota_project(self, quota_project_id): def refresh(self, request): from google.auth.transport.requests import AuthorizedSession - iam_sign_endpoint = iam._IAM_IDTOKEN_ENDPOINT.replace( - credentials.DEFAULT_UNIVERSE_DOMAIN, + iam_sign_endpoint = iam._build_iam_endpoint( + self._target_credentials.signer_email, self._target_credentials.universe_domain, - ).format(self._target_credentials.signer_email) + self._target_credentials._iam_endpoint_override, + "generateIdToken", + ) body = { "audience": self._target_audience, diff --git a/packages/google-auth/tests/test_iam.py b/packages/google-auth/tests/test_iam.py index 51e045e9864d..197a647dfac9 100644 --- a/packages/google-auth/tests/test_iam.py +++ b/packages/google-auth/tests/test_iam.py @@ -110,3 +110,185 @@ 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", + ), + 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/", + "signBlob", + "https://us-east1-iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/sa@example.com:signBlob", + id="override_rewrites_action_with_trailing_slash", + ), + 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/", + "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_host", + [ + pytest.param( + "googleapis.com", + "iamcredentials.mtls.googleapis.com", + id="default_universe_uses_mtls", + ), + pytest.param( + "GOOGLEAPIS.COM", + "iamcredentials.mtls.googleapis.com", + id="default_universe_uppercase_uses_mtls", + ), + pytest.param( + "example.com", + "iamcredentials.example.com", + id="custom_universe_omits_mtls", + ), + ], +) +def test_build_iam_endpoint_mtls_scoped_to_default_universe( + universe_domain, expected_host +): + 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 == f"https://{expected_host}/v1/projects/-" + "/serviceAccounts/sa@example.com:signBlob" + ) + + +@pytest.mark.parametrize( + "bad_override", + [ + "us-east1-iamcredentials.googleapis.com", + "//us-east1-iamcredentials.googleapis.com", + "https://", + "https://:443/path", + "https://user@/path", + "https://[invalid", + "https://us-east1-iamcredentials.googleapis.com:notaport/v1", + ], +) +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" + ) diff --git a/packages/google-auth/tests/test_impersonated_credentials.py b/packages/google-auth/tests/test_impersonated_credentials.py index 777a2d3dd523..259d8a3901a5 100644 --- a/packages/google-auth/tests/test_impersonated_credentials.py +++ b/packages/google-auth/tests/test_impersonated_credentials.py @@ -1087,6 +1087,145 @@ def test_sign_jwt_request_invalid_response_error(self): ) assert excinfo.value.args[1] == "invalid_data" + @pytest.mark.parametrize( + "iam_endpoint_override,expected_sign_url", + [ + pytest.param( + "https://us-east1-iamcredentials.googleapis.com/v1/projects/-" + "/serviceAccounts/impersonated@project.iam.gserviceaccount.com:generateAccessToken", + "https://us-east1-iamcredentials.googleapis.com/v1/projects/-" + "/serviceAccounts/impersonated@project.iam.gserviceaccount.com:signBlob", + id="full_generate_access_token_url", + ), + pytest.param( + "https://iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/impersonated@project.iam.gserviceaccount.com:generateAccessToken?alt=json", + "https://iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/impersonated@project.iam.gserviceaccount.com:signBlob?alt=json", + id="full_url_with_query", + ), + pytest.param( + "https://proxy.example.com/iam/", + "https://proxy.example.com/iam/v1/projects/-" + "/serviceAccounts/impersonated@project.iam.gserviceaccount.com:signBlob", + id="proxy_base_url_with_path_prefix", + ), + pytest.param( + "https://us-east1-iamcredentials.googleapis.com", + "https://us-east1-iamcredentials.googleapis.com/v1/projects/-" + "/serviceAccounts/impersonated@project.iam.gserviceaccount.com:signBlob", + id="origin_only_override", + ), + ], + ) + def test_sign_bytes_uses_iam_endpoint_override( + self, + iam_endpoint_override, + expected_sign_url, + mock_authorizedsession_sign, + ): + creds = self.make_credentials( + lifetime=None, iam_endpoint_override=iam_endpoint_override + ) + signature = creds.sign_bytes(b"signed bytes") + + assert signature == b"signature" + mock_authorizedsession_sign.assert_called_once_with( + mock.ANY, + "POST", + expected_sign_url, + None, + json={"payload": "c2lnbmVkIGJ5dGVz", "delegates": []}, + headers={"Content-Type": "application/json"}, + ) + + def test_sign_bytes_rejects_schemeless_iam_endpoint_override(self): + creds = self.make_credentials( + lifetime=None, + iam_endpoint_override="us-east1-iamcredentials.googleapis.com", + ) + with pytest.raises( + exceptions.InvalidValue, match="Invalid iam_endpoint_override" + ): + creds.sign_bytes(b"signed bytes") + + @pytest.mark.parametrize( + "iam_endpoint_override,expected_token_url", + [ + pytest.param( + "https://proxy.example.com/iam/", + "https://proxy.example.com/iam/v1/projects/-" + "/serviceAccounts/impersonated@project.iam.gserviceaccount.com:generateAccessToken", + id="proxy_base_url_with_path_prefix", + ), + pytest.param( + "https://us-east1-iamcredentials.googleapis.com", + "https://us-east1-iamcredentials.googleapis.com/v1/projects/-" + "/serviceAccounts/impersonated@project.iam.gserviceaccount.com:generateAccessToken", + id="origin_only_override", + ), + ], + ) + def test_refresh_expands_iam_endpoint_override( + self, iam_endpoint_override, expected_token_url, mock_donor_credentials + ): + creds = self.make_credentials( + lifetime=None, iam_endpoint_override=iam_endpoint_override + ) + expire_time = ( + _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500) + ).isoformat("T") + "Z" + request = self.make_request( + data=json.dumps({"accessToken": "token", "expireTime": expire_time}), + status=http_client.OK, + ) + + creds.refresh(request) + + assert creds.valid + assert request.call_args[1]["url"] == expected_token_url + + def test_refresh_rejects_schemeless_iam_endpoint_override( + self, mock_donor_credentials + ): + creds = self.make_credentials( + lifetime=None, + iam_endpoint_override="us-east1-iamcredentials.googleapis.com", + ) + request = self.make_request(data="{}", status=http_client.OK) + + with pytest.raises( + exceptions.InvalidValue, match="Invalid iam_endpoint_override" + ): + creds.refresh(request) + + def test_id_token_refresh_uses_iam_endpoint_override( + self, mock_authorizedsession_idtoken + ): + override = ( + "https://us-east1-iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/impersonated@project.iam.gserviceaccount.com:generateAccessToken" + ) + source = service_account.Credentials( + SIGNER, "some@email.com", TOKEN_URI, universe_domain="example.com" + ) + target_creds = self.make_credentials( + lifetime=None, source_credentials=source, iam_endpoint_override=override + ) + id_creds = impersonated_credentials.IDTokenCredentials( + target_creds, target_audience="https://example.com" + ) + request = mock.create_autospec(transport.Request) + + id_creds.refresh(request) + + assert id_creds.token == ID_TOKEN_DATA + assert ( + mock_authorizedsession_idtoken.call_args[0][2] + == "https://us-east1-iamcredentials.example.com/v1/projects/-" + "/serviceAccounts/impersonated@project.iam.gserviceaccount.com:generateIdToken" + ) + @pytest.mark.parametrize( "source_info", [