Skip to content
Merged
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
93 changes: 93 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,97 @@
_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 not a valid HTTPS URL without
userinfo, fragments, whitespace, or control characters.
"""
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
else:
domain = f"iamcredentials.{universe_domain}"
return (
f"https://{domain}/v1/projects/-/"
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 (
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}"
)
Comment thread
parthea marked this conversation as resolved.
Resolved

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))
Comment thread
parthea marked this conversation as resolved.
Resolved


class Signer(crypt.Signer):
"""Signs messages using the IAM `signBlob API`_.
Expand Down
265 changes: 265 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,268 @@ 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(
"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",
),
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):
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",
[
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):
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