Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions packages/google-auth/google/auth/iam.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -56,6 +58,53 @@
_IAM_IDTOKEN_ENDPOINT = _IAM_BASE_URL + ":generateIdToken"


def _build_iam_endpoint(

@chalmerlowe chalmerlowe Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SYNC WARNING:

I noticed a sync issue between #19194 (_get_iam_idtoken_endpoint) and #19219 (_build_iam_endpoint), which both add IAM Credentials API URL builders in packages/google-auth/google/auth/iam.py. And which see to be trying to build out:

f"https://{host_prefix}{universe_domain}/v1/projects/-/"
f"serviceAccounts/{target_principal}:{action}"

I recommend the following actions:

  • Combine these two functions into a single helper in google/auth/iam.py (using _build_iam_endpoint so it covers generateAccessToken, signBlob, generateIdToken, and iam_endpoint_override).
  • Scope the mtls. host prefix strictly to googleapis.com (matching #19194 and google.api_core.universe.get_api_endpoint), rather than prepending mtls. to non-default universes.
  • Import that single helper directly across google-auth in whichever PR lands second (no # TODO(universe-domain): copy needed since both live in google-auth).

I know that you have better context on this than I do, so if any of these suggestions are wrong, please leave a comment here. Gemini will pick them up and learn from them during the next sync sweep.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense, I will update _build_iam_endpoint here to only use the mtls. prefix on googleapis.com so it matches #19194 and google-api-core. Whichever PR lands second can drop the duplicate helper and import _build_iam_endpoint directly across google-auth.

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.

Args:
target_principal (str): The target service account email.
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"``, or ``"generateIdToken"``).

Returns:
str: The resolved IAM Credentials API endpoint URL.

Raises:
google.auth.exceptions.InvalidValue: If ``iam_endpoint_override`` is
missing a URL scheme or host.
"""
if not iam_endpoint_override:
host = (
_IAM_DOMAIN
if universe_domain == credentials.DEFAULT_UNIVERSE_DOMAIN
else f"iamcredentials.{universe_domain}"
)
return (
f"https://{host}/v1/projects/-/serviceAccounts/{target_principal}:{action}"
)

parsed = urllib.parse.urlsplit(iam_endpoint_override)
if not parsed.scheme or not parsed.netloc:
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`_.

Expand Down
23 changes: 14 additions & 9 deletions packages/google-auth/google/auth/impersonated_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -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_endpoint_override or iam._build_iam_endpoint(
principal, universe_domain, None, "generateAccessToken"
)

body = json.dumps(body).encode("utf-8")

Expand Down Expand Up @@ -401,9 +401,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"),
Expand Down Expand Up @@ -647,10 +650,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,
Expand Down
100 changes: 100 additions & 0 deletions packages/google-auth/tests/test_iam.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,103 @@ 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(
"example.com",
None,
"signBlob",
"https://iamcredentials.example.com/v1/projects/-"
"/serviceAccounts/[email protected]:signBlob",
id="custom_universe",
),
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(
"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",
),
],
)
def test_build_iam_endpoint(universe_domain, override, action, expected_url):
assert (
iam._build_iam_endpoint("[email protected]", 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(
"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(
"[email protected]",
universe_domain,
None,
"signBlob",
)
assert (
url == f"https://{expected_host}/v1/projects/-"
"/serviceAccounts/[email protected]:signBlob"
)


@pytest.mark.parametrize(
"bad_override",
[
"us-east1-iamcredentials.googleapis.com",
"https://",
],
)
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"
)
89 changes: 89 additions & 0 deletions packages/google-auth/tests/test_impersonated_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -1087,6 +1087,95 @@ 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/[email protected]:generateAccessToken",
"https://us-east1-iamcredentials.googleapis.com/v1/projects/-"
"/serviceAccounts/[email protected]:signBlob",
id="full_generate_access_token_url",
),
pytest.param(
"https://iamcredentials.example.com/v1/projects/-"
"/serviceAccounts/[email protected]:generateAccessToken?alt=json",
"https://iamcredentials.example.com/v1/projects/-"
"/serviceAccounts/[email protected]:signBlob?alt=json",
id="full_url_with_query",
),
pytest.param(
"https://proxy.example.com/iam/",
"https://proxy.example.com/iam/v1/projects/-"
"/serviceAccounts/[email protected]: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/[email protected]: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")

def test_id_token_refresh_uses_iam_endpoint_override(
self, mock_authorizedsession_idtoken
):
override = (
"https://us-east1-iamcredentials.example.com/v1/projects/-"
"/serviceAccounts/[email protected]:generateAccessToken"
)
source = service_account.Credentials(
SIGNER, "[email protected]", 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/[email protected]:generateIdToken"
)

@pytest.mark.parametrize(
"source_info",
[
Expand Down
Loading