tba-protocol-oauth 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.
- tba_protocol_oauth/__init__.py +122 -0
- tba_protocol_oauth/bindings.py +116 -0
- tba_protocol_oauth/capability_requirements.py +5 -0
- tba_protocol_oauth/claim_sets.py +19 -0
- tba_protocol_oauth/claims.py +79 -0
- tba_protocol_oauth/compatibility.py +39 -0
- tba_protocol_oauth/errors.py +25 -0
- tba_protocol_oauth/features.py +36 -0
- tba_protocol_oauth/jwtoken.py +16 -0
- tba_protocol_oauth/migrations.py +37 -0
- tba_protocol_oauth/protocol.py +282 -0
- tba_protocol_oauth/py.typed +0 -0
- tba_protocol_oauth/reusable_components.py +5 -0
- tba_protocol_oauth/schemas.py +198 -0
- tba_protocol_oauth/standards/__init__.py +9 -0
- tba_protocol_oauth/standards/_dpop/__init__.py +57 -0
- tba_protocol_oauth/standards/_dpop/metadata.py +18 -0
- tba_protocol_oauth/standards/_dpop/primitives.py +194 -0
- tba_protocol_oauth/standards/_dpop/proofs.py +393 -0
- tba_protocol_oauth/standards/_dpop/state.py +74 -0
- tba_protocol_oauth/standards/_introspection_activity.py +32 -0
- tba_protocol_oauth/standards/_mtls_identity.py +98 -0
- tba_protocol_oauth/standards/_rfc8693/__init__.py +26 -0
- tba_protocol_oauth/standards/_rfc8693/endpoint.py +56 -0
- tba_protocol_oauth/standards/_rfc8693/runtime.py +289 -0
- tba_protocol_oauth/standards/_rfc9700/__init__.py +45 -0
- tba_protocol_oauth/standards/_rfc9700/security_profile.py +265 -0
- tba_protocol_oauth/standards/_rfc9700/sender_constraints.py +397 -0
- tba_protocol_oauth/standards/assertion_framework.py +173 -0
- tba_protocol_oauth/standards/authorization_framework.py +102 -0
- tba_protocol_oauth/standards/authorization_server_metadata.py +43 -0
- tba_protocol_oauth/standards/authorization_server_metadata_endpoint.py +21 -0
- tba_protocol_oauth/standards/bearer_token_usage.py +86 -0
- tba_protocol_oauth/standards/client_registration_management.py +89 -0
- tba_protocol_oauth/standards/device_authorization.py +140 -0
- tba_protocol_oauth/standards/dpop.py +59 -0
- tba_protocol_oauth/standards/dynamic_client_registration.py +68 -0
- tba_protocol_oauth/standards/gnap.py +6 -0
- tba_protocol_oauth/standards/introspection.py +56 -0
- tba_protocol_oauth/standards/issuer_identification.py +130 -0
- tba_protocol_oauth/standards/json_web_token.py +159 -0
- tba_protocol_oauth/standards/jwt_access_tokens.py +44 -0
- tba_protocol_oauth/standards/jwt_best_practices.py +44 -0
- tba_protocol_oauth/standards/jwt_client_auth.py +208 -0
- tba_protocol_oauth/standards/jwt_secured_authorization_requests.py +421 -0
- tba_protocol_oauth/standards/legacy_jwt_client_assertions.py +113 -0
- tba_protocol_oauth/standards/mutual_tls_client_authentication.py +394 -0
- tba_protocol_oauth/standards/native_apps.py +132 -0
- tba_protocol_oauth/standards/oauth_security_bcp.py +47 -0
- tba_protocol_oauth/standards/proof_key_for_code_exchange.py +82 -0
- tba_protocol_oauth/standards/protected_resource_metadata.py +103 -0
- tba_protocol_oauth/standards/pushed_authorization_requests.py +198 -0
- tba_protocol_oauth/standards/resource_indicators.py +127 -0
- tba_protocol_oauth/standards/resource_verifier_contract.py +91 -0
- tba_protocol_oauth/standards/revocation.py +59 -0
- tba_protocol_oauth/standards/rich_authorization_requests.py +221 -0
- tba_protocol_oauth/standards/token_endpoint.py +76 -0
- tba_protocol_oauth/standards/token_exchange.py +60 -0
- tba_protocol_oauth/versions.py +110 -0
- tba_protocol_oauth-0.4.0.dev2.dist-info/METADATA +114 -0
- tba_protocol_oauth-0.4.0.dev2.dist-info/RECORD +62 -0
- tba_protocol_oauth-0.4.0.dev2.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""RFC 7521 assertion-framework helpers.
|
|
2
|
+
|
|
3
|
+
This module owns the runtime validation and contract helpers for JWT bearer
|
|
4
|
+
assertion grants and client assertions at the token endpoint.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import time
|
|
10
|
+
from typing import Any, Final, Iterable
|
|
11
|
+
|
|
12
|
+
from tba_primitives_identity.standards import StandardOwner, describe_owner
|
|
13
|
+
|
|
14
|
+
from tba_contracts_identity.protocol_configuration import (
|
|
15
|
+
protocol_settings as settings,
|
|
16
|
+
)
|
|
17
|
+
from tba_primitives_identity.errors import InvalidTokenError
|
|
18
|
+
from tba_protocol_oauth.standards.json_web_token import decode_jwt
|
|
19
|
+
|
|
20
|
+
STATUS: Final[str] = "assertion-framework-runtime-integrated"
|
|
21
|
+
RFC7521_SPEC_URL: Final[str] = "https://www.rfc-editor.org/rfc/rfc7521"
|
|
22
|
+
JWT_BEARER_GRANT_TYPE: Final[str] = "urn:ietf:params:oauth:grant-type:jwt-bearer"
|
|
23
|
+
JWT_BEARER_ASSERTION_TYPE: Final[str] = (
|
|
24
|
+
"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
|
|
25
|
+
)
|
|
26
|
+
REQUIRED_CLAIMS: Final[set[str]] = {"iss", "sub", "aud", "exp"}
|
|
27
|
+
OPTIONAL_FRESHNESS_CLAIMS: Final[set[str]] = {"iat", "nbf", "jti"}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
OWNER = StandardOwner(
|
|
31
|
+
label="RFC 7521",
|
|
32
|
+
title="Assertion Framework for OAuth 2.0 Client Authentication and Authorization Grants",
|
|
33
|
+
runtime_status=STATUS,
|
|
34
|
+
public_surface=("/token",),
|
|
35
|
+
notes=(
|
|
36
|
+
"Runtime-integrated JWT bearer assertion validation for assertion grants and "
|
|
37
|
+
"client_assertion payloads at the token endpoint."
|
|
38
|
+
),
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _coerce_audiences(audience: str | Iterable[str] | None) -> set[str]:
|
|
43
|
+
if audience is None:
|
|
44
|
+
return set()
|
|
45
|
+
if isinstance(audience, str):
|
|
46
|
+
return {audience}
|
|
47
|
+
return {str(item) for item in audience}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _coerce_aud_claim(value: object) -> set[str]:
|
|
51
|
+
if isinstance(value, str):
|
|
52
|
+
return {value}
|
|
53
|
+
if isinstance(value, (list, tuple, set)):
|
|
54
|
+
return {str(item) for item in value}
|
|
55
|
+
raise ValueError("invalid aud claim")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _require_timestamp(claims: dict[str, object], name: str) -> int:
|
|
59
|
+
value = claims.get(name)
|
|
60
|
+
if not isinstance(value, int):
|
|
61
|
+
raise InvalidTokenError(f"'{name}' claim must be an integer timestamp")
|
|
62
|
+
return value
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def validate_temporal_claims(
|
|
66
|
+
claims: dict[str, object],
|
|
67
|
+
*,
|
|
68
|
+
now: int | None = None,
|
|
69
|
+
leeway_seconds: int = 30,
|
|
70
|
+
) -> None:
|
|
71
|
+
current = int(time.time()) if now is None else int(now)
|
|
72
|
+
exp = _require_timestamp(claims, "exp")
|
|
73
|
+
if exp <= current - leeway_seconds:
|
|
74
|
+
raise InvalidTokenError("assertion is expired")
|
|
75
|
+
nbf = claims.get("nbf")
|
|
76
|
+
if nbf is not None:
|
|
77
|
+
if not isinstance(nbf, int):
|
|
78
|
+
raise InvalidTokenError("'nbf' claim must be an integer timestamp")
|
|
79
|
+
if nbf > current + leeway_seconds:
|
|
80
|
+
raise InvalidTokenError("assertion is not yet valid")
|
|
81
|
+
iat = claims.get("iat")
|
|
82
|
+
if iat is not None:
|
|
83
|
+
if not isinstance(iat, int):
|
|
84
|
+
raise InvalidTokenError("'iat' claim must be an integer timestamp")
|
|
85
|
+
if iat > current + leeway_seconds:
|
|
86
|
+
raise InvalidTokenError("assertion 'iat' claim is in the future")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def validate_jwt_assertion(
|
|
90
|
+
assertion: str,
|
|
91
|
+
*,
|
|
92
|
+
audience: str | Iterable[str] | None = None,
|
|
93
|
+
expected_issuer: str | None = None,
|
|
94
|
+
expected_subject: str | None = None,
|
|
95
|
+
now: int | None = None,
|
|
96
|
+
leeway_seconds: int = 30,
|
|
97
|
+
decoder=decode_jwt,
|
|
98
|
+
) -> dict[str, object]:
|
|
99
|
+
"""Validate a JWT bearer assertion per RFC 7521."""
|
|
100
|
+
|
|
101
|
+
if not settings.enable_rfc7521:
|
|
102
|
+
raise RuntimeError(f"RFC 7521 support disabled: {RFC7521_SPEC_URL}")
|
|
103
|
+
claims = dict(decoder(assertion))
|
|
104
|
+
missing = REQUIRED_CLAIMS - claims.keys()
|
|
105
|
+
if missing:
|
|
106
|
+
raise ValueError(f"missing claims: {', '.join(sorted(missing))}")
|
|
107
|
+
validate_temporal_claims(claims, now=now, leeway_seconds=leeway_seconds)
|
|
108
|
+
if expected_issuer is not None and claims.get("iss") != expected_issuer:
|
|
109
|
+
raise ValueError("invalid issuer")
|
|
110
|
+
if expected_subject is not None and claims.get("sub") != expected_subject:
|
|
111
|
+
raise ValueError("invalid subject")
|
|
112
|
+
expected_audiences = _coerce_audiences(audience)
|
|
113
|
+
if expected_audiences:
|
|
114
|
+
aud_values = _coerce_aud_claim(claims["aud"])
|
|
115
|
+
if aud_values.isdisjoint(expected_audiences):
|
|
116
|
+
raise ValueError("invalid audience")
|
|
117
|
+
return claims
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def validate_assertion_grant_request(
|
|
121
|
+
request_data: dict[str, str],
|
|
122
|
+
*,
|
|
123
|
+
audience: str | Iterable[str] | None,
|
|
124
|
+
now: int | None = None,
|
|
125
|
+
) -> dict[str, object]:
|
|
126
|
+
if str(request_data.get("grant_type") or "") != JWT_BEARER_GRANT_TYPE:
|
|
127
|
+
raise ValueError("invalid grant_type for RFC 7521 assertion processing")
|
|
128
|
+
assertion = str(request_data.get("assertion") or "").strip()
|
|
129
|
+
if not assertion:
|
|
130
|
+
raise ValueError("assertion parameter is required")
|
|
131
|
+
return validate_jwt_assertion(assertion, audience=audience, now=now)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def build_assertion_contract_examples(
|
|
135
|
+
token_endpoint_audience: str,
|
|
136
|
+
) -> list[dict[str, Any]]:
|
|
137
|
+
return [
|
|
138
|
+
{
|
|
139
|
+
"grant_type": JWT_BEARER_GRANT_TYPE,
|
|
140
|
+
"assertion": "<jwt-bearer-assertion>",
|
|
141
|
+
"scope": "openid profile email",
|
|
142
|
+
"client_id": "<client-id>",
|
|
143
|
+
"client_assertion_type": JWT_BEARER_ASSERTION_TYPE,
|
|
144
|
+
"client_assertion": "<client-auth-assertion>",
|
|
145
|
+
"audience": token_endpoint_audience,
|
|
146
|
+
}
|
|
147
|
+
]
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def describe() -> dict[str, object]:
|
|
151
|
+
return describe_owner(
|
|
152
|
+
OWNER,
|
|
153
|
+
spec_url=RFC7521_SPEC_URL,
|
|
154
|
+
assertion_grant_type=JWT_BEARER_GRANT_TYPE,
|
|
155
|
+
client_assertion_type=JWT_BEARER_ASSERTION_TYPE,
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
__all__ = [
|
|
160
|
+
"STATUS",
|
|
161
|
+
"RFC7521_SPEC_URL",
|
|
162
|
+
"JWT_BEARER_GRANT_TYPE",
|
|
163
|
+
"JWT_BEARER_ASSERTION_TYPE",
|
|
164
|
+
"REQUIRED_CLAIMS",
|
|
165
|
+
"OPTIONAL_FRESHNESS_CLAIMS",
|
|
166
|
+
"StandardOwner",
|
|
167
|
+
"OWNER",
|
|
168
|
+
"build_assertion_contract_examples",
|
|
169
|
+
"describe",
|
|
170
|
+
"validate_assertion_grant_request",
|
|
171
|
+
"validate_jwt_assertion",
|
|
172
|
+
"validate_temporal_claims",
|
|
173
|
+
]
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Utilities for the core OAuth 2.0 authorization framework.
|
|
2
|
+
|
|
3
|
+
This module provides helpers for validating token endpoint requests according
|
|
4
|
+
to RFC 6749 Section 5.2. Validation can be toggled on or off via the
|
|
5
|
+
``enable_rfc6749`` setting in :mod:`runtime_cfg`.
|
|
6
|
+
|
|
7
|
+
The public ``enforce_*`` helpers automatically respect the runtime flag making
|
|
8
|
+
RFC 6749 enforcement modular.
|
|
9
|
+
|
|
10
|
+
See RFC 6749: https://www.rfc-editor.org/rfc/rfc6749
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from typing import Final, Iterable, Mapping
|
|
16
|
+
|
|
17
|
+
from tba_contracts_identity.protocol_configuration import (
|
|
18
|
+
protocol_settings as settings,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
RFC6749_SPEC_URL: Final = "https://www.rfc-editor.org/rfc/rfc6749"
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"RFC6749Error",
|
|
25
|
+
"validate_grant_type",
|
|
26
|
+
"validate_password_grant",
|
|
27
|
+
"validate_authorization_code_grant",
|
|
28
|
+
"is_enabled",
|
|
29
|
+
"enforce_grant_type",
|
|
30
|
+
"enforce_password_grant",
|
|
31
|
+
"enforce_authorization_code_grant",
|
|
32
|
+
"RFC6749_SPEC_URL",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class RFC6749Error(ValueError):
|
|
37
|
+
"""Error raised for RFC 6749 validation failures."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def validate_grant_type(grant_type: str | None, allowed: Iterable[str]) -> None:
|
|
41
|
+
"""Validate presence and supported values of ``grant_type``.
|
|
42
|
+
|
|
43
|
+
Raises:
|
|
44
|
+
RFC6749Error: If ``grant_type`` is missing or not in ``allowed``.
|
|
45
|
+
"""
|
|
46
|
+
if not grant_type:
|
|
47
|
+
raise RFC6749Error("invalid_request")
|
|
48
|
+
if grant_type not in set(allowed):
|
|
49
|
+
raise RFC6749Error("unsupported_grant_type")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def validate_password_grant(form: Mapping[str, str]) -> None:
|
|
53
|
+
"""Ensure required parameters for the password grant are present.
|
|
54
|
+
|
|
55
|
+
RFC 6749 §4.3 mandates both ``username`` and ``password`` parameters. Missing
|
|
56
|
+
parameters result in ``invalid_request`` errors.
|
|
57
|
+
"""
|
|
58
|
+
if "username" not in form or "password" not in form:
|
|
59
|
+
raise RFC6749Error("invalid_request")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def validate_authorization_code_grant(form: Mapping[str, str]) -> None:
|
|
63
|
+
"""Ensure required parameters for the authorization code grant are present.
|
|
64
|
+
|
|
65
|
+
RFC 6749 §4.1.3 requires ``code``, ``redirect_uri`` and ``client_id``
|
|
66
|
+
parameters on the token endpoint when exchanging an authorization code.
|
|
67
|
+
Missing parameters result in ``invalid_request`` errors.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
required = {"code", "redirect_uri", "client_id"}
|
|
71
|
+
if not required.issubset(form):
|
|
72
|
+
raise RFC6749Error("invalid_request")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def is_enabled() -> bool:
|
|
76
|
+
"""Return ``True`` if RFC 6749 enforcement is active."""
|
|
77
|
+
|
|
78
|
+
return settings.enable_rfc6749
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def enforce_grant_type(grant_type: str | None, allowed: Iterable[str]) -> None:
|
|
82
|
+
"""Validate ``grant_type`` only when RFC 6749 enforcement is enabled."""
|
|
83
|
+
|
|
84
|
+
if not is_enabled():
|
|
85
|
+
return
|
|
86
|
+
validate_grant_type(grant_type, allowed)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def enforce_password_grant(form: Mapping[str, str]) -> None:
|
|
90
|
+
"""Validate password grant requirements when enforcement is enabled."""
|
|
91
|
+
|
|
92
|
+
if not is_enabled():
|
|
93
|
+
return
|
|
94
|
+
validate_password_grant(form)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def enforce_authorization_code_grant(form: Mapping[str, str]) -> None:
|
|
98
|
+
"""Validate authorization code grant requirements when enabled."""
|
|
99
|
+
|
|
100
|
+
if not is_enabled():
|
|
101
|
+
return
|
|
102
|
+
validate_authorization_code_grant(form)
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""OAuth authorization server metadata constants.
|
|
2
|
+
|
|
3
|
+
These constants collect the well-known JWKS path and issuer base URL.
|
|
4
|
+
OIDC modules should import from here rather than redefining these defaults.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
from typing import Final
|
|
11
|
+
|
|
12
|
+
from tba_primitives_identity.standards import StandardOwner, describe_owner
|
|
13
|
+
|
|
14
|
+
JWKS_PATH: Final[str] = "/.well-known/jwks.json"
|
|
15
|
+
ISSUER: Final[str] = os.getenv("AUTHN_ISSUER", "https://authn.example.com")
|
|
16
|
+
RFC8414_METADATA_PATH: Final[str] = "/.well-known/oauth-authorization-server"
|
|
17
|
+
RFC8414_SPEC_URL: Final[str] = "https://www.rfc-editor.org/rfc/rfc8414"
|
|
18
|
+
OWNER = StandardOwner(
|
|
19
|
+
label="RFC 8414",
|
|
20
|
+
title="OAuth 2.0 Authorization Server Metadata",
|
|
21
|
+
runtime_status="profile-aware-authorization-server-metadata",
|
|
22
|
+
public_surface=(RFC8414_METADATA_PATH,),
|
|
23
|
+
notes=("HTTP publication is composed above the protocol layer.",),
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def describe() -> dict[str, object]:
|
|
28
|
+
return describe_owner(
|
|
29
|
+
OWNER,
|
|
30
|
+
specification_version="RFC 8414",
|
|
31
|
+
metadata_path=RFC8414_METADATA_PATH,
|
|
32
|
+
spec_url=RFC8414_SPEC_URL,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
"ISSUER",
|
|
38
|
+
"JWKS_PATH",
|
|
39
|
+
"OWNER",
|
|
40
|
+
"RFC8414_METADATA_PATH",
|
|
41
|
+
"RFC8414_SPEC_URL",
|
|
42
|
+
"describe",
|
|
43
|
+
]
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""OAuth authorization server metadata endpoint exports."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from tba_protocol_oauth.standards.authorization_server_metadata import (
|
|
6
|
+
ISSUER,
|
|
7
|
+
JWKS_PATH,
|
|
8
|
+
OWNER,
|
|
9
|
+
RFC8414_METADATA_PATH,
|
|
10
|
+
RFC8414_SPEC_URL,
|
|
11
|
+
describe,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"ISSUER",
|
|
16
|
+
"JWKS_PATH",
|
|
17
|
+
"OWNER",
|
|
18
|
+
"RFC8414_METADATA_PATH",
|
|
19
|
+
"RFC8414_SPEC_URL",
|
|
20
|
+
"describe",
|
|
21
|
+
]
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Helpers for OAuth 2.0 Bearer Token Usage (RFC 6750).
|
|
2
|
+
|
|
3
|
+
This module extracts bearer tokens from HTTP requests according to
|
|
4
|
+
:rfc:`6750`. Support can be disabled entirely via ``settings.enable_rfc6750``.
|
|
5
|
+
Optional mechanisms for supplying the token in the URI query parameter or the
|
|
6
|
+
request body can also be toggled via settings to allow deployments to opt out
|
|
7
|
+
of these potentially insecure features.
|
|
8
|
+
|
|
9
|
+
See RFC 6750: https://www.rfc-editor.org/rfc/rfc6750
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from urllib.parse import parse_qs
|
|
15
|
+
|
|
16
|
+
from tigrbl.requests import Request
|
|
17
|
+
from typing import Final
|
|
18
|
+
|
|
19
|
+
from tba_contracts_identity.protocol_configuration import (
|
|
20
|
+
protocol_settings as settings,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
RFC6750_SPEC_URL: Final = "https://www.rfc-editor.org/rfc/rfc6750"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _active_settings():
|
|
27
|
+
try:
|
|
28
|
+
from tba_contracts_identity.protocol_configuration import (
|
|
29
|
+
protocol_settings as runtime_settings,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
return runtime_settings
|
|
33
|
+
except Exception: # pragma: no cover - import fallback
|
|
34
|
+
return settings
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
async def extract_bearer_token(request: Request, authorization: str) -> str | None:
|
|
38
|
+
"""Return the bearer token present in *request* if any.
|
|
39
|
+
|
|
40
|
+
The function follows the extraction rules from RFC 6750:
|
|
41
|
+
|
|
42
|
+
- The ``Authorization`` header uses a case-insensitive ``Bearer`` scheme.
|
|
43
|
+
- Extraction occurs only when ``settings.enable_rfc6750`` is ``True``.
|
|
44
|
+
- If ``settings.enable_rfc6750_query`` is ``True`` an ``access_token``
|
|
45
|
+
parameter in the URI query is accepted.
|
|
46
|
+
- If ``settings.enable_rfc6750_form`` is ``True`` an ``access_token``
|
|
47
|
+
field in an ``application/x-www-form-urlencoded`` body is accepted.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
active_settings = _active_settings()
|
|
51
|
+
if not active_settings.enable_rfc6750:
|
|
52
|
+
return None
|
|
53
|
+
|
|
54
|
+
if not isinstance(authorization, str) or not authorization.strip():
|
|
55
|
+
authorization = request.headers.get("Authorization", "")
|
|
56
|
+
parts = authorization.split()
|
|
57
|
+
if len(parts) == 2 and parts[0].lower() == "bearer":
|
|
58
|
+
return parts[1]
|
|
59
|
+
|
|
60
|
+
if active_settings.enable_rfc6750_query:
|
|
61
|
+
token = request.query_params.get("access_token")
|
|
62
|
+
if token:
|
|
63
|
+
return token
|
|
64
|
+
|
|
65
|
+
if (
|
|
66
|
+
active_settings.enable_rfc6750_form
|
|
67
|
+
and request.method in {"POST", "PUT", "PATCH"}
|
|
68
|
+
and "application/x-www-form-urlencoded"
|
|
69
|
+
in request.headers.get("Content-Type", "")
|
|
70
|
+
):
|
|
71
|
+
form_reader = getattr(request, "form", None)
|
|
72
|
+
if callable(form_reader):
|
|
73
|
+
form = await form_reader()
|
|
74
|
+
token = form.get("access_token")
|
|
75
|
+
else:
|
|
76
|
+
body = getattr(request, "body", b"") or b""
|
|
77
|
+
parsed = parse_qs(body.decode("utf-8"), keep_blank_values=True)
|
|
78
|
+
values = parsed.get("access_token") or []
|
|
79
|
+
token = values[0] if values else None
|
|
80
|
+
if token:
|
|
81
|
+
return token
|
|
82
|
+
|
|
83
|
+
return None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
__all__ = ["extract_bearer_token", "RFC6750_SPEC_URL"]
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""OAuth 2.0 Dynamic Client Registration Management Protocol owner module."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Final
|
|
7
|
+
|
|
8
|
+
from tba_capability_client_registration import ClientRegistrationCapability
|
|
9
|
+
from tba_contracts_identity.oauth import (
|
|
10
|
+
ClientRegistrationRecord,
|
|
11
|
+
ClientRegistrationUpdateRequest,
|
|
12
|
+
)
|
|
13
|
+
from tba_primitives_identity.standards import StandardOwner, describe_owner
|
|
14
|
+
|
|
15
|
+
STATUS: Final[str] = "persistence-backed-client-management-runtime"
|
|
16
|
+
RFC7592_SPEC_URL: Final[str] = "https://www.rfc-editor.org/rfc/rfc7592"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
OWNER = StandardOwner(
|
|
20
|
+
label="RFC 7592",
|
|
21
|
+
title="OAuth 2.0 Dynamic Client Registration Management Protocol",
|
|
22
|
+
runtime_status=STATUS,
|
|
23
|
+
public_surface=("/register/{client_id}",),
|
|
24
|
+
notes="Authoritative standards-tree owner module. Registration management is mounted on the public release path with bearer-authenticated GET/PUT/DELETE semantics, durable client-registration metadata persistence, and audit-observable update/delete behavior.",
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ClientRegistrationManagementDisabledError(RuntimeError):
|
|
29
|
+
"""Raised when composition disables RFC 7592 management."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True, slots=True)
|
|
33
|
+
class RFC7592ClientRegistrationManagementService:
|
|
34
|
+
"""Map RFC 7592 lifecycle operations to the registration capability."""
|
|
35
|
+
|
|
36
|
+
capability: ClientRegistrationCapability
|
|
37
|
+
enabled: bool = True
|
|
38
|
+
|
|
39
|
+
def _require_enabled(self) -> None:
|
|
40
|
+
if not self.enabled:
|
|
41
|
+
raise ClientRegistrationManagementDisabledError(
|
|
42
|
+
f"RFC 7592 support is disabled: {RFC7592_SPEC_URL}"
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
async def get(self, client_id: str) -> ClientRegistrationRecord | None:
|
|
46
|
+
self._require_enabled()
|
|
47
|
+
call = await self.capability.call("get_registration", client_id)
|
|
48
|
+
if call.value is not None and not isinstance(
|
|
49
|
+
call.value, ClientRegistrationRecord
|
|
50
|
+
):
|
|
51
|
+
raise TypeError(
|
|
52
|
+
"client.registration must return ClientRegistrationRecord or None"
|
|
53
|
+
)
|
|
54
|
+
return call.value
|
|
55
|
+
|
|
56
|
+
async def update(
|
|
57
|
+
self,
|
|
58
|
+
request: ClientRegistrationUpdateRequest,
|
|
59
|
+
) -> ClientRegistrationRecord:
|
|
60
|
+
self._require_enabled()
|
|
61
|
+
call = await self.capability.call("update_registration", request)
|
|
62
|
+
if not isinstance(call.value, ClientRegistrationRecord):
|
|
63
|
+
raise TypeError("client.registration must return ClientRegistrationRecord")
|
|
64
|
+
return call.value
|
|
65
|
+
|
|
66
|
+
async def delete(self, client_id: str) -> ClientRegistrationRecord:
|
|
67
|
+
self._require_enabled()
|
|
68
|
+
call = await self.capability.call("disable_registration", client_id)
|
|
69
|
+
if not isinstance(call.value, ClientRegistrationRecord):
|
|
70
|
+
raise TypeError("client.registration must return ClientRegistrationRecord")
|
|
71
|
+
return call.value
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def describe() -> dict[str, object]:
|
|
75
|
+
return describe_owner(
|
|
76
|
+
OWNER,
|
|
77
|
+
spec_url=RFC7592_SPEC_URL,
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
__all__ = [
|
|
82
|
+
"STATUS",
|
|
83
|
+
"RFC7592_SPEC_URL",
|
|
84
|
+
"ClientRegistrationManagementDisabledError",
|
|
85
|
+
"RFC7592ClientRegistrationManagementService",
|
|
86
|
+
"StandardOwner",
|
|
87
|
+
"OWNER",
|
|
88
|
+
"describe",
|
|
89
|
+
]
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""OAuth 2.0 Device Authorization Grant owner and helper module."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
import secrets
|
|
7
|
+
import string
|
|
8
|
+
from datetime import datetime, timezone
|
|
9
|
+
from typing import Final, Literal
|
|
10
|
+
from tba_primitives_identity.standards import StandardOwner, describe_owner
|
|
11
|
+
|
|
12
|
+
from tba_contracts_identity.protocol_configuration import (
|
|
13
|
+
protocol_settings as settings,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
try: # pragma: no cover - exercised when full runtime deps are installed
|
|
17
|
+
from tigrbl.types import BaseModel
|
|
18
|
+
except (
|
|
19
|
+
Exception
|
|
20
|
+
): # pragma: no cover - dependency-light fallback for checkpoint tests/evidence
|
|
21
|
+
from pydantic import BaseModel
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
STATUS: Final[str] = "persistence-backed-device-flow-runtime"
|
|
25
|
+
RFC8628_SPEC_URL: Final[str] = "https://www.rfc-editor.org/rfc/rfc8628"
|
|
26
|
+
DEVICE_VERIFICATION_URI: Final[str] = "https://example.com/device"
|
|
27
|
+
DEVICE_CODE_GRANT_TYPE: Final[str] = "urn:ietf:params:oauth:grant-type:device_code"
|
|
28
|
+
DEVICE_CODE_EXPIRES_IN: Final[int] = 600
|
|
29
|
+
DEVICE_CODE_INTERVAL: Final[int] = 5
|
|
30
|
+
DEVICE_CODE_SLOW_DOWN_INCREMENT: Final[int] = 5
|
|
31
|
+
_USER_CODE_CHARSET: Final[str] = string.ascii_uppercase + string.digits
|
|
32
|
+
_USER_CODE_RE: Final[re.Pattern[str]] = re.compile(r"^[A-Z0-9]{8,}$")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
OWNER = StandardOwner(
|
|
36
|
+
label="RFC 8628",
|
|
37
|
+
title="OAuth 2.0 Device Authorization Grant",
|
|
38
|
+
runtime_status=STATUS,
|
|
39
|
+
public_surface=("/device_authorization", "/token"),
|
|
40
|
+
notes=(
|
|
41
|
+
"Canonical standards-tree owner module for device-code lifecycle helpers. "
|
|
42
|
+
"The canonical /device_authorization and /token grant path are now "
|
|
43
|
+
"persistence-backed with authorization_pending / slow_down / access_denied / "
|
|
44
|
+
"expired_token semantics, replay protection, and audit-observable approval/denial state."
|
|
45
|
+
),
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class DeviceAuthIn(BaseModel):
|
|
50
|
+
client_id: str
|
|
51
|
+
scope: str | None = None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class DeviceAuthOut(BaseModel):
|
|
55
|
+
device_code: str
|
|
56
|
+
user_code: str
|
|
57
|
+
verification_uri: str
|
|
58
|
+
verification_uri_complete: str
|
|
59
|
+
expires_in: int
|
|
60
|
+
interval: int
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class DeviceGrantForm(BaseModel):
|
|
64
|
+
grant_type: Literal["urn:ietf:params:oauth:grant-type:device_code"]
|
|
65
|
+
device_code: str
|
|
66
|
+
client_id: str
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def generate_user_code(length: int = 8) -> str:
|
|
70
|
+
if length <= 0:
|
|
71
|
+
raise ValueError("length must be positive")
|
|
72
|
+
return "".join(secrets.choice(_USER_CODE_CHARSET) for _ in range(length))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def validate_user_code(code: str) -> bool:
|
|
76
|
+
if not settings.enable_rfc8628:
|
|
77
|
+
return True
|
|
78
|
+
return bool(_USER_CODE_RE.fullmatch(code))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def generate_device_code() -> str:
|
|
82
|
+
return secrets.token_urlsafe(32)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def next_device_poll_interval(
|
|
86
|
+
current_interval: int | None = None, *, slow_down_count: int = 0
|
|
87
|
+
) -> int:
|
|
88
|
+
base = max(int(current_interval or DEVICE_CODE_INTERVAL), DEVICE_CODE_INTERVAL)
|
|
89
|
+
if slow_down_count <= 0:
|
|
90
|
+
return base
|
|
91
|
+
return base + (DEVICE_CODE_SLOW_DOWN_INCREMENT * int(slow_down_count))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def poll_too_frequently(
|
|
95
|
+
*, last_polled_at: datetime | None, now: datetime, interval: int | None = None
|
|
96
|
+
) -> bool:
|
|
97
|
+
if last_polled_at is None:
|
|
98
|
+
return False
|
|
99
|
+
effective_interval = max(
|
|
100
|
+
int(interval or DEVICE_CODE_INTERVAL), DEVICE_CODE_INTERVAL
|
|
101
|
+
)
|
|
102
|
+
last = (
|
|
103
|
+
last_polled_at
|
|
104
|
+
if last_polled_at.tzinfo is not None
|
|
105
|
+
else last_polled_at.replace(tzinfo=timezone.utc)
|
|
106
|
+
)
|
|
107
|
+
return (now - last).total_seconds() < effective_interval
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def describe() -> dict[str, object]:
|
|
111
|
+
return describe_owner(
|
|
112
|
+
OWNER,
|
|
113
|
+
poll_interval_seconds=DEVICE_CODE_INTERVAL,
|
|
114
|
+
slow_down_increment_seconds=DEVICE_CODE_SLOW_DOWN_INCREMENT,
|
|
115
|
+
replay_protection_supported=True,
|
|
116
|
+
approval_denial_supported=True,
|
|
117
|
+
spec_url=RFC8628_SPEC_URL,
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
__all__ = [
|
|
122
|
+
"STATUS",
|
|
123
|
+
"RFC8628_SPEC_URL",
|
|
124
|
+
"DEVICE_VERIFICATION_URI",
|
|
125
|
+
"DEVICE_CODE_GRANT_TYPE",
|
|
126
|
+
"DEVICE_CODE_EXPIRES_IN",
|
|
127
|
+
"DEVICE_CODE_INTERVAL",
|
|
128
|
+
"DEVICE_CODE_SLOW_DOWN_INCREMENT",
|
|
129
|
+
"StandardOwner",
|
|
130
|
+
"OWNER",
|
|
131
|
+
"DeviceAuthIn",
|
|
132
|
+
"DeviceAuthOut",
|
|
133
|
+
"DeviceGrantForm",
|
|
134
|
+
"generate_user_code",
|
|
135
|
+
"validate_user_code",
|
|
136
|
+
"generate_device_code",
|
|
137
|
+
"next_device_poll_interval",
|
|
138
|
+
"poll_too_frequently",
|
|
139
|
+
"describe",
|
|
140
|
+
]
|