Skip to content
Open
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
73 changes: 73 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,77 @@
_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.<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.
"""
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}"
)
Comment on lines +110 to +121

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.

Could we tighten the iam_endpoint_override check a bit? Right now it accepts non-HTTPS schemes (like ftp:// or http://), invalid ports (like https://host:abc since parsed.port is not checked), userinfo (@ in netloc), fragments (#), and whitespace/control chars, and non-str inputs raise AttributeError/TypeError instead of InvalidValue. Checking isinstance(..., str), rejecting whitespace/control chars, #, and @, touching parsed.port, and restricting to https would match the rest of google-auth.

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}"
return urllib.parse.urlunsplit(parsed._replace(path=path))
Comment on lines +122 to +129

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.

If iam_endpoint_override has a trailing slash after an action (like ...:generateAccessToken/), endswith misses and the else branch appends /v1/projects/-/serviceAccounts/... a second time. Stripping trailing slashes before the for loop handles that cleanly.



class Signer(crypt.Signer):
"""Signs messages using the IAM `signBlob API`_.
Expand Down
213 changes: 213 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,216 @@ 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(
"GOOGLEAPIS.COM",
None,
"generateIdToken",
"https://iamcredentials.googleapis.com/v1/projects/-"
"/serviceAccounts/[email protected]:generateIdToken",
id="default_universe_uppercase",
),
pytest.param(
"example.com",
None,
"signBlob",
"https://iamcredentials.example.com/v1/projects/-"
"/serviceAccounts/[email protected]:signBlob",
id="custom_universe_sign_blob",
),
pytest.param(
"example.com",
None,
"signJwt",
"https://iamcredentials.example.com/v1/projects/-"
"/serviceAccounts/[email protected]:signJwt",
id="custom_universe_sign_jwt",
),
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(
"example.com",
"https://us-east1-iamcredentials.example.com/v1/projects/-"
"/serviceAccounts/[email protected]:generateAccessToken?alt=json",
"generateAccessToken",
"https://us-east1-iamcredentials.example.com/v1/projects/-"
"/serviceAccounts/[email protected]:generateAccessToken?alt=json",
id="override_preserves_generate_access_token",
),
pytest.param(
"example.com",
"https://us-east1-iamcredentials.example.com/v1/projects/-"
"/serviceAccounts/[email protected]:signBlob",
"generateIdToken",
"https://us-east1-iamcredentials.example.com/v1/projects/-"
"/serviceAccounts/[email protected]:generateIdToken",
id="override_rewrites_sign_blob",
),
pytest.param(
"example.com",
"https://us-east1-iamcredentials.example.com/v1/projects/-"
"/serviceAccounts/[email protected]:signJwt",
"signBlob",
"https://us-east1-iamcredentials.example.com/v1/projects/-"
"/serviceAccounts/[email protected]:signBlob",
id="override_rewrites_sign_jwt",
),
pytest.param(
"example.com",
"https://us-east1-iamcredentials.example.com/v1/projects/-"
"/serviceAccounts/[email protected]:generateIdToken",
"generateAccessToken",
"https://us-east1-iamcredentials.example.com/v1/projects/-"
"/serviceAccounts/[email protected]: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/[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",
),
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_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("[email protected]", 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/[email protected]:signBlob",
id="default_universe_uses_mtls",
),
pytest.param(
"GOOGLEAPIS.COM",
"https://iamcredentials.mtls.googleapis.com/v1/projects/-"
"/serviceAccounts/[email protected]:signBlob",
id="default_universe_uppercase_uses_mtls",
),
pytest.param(
"example.com",
"https://iamcredentials.example.com/v1/projects/-"
"/serviceAccounts/[email protected]: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(
"[email protected]",
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("[email protected]")
== "https://iamcredentials.custom.universe.domain/v1/projects/-"
"/serviceAccounts/[email protected]: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(
"[email protected]", "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(
"[email protected]", bad_universe_domain, None, "generateIdToken"
)
Loading