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,59 @@
|
|
|
1
|
+
"""RFC 9449 DPoP public surface."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from ._dpop import (
|
|
6
|
+
DPoPNonceRecord,
|
|
7
|
+
DPoPProofClaims,
|
|
8
|
+
OWNER,
|
|
9
|
+
RFC9449_SPEC_URL,
|
|
10
|
+
StandardOwner,
|
|
11
|
+
access_token_hash,
|
|
12
|
+
ath_for_access_token,
|
|
13
|
+
consume_nonce,
|
|
14
|
+
consume_nonce_async,
|
|
15
|
+
create_proof,
|
|
16
|
+
decode_proof,
|
|
17
|
+
describe,
|
|
18
|
+
issue_nonce,
|
|
19
|
+
issue_nonce_async,
|
|
20
|
+
jwk_from_public_key,
|
|
21
|
+
jwk_thumbprint,
|
|
22
|
+
make_proof,
|
|
23
|
+
makeProof,
|
|
24
|
+
proof_claims,
|
|
25
|
+
register_nonce,
|
|
26
|
+
register_nonce_async,
|
|
27
|
+
replay_table_snapshot,
|
|
28
|
+
replay_table_snapshot_async,
|
|
29
|
+
verify_proof,
|
|
30
|
+
verify_proof_async,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"DPoPNonceRecord",
|
|
35
|
+
"DPoPProofClaims",
|
|
36
|
+
"OWNER",
|
|
37
|
+
"RFC9449_SPEC_URL",
|
|
38
|
+
"StandardOwner",
|
|
39
|
+
"access_token_hash",
|
|
40
|
+
"ath_for_access_token",
|
|
41
|
+
"consume_nonce",
|
|
42
|
+
"consume_nonce_async",
|
|
43
|
+
"create_proof",
|
|
44
|
+
"decode_proof",
|
|
45
|
+
"describe",
|
|
46
|
+
"issue_nonce",
|
|
47
|
+
"issue_nonce_async",
|
|
48
|
+
"jwk_from_public_key",
|
|
49
|
+
"jwk_thumbprint",
|
|
50
|
+
"makeProof",
|
|
51
|
+
"make_proof",
|
|
52
|
+
"proof_claims",
|
|
53
|
+
"register_nonce",
|
|
54
|
+
"register_nonce_async",
|
|
55
|
+
"replay_table_snapshot",
|
|
56
|
+
"replay_table_snapshot_async",
|
|
57
|
+
"verify_proof",
|
|
58
|
+
"verify_proof_async",
|
|
59
|
+
]
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""OAuth 2.0 Dynamic Client Registration 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
|
+
ClientRegistrationCreateRequest,
|
|
11
|
+
ClientRegistrationRecord,
|
|
12
|
+
)
|
|
13
|
+
from tba_primitives_identity.standards import StandardOwner, describe_owner
|
|
14
|
+
|
|
15
|
+
STATUS: Final[str] = "dynamic-client-registration-runtime"
|
|
16
|
+
RFC7591_SPEC_URL: Final[str] = "https://www.rfc-editor.org/rfc/rfc7591"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
OWNER = StandardOwner(
|
|
20
|
+
label="RFC 7591",
|
|
21
|
+
title="OAuth 2.0 Dynamic Client Registration Protocol",
|
|
22
|
+
runtime_status=STATUS,
|
|
23
|
+
public_surface=("/register",),
|
|
24
|
+
notes="Authoritative standards-tree owner module. Canonical /register route is now mounted on the release path with request/response schemas, persistence backing, and OpenAPI visibility.",
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class DynamicClientRegistrationDisabledError(RuntimeError):
|
|
29
|
+
"""Raised when composition disables RFC 7591 registration."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True, slots=True)
|
|
33
|
+
class RFC7591DynamicClientRegistrationService:
|
|
34
|
+
"""Map normalized RFC 7591 input to client-registration capability calls."""
|
|
35
|
+
|
|
36
|
+
capability: ClientRegistrationCapability
|
|
37
|
+
enabled: bool = True
|
|
38
|
+
|
|
39
|
+
async def register(
|
|
40
|
+
self,
|
|
41
|
+
request: ClientRegistrationCreateRequest,
|
|
42
|
+
) -> ClientRegistrationRecord:
|
|
43
|
+
if not self.enabled:
|
|
44
|
+
raise DynamicClientRegistrationDisabledError(
|
|
45
|
+
f"RFC 7591 support is disabled: {RFC7591_SPEC_URL}"
|
|
46
|
+
)
|
|
47
|
+
call = await self.capability.call("register_client", request)
|
|
48
|
+
if not isinstance(call.value, ClientRegistrationRecord):
|
|
49
|
+
raise TypeError("client.registration must return ClientRegistrationRecord")
|
|
50
|
+
return call.value
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def describe() -> dict[str, object]:
|
|
54
|
+
return describe_owner(
|
|
55
|
+
OWNER,
|
|
56
|
+
spec_url=RFC7591_SPEC_URL,
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
__all__ = [
|
|
61
|
+
"STATUS",
|
|
62
|
+
"RFC7591_SPEC_URL",
|
|
63
|
+
"DynamicClientRegistrationDisabledError",
|
|
64
|
+
"RFC7591DynamicClientRegistrationService",
|
|
65
|
+
"StandardOwner",
|
|
66
|
+
"OWNER",
|
|
67
|
+
"describe",
|
|
68
|
+
]
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""RFC 7662 capability mapping without HTTP or persistence ownership."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Final
|
|
7
|
+
|
|
8
|
+
from tba_contracts_identity.tokens import (
|
|
9
|
+
TokenIntrospectionRequest,
|
|
10
|
+
TokenIntrospectionResult,
|
|
11
|
+
)
|
|
12
|
+
from tba_capability_token_introspection import TokenIntrospectionCapability
|
|
13
|
+
|
|
14
|
+
from ._introspection_activity import apply_introspection_activity_constraints
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
RFC7662_SPEC_URL: Final[str] = "https://www.rfc-editor.org/rfc/rfc7662"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class IntrospectionDisabledError(RuntimeError):
|
|
21
|
+
"""Raised when composition disables the RFC 7662 protocol feature."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True, slots=True)
|
|
25
|
+
class RFC7662IntrospectionService:
|
|
26
|
+
"""Map RFC 7662 semantics to protocol-neutral token introspection."""
|
|
27
|
+
|
|
28
|
+
capability: TokenIntrospectionCapability
|
|
29
|
+
enabled: bool = True
|
|
30
|
+
|
|
31
|
+
async def introspect(self, token: str) -> dict[str, object]:
|
|
32
|
+
if not self.enabled:
|
|
33
|
+
raise IntrospectionDisabledError(
|
|
34
|
+
f"RFC 7662 support is disabled: {RFC7662_SPEC_URL}"
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
call = await self.capability.call(
|
|
38
|
+
"introspect_token",
|
|
39
|
+
TokenIntrospectionRequest(token),
|
|
40
|
+
)
|
|
41
|
+
result = call.value
|
|
42
|
+
if not isinstance(result, TokenIntrospectionResult):
|
|
43
|
+
raise TypeError("token.introspection must return TokenIntrospectionResult")
|
|
44
|
+
|
|
45
|
+
payload: dict[str, object] = dict(result.claims)
|
|
46
|
+
payload["active"] = result.active
|
|
47
|
+
if result.reason is not None:
|
|
48
|
+
payload.setdefault("inactive_reason", result.reason)
|
|
49
|
+
return apply_introspection_activity_constraints(payload)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
__all__ = [
|
|
53
|
+
"IntrospectionDisabledError",
|
|
54
|
+
"RFC7662IntrospectionService",
|
|
55
|
+
"RFC7662_SPEC_URL",
|
|
56
|
+
]
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Authorization server issuer identification owner and helper module."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Final, Mapping, Sequence
|
|
6
|
+
|
|
7
|
+
from tba_primitives_identity.standards import StandardOwner, describe_owner
|
|
8
|
+
from urllib.parse import parse_qs, urlparse
|
|
9
|
+
|
|
10
|
+
from tba_contracts_identity.protocol_configuration import (
|
|
11
|
+
protocol_settings as settings,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
STATUS: Final[str] = "authorization-response-issuer-runtime"
|
|
15
|
+
RFC9207_SPEC_URL: Final[str] = "https://www.rfc-editor.org/rfc/rfc9207"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
OWNER = StandardOwner(
|
|
19
|
+
label="RFC 9207",
|
|
20
|
+
title="OAuth 2.0 Authorization Server Issuer Identification",
|
|
21
|
+
runtime_status=STATUS,
|
|
22
|
+
public_surface=("/authorize", "/.well-known/openid-configuration"),
|
|
23
|
+
notes=(
|
|
24
|
+
"Canonical standards-tree owner module for issuer parameter emission, redirect-response "
|
|
25
|
+
"parsing, and mix-up resistant validation of authorization-response issuer identifiers."
|
|
26
|
+
),
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class IssuerIdentificationError(ValueError):
|
|
31
|
+
"""Raised when an authorization response issuer parameter is invalid."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _validate_issuer_identifier(value: str) -> str:
|
|
35
|
+
issuer = str(value or "").strip()
|
|
36
|
+
parsed = urlparse(issuer)
|
|
37
|
+
if (
|
|
38
|
+
not issuer
|
|
39
|
+
or parsed.scheme != "https"
|
|
40
|
+
or not parsed.netloc
|
|
41
|
+
or parsed.query
|
|
42
|
+
or parsed.fragment
|
|
43
|
+
):
|
|
44
|
+
raise IssuerIdentificationError(
|
|
45
|
+
f"invalid issuer identifier: {RFC9207_SPEC_URL}"
|
|
46
|
+
)
|
|
47
|
+
return issuer.rstrip("/") if issuer.endswith("/") else issuer
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _coerce_issuer_values(value: object) -> list[str]:
|
|
51
|
+
if value is None or value == "":
|
|
52
|
+
return []
|
|
53
|
+
if isinstance(value, Sequence) and not isinstance(value, (bytes, bytearray, str)):
|
|
54
|
+
return [str(item) for item in value if str(item)]
|
|
55
|
+
return [str(value)]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def extract_issuer(params: Mapping[str, object], expected_issuer: str) -> str:
|
|
59
|
+
if not settings.enable_rfc9207:
|
|
60
|
+
raise NotImplementedError(
|
|
61
|
+
f"issuer identification not enabled: {RFC9207_SPEC_URL}"
|
|
62
|
+
)
|
|
63
|
+
expected = _validate_issuer_identifier(expected_issuer)
|
|
64
|
+
values = _coerce_issuer_values(params.get("iss"))
|
|
65
|
+
if not values:
|
|
66
|
+
raise IssuerIdentificationError(f"missing iss parameter: {RFC9207_SPEC_URL}")
|
|
67
|
+
normalized = [_validate_issuer_identifier(item) for item in values]
|
|
68
|
+
if len(set(normalized)) != 1:
|
|
69
|
+
raise IssuerIdentificationError(
|
|
70
|
+
f"multiple mismatched issuer identifiers in authorization response: {RFC9207_SPEC_URL}"
|
|
71
|
+
)
|
|
72
|
+
issuer = normalized[0]
|
|
73
|
+
if issuer != expected:
|
|
74
|
+
raise IssuerIdentificationError(f"issuer mismatch: {RFC9207_SPEC_URL}")
|
|
75
|
+
return issuer
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def authorization_response_issuer(issuer: str | None = None) -> tuple[str, str]:
|
|
79
|
+
if not settings.enable_rfc9207:
|
|
80
|
+
raise NotImplementedError(
|
|
81
|
+
f"issuer identification not enabled: {RFC9207_SPEC_URL}"
|
|
82
|
+
)
|
|
83
|
+
effective = issuer or settings.issuer
|
|
84
|
+
return ("iss", _validate_issuer_identifier(str(effective)))
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def extract_issuer_from_redirect_uri(redirect_uri: str, expected_issuer: str) -> str:
|
|
88
|
+
parsed = urlparse(str(redirect_uri))
|
|
89
|
+
candidates: dict[str, object] = {}
|
|
90
|
+
query_map = {
|
|
91
|
+
key: values
|
|
92
|
+
for key, values in parse_qs(parsed.query, keep_blank_values=True).items()
|
|
93
|
+
}
|
|
94
|
+
fragment_map = {
|
|
95
|
+
key: values
|
|
96
|
+
for key, values in parse_qs(parsed.fragment, keep_blank_values=True).items()
|
|
97
|
+
}
|
|
98
|
+
if "iss" in query_map:
|
|
99
|
+
candidates["iss"] = query_map["iss"]
|
|
100
|
+
elif "iss" in fragment_map:
|
|
101
|
+
candidates["iss"] = fragment_map["iss"]
|
|
102
|
+
return extract_issuer(candidates, expected_issuer)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def issuer_metadata(issuer: str | None = None) -> dict[str, object]:
|
|
106
|
+
return {
|
|
107
|
+
"authorization_response_iss_parameter_supported": bool(settings.enable_rfc9207),
|
|
108
|
+
"issuer": _validate_issuer_identifier(str(issuer or settings.issuer)),
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def describe() -> dict[str, object]:
|
|
113
|
+
return describe_owner(
|
|
114
|
+
OWNER,
|
|
115
|
+
spec_url=RFC9207_SPEC_URL,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
__all__ = [
|
|
120
|
+
"STATUS",
|
|
121
|
+
"RFC9207_SPEC_URL",
|
|
122
|
+
"StandardOwner",
|
|
123
|
+
"IssuerIdentificationError",
|
|
124
|
+
"OWNER",
|
|
125
|
+
"extract_issuer",
|
|
126
|
+
"authorization_response_issuer",
|
|
127
|
+
"extract_issuer_from_redirect_uri",
|
|
128
|
+
"issuer_metadata",
|
|
129
|
+
"describe",
|
|
130
|
+
]
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""RFC 7519 - JSON Web Token (JWT).
|
|
2
|
+
|
|
3
|
+
The canonical helpers prefer the runtime ``JWTCoder`` implementation, but they
|
|
4
|
+
also provide a dependency-light HS256 fallback for checkpoint environments where
|
|
5
|
+
Tigrbl/Swarmauri runtime services are not importable.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import base64
|
|
11
|
+
import hashlib
|
|
12
|
+
import hmac
|
|
13
|
+
import json
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
from typing import Any, Final
|
|
17
|
+
|
|
18
|
+
try:
|
|
19
|
+
import jwt as pyjwt
|
|
20
|
+
except ModuleNotFoundError: # pragma: no cover - dependency-light fallback
|
|
21
|
+
pyjwt = None
|
|
22
|
+
|
|
23
|
+
from tba_contracts_identity.protocol_configuration import (
|
|
24
|
+
protocol_settings as settings,
|
|
25
|
+
)
|
|
26
|
+
from tba_primitives_identity.errors import InvalidTokenError
|
|
27
|
+
from tba_protocol_oauth.jwtoken import JWTCoder
|
|
28
|
+
|
|
29
|
+
RFC7519_SPEC_URL: Final[str] = "https://www.rfc-editor.org/rfc/rfc7519"
|
|
30
|
+
_FALLBACK_ALGORITHM: Final[str] = "HS256"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _runtime_coder() -> JWTCoder | None:
|
|
34
|
+
try:
|
|
35
|
+
return JWTCoder.default()
|
|
36
|
+
except Exception:
|
|
37
|
+
return None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _call_runtime(operation):
|
|
41
|
+
def _call():
|
|
42
|
+
return operation(JWTCoder.default())
|
|
43
|
+
|
|
44
|
+
result: dict[str, Any] = {}
|
|
45
|
+
|
|
46
|
+
def _worker() -> None:
|
|
47
|
+
try:
|
|
48
|
+
result["value"] = _call()
|
|
49
|
+
except Exception as exc:
|
|
50
|
+
result["error"] = exc
|
|
51
|
+
|
|
52
|
+
try:
|
|
53
|
+
import asyncio
|
|
54
|
+
|
|
55
|
+
asyncio.get_running_loop()
|
|
56
|
+
except RuntimeError:
|
|
57
|
+
return _call()
|
|
58
|
+
|
|
59
|
+
thread = threading.Thread(target=_worker, daemon=True)
|
|
60
|
+
thread.start()
|
|
61
|
+
thread.join()
|
|
62
|
+
if "error" in result:
|
|
63
|
+
raise result["error"]
|
|
64
|
+
return result.get("value")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _b64url_encode(data: bytes) -> str:
|
|
68
|
+
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _b64url_decode(data: str) -> bytes:
|
|
72
|
+
padding = "=" * (-len(data) % 4)
|
|
73
|
+
return base64.urlsafe_b64decode((data + padding).encode("ascii"))
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _secret_bytes() -> bytes:
|
|
77
|
+
secret = getattr(settings, "jwt_secret", "")
|
|
78
|
+
return secret.encode("utf-8") if isinstance(secret, str) else bytes(secret)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _fallback_encode(**claims: Any) -> str:
|
|
82
|
+
if pyjwt is not None:
|
|
83
|
+
return str(
|
|
84
|
+
pyjwt.encode(claims, settings.jwt_secret, algorithm=_FALLBACK_ALGORITHM)
|
|
85
|
+
)
|
|
86
|
+
header = {"alg": _FALLBACK_ALGORITHM, "typ": "JWT"}
|
|
87
|
+
header_b64 = _b64url_encode(
|
|
88
|
+
json.dumps(header, separators=(",", ":"), sort_keys=True).encode("utf-8")
|
|
89
|
+
)
|
|
90
|
+
payload_b64 = _b64url_encode(
|
|
91
|
+
json.dumps(claims, separators=(",", ":"), sort_keys=True, default=str).encode(
|
|
92
|
+
"utf-8"
|
|
93
|
+
)
|
|
94
|
+
)
|
|
95
|
+
signing_input = f"{header_b64}.{payload_b64}".encode("ascii")
|
|
96
|
+
signature = hmac.new(_secret_bytes(), signing_input, hashlib.sha256).digest()
|
|
97
|
+
return f"{header_b64}.{payload_b64}.{_b64url_encode(signature)}"
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _fallback_decode(token: str) -> dict[str, Any]:
|
|
101
|
+
try:
|
|
102
|
+
if pyjwt is not None:
|
|
103
|
+
payload = pyjwt.decode_complete(
|
|
104
|
+
token, options={"verify_signature": False}
|
|
105
|
+
).get("payload", {})
|
|
106
|
+
options = {"require": ["exp"]} if "exp" in payload else {}
|
|
107
|
+
decode_options = {"verify_aud": False}
|
|
108
|
+
decode_options.update(options)
|
|
109
|
+
return dict(
|
|
110
|
+
pyjwt.decode(
|
|
111
|
+
token,
|
|
112
|
+
settings.jwt_secret,
|
|
113
|
+
algorithms=[_FALLBACK_ALGORITHM],
|
|
114
|
+
options=decode_options,
|
|
115
|
+
)
|
|
116
|
+
)
|
|
117
|
+
parts = token.split(".")
|
|
118
|
+
if len(parts) != 3:
|
|
119
|
+
raise InvalidTokenError("malformed token")
|
|
120
|
+
header_b64, payload_b64, signature_b64 = parts
|
|
121
|
+
signing_input = f"{header_b64}.{payload_b64}".encode("ascii")
|
|
122
|
+
expected = hmac.new(_secret_bytes(), signing_input, hashlib.sha256).digest()
|
|
123
|
+
actual = _b64url_decode(signature_b64)
|
|
124
|
+
if not hmac.compare_digest(expected, actual):
|
|
125
|
+
raise InvalidTokenError("unable to verify token")
|
|
126
|
+
payload = json.loads(_b64url_decode(payload_b64).decode("utf-8"))
|
|
127
|
+
if "exp" in payload and int(payload["exp"]) < int(time.time()):
|
|
128
|
+
raise InvalidTokenError("unable to verify token")
|
|
129
|
+
return dict(payload)
|
|
130
|
+
except InvalidTokenError:
|
|
131
|
+
raise
|
|
132
|
+
except Exception as exc:
|
|
133
|
+
raise InvalidTokenError("unable to verify token") from exc
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def encode_jwt(**claims: Any) -> str:
|
|
137
|
+
"""Encode *claims* as a JWT string."""
|
|
138
|
+
if not settings.enable_rfc7519:
|
|
139
|
+
raise RuntimeError(f"RFC 7519 support disabled: {RFC7519_SPEC_URL}")
|
|
140
|
+
sub = claims.pop("sub", "")
|
|
141
|
+
try:
|
|
142
|
+
return _call_runtime(lambda coder: coder.sign(sub=sub, **claims))
|
|
143
|
+
except Exception:
|
|
144
|
+
pass
|
|
145
|
+
return _fallback_encode(sub=sub, **claims)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def decode_jwt(token: str) -> dict[str, Any]:
|
|
149
|
+
"""Decode and verify *token* returning the claims dictionary."""
|
|
150
|
+
if not settings.enable_rfc7519:
|
|
151
|
+
raise RuntimeError(f"RFC 7519 support disabled: {RFC7519_SPEC_URL}")
|
|
152
|
+
try:
|
|
153
|
+
return _call_runtime(lambda coder: coder.decode(token, verify_revocation=False))
|
|
154
|
+
except Exception:
|
|
155
|
+
pass
|
|
156
|
+
return _fallback_decode(token)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
__all__ = ["encode_jwt", "decode_jwt", "RFC7519_SPEC_URL"]
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Domain-organized JWT access-token profile helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Dict, Final, Iterable, Set
|
|
6
|
+
|
|
7
|
+
from tba_primitives_identity.errors import InvalidTokenError
|
|
8
|
+
|
|
9
|
+
RFC9068_SPEC_URL: Final[str] = "https://www.rfc-editor.org/rfc/rfc9068"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def add_jwt_access_token_claims(
|
|
13
|
+
payload: Dict[str, Any], *, issuer: str, audience: Iterable[str] | str
|
|
14
|
+
) -> Dict[str, Any]:
|
|
15
|
+
augmented = dict(payload)
|
|
16
|
+
augmented["iss"] = issuer
|
|
17
|
+
augmented["aud"] = audience if isinstance(audience, str) else list(audience)
|
|
18
|
+
return augmented
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def validate_jwt_access_token_claims(
|
|
22
|
+
payload: Dict[str, Any], *, issuer: str, audience: Iterable[str] | str
|
|
23
|
+
) -> None:
|
|
24
|
+
if payload.get("iss") != issuer:
|
|
25
|
+
raise InvalidTokenError(f"issuer mismatch per RFC 9068: {RFC9068_SPEC_URL}")
|
|
26
|
+
token_aud = payload.get("aud")
|
|
27
|
+
expected: Set[str] = {audience} if isinstance(audience, str) else set(audience)
|
|
28
|
+
presented: Set[str] = (
|
|
29
|
+
{token_aud} if isinstance(token_aud, str) else set(token_aud or [])
|
|
30
|
+
)
|
|
31
|
+
if not (expected & presented):
|
|
32
|
+
raise InvalidTokenError(f"audience mismatch per RFC 9068: {RFC9068_SPEC_URL}")
|
|
33
|
+
for claim in ("sub", "exp"):
|
|
34
|
+
if claim not in payload:
|
|
35
|
+
raise InvalidTokenError(
|
|
36
|
+
f"{claim} claim required by RFC 9068: {RFC9068_SPEC_URL}"
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
__all__ = [
|
|
41
|
+
"RFC9068_SPEC_URL",
|
|
42
|
+
"add_jwt_access_token_claims",
|
|
43
|
+
"validate_jwt_access_token_claims",
|
|
44
|
+
]
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""JWT Best Current Practices validation utilities."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import json
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from tba_contracts_identity.protocol_configuration import (
|
|
10
|
+
protocol_settings as settings,
|
|
11
|
+
)
|
|
12
|
+
from tba_primitives_identity.errors import InvalidTokenError as BaseInvalidTokenError
|
|
13
|
+
from tba_protocol_oauth.jwtoken import JWTCoder
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class InvalidTokenError(BaseInvalidTokenError):
|
|
17
|
+
"""Raised when a JWT violates RFC 8725 recommendations."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
RFC8725_SPEC_URL = "https://www.rfc-editor.org/rfc/rfc8725"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def validate_jwt_best_practices(
|
|
24
|
+
token: str,
|
|
25
|
+
*,
|
|
26
|
+
enabled: bool | None = None,
|
|
27
|
+
) -> dict[str, Any]:
|
|
28
|
+
if enabled is None:
|
|
29
|
+
enabled = settings.enable_rfc8725
|
|
30
|
+
claims = JWTCoder.default().decode(token, verify_revocation=False)
|
|
31
|
+
if not enabled:
|
|
32
|
+
return claims
|
|
33
|
+
head_b64 = token.split(".")[0]
|
|
34
|
+
pad = "=" * ((4 - (len(head_b64) % 4)) % 4)
|
|
35
|
+
header = json.loads(base64.urlsafe_b64decode(head_b64 + pad))
|
|
36
|
+
if header.get("alg", "").lower() == "none":
|
|
37
|
+
raise InvalidTokenError("alg 'none' is prohibited by RFC 8725")
|
|
38
|
+
for required in ("iss", "aud", "exp", "sub"):
|
|
39
|
+
if required not in claims:
|
|
40
|
+
raise InvalidTokenError(f"missing '{required}' claim required by RFC 8725")
|
|
41
|
+
return claims
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
__all__ = ["InvalidTokenError", "RFC8725_SPEC_URL", "validate_jwt_best_practices"]
|