ttu-iam 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+ node_modules/
2
+ dist/
3
+ .turbo/
4
+ *.tsbuildinfo
5
+ .env
6
+ .env.*
7
+ !.env.example
8
+ .DS_Store
9
+
10
+ __pycache__/
11
+ *.egg-info/
12
+ .venv/
13
+ .pytest_cache/
14
+ .ruff_cache/
15
+ python/dist/
ttu_iam-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,38 @@
1
+ Metadata-Version: 2.5
2
+ Name: ttu-iam
3
+ Version: 0.1.0
4
+ Summary: Official Python SDK for TTU IAM: OIDC/SSO, PKCE, access/ID token verify, map_subject, and Flask/FastAPI integrations
5
+ Requires-Python: >=3.11
6
+ Requires-Dist: httpx>=0.27.0
7
+ Requires-Dist: joserfc>=1.0.0
8
+ Requires-Dist: pydantic>=2.8.0
9
+ Provides-Extra: fastapi
10
+ Requires-Dist: fastapi>=0.115.0; extra == 'fastapi'
11
+ Requires-Dist: starlette>=0.40.0; extra == 'fastapi'
12
+ Provides-Extra: flask
13
+ Requires-Dist: flask>=3.0.0; extra == 'flask'
14
+ Description-Content-Type: text/markdown
15
+
16
+ # ttu-iam (Python SDK)
17
+
18
+ The Python SDK provides protocol helpers (OIDC discovery, PKCE, callback validation, ID and access token verification, `map_subject`) plus Flask and FastAPI integration boundaries. Applications own business roles and permissions after mapping `sub`; see [the integration contract](../docs/integration-contract.md#authorization-direction).
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ uv add ttu-iam
24
+ uv add "ttu-iam[flask]" # Flask integration boundary
25
+ uv add "ttu-iam[fastapi]" # FastAPI integration boundary
26
+ ```
27
+
28
+ Published releases: [ttu-iam on PyPI](https://pypi.org/project/ttu-iam/). First public version is `0.1.0` (OIDC discovery, PKCE, callback validation, ID/access token verification, `map_subject`; Flask/FastAPI extras are integration boundaries).
29
+
30
+ ## Local Development
31
+
32
+ ```bash
33
+ cd python
34
+ uv sync --all-extras
35
+ uv run ruff check .
36
+ uv run pyright
37
+ uv run pytest
38
+ ```
@@ -0,0 +1,23 @@
1
+ # ttu-iam (Python SDK)
2
+
3
+ The Python SDK provides protocol helpers (OIDC discovery, PKCE, callback validation, ID and access token verification, `map_subject`) plus Flask and FastAPI integration boundaries. Applications own business roles and permissions after mapping `sub`; see [the integration contract](../docs/integration-contract.md#authorization-direction).
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ uv add ttu-iam
9
+ uv add "ttu-iam[flask]" # Flask integration boundary
10
+ uv add "ttu-iam[fastapi]" # FastAPI integration boundary
11
+ ```
12
+
13
+ Published releases: [ttu-iam on PyPI](https://pypi.org/project/ttu-iam/). First public version is `0.1.0` (OIDC discovery, PKCE, callback validation, ID/access token verification, `map_subject`; Flask/FastAPI extras are integration boundaries).
14
+
15
+ ## Local Development
16
+
17
+ ```bash
18
+ cd python
19
+ uv sync --all-extras
20
+ uv run ruff check .
21
+ uv run pyright
22
+ uv run pytest
23
+ ```
@@ -0,0 +1,45 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "ttu-iam"
7
+ version = "0.1.0"
8
+ description = "Official Python SDK for TTU IAM: OIDC/SSO, PKCE, access/ID token verify, map_subject, and Flask/FastAPI integrations"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ dependencies = [
12
+ "httpx>=0.27.0",
13
+ "joserfc>=1.0.0",
14
+ "pydantic>=2.8.0",
15
+ ]
16
+
17
+ [project.optional-dependencies]
18
+ flask = ["flask>=3.0.0"]
19
+ fastapi = ["fastapi>=0.115.0", "starlette>=0.40.0"]
20
+
21
+ [dependency-groups]
22
+ dev = [
23
+ "pyright>=1.1.390",
24
+ "pytest>=8.3.0",
25
+ "ruff>=0.9.0",
26
+ ]
27
+
28
+ [tool.hatch.build.targets.wheel]
29
+ packages = ["src/ttu_iam"]
30
+
31
+ [tool.ruff]
32
+ line-length = 100
33
+ target-version = "py311"
34
+
35
+ [tool.ruff.lint]
36
+ select = ["E", "F", "I", "B", "UP", "S"]
37
+ ignore = ["S101"]
38
+
39
+ [tool.pyright]
40
+ include = ["src", "tests"]
41
+ pythonVersion = "3.11"
42
+ typeCheckingMode = "strict"
43
+
44
+ [tool.pytest.ini_options]
45
+ testpaths = ["tests"]
@@ -0,0 +1,45 @@
1
+ from .access_token import verify_access_token
2
+ from .discovery import OidcCache, fetch_oidc_discovery, fetch_oidc_jwks, validate_discovery_document
3
+ from .errors import IamError, IamErrorCode
4
+ from .id_token import verify_id_token
5
+ from .identity import map_subject
6
+ from .oidc import (
7
+ build_discovery_url,
8
+ resolve_callback_uri,
9
+ validate_redirect_uri,
10
+ validate_trusted_public_origin,
11
+ )
12
+ from .pkce import compute_s256_code_challenge, generate_pkce_pair
13
+ from .types import (
14
+ AccessTokenClaims,
15
+ IamConfig,
16
+ IamUserClaims,
17
+ OidcDiscoveryMetadata,
18
+ PkcePair,
19
+ )
20
+
21
+ __version__ = "0.0.0"
22
+
23
+ __all__ = [
24
+ "AccessTokenClaims",
25
+ "IamConfig",
26
+ "IamError",
27
+ "IamErrorCode",
28
+ "IamUserClaims",
29
+ "OidcCache",
30
+ "OidcDiscoveryMetadata",
31
+ "PkcePair",
32
+ "__version__",
33
+ "build_discovery_url",
34
+ "compute_s256_code_challenge",
35
+ "fetch_oidc_discovery",
36
+ "fetch_oidc_jwks",
37
+ "generate_pkce_pair",
38
+ "map_subject",
39
+ "resolve_callback_uri",
40
+ "validate_discovery_document",
41
+ "validate_redirect_uri",
42
+ "validate_trusted_public_origin",
43
+ "verify_access_token",
44
+ "verify_id_token",
45
+ ]
@@ -0,0 +1,124 @@
1
+ import math
2
+ import time
3
+ from typing import Any, cast
4
+
5
+ from joserfc import jwt
6
+ from joserfc.errors import JoseError
7
+ from joserfc.jwk import KeySet
8
+
9
+ from .errors import IamError, IamErrorCode
10
+ from .types import AccessTokenClaims
11
+
12
+ ACCESS_TOKEN_ALGORITHMS: tuple[str, ...] = ("RS256", "ES256")
13
+ ACCESS_TOKEN_TYP = "at+jwt" # noqa: S105
14
+ DEFAULT_CLOCK_TOLERANCE_SECONDS = 60.0
15
+
16
+
17
+ def verify_access_token(
18
+ token: str,
19
+ *,
20
+ issuer: str,
21
+ audience: str | tuple[str, ...],
22
+ key_set: KeySet,
23
+ now: float | None = None,
24
+ clock_tolerance_seconds: float = DEFAULT_CLOCK_TOLERANCE_SECONDS,
25
+ ) -> AccessTokenClaims:
26
+ claims = _verify_signature(token, key_set)
27
+ current = time.time() if now is None else now
28
+ return _assert_claims(
29
+ claims,
30
+ issuer=issuer,
31
+ audience=audience,
32
+ now=current,
33
+ tolerance=clock_tolerance_seconds,
34
+ )
35
+
36
+
37
+ def _verify_signature(token: str, key_set: KeySet) -> dict[str, Any]:
38
+ try:
39
+ decoded = jwt.decode(token, key_set, algorithms=ACCESS_TOKEN_ALGORITHMS)
40
+ except (JoseError, ValueError, TypeError) as exc:
41
+ raise _token_error("Access token signature or header is invalid.") from exc
42
+
43
+ typ = decoded.header.get("typ")
44
+ if _normalize_typ(typ) != ACCESS_TOKEN_TYP:
45
+ raise _token_error("Access token typ must be at+jwt.")
46
+ return dict(decoded.claims)
47
+
48
+
49
+ def _normalize_typ(typ: object) -> str | None:
50
+ if not isinstance(typ, str):
51
+ return None
52
+ return typ.rsplit("/", 1)[-1]
53
+
54
+
55
+ def _assert_claims(
56
+ claims: dict[str, Any],
57
+ *,
58
+ issuer: str,
59
+ audience: str | tuple[str, ...],
60
+ now: float,
61
+ tolerance: float,
62
+ ) -> AccessTokenClaims:
63
+ subject = claims.get("sub")
64
+ if not isinstance(subject, str) or subject == "":
65
+ raise _token_error("Access token is missing sub.")
66
+ if claims.get("iss") != issuer:
67
+ raise _token_error("Access token issuer does not match the configured issuer.")
68
+
69
+ token_audiences = _normalize_audience(claims.get("aud"))
70
+ _assert_expected_audience(token_audiences, audience)
71
+
72
+ expires_at = _require_numeric_date(claims, "exp")
73
+ if now >= expires_at + tolerance:
74
+ raise _token_error("Access token has expired.")
75
+
76
+ issued_at = _require_numeric_date(claims, "iat")
77
+ if issued_at > now + tolerance:
78
+ raise _token_error("Access token was issued in the future.")
79
+
80
+ if "nbf" in claims and _require_numeric_date(claims, "nbf") > now + tolerance:
81
+ raise _token_error("Access token is not yet valid.")
82
+
83
+ client_id = claims.get("client_id")
84
+ scope = claims.get("scope")
85
+ jti = claims.get("jti")
86
+ return AccessTokenClaims(
87
+ sub=subject,
88
+ client_id=client_id if isinstance(client_id, str) else None,
89
+ scope=scope if isinstance(scope, str) else None,
90
+ aud=token_audiences[0] if len(token_audiences) == 1 else tuple(token_audiences),
91
+ iss=issuer,
92
+ exp=int(expires_at) if expires_at.is_integer() else expires_at,
93
+ iat=int(issued_at) if issued_at.is_integer() else issued_at,
94
+ jti=jti if isinstance(jti, str) else None,
95
+ )
96
+
97
+
98
+ def _normalize_audience(audience: object) -> list[str]:
99
+ audiences: list[object] = (
100
+ cast("list[object]", audience) if isinstance(audience, list) else [audience]
101
+ )
102
+ if not audiences or not all(isinstance(value, str) for value in audiences):
103
+ raise _token_error("Access token audience is missing or invalid.")
104
+ return cast("list[str]", audiences)
105
+
106
+
107
+ def _assert_expected_audience(
108
+ token_audiences: list[str],
109
+ expected: str | tuple[str, ...],
110
+ ) -> None:
111
+ expected_list = list(expected) if isinstance(expected, tuple) else [expected]
112
+ if not any(value in token_audiences for value in expected_list):
113
+ raise _token_error("Access token audience does not include the expected audience.")
114
+
115
+
116
+ def _require_numeric_date(claims: dict[str, Any], name: str) -> float:
117
+ value = claims.get(name)
118
+ if isinstance(value, bool) or not isinstance(value, int | float) or not math.isfinite(value):
119
+ raise _token_error(f"Access token is missing {name}.")
120
+ return float(value)
121
+
122
+
123
+ def _token_error(message: str) -> IamError:
124
+ return IamError(IamErrorCode.TOKEN_VERIFICATION_FAILED, message)
@@ -0,0 +1,173 @@
1
+ import math
2
+ import time
3
+ from collections.abc import Callable
4
+ from dataclasses import dataclass, field
5
+ from typing import Any, TypeVar, cast
6
+ from urllib.parse import urlsplit
7
+
8
+ import httpx
9
+ from joserfc.errors import JoseError
10
+ from joserfc.jwk import KeySet, KeySetSerialization
11
+ from pydantic import ValidationError
12
+
13
+ from .errors import IamError, IamErrorCode
14
+ from .oidc import build_discovery_url, is_allowed_scheme
15
+ from .types import OidcDiscoveryMetadata
16
+
17
+ DEFAULT_CACHE_TTL_SECONDS = 600.0
18
+ MAX_CACHE_TTL_SECONDS = 3600.0
19
+ FETCH_TIMEOUT_SECONDS = 5.0
20
+
21
+ _T = TypeVar("_T")
22
+
23
+
24
+ @dataclass
25
+ class OidcCache:
26
+ discovery: dict[str, tuple[float, OidcDiscoveryMetadata]] = field(
27
+ default_factory=dict[str, tuple[float, OidcDiscoveryMetadata]],
28
+ )
29
+ jwks: dict[str, tuple[float, KeySet]] = field(default_factory=dict[str, tuple[float, KeySet]])
30
+
31
+
32
+ _DEFAULT_CACHE = OidcCache()
33
+
34
+
35
+ def validate_discovery_document(issuer: str, document: object) -> OidcDiscoveryMetadata:
36
+ expected_issuer = issuer.rstrip("/")
37
+ build_discovery_url(issuer)
38
+
39
+ try:
40
+ metadata = OidcDiscoveryMetadata.model_validate(document)
41
+ except ValidationError as exc:
42
+ raise _discovery_error("Discovery document is missing required fields.") from exc
43
+
44
+ if metadata.issuer != expected_issuer:
45
+ raise _discovery_error(
46
+ f'Discovery document issuer does not match configured issuer "{expected_issuer}".',
47
+ )
48
+
49
+ _require_secure_url("authorization_endpoint", metadata.authorization_endpoint)
50
+ _require_secure_url("token_endpoint", metadata.token_endpoint)
51
+ _require_secure_url("jwks_uri", metadata.jwks_uri)
52
+ return metadata
53
+
54
+
55
+ def fetch_oidc_discovery(
56
+ issuer: str,
57
+ *,
58
+ client: httpx.Client | None = None,
59
+ cache: OidcCache | None = None,
60
+ cache_ttl_seconds: float | None = None,
61
+ clock: Callable[[], float] = time.monotonic,
62
+ ) -> OidcDiscoveryMetadata:
63
+ discovery_url = build_discovery_url(issuer)
64
+ store = cache if cache is not None else _DEFAULT_CACHE
65
+
66
+ cached = _read_cache(store.discovery, discovery_url, clock())
67
+ if cached is not None:
68
+ return cached
69
+
70
+ document = _get_json(discovery_url, client)
71
+ metadata = validate_discovery_document(issuer, document)
72
+ _write_cache(
73
+ store.discovery,
74
+ discovery_url,
75
+ metadata,
76
+ clock(),
77
+ _resolve_ttl_seconds(cache_ttl_seconds),
78
+ )
79
+ return metadata
80
+
81
+
82
+ def fetch_oidc_jwks(
83
+ metadata: OidcDiscoveryMetadata,
84
+ *,
85
+ client: httpx.Client | None = None,
86
+ cache: OidcCache | None = None,
87
+ cache_ttl_seconds: float | None = None,
88
+ clock: Callable[[], float] = time.monotonic,
89
+ ) -> KeySet:
90
+ store = cache if cache is not None else _DEFAULT_CACHE
91
+
92
+ cached = _read_cache(store.jwks, metadata.jwks_uri, clock())
93
+ if cached is not None:
94
+ return cached
95
+
96
+ document = _get_json(metadata.jwks_uri, client)
97
+ if not isinstance(document, dict):
98
+ raise _discovery_error(f"JWKS document at {metadata.jwks_uri} must be a JSON object.")
99
+ jwks_document = cast("dict[str, Any]", document)
100
+ if not isinstance(jwks_document.get("keys"), list):
101
+ raise _discovery_error(f"JWKS document at {metadata.jwks_uri} must contain a keys array.")
102
+
103
+ try:
104
+ key_set = KeySet.import_key_set(cast(KeySetSerialization, jwks_document))
105
+ except (JoseError, ValueError, TypeError) as exc:
106
+ raise _discovery_error(f"JWKS document at {metadata.jwks_uri} is invalid.") from exc
107
+
108
+ _write_cache(
109
+ store.jwks,
110
+ metadata.jwks_uri,
111
+ key_set,
112
+ clock(),
113
+ _resolve_ttl_seconds(cache_ttl_seconds),
114
+ )
115
+ return key_set
116
+
117
+
118
+ def _require_secure_url(field_name: str, value: str) -> None:
119
+ try:
120
+ parsed = urlsplit(value)
121
+ _ = parsed.port
122
+ except ValueError as exc:
123
+ raise _discovery_error(f"Discovery document {field_name} is not a valid URL.") from exc
124
+
125
+ if not parsed.scheme or not parsed.hostname or not is_allowed_scheme(parsed):
126
+ raise _discovery_error(
127
+ f"Discovery document {field_name} must use HTTPS unless targeting localhost.",
128
+ )
129
+
130
+
131
+ def _get_json(url: str, client: httpx.Client | None) -> object:
132
+ owns_client = client is None
133
+ http = client if client is not None else httpx.Client(timeout=FETCH_TIMEOUT_SECONDS)
134
+ try:
135
+ response = http.get(url, headers={"accept": "application/json"})
136
+ response.raise_for_status()
137
+ return response.json()
138
+ except (httpx.HTTPError, ValueError) as exc:
139
+ raise _discovery_error(f"Request to {url} failed.") from exc
140
+ finally:
141
+ if owns_client:
142
+ http.close()
143
+
144
+
145
+ def _read_cache(store: dict[str, tuple[float, _T]], key: str, now: float) -> _T | None:
146
+ entry = store.get(key)
147
+ if entry is not None and entry[0] > now:
148
+ return entry[1]
149
+ store.pop(key, None)
150
+ return None
151
+
152
+
153
+ def _write_cache(
154
+ store: dict[str, tuple[float, _T]],
155
+ key: str,
156
+ value: _T,
157
+ now: float,
158
+ ttl_seconds: float,
159
+ ) -> None:
160
+ if ttl_seconds > 0:
161
+ store[key] = (now + ttl_seconds, value)
162
+
163
+
164
+ def _resolve_ttl_seconds(ttl_seconds: float | None) -> float:
165
+ if ttl_seconds is None:
166
+ return DEFAULT_CACHE_TTL_SECONDS
167
+ if not math.isfinite(ttl_seconds) or ttl_seconds < 0:
168
+ return 0.0
169
+ return min(ttl_seconds, MAX_CACHE_TTL_SECONDS)
170
+
171
+
172
+ def _discovery_error(message: str) -> IamError:
173
+ return IamError(IamErrorCode.DISCOVERY_FAILED, message)
@@ -0,0 +1,21 @@
1
+ from enum import StrEnum
2
+
3
+
4
+ class IamErrorCode(StrEnum):
5
+ INVALID_ISSUER = "INVALID_ISSUER"
6
+ MISSING_CLIENT_ID = "MISSING_CLIENT_ID"
7
+ UNTRUSTED_PUBLIC_ORIGIN = "UNTRUSTED_PUBLIC_ORIGIN"
8
+ INVALID_REDIRECT_URI = "INVALID_REDIRECT_URI"
9
+ UNREGISTERED_CALLBACK_URI = "UNREGISTERED_CALLBACK_URI"
10
+ AMBIGUOUS_CALLBACK_URI = "AMBIGUOUS_CALLBACK_URI"
11
+ SECRET_IN_BROWSER_FORBIDDEN = "SECRET_IN_BROWSER_FORBIDDEN" # noqa: S105
12
+ DISCOVERY_FAILED = "DISCOVERY_FAILED"
13
+ TOKEN_VERIFICATION_FAILED = "TOKEN_VERIFICATION_FAILED" # noqa: S105
14
+ TOKEN_EXCHANGE_FAILED = "TOKEN_EXCHANGE_FAILED" # noqa: S105
15
+
16
+
17
+ class IamError(Exception):
18
+ def __init__(self, code: IamErrorCode, message: str, *, request_id: str | None = None) -> None:
19
+ super().__init__(message)
20
+ self.code = code
21
+ self.request_id = request_id
@@ -0,0 +1,13 @@
1
+ from .oidc import build_discovery_url, resolve_callback_uri
2
+ from .types import IamConfig
3
+
4
+
5
+ class FastApiIamSecurity:
6
+ """FastAPI / Starlette integration boundary (`pip install 'ttu-iam[fastapi]'`)."""
7
+
8
+ def __init__(self, config: IamConfig) -> None:
9
+ self.discovery_url = build_discovery_url(config.issuer)
10
+ self.callback_uri = resolve_callback_uri(
11
+ config.public_origin,
12
+ config.registered_redirect_uris,
13
+ )
@@ -0,0 +1,13 @@
1
+ from .oidc import build_discovery_url, resolve_callback_uri
2
+ from .types import IamConfig
3
+
4
+
5
+ class FlaskIamExtension:
6
+ """Flask 3 integration boundary (`pip install 'ttu-iam[flask]'`)."""
7
+
8
+ def __init__(self, config: IamConfig) -> None:
9
+ self.discovery_url = build_discovery_url(config.issuer)
10
+ self.callback_uri = resolve_callback_uri(
11
+ config.public_origin,
12
+ config.registered_redirect_uris,
13
+ )
@@ -0,0 +1,126 @@
1
+ import math
2
+ import time
3
+ from typing import Any, cast
4
+
5
+ from joserfc import jwt
6
+ from joserfc.errors import JoseError
7
+ from joserfc.jwk import KeySet
8
+
9
+ from .errors import IamError, IamErrorCode
10
+ from .types import IamUserClaims
11
+
12
+ ID_TOKEN_ALGORITHMS: tuple[str, ...] = ("RS256", "ES256")
13
+ DEFAULT_CLOCK_TOLERANCE_SECONDS = 60.0
14
+
15
+
16
+ def verify_id_token(
17
+ token: str,
18
+ *,
19
+ issuer: str,
20
+ client_id: str,
21
+ expected_nonce: str,
22
+ key_set: KeySet,
23
+ now: float | None = None,
24
+ clock_tolerance_seconds: float = DEFAULT_CLOCK_TOLERANCE_SECONDS,
25
+ ) -> IamUserClaims:
26
+ claims = _verify_signature(token, key_set)
27
+ current = time.time() if now is None else now
28
+ subject = _assert_claims(
29
+ claims,
30
+ issuer=issuer,
31
+ client_id=client_id,
32
+ expected_nonce=expected_nonce,
33
+ now=current,
34
+ tolerance=clock_tolerance_seconds,
35
+ )
36
+ return _to_user_claims(claims, subject)
37
+
38
+
39
+ def _verify_signature(token: str, key_set: KeySet) -> dict[str, Any]:
40
+ try:
41
+ decoded = jwt.decode(token, key_set, algorithms=ID_TOKEN_ALGORITHMS)
42
+ except (JoseError, ValueError, TypeError) as exc:
43
+ raise _token_error("ID token signature or header is invalid.") from exc
44
+ return dict(decoded.claims)
45
+
46
+
47
+ def _assert_claims(
48
+ claims: dict[str, Any],
49
+ *,
50
+ issuer: str,
51
+ client_id: str,
52
+ expected_nonce: str,
53
+ now: float,
54
+ tolerance: float,
55
+ ) -> str:
56
+ subject = claims.get("sub")
57
+ if not isinstance(subject, str) or subject == "":
58
+ raise _token_error("ID token is missing sub.")
59
+ if claims.get("iss") != issuer:
60
+ raise _token_error("ID token issuer does not match the configured issuer.")
61
+
62
+ _assert_audience(claims, client_id)
63
+
64
+ expires_at = _require_numeric_date(claims, "exp")
65
+ if now >= expires_at + tolerance:
66
+ raise _token_error("ID token has expired.")
67
+
68
+ issued_at = _require_numeric_date(claims, "iat")
69
+ if issued_at > now + tolerance:
70
+ raise _token_error("ID token was issued in the future.")
71
+
72
+ if "nbf" in claims and _require_numeric_date(claims, "nbf") > now + tolerance:
73
+ raise _token_error("ID token is not yet valid.")
74
+
75
+ if claims.get("nonce") != expected_nonce:
76
+ raise _token_error("ID token nonce does not match the expected nonce.")
77
+
78
+ return subject
79
+
80
+
81
+ def _assert_audience(claims: dict[str, Any], client_id: str) -> None:
82
+ audience: object = claims.get("aud")
83
+ audiences: list[object] = (
84
+ cast("list[object]", audience) if isinstance(audience, list) else [audience]
85
+ )
86
+
87
+ if not all(isinstance(value, str) for value in audiences) or client_id not in audiences:
88
+ raise _token_error("ID token audience does not include this client.")
89
+ if "azp" in claims and claims["azp"] != client_id:
90
+ raise _token_error("ID token authorized party does not match this client.")
91
+ if len(audiences) > 1 and "azp" not in claims:
92
+ raise _token_error("ID token with multiple audiences must include azp.")
93
+
94
+
95
+ def _require_numeric_date(claims: dict[str, Any], name: str) -> float:
96
+ value = claims.get(name)
97
+ if isinstance(value, bool) or not isinstance(value, int | float) or not math.isfinite(value):
98
+ raise _token_error(f"ID token is missing {name}.")
99
+ return float(value)
100
+
101
+
102
+ def _to_user_claims(claims: dict[str, Any], subject: str) -> IamUserClaims:
103
+ email = claims.get("email")
104
+ email_verified = claims.get("email_verified")
105
+ name = claims.get("name")
106
+ affiliations: object = claims.get("affiliations")
107
+ return IamUserClaims(
108
+ sub=subject,
109
+ email=email if isinstance(email, str) else None,
110
+ email_verified=email_verified if isinstance(email_verified, bool) else None,
111
+ name=name if isinstance(name, str) else None,
112
+ affiliations=_string_tuple(affiliations),
113
+ )
114
+
115
+
116
+ def _string_tuple(value: object) -> tuple[str, ...] | None:
117
+ if not isinstance(value, list):
118
+ return None
119
+ items = cast("list[object]", value)
120
+ if not all(isinstance(item, str) for item in items):
121
+ return None
122
+ return tuple(cast("list[str]", items))
123
+
124
+
125
+ def _token_error(message: str) -> IamError:
126
+ return IamError(IamErrorCode.TOKEN_VERIFICATION_FAILED, message)
@@ -0,0 +1,14 @@
1
+ from collections.abc import Mapping
2
+ from typing import cast
3
+
4
+
5
+ def map_subject(claims: object) -> str:
6
+ """Return the stable IAM subject (`sub`) for app-local user mapping."""
7
+ subject: object | None
8
+ if isinstance(claims, Mapping):
9
+ subject = cast("Mapping[str, object]", claims).get("sub")
10
+ else:
11
+ subject = getattr(claims, "sub", None)
12
+ if not isinstance(subject, str) or subject == "":
13
+ raise TypeError("Claims must include a non-empty sub.")
14
+ return subject