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
77 changes: 77 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 @@ -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(

@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.

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, 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`_.
Expand Down
32 changes: 20 additions & 12 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._build_iam_endpoint(
principal, universe_domain, iam_endpoint_override, "generateAccessToken"
)

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

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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"),
Expand Down Expand Up @@ -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,
Expand Down
182 changes: 182 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,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"
)
Loading
Loading