tba-protocol-oidc 0.4.0.dev2__py3-none-any.whl

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.
Files changed (36) hide show
  1. tba_protocol_oidc/__init__.py +92 -0
  2. tba_protocol_oidc/bindings.py +37 -0
  3. tba_protocol_oidc/capability_requirements.py +5 -0
  4. tba_protocol_oidc/claim_sets.py +119 -0
  5. tba_protocol_oidc/claims.py +19 -0
  6. tba_protocol_oidc/compatibility.py +37 -0
  7. tba_protocol_oidc/discovery.py +23 -0
  8. tba_protocol_oidc/eap_acr_values.py +27 -0
  9. tba_protocol_oidc/errors.py +16 -0
  10. tba_protocol_oidc/features.py +26 -0
  11. tba_protocol_oidc/id_token.py +26 -0
  12. tba_protocol_oidc/id_token_profile.py +55 -0
  13. tba_protocol_oidc/jwks_service.py +12 -0
  14. tba_protocol_oidc/migrations.py +14 -0
  15. tba_protocol_oidc/provider.py +223 -0
  16. tba_protocol_oidc/py.typed +0 -0
  17. tba_protocol_oidc/reusable_components.py +23 -0
  18. tba_protocol_oidc/schemas.py +31 -0
  19. tba_protocol_oidc/standards/__init__.py +8 -0
  20. tba_protocol_oidc/standards/_rp_logout_validation.py +113 -0
  21. tba_protocol_oidc/standards/backchannel_logout.py +236 -0
  22. tba_protocol_oidc/standards/core.py +35 -0
  23. tba_protocol_oidc/standards/discovery.py +53 -0
  24. tba_protocol_oidc/standards/discovery_metadata.py +148 -0
  25. tba_protocol_oidc/standards/frontchannel_logout.py +107 -0
  26. tba_protocol_oidc/standards/id_token.py +134 -0
  27. tba_protocol_oidc/standards/openid4vc.py +80 -0
  28. tba_protocol_oidc/standards/rp_initiated_logout.py +279 -0
  29. tba_protocol_oidc/standards/session_mgmt.py +222 -0
  30. tba_protocol_oidc/standards/set_delivery.py +31 -0
  31. tba_protocol_oidc/standards/userinfo.py +54 -0
  32. tba_protocol_oidc/tenant_discovery.py +226 -0
  33. tba_protocol_oidc/versions.py +25 -0
  34. tba_protocol_oidc-0.4.0.dev2.dist-info/METADATA +139 -0
  35. tba_protocol_oidc-0.4.0.dev2.dist-info/RECORD +36 -0
  36. tba_protocol_oidc-0.4.0.dev2.dist-info/WHEEL +4 -0
@@ -0,0 +1,53 @@
1
+ """Pure OIDC Discovery 1.0 metadata ownership and projection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Final
6
+
7
+ from tba_protocol_oauth.standards.authorization_server_metadata import (
8
+ ISSUER,
9
+ JWKS_PATH,
10
+ )
11
+ from tba_primitives_identity.standards import StandardOwner, describe_owner
12
+
13
+ from .discovery_metadata import OidcDiscoveryDeployment, build_openid_config
14
+
15
+
16
+ OIDC_DISCOVERY_SPEC_URL: Final[str] = (
17
+ "https://openid.net/specs/openid-connect-discovery-1_0.html"
18
+ )
19
+ OWNER = StandardOwner(
20
+ label="OIDC Discovery 1.0",
21
+ title="OpenID Connect Discovery 1.0",
22
+ runtime_status="profile-aware-discovery-metadata",
23
+ public_surface=("/.well-known/openid-configuration",),
24
+ notes=(
25
+ "Versioned metadata semantics only; HTTP publication and durable "
26
+ "tenant/realm existence checks are composed above the protocol layer."
27
+ ),
28
+ )
29
+
30
+
31
+ _build_openid_config = build_openid_config
32
+
33
+
34
+ def describe() -> dict[str, object]:
35
+ return describe_owner(
36
+ OWNER,
37
+ specification_version="1.0",
38
+ jwks_publication=True,
39
+ tenant_and_realm_profiles=True,
40
+ spec_url=OIDC_DISCOVERY_SPEC_URL,
41
+ )
42
+
43
+
44
+ __all__ = [
45
+ "ISSUER",
46
+ "JWKS_PATH",
47
+ "OIDC_DISCOVERY_SPEC_URL",
48
+ "OidcDiscoveryDeployment",
49
+ "OWNER",
50
+ "_build_openid_config",
51
+ "build_openid_config",
52
+ "describe",
53
+ ]
@@ -0,0 +1,148 @@
1
+ """Pure OpenID discovery metadata helpers.
2
+
3
+ The helpers in this module avoid importing the full framework/runtime stack so
4
+ profile-aware discovery snapshots can be generated during governance and
5
+ contract/reporting workflows.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any, Mapping, Protocol
11
+
12
+ from tba_provider_identity_jose.standards.rfc7516 import jwe_policy_metadata
13
+ from tba_protocol_oauth.standards.jwt_client_auth import (
14
+ token_endpoint_auth_methods_supported,
15
+ token_endpoint_auth_signing_alg_values_supported,
16
+ )
17
+ from tba_protocol_oauth.standards.mutual_tls_client_authentication import (
18
+ SUPPORTED_MTLS_AUTH_METHODS,
19
+ )
20
+ from tba_protocol_oauth.standards.authorization_server_metadata import (
21
+ ISSUER,
22
+ JWKS_PATH,
23
+ )
24
+ from tba_protocol_oauth.standards.oauth_security_bcp import (
25
+ discovery_policy_metadata,
26
+ )
27
+
28
+ OAUTH_PROTECTED_RESOURCE_PATH = "/.well-known/oauth-protected-resource"
29
+
30
+
31
+ class OidcDiscoveryDeployment(Protocol):
32
+ """Runtime-neutral deployment view required by discovery projection."""
33
+
34
+ issuer: str | None
35
+ profile: str
36
+ flags: Mapping[str, Any]
37
+ active_capabilities: tuple[str, ...]
38
+
39
+ def flag_enabled(self, flag: str) -> bool: ...
40
+
41
+ def route_enabled(self, path: str) -> bool: ...
42
+
43
+ def capability_enabled(self, capability: str) -> bool: ...
44
+
45
+
46
+ def build_openid_config(deployment: OidcDiscoveryDeployment) -> dict[str, Any]:
47
+ """Project an injected deployment into OIDC discovery metadata."""
48
+ issuer = str(deployment.issuer or ISSUER)
49
+ scopes = ["openid", "profile", "email", "address", "phone"]
50
+ claims = ["sub", "name", "email", "address", "phone_number"]
51
+ auth_methods = token_endpoint_auth_methods_supported()
52
+ if deployment.flag_enabled("enable_rfc8705") or deployment.profile in {
53
+ "hardening",
54
+ "fapi2-security",
55
+ "peer-claim",
56
+ }:
57
+ auth_methods = list(
58
+ dict.fromkeys([*auth_methods, *SUPPORTED_MTLS_AUTH_METHODS])
59
+ )
60
+ policy_metadata = discovery_policy_metadata(deployment)
61
+ if "token_endpoint_auth_methods_supported" in policy_metadata:
62
+ auth_methods = list(policy_metadata["token_endpoint_auth_methods_supported"])
63
+ auth_signing_algs = token_endpoint_auth_signing_alg_values_supported()
64
+ config: dict[str, Any] = {
65
+ "issuer": issuer,
66
+ "authorization_endpoint": f"{issuer}/authorize",
67
+ "token_endpoint": f"{issuer}/token",
68
+ "jwks_uri": f"{issuer}{JWKS_PATH}",
69
+ "subject_types_supported": ["public"],
70
+ "id_token_signing_alg_values_supported": ["RS256"],
71
+ "scopes_supported": scopes,
72
+ "claims_supported": claims,
73
+ "token_endpoint_auth_methods_supported": auth_methods,
74
+ }
75
+ if auth_signing_algs:
76
+ config["token_endpoint_auth_signing_alg_values_supported"] = auth_signing_algs
77
+ config.update(policy_metadata)
78
+ if bool(
79
+ deployment.flags.get("enable_oidc_userinfo", False)
80
+ ) and deployment.route_enabled("/userinfo"):
81
+ config["userinfo_endpoint"] = f"{issuer}/userinfo"
82
+ if bool(deployment.flags.get("enable_id_token_encryption", False)):
83
+ config.update(jwe_policy_metadata())
84
+ if bool(deployment.flags.get("enable_rfc7591", False)) and deployment.route_enabled(
85
+ "/register"
86
+ ):
87
+ config["registration_endpoint"] = f"{issuer}/register"
88
+ if bool(deployment.flags.get("enable_rfc7009", False)) and deployment.route_enabled(
89
+ "/revoke"
90
+ ):
91
+ config["revocation_endpoint"] = f"{issuer}/revoke"
92
+ config["revocation_endpoint_auth_methods_supported"] = auth_methods
93
+ if bool(deployment.flags.get("enable_rfc7662", False)) and deployment.route_enabled(
94
+ "/introspect"
95
+ ):
96
+ config["introspection_endpoint"] = f"{issuer}/introspect"
97
+ config["introspection_endpoint_auth_methods_supported"] = auth_methods
98
+ if bool(
99
+ deployment.flags.get("enable_oidc_rp_initiated_logout", False)
100
+ ) and deployment.route_enabled("/logout"):
101
+ config["end_session_endpoint"] = f"{issuer}/logout"
102
+ if bool(
103
+ deployment.flags.get("enable_oidc_frontchannel_logout", False)
104
+ ) and deployment.route_enabled("/logout"):
105
+ config["frontchannel_logout_supported"] = True
106
+ config["frontchannel_logout_session_supported"] = True
107
+ if bool(
108
+ deployment.flags.get("enable_oidc_backchannel_logout", False)
109
+ ) and deployment.route_enabled("/logout"):
110
+ config["backchannel_logout_supported"] = True
111
+ config["backchannel_logout_session_supported"] = True
112
+ if bool(deployment.flags.get("enable_rfc8628", False)) and deployment.route_enabled(
113
+ "/device_authorization"
114
+ ):
115
+ config["device_authorization_endpoint"] = f"{issuer}/device_authorization"
116
+ if bool(deployment.flags.get("enable_rfc9126", False)) and deployment.route_enabled(
117
+ "/par"
118
+ ):
119
+ config["pushed_authorization_request_endpoint"] = f"{issuer}/par"
120
+ if bool(deployment.flags.get("enable_rfc9728", False)) and deployment.route_enabled(
121
+ OAUTH_PROTECTED_RESOURCE_PATH
122
+ ):
123
+ config["protected_resource_metadata"] = (
124
+ f"{issuer}{OAUTH_PROTECTED_RESOURCE_PATH}"
125
+ )
126
+ if (
127
+ deployment.flag_enabled("enable_rfc8705")
128
+ or deployment.profile == "fapi2-security"
129
+ ):
130
+ config["mtls_endpoint_aliases"] = {
131
+ "token_endpoint": f"{issuer}/token",
132
+ "revocation_endpoint": f"{issuer}/revoke",
133
+ "introspection_endpoint": f"{issuer}/introspect",
134
+ "registration_endpoint": f"{issuer}/register",
135
+ }
136
+ config["tba_auth_capabilities"] = sorted(
137
+ capability
138
+ for capability in deployment.active_capabilities
139
+ if deployment.capability_enabled(capability)
140
+ )
141
+ return config
142
+
143
+
144
+ __all__ = [
145
+ "OAUTH_PROTECTED_RESOURCE_PATH",
146
+ "OidcDiscoveryDeployment",
147
+ "build_openid_config",
148
+ ]
@@ -0,0 +1,107 @@
1
+ """OpenID Connect Front-Channel Logout planning and durable completion tracking."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Final, Mapping
6
+ from tba_primitives_identity.standards import StandardOwner, describe_owner
7
+ from urllib.parse import urlencode
8
+ from uuid import UUID
9
+
10
+ from tba_contracts_identity.protocol_configuration import (
11
+ protocol_settings as settings,
12
+ )
13
+
14
+ STATUS: Final[str] = "frontchannel-logout-fanout-runtime"
15
+ _DEFAULT_MAX_RETRIES: Final[int] = 3
16
+
17
+
18
+ OWNER = StandardOwner(
19
+ label="OIDC Front-Channel Logout",
20
+ title="OpenID Connect Front-Channel Logout",
21
+ runtime_status=STATUS,
22
+ public_surface=("/logout",),
23
+ notes=(
24
+ "Logout fanout planning is implementation-backed. Client registration metadata can declare "
25
+ "frontchannel_logout_uri, optional sid inclusion, bounded retry policy, and durable delivery state on logout_state metadata."
26
+ ),
27
+ )
28
+
29
+
30
+ async def build_frontchannel_descriptor(
31
+ *,
32
+ client_id: UUID,
33
+ sid: str,
34
+ iss: str | None = None,
35
+ logout_id: UUID | None = None,
36
+ registration_metadata: Mapping[str, Any],
37
+ ) -> dict[str, object] | None:
38
+ metadata = dict(registration_metadata)
39
+ logout_uri = metadata.get("frontchannel_logout_uri")
40
+ if not logout_uri:
41
+ return None
42
+ include_sid = bool(metadata.get("frontchannel_logout_session_required", True))
43
+ retry_window_s = int(metadata.get("frontchannel_retry_window_seconds", 30) or 30)
44
+ params = {"iss": iss or settings.issuer}
45
+ if logout_id is not None:
46
+ params["logout_id"] = str(logout_id)
47
+ if include_sid:
48
+ params["sid"] = sid
49
+ joiner = "&" if "?" in str(logout_uri) else "?"
50
+ redirect_uri = (
51
+ f"{logout_uri}{joiner}{urlencode(params)}" if params else str(logout_uri)
52
+ )
53
+ return {
54
+ "client_id": str(client_id),
55
+ "logout_uri": str(logout_uri),
56
+ "redirect_uri": redirect_uri,
57
+ "iss": params["iss"],
58
+ "sid_included": include_sid,
59
+ "sid": sid if include_sid else None,
60
+ "logout_id": str(logout_id) if logout_id is not None else None,
61
+ "delivery": {
62
+ "channel": "frontchannel",
63
+ "status": "pending",
64
+ "attempts": 0,
65
+ "max_retries": _DEFAULT_MAX_RETRIES,
66
+ "retry_window_seconds": retry_window_s,
67
+ "replay_protected": True,
68
+ },
69
+ }
70
+
71
+
72
+ def validate_frontchannel_request(
73
+ *,
74
+ params: dict[str, Any],
75
+ expected_sid: str | None = None,
76
+ expected_iss: str | None = None,
77
+ expected_logout_id: UUID | str | None = None,
78
+ ) -> dict[str, Any]:
79
+ payload = {str(key): value for key, value in dict(params or {}).items()}
80
+ if expected_iss is not None and str(payload.get("iss") or "") != str(expected_iss):
81
+ raise ValueError("frontchannel issuer mismatch")
82
+ if expected_sid is not None and str(payload.get("sid") or "") != str(expected_sid):
83
+ raise ValueError("frontchannel sid mismatch")
84
+ if expected_logout_id is not None and str(payload.get("logout_id") or "") != str(
85
+ expected_logout_id
86
+ ):
87
+ raise ValueError("frontchannel logout_id mismatch")
88
+ return payload
89
+
90
+
91
+ def describe() -> dict[str, object]:
92
+ return describe_owner(
93
+ OWNER,
94
+ fanout_supported=True,
95
+ delivery_state_persisted=True,
96
+ retry_semantics_supported=True,
97
+ )
98
+
99
+
100
+ __all__ = [
101
+ "STATUS",
102
+ "StandardOwner",
103
+ "OWNER",
104
+ "build_frontchannel_descriptor",
105
+ "validate_frontchannel_request",
106
+ "describe",
107
+ ]
@@ -0,0 +1,134 @@
1
+ """OIDC ID Token wire claims, signing invocation, and validation rules."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import json
7
+ from datetime import timedelta
8
+ from hashlib import sha256
9
+ from typing import Any, Iterable, Mapping
10
+
11
+ from tba_provider_identity_jose.framework import JWAAlg
12
+ from tba_contracts_identity.protocol_configuration import (
13
+ protocol_settings as settings,
14
+ )
15
+ from tba_primitives_identity.errors import InvalidTokenError
16
+ from tba_provider_identity_jose.oidc_key_runtime import (
17
+ _RSA_KEY_PATH, # noqa: F401 - private compatibility patch point
18
+ ensure_rsa_jwt_key,
19
+ id_token_service,
20
+ rsa_key_provider,
21
+ rotate_rsa_jwt_key as _rotate_rsa_jwt_key,
22
+ rotation_jwks_cache,
23
+ )
24
+ from tba_provider_identity_jose.standards.rfc7516 import decrypt_jwe, encrypt_jwe
25
+
26
+ from ..id_token_profile import validate_id_token_profile
27
+
28
+ # Mutable compatibility hooks retained for one release boundary. Environment
29
+ # key operations remain implemented by the layer-20 provider.
30
+ _provider = rsa_key_provider
31
+ _service_cache = None
32
+
33
+
34
+ def _header(token: str) -> Mapping[str, object]:
35
+ try:
36
+ segment = token.split(".")[0]
37
+ header = json.loads(
38
+ base64.urlsafe_b64decode(segment + "=" * (-len(segment) % 4))
39
+ )
40
+ except Exception as exc:
41
+ raise InvalidTokenError("invalid ID Token protected header") from exc
42
+ if not isinstance(header, dict):
43
+ raise InvalidTokenError("invalid ID Token protected header")
44
+ return header
45
+
46
+
47
+ def _header_alg(token: str) -> str:
48
+ return str(_header(token).get("alg", "")).lower()
49
+
50
+
51
+ def oidc_hash(value: str) -> str:
52
+ """Return the OIDC half-hash used by at_hash/c_hash/s_hash."""
53
+ digest = sha256(value.encode("ascii")).digest()
54
+ return (
55
+ base64.urlsafe_b64encode(digest[: len(digest) // 2]).decode("ascii").rstrip("=")
56
+ )
57
+
58
+
59
+ async def mint_id_token(
60
+ *,
61
+ sub: str,
62
+ aud: Iterable[str] | str,
63
+ nonce: str,
64
+ issuer: str,
65
+ ttl: timedelta = timedelta(minutes=5),
66
+ **extra: Mapping[str, Any] | Any,
67
+ ) -> str:
68
+ service, kid = await id_token_service()
69
+ claims: dict[str, Any] = {"nonce": nonce}
70
+ claims.update(extra)
71
+ token = await service.mint(
72
+ claims,
73
+ alg=JWAAlg.RS256,
74
+ kid=kid,
75
+ lifetime_s=int(ttl.total_seconds()),
76
+ issuer=issuer,
77
+ subject=sub,
78
+ audience=aud,
79
+ )
80
+ if settings.enable_id_token_encryption:
81
+ token = await encrypt_jwe(
82
+ token, {"kty": "oct", "k": settings.id_token_encryption_key.encode()}
83
+ )
84
+ return token
85
+
86
+
87
+ async def verify_id_token(
88
+ token: str,
89
+ *,
90
+ issuer: str,
91
+ audience: Iterable[str] | str,
92
+ nonce: str | None = None,
93
+ now: int | None = None,
94
+ clock_skew: int = 0,
95
+ ) -> dict:
96
+ if settings.enable_id_token_encryption:
97
+ token = await decrypt_jwe(
98
+ token, {"kty": "oct", "k": settings.id_token_encryption_key.encode()}
99
+ )
100
+ if _header_alg(token) in {"", "none"}:
101
+ raise InvalidTokenError("unsigned JWTs are not accepted")
102
+ service, _ = await id_token_service()
103
+ claims = await service.verify(token, issuer=issuer, audience=audience)
104
+ accepted_audiences = (audience,) if isinstance(audience, str) else tuple(audience)
105
+ if not accepted_audiences:
106
+ raise InvalidTokenError("ID Token audience is required")
107
+ try:
108
+ validate_id_token_profile(
109
+ _header(token),
110
+ claims,
111
+ expected_issuer=issuer,
112
+ client_id=accepted_audiences[0],
113
+ expected_nonce=nonce,
114
+ now=now,
115
+ clock_skew=clock_skew,
116
+ )
117
+ except ValueError as exc:
118
+ raise InvalidTokenError(str(exc)) from exc
119
+ return claims
120
+
121
+
122
+ async def rotate_rsa_jwt_key() -> str:
123
+ return await _rotate_rsa_jwt_key()
124
+
125
+
126
+ __all__ = [
127
+ "ensure_rsa_jwt_key",
128
+ "mint_id_token",
129
+ "oidc_hash",
130
+ "rsa_key_provider",
131
+ "rotate_rsa_jwt_key",
132
+ "rotation_jwks_cache",
133
+ "verify_id_token",
134
+ ]
@@ -0,0 +1,80 @@
1
+ """Wire-level structural contracts for OID4VCI 1.0 and OID4VP 1.0."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any, Mapping, Sequence
7
+
8
+
9
+ @dataclass(frozen=True, slots=True)
10
+ class CredentialOffer:
11
+ credential_issuer: str
12
+ credential_configuration_ids: tuple[str, ...]
13
+ grants: Mapping[str, Any]
14
+
15
+
16
+ def parse_credential_offer(value: Mapping[str, Any]) -> CredentialOffer:
17
+ issuer = value.get("credential_issuer")
18
+ ids = value.get("credential_configuration_ids")
19
+ grants = value.get("grants", {})
20
+ if not isinstance(issuer, str) or not issuer.startswith("https://"):
21
+ raise ValueError("credential_issuer must be an HTTPS URL")
22
+ if (
23
+ not isinstance(ids, list)
24
+ or not ids
25
+ or not all(isinstance(i, str) and i for i in ids)
26
+ ):
27
+ raise ValueError(
28
+ "credential_configuration_ids must be a non-empty string array"
29
+ )
30
+ if not isinstance(grants, Mapping):
31
+ raise ValueError("grants must be an object")
32
+ return CredentialOffer(issuer, tuple(ids), dict(grants))
33
+
34
+
35
+ @dataclass(frozen=True, slots=True)
36
+ class PresentationRequest:
37
+ client_id: str
38
+ nonce: str
39
+ response_type: str
40
+ response_mode: str | None
41
+ dcql_query: Mapping[str, Any] | None
42
+
43
+
44
+ def parse_presentation_request(value: Mapping[str, Any]) -> PresentationRequest:
45
+ client_id, nonce = value.get("client_id"), value.get("nonce")
46
+ if (
47
+ not isinstance(client_id, str)
48
+ or not client_id
49
+ or not isinstance(nonce, str)
50
+ or not nonce
51
+ ):
52
+ raise ValueError("OID4VP request requires client_id and nonce")
53
+ if value.get("response_type") != "vp_token":
54
+ raise ValueError("OID4VP response_type must be vp_token")
55
+ query = value.get("dcql_query")
56
+ if query is not None and not isinstance(query, Mapping):
57
+ raise ValueError("dcql_query must be an object")
58
+ return PresentationRequest(
59
+ client_id, nonce, "vp_token", value.get("response_mode"), query
60
+ )
61
+
62
+
63
+ @dataclass(frozen=True, slots=True)
64
+ class HaipPolicy:
65
+ credential_formats: Sequence[str] = ("dc+sd-jwt", "mso_mdoc")
66
+ require_signed_request: bool = True
67
+ require_encrypted_response: bool = True
68
+ require_key_binding: bool = True
69
+
70
+ def accepts_format(self, value: str) -> bool:
71
+ return value in self.credential_formats
72
+
73
+
74
+ __all__ = [
75
+ "CredentialOffer",
76
+ "HaipPolicy",
77
+ "PresentationRequest",
78
+ "parse_credential_offer",
79
+ "parse_presentation_request",
80
+ ]