cc-platform-sdk 1.0.0__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.
- cc_platform_sdk/__init__.py +11 -0
- cc_platform_sdk/auth/__init__.py +106 -0
- cc_platform_sdk/auth/acting_user.py +288 -0
- cc_platform_sdk/auth/config.py +150 -0
- cc_platform_sdk/auth/credential_provider.py +177 -0
- cc_platform_sdk/auth/exceptions.py +113 -0
- cc_platform_sdk/auth/jwks_client.py +287 -0
- cc_platform_sdk/auth/middleware.py +210 -0
- cc_platform_sdk/auth/models.py +190 -0
- cc_platform_sdk/auth/security_identity.py +167 -0
- cc_platform_sdk/core/__init__.py +13 -0
- cc_platform_sdk/core/config/__init__.py +59 -0
- cc_platform_sdk/core/config/settings.py +110 -0
- cc_platform_sdk/core/config/standard_config.py +489 -0
- cc_platform_sdk/core/context/__init__.py +83 -0
- cc_platform_sdk/core/context/context.py +552 -0
- cc_platform_sdk/core/context/middleware.py +135 -0
- cc_platform_sdk/core/errors/__init__.py +118 -0
- cc_platform_sdk/core/errors/catalog.py +541 -0
- cc_platform_sdk/core/errors/codes.py +267 -0
- cc_platform_sdk/core/errors/exceptions.py +349 -0
- cc_platform_sdk/core/errors/protocol_mappings.py +288 -0
- cc_platform_sdk/core/feature_flags/__init__.py +29 -0
- cc_platform_sdk/core/feature_flags/provider.py +108 -0
- cc_platform_sdk/core/feature_flags/types.py +137 -0
- cc_platform_sdk/core/protocol/__init__.py +94 -0
- cc_platform_sdk/core/protocol/envelope.py +317 -0
- cc_platform_sdk/core/protocol/headers.py +215 -0
- cc_platform_sdk/core/protocol/service_tier.py +119 -0
- cc_platform_sdk/events/__init__.py +16 -0
- cc_platform_sdk/events/envelope.py +104 -0
- cc_platform_sdk/events/validation.py +21 -0
- cc_platform_sdk/infra/__init__.py +1 -0
- cc_platform_sdk/infra/cache/__init__.py +23 -0
- cc_platform_sdk/infra/cache/client.py +318 -0
- cc_platform_sdk/infra/ratelimit/__init__.py +22 -0
- cc_platform_sdk/infra/ratelimit/config.py +199 -0
- cc_platform_sdk/infra/ratelimit/limiter.py +276 -0
- cc_platform_sdk/lifecycle/__init__.py +53 -0
- cc_platform_sdk/lifecycle/health.py +83 -0
- cc_platform_sdk/lifecycle/lifecycle.py +338 -0
- cc_platform_sdk/lifecycle/types.py +147 -0
- cc_platform_sdk/observability/__init__.py +96 -0
- cc_platform_sdk/observability/correlation.py +177 -0
- cc_platform_sdk/observability/diagnostics.py +116 -0
- cc_platform_sdk/observability/envelope.py +140 -0
- cc_platform_sdk/observability/instrumentation.py +326 -0
- cc_platform_sdk/observability/interfaces.py +196 -0
- cc_platform_sdk/observability/logging/__init__.py +7 -0
- cc_platform_sdk/observability/logging/logger.py +119 -0
- cc_platform_sdk/observability/metrics/__init__.py +8 -0
- cc_platform_sdk/observability/metrics/helpers.py +67 -0
- cc_platform_sdk/observability/metrics/registry.py +260 -0
- cc_platform_sdk/observability/noop.py +128 -0
- cc_platform_sdk/observability/tracing/__init__.py +27 -0
- cc_platform_sdk/observability/tracing/config.py +55 -0
- cc_platform_sdk/observability/tracing/tracer.py +338 -0
- cc_platform_sdk/transport/__init__.py +1 -0
- cc_platform_sdk/transport/grpc/__init__.py +28 -0
- cc_platform_sdk/transport/grpc/interceptors.py +561 -0
- cc_platform_sdk/transport/http/__init__.py +41 -0
- cc_platform_sdk/transport/http/client.py +515 -0
- cc_platform_sdk/transport/http/retry.py +294 -0
- cc_platform_sdk/transport/kafka/__init__.py +50 -0
- cc_platform_sdk/transport/kafka/consumer.py +479 -0
- cc_platform_sdk/transport/kafka/errors.py +127 -0
- cc_platform_sdk/transport/kafka/producer.py +383 -0
- cc_platform_sdk/transport/serviceclient/__init__.py +87 -0
- cc_platform_sdk/transport/serviceclient/client.py +209 -0
- cc_platform_sdk/transport/serviceclient/discovery.py +89 -0
- cc_platform_sdk/transport/serviceclient/grpc_adapter.py +138 -0
- cc_platform_sdk/transport/serviceclient/http_adapter.py +143 -0
- cc_platform_sdk/transport/serviceclient/kafka_adapter.py +91 -0
- cc_platform_sdk/transport/serviceclient/types.py +211 -0
- cc_platform_sdk/utils/__init__.py +37 -0
- cc_platform_sdk/utils/ids.py +53 -0
- cc_platform_sdk/utils/serialization.py +99 -0
- cc_platform_sdk/utils/time.py +76 -0
- cc_platform_sdk-1.0.0.dist-info/METADATA +40 -0
- cc_platform_sdk-1.0.0.dist-info/RECORD +82 -0
- cc_platform_sdk-1.0.0.dist-info/WHEEL +4 -0
- cc_platform_sdk-1.0.0.dist-info/licenses/LICENSE +191 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Conscious Clouds Platform SDK for Python.
|
|
2
|
+
|
|
3
|
+
A framework-agnostic SDK providing standardized patterns for microservice
|
|
4
|
+
development: error handling, protocol envelopes, observability, auth,
|
|
5
|
+
transport, and infrastructure utilities.
|
|
6
|
+
|
|
7
|
+
This SDK contains zero product-specific references. Products (ENO, Omni, etc.)
|
|
8
|
+
extend it with their own defaults, event catalogs, and framework plugins.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
__version__ = "1.0.0"
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Authentication and authorization primitives.
|
|
2
|
+
|
|
3
|
+
Provides JWT validation via JWKS, token payload models, acting-user
|
|
4
|
+
HMAC verification, credential providers for outbound authentication,
|
|
5
|
+
canonical security identity, and a typed exception hierarchy. All
|
|
6
|
+
symbols are re-exported from submodules for convenient single-import
|
|
7
|
+
usage::
|
|
8
|
+
|
|
9
|
+
from cc_platform_sdk.auth import (
|
|
10
|
+
AuthConfig,
|
|
11
|
+
JWKSClient,
|
|
12
|
+
TokenPayload,
|
|
13
|
+
UserClaims,
|
|
14
|
+
SecurityIdentity,
|
|
15
|
+
CredentialProvider,
|
|
16
|
+
InvalidTokenError,
|
|
17
|
+
)
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from cc_platform_sdk.auth.acting_user import (
|
|
23
|
+
ActingUserContext,
|
|
24
|
+
HeaderNames,
|
|
25
|
+
extract_acting_user_headers,
|
|
26
|
+
sign_acting_user_headers,
|
|
27
|
+
verify_acting_user_signature,
|
|
28
|
+
)
|
|
29
|
+
from cc_platform_sdk.auth.config import AuthConfig, validate_config
|
|
30
|
+
from cc_platform_sdk.auth.credential_provider import (
|
|
31
|
+
BearerTokenProvider,
|
|
32
|
+
CredentialProvider,
|
|
33
|
+
CredentialResult,
|
|
34
|
+
MtlsConfig,
|
|
35
|
+
NoopCredentialProvider,
|
|
36
|
+
StaticTokenProvider,
|
|
37
|
+
)
|
|
38
|
+
from cc_platform_sdk.auth.exceptions import (
|
|
39
|
+
AuthenticationError,
|
|
40
|
+
InsufficientRoleError,
|
|
41
|
+
InsufficientScopeError,
|
|
42
|
+
InvalidTokenError,
|
|
43
|
+
JWKSError,
|
|
44
|
+
MissingTokenError,
|
|
45
|
+
TokenExpiredError,
|
|
46
|
+
)
|
|
47
|
+
from cc_platform_sdk.auth.jwks_client import JWKSClient, extract_bearer_token
|
|
48
|
+
from cc_platform_sdk.auth.models import (
|
|
49
|
+
TokenPayload,
|
|
50
|
+
UserClaims,
|
|
51
|
+
create_user_claims,
|
|
52
|
+
)
|
|
53
|
+
from cc_platform_sdk.auth.middleware import (
|
|
54
|
+
AuthMiddleware,
|
|
55
|
+
AuthMiddlewareConfig,
|
|
56
|
+
OutboundCredentialInterceptor,
|
|
57
|
+
)
|
|
58
|
+
from cc_platform_sdk.auth.security_identity import (
|
|
59
|
+
SecurityIdentity,
|
|
60
|
+
create_security_identity,
|
|
61
|
+
is_service_identity,
|
|
62
|
+
is_user_identity,
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
__all__ = [
|
|
66
|
+
# config
|
|
67
|
+
"AuthConfig",
|
|
68
|
+
"validate_config",
|
|
69
|
+
# models
|
|
70
|
+
"TokenPayload",
|
|
71
|
+
"UserClaims",
|
|
72
|
+
"create_user_claims",
|
|
73
|
+
# security identity
|
|
74
|
+
"SecurityIdentity",
|
|
75
|
+
"create_security_identity",
|
|
76
|
+
"is_service_identity",
|
|
77
|
+
"is_user_identity",
|
|
78
|
+
# credential providers
|
|
79
|
+
"CredentialProvider",
|
|
80
|
+
"CredentialResult",
|
|
81
|
+
"BearerTokenProvider",
|
|
82
|
+
"StaticTokenProvider",
|
|
83
|
+
"NoopCredentialProvider",
|
|
84
|
+
"MtlsConfig",
|
|
85
|
+
# jwks
|
|
86
|
+
"JWKSClient",
|
|
87
|
+
"extract_bearer_token",
|
|
88
|
+
# acting user
|
|
89
|
+
"HeaderNames",
|
|
90
|
+
"ActingUserContext",
|
|
91
|
+
"sign_acting_user_headers",
|
|
92
|
+
"extract_acting_user_headers",
|
|
93
|
+
"verify_acting_user_signature",
|
|
94
|
+
# middleware
|
|
95
|
+
"AuthMiddleware",
|
|
96
|
+
"AuthMiddlewareConfig",
|
|
97
|
+
"OutboundCredentialInterceptor",
|
|
98
|
+
# exceptions
|
|
99
|
+
"AuthenticationError",
|
|
100
|
+
"InvalidTokenError",
|
|
101
|
+
"TokenExpiredError",
|
|
102
|
+
"MissingTokenError",
|
|
103
|
+
"InsufficientScopeError",
|
|
104
|
+
"InsufficientRoleError",
|
|
105
|
+
"JWKSError",
|
|
106
|
+
]
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"""HMAC-SHA256 based acting-user header signing and verification.
|
|
2
|
+
|
|
3
|
+
When a gateway proxies a request on behalf of an authenticated user, it
|
|
4
|
+
attaches a set of signed headers that downstream services can verify.
|
|
5
|
+
This module provides the primitives to create and verify those headers.
|
|
6
|
+
|
|
7
|
+
Header names are **configurable** -- callers supply a
|
|
8
|
+
:class:`HeaderNames` instance so products can pick their own prefixes
|
|
9
|
+
without hard-coding ``X-Acting-*`` defaults.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import base64
|
|
15
|
+
import hashlib
|
|
16
|
+
import hmac
|
|
17
|
+
import uuid
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from datetime import datetime, timezone
|
|
20
|
+
from typing import Any, Callable, Optional
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
# ---------------------------------------------------------------------------
|
|
24
|
+
# Header name configuration
|
|
25
|
+
# ---------------------------------------------------------------------------
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class HeaderNames:
|
|
29
|
+
"""Configurable header names for acting-user context propagation.
|
|
30
|
+
|
|
31
|
+
Products supply their own instances so no ``X-Acting-*`` defaults
|
|
32
|
+
are baked into the SDK.
|
|
33
|
+
|
|
34
|
+
Attributes:
|
|
35
|
+
user_id: Header carrying the acting user's ID.
|
|
36
|
+
email: Header carrying the acting user's email.
|
|
37
|
+
roles: Header carrying a comma-separated role list.
|
|
38
|
+
timestamp: Header carrying the ISO-8601 signing timestamp.
|
|
39
|
+
nonce: Header carrying the one-time nonce (UUID v4).
|
|
40
|
+
signature: Header carrying the Base64-encoded HMAC-SHA256 signature.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
user_id: str
|
|
44
|
+
email: str
|
|
45
|
+
roles: str
|
|
46
|
+
timestamp: str
|
|
47
|
+
nonce: str
|
|
48
|
+
signature: str
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# ---------------------------------------------------------------------------
|
|
52
|
+
# Context dataclass
|
|
53
|
+
# ---------------------------------------------------------------------------
|
|
54
|
+
|
|
55
|
+
@dataclass
|
|
56
|
+
class ActingUserContext:
|
|
57
|
+
"""Represents the acting-user context extracted from request headers.
|
|
58
|
+
|
|
59
|
+
Attributes:
|
|
60
|
+
user_id: UUID of the original user on whose behalf the request is made.
|
|
61
|
+
email: Email address for audit logging.
|
|
62
|
+
roles: The original user's roles.
|
|
63
|
+
timestamp: When the signature was created.
|
|
64
|
+
timestamp_raw: Original timestamp string from the header -- used for
|
|
65
|
+
HMAC verification to avoid format mismatch between runtimes.
|
|
66
|
+
nonce: Unique request identifier for replay protection (UUID v4).
|
|
67
|
+
signature: Base64-encoded HMAC-SHA256 signature.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
user_id: str
|
|
71
|
+
email: str
|
|
72
|
+
roles: list[str] = field(default_factory=list)
|
|
73
|
+
timestamp: Optional[datetime] = None
|
|
74
|
+
timestamp_raw: str = ""
|
|
75
|
+
nonce: str = ""
|
|
76
|
+
signature: str = ""
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# ---------------------------------------------------------------------------
|
|
80
|
+
# Signing
|
|
81
|
+
# ---------------------------------------------------------------------------
|
|
82
|
+
|
|
83
|
+
_MAX_TIMESTAMP_SKEW_SECONDS = 60
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def sign_acting_user_headers(
|
|
87
|
+
user_id: str,
|
|
88
|
+
email: str,
|
|
89
|
+
roles: list[str],
|
|
90
|
+
hmac_secret: str,
|
|
91
|
+
header_names: HeaderNames,
|
|
92
|
+
*,
|
|
93
|
+
timestamp: str | None = None,
|
|
94
|
+
nonce: str | None = None,
|
|
95
|
+
) -> dict[str, str]:
|
|
96
|
+
"""Create HMAC-signed acting-user headers.
|
|
97
|
+
|
|
98
|
+
This is called by the gateway before proxying a request to an
|
|
99
|
+
internal service.
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
user_id: UUID of the acting user.
|
|
103
|
+
email: Email of the acting user.
|
|
104
|
+
roles: Roles of the acting user.
|
|
105
|
+
hmac_secret: Shared HMAC secret (must be >= 32 bytes).
|
|
106
|
+
header_names: Header name configuration.
|
|
107
|
+
timestamp: Override timestamp (default: datetime.now(timezone.utc).isoformat()).
|
|
108
|
+
nonce: Override nonce (default: uuid.uuid4()).
|
|
109
|
+
|
|
110
|
+
Returns:
|
|
111
|
+
A dict mapping header names to their values (ready for injection
|
|
112
|
+
into the outbound request).
|
|
113
|
+
|
|
114
|
+
Raises:
|
|
115
|
+
ValueError: If the secret is missing, too short, or required
|
|
116
|
+
fields are empty.
|
|
117
|
+
"""
|
|
118
|
+
_validate_hmac_inputs(user_id, email, hmac_secret)
|
|
119
|
+
|
|
120
|
+
ts = timestamp or datetime.now(timezone.utc).isoformat()
|
|
121
|
+
nonce = nonce or str(uuid.uuid4())
|
|
122
|
+
roles_str = ",".join(roles)
|
|
123
|
+
|
|
124
|
+
canonical = _build_canonical(user_id, email, roles_str, ts, nonce)
|
|
125
|
+
sig = _compute_hmac(canonical, hmac_secret)
|
|
126
|
+
|
|
127
|
+
return {
|
|
128
|
+
header_names.user_id: user_id,
|
|
129
|
+
header_names.email: email,
|
|
130
|
+
header_names.roles: roles_str,
|
|
131
|
+
header_names.timestamp: ts,
|
|
132
|
+
header_names.nonce: nonce,
|
|
133
|
+
header_names.signature: sig,
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
# ---------------------------------------------------------------------------
|
|
138
|
+
# Extraction
|
|
139
|
+
# ---------------------------------------------------------------------------
|
|
140
|
+
|
|
141
|
+
def extract_acting_user_headers(
|
|
142
|
+
headers: dict[str, str],
|
|
143
|
+
header_names: HeaderNames,
|
|
144
|
+
) -> Optional[ActingUserContext]:
|
|
145
|
+
"""Extract acting-user context from request headers.
|
|
146
|
+
|
|
147
|
+
Returns ``None`` when the user-id header is absent, which simply
|
|
148
|
+
means no acting-user context is present (e.g. a direct S2S call).
|
|
149
|
+
|
|
150
|
+
Args:
|
|
151
|
+
headers: A dictionary (or dict-like) of request headers.
|
|
152
|
+
header_names: Header name configuration.
|
|
153
|
+
|
|
154
|
+
Returns:
|
|
155
|
+
An :class:`ActingUserContext` or ``None``.
|
|
156
|
+
"""
|
|
157
|
+
getter: Callable[[str], str] = lambda name: headers.get(name, "")
|
|
158
|
+
|
|
159
|
+
uid = getter(header_names.user_id)
|
|
160
|
+
if not uid:
|
|
161
|
+
return None
|
|
162
|
+
|
|
163
|
+
email = getter(header_names.email)
|
|
164
|
+
roles_str = getter(header_names.roles)
|
|
165
|
+
ts_raw = getter(header_names.timestamp)
|
|
166
|
+
nonce = getter(header_names.nonce)
|
|
167
|
+
sig = getter(header_names.signature)
|
|
168
|
+
|
|
169
|
+
roles = roles_str.split(",") if roles_str else []
|
|
170
|
+
|
|
171
|
+
ts: Optional[datetime] = None
|
|
172
|
+
if ts_raw:
|
|
173
|
+
try:
|
|
174
|
+
ts = datetime.fromisoformat(ts_raw)
|
|
175
|
+
except ValueError:
|
|
176
|
+
pass
|
|
177
|
+
|
|
178
|
+
return ActingUserContext(
|
|
179
|
+
user_id=uid,
|
|
180
|
+
email=email,
|
|
181
|
+
roles=roles,
|
|
182
|
+
timestamp=ts,
|
|
183
|
+
timestamp_raw=ts_raw,
|
|
184
|
+
nonce=nonce,
|
|
185
|
+
signature=sig,
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
# ---------------------------------------------------------------------------
|
|
190
|
+
# Verification
|
|
191
|
+
# ---------------------------------------------------------------------------
|
|
192
|
+
|
|
193
|
+
def verify_acting_user_signature(
|
|
194
|
+
context: ActingUserContext,
|
|
195
|
+
hmac_secret: str,
|
|
196
|
+
max_skew_seconds: int = _MAX_TIMESTAMP_SKEW_SECONDS,
|
|
197
|
+
) -> None:
|
|
198
|
+
"""Verify the HMAC-SHA256 signature on an acting-user context.
|
|
199
|
+
|
|
200
|
+
Args:
|
|
201
|
+
context: The extracted acting-user context.
|
|
202
|
+
hmac_secret: The shared HMAC secret.
|
|
203
|
+
max_skew_seconds: Maximum allowed clock-skew in seconds.
|
|
204
|
+
|
|
205
|
+
Raises:
|
|
206
|
+
ValueError: On any verification failure (missing data, expired
|
|
207
|
+
timestamp, invalid signature, etc.).
|
|
208
|
+
"""
|
|
209
|
+
if not hmac_secret:
|
|
210
|
+
raise ValueError("HMAC secret is not configured")
|
|
211
|
+
if len(hmac_secret) < 32:
|
|
212
|
+
raise ValueError("HMAC secret must be at least 32 bytes")
|
|
213
|
+
if not context.signature:
|
|
214
|
+
raise ValueError("Missing signature in acting-user context")
|
|
215
|
+
|
|
216
|
+
# -- Timestamp validation ----------------------------------------------
|
|
217
|
+
if context.timestamp is None:
|
|
218
|
+
raise ValueError("Acting-user timestamp is missing or invalid")
|
|
219
|
+
|
|
220
|
+
now = datetime.now(timezone.utc)
|
|
221
|
+
# Ensure context.timestamp is timezone-aware for comparison
|
|
222
|
+
ts = context.timestamp
|
|
223
|
+
if ts.tzinfo is None:
|
|
224
|
+
ts = ts.replace(tzinfo=timezone.utc)
|
|
225
|
+
|
|
226
|
+
delta = abs((now - ts).total_seconds())
|
|
227
|
+
if delta > max_skew_seconds:
|
|
228
|
+
raise ValueError(
|
|
229
|
+
f"Acting-user timestamp skew ({delta:.1f}s) exceeds "
|
|
230
|
+
f"maximum ({max_skew_seconds}s)"
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
# -- Reconstruct canonical string & verify HMAC ------------------------
|
|
234
|
+
# CRITICAL: Use timestamp_raw (the original string from the header)
|
|
235
|
+
# to avoid format mismatch between different runtimes.
|
|
236
|
+
ts_str = context.timestamp_raw or context.timestamp.isoformat()
|
|
237
|
+
roles_str = ",".join(context.roles)
|
|
238
|
+
canonical = _build_canonical(
|
|
239
|
+
context.user_id, context.email, roles_str, ts_str, context.nonce
|
|
240
|
+
)
|
|
241
|
+
expected = _compute_hmac(canonical, hmac_secret)
|
|
242
|
+
|
|
243
|
+
if not hmac.compare_digest(context.signature, expected):
|
|
244
|
+
raise ValueError("Invalid acting-user signature")
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
# ---------------------------------------------------------------------------
|
|
248
|
+
# Internal helpers
|
|
249
|
+
# ---------------------------------------------------------------------------
|
|
250
|
+
|
|
251
|
+
def _validate_hmac_inputs(user_id: str, email: str, secret: str) -> None:
|
|
252
|
+
if not secret:
|
|
253
|
+
raise ValueError("HMAC secret is not configured")
|
|
254
|
+
if len(secret) < 32:
|
|
255
|
+
raise ValueError("HMAC secret must be at least 32 bytes")
|
|
256
|
+
if not user_id:
|
|
257
|
+
raise ValueError("Acting user ID is required")
|
|
258
|
+
if not email:
|
|
259
|
+
raise ValueError("Acting user email is required")
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _build_canonical(
|
|
263
|
+
user_id: str,
|
|
264
|
+
email: str,
|
|
265
|
+
roles_str: str,
|
|
266
|
+
timestamp: str,
|
|
267
|
+
nonce: str,
|
|
268
|
+
) -> str:
|
|
269
|
+
"""Build the canonical string used as HMAC input.
|
|
270
|
+
|
|
271
|
+
Order matters and must match the signing side exactly.
|
|
272
|
+
"""
|
|
273
|
+
return "\n".join([user_id, email, roles_str, timestamp, nonce])
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _compute_hmac(canonical: str, secret: str) -> str:
|
|
277
|
+
"""Compute HMAC-SHA256 and return Base64-encoded result."""
|
|
278
|
+
mac = hmac.new(secret.encode(), canonical.encode(), hashlib.sha256)
|
|
279
|
+
return base64.b64encode(mac.digest()).decode()
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
__all__ = [
|
|
283
|
+
"HeaderNames",
|
|
284
|
+
"ActingUserContext",
|
|
285
|
+
"sign_acting_user_headers",
|
|
286
|
+
"extract_acting_user_headers",
|
|
287
|
+
"verify_acting_user_signature",
|
|
288
|
+
]
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Authentication configuration.
|
|
2
|
+
|
|
3
|
+
Provides :class:`AuthConfig`, a Pydantic ``BaseSettings`` model that reads
|
|
4
|
+
authentication parameters from environment variables. The three core fields
|
|
5
|
+
-- ``jwks_url``, ``jwt_issuer``, and ``jwt_audience`` -- are **required** and
|
|
6
|
+
have no defaults. Products must supply their own values, either via
|
|
7
|
+
environment variables or by instantiating ``AuthConfig`` directly.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from pydantic import Field, field_validator
|
|
13
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class AuthConfig(BaseSettings):
|
|
17
|
+
"""Authentication configuration for platform services.
|
|
18
|
+
|
|
19
|
+
Environment variables (case-insensitive):
|
|
20
|
+
|
|
21
|
+
==================== =========================================
|
|
22
|
+
Variable Field
|
|
23
|
+
==================== =========================================
|
|
24
|
+
JWKS_URL URL to fetch JWKS keys
|
|
25
|
+
JWT_ISSUER Expected ``iss`` claim
|
|
26
|
+
JWT_AUDIENCE Expected ``aud`` claim (str or list)
|
|
27
|
+
JWT_ALGORITHM Signing algorithm (default ``RS256``)
|
|
28
|
+
JWT_LEEWAY_SECONDS Clock-skew tolerance (default ``5``)
|
|
29
|
+
JWKS_CACHE_TTL_SECONDS JWKS cache duration (default ``300``)
|
|
30
|
+
TOKEN_CACHE_TTL_SECONDS Validated-token cache TTL (default ``600``)
|
|
31
|
+
TOKEN_CACHE_PREFIX Redis key prefix (default ``auth:token:``)
|
|
32
|
+
ACCESS_TOKEN_EXPIRY_SECONDS Access token lifetime (default ``900``)
|
|
33
|
+
REFRESH_TOKEN_EXPIRY_SECONDS Refresh token lifetime (default ``604800``)
|
|
34
|
+
COOKIE_PATH Cookie path (default ``/``)
|
|
35
|
+
COOKIE_SECURE Cookie secure flag (default ``False``)
|
|
36
|
+
COOKIE_SAME_SITE Cookie SameSite attribute (default ``lax``)
|
|
37
|
+
==================== =========================================
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
model_config = SettingsConfigDict(
|
|
41
|
+
env_file=".env",
|
|
42
|
+
env_file_encoding="utf-8",
|
|
43
|
+
case_sensitive=False,
|
|
44
|
+
extra="ignore",
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
# --- Required (no defaults) -------------------------------------------
|
|
48
|
+
|
|
49
|
+
jwks_url: str = Field(
|
|
50
|
+
description="URL to fetch JWKS keys from the identity provider",
|
|
51
|
+
)
|
|
52
|
+
jwt_issuer: str = Field(
|
|
53
|
+
description="Expected token issuer (iss claim)",
|
|
54
|
+
)
|
|
55
|
+
jwt_audience: str | list[str] = Field(
|
|
56
|
+
description="Expected token audience (aud claim). String or list of strings.",
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
# --- Optional with sensible defaults ----------------------------------
|
|
60
|
+
|
|
61
|
+
jwt_algorithm: str = Field(
|
|
62
|
+
default="RS256",
|
|
63
|
+
description="JWT signing algorithm",
|
|
64
|
+
)
|
|
65
|
+
jwt_leeway_seconds: int = Field(
|
|
66
|
+
default=5,
|
|
67
|
+
description="Clock-skew tolerance in seconds (0-60)",
|
|
68
|
+
)
|
|
69
|
+
jwks_cache_ttl_seconds: int = Field(
|
|
70
|
+
default=300,
|
|
71
|
+
description="JWKS cache TTL in seconds (5 minutes)",
|
|
72
|
+
)
|
|
73
|
+
token_cache_ttl_seconds: int = Field(
|
|
74
|
+
default=600,
|
|
75
|
+
description="Validated-token cache TTL in seconds (10 minutes)",
|
|
76
|
+
)
|
|
77
|
+
token_cache_prefix: str = Field(
|
|
78
|
+
default="auth:token:",
|
|
79
|
+
description="Redis key prefix for cached token payloads",
|
|
80
|
+
)
|
|
81
|
+
access_token_expiry_seconds: int = Field(
|
|
82
|
+
default=900,
|
|
83
|
+
description="Access token lifetime in seconds (15 minutes)",
|
|
84
|
+
)
|
|
85
|
+
refresh_token_expiry_seconds: int = Field(
|
|
86
|
+
default=604800,
|
|
87
|
+
description="Refresh token lifetime in seconds (7 days)",
|
|
88
|
+
)
|
|
89
|
+
cookie_path: str = Field(
|
|
90
|
+
default="/",
|
|
91
|
+
description="Cookie path",
|
|
92
|
+
)
|
|
93
|
+
cookie_secure: bool = Field(
|
|
94
|
+
default=False,
|
|
95
|
+
description="Cookie secure flag (HTTPS only)",
|
|
96
|
+
)
|
|
97
|
+
cookie_same_site: str = Field(
|
|
98
|
+
default="lax",
|
|
99
|
+
description="Cookie SameSite attribute (strict, lax, none)",
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
@field_validator("jwt_leeway_seconds")
|
|
103
|
+
@classmethod
|
|
104
|
+
def validate_leeway_bounds(cls, v: int) -> int:
|
|
105
|
+
"""Validate that leeway is within 0-60 seconds."""
|
|
106
|
+
if v < 0 or v > 60:
|
|
107
|
+
raise ValueError(
|
|
108
|
+
f"jwt_leeway_seconds must be between 0 and 60, got {v}"
|
|
109
|
+
)
|
|
110
|
+
return v
|
|
111
|
+
|
|
112
|
+
@field_validator("cookie_same_site")
|
|
113
|
+
@classmethod
|
|
114
|
+
def validate_same_site(cls, v: str) -> str:
|
|
115
|
+
"""Validate that cookie_same_site is a valid value."""
|
|
116
|
+
valid = {"strict", "lax", "none"}
|
|
117
|
+
if v.lower() not in valid:
|
|
118
|
+
raise ValueError(
|
|
119
|
+
f"cookie_same_site must be one of {valid}, got {v!r}"
|
|
120
|
+
)
|
|
121
|
+
return v.lower()
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def validate_config(config: AuthConfig) -> None:
|
|
125
|
+
"""Validate that all required ``AuthConfig`` fields are set.
|
|
126
|
+
|
|
127
|
+
Args:
|
|
128
|
+
config: The configuration instance to validate.
|
|
129
|
+
|
|
130
|
+
Raises:
|
|
131
|
+
ValueError: If any required field is missing or empty.
|
|
132
|
+
"""
|
|
133
|
+
missing: list[str] = []
|
|
134
|
+
if not config.jwks_url:
|
|
135
|
+
missing.append("jwks_url")
|
|
136
|
+
if not config.jwt_issuer:
|
|
137
|
+
missing.append("jwt_issuer")
|
|
138
|
+
if not config.jwt_audience:
|
|
139
|
+
missing.append("jwt_audience")
|
|
140
|
+
if missing:
|
|
141
|
+
raise ValueError(
|
|
142
|
+
f"AuthConfig validation failed -- required fields missing: "
|
|
143
|
+
f"{', '.join(missing)}"
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
__all__ = [
|
|
148
|
+
"AuthConfig",
|
|
149
|
+
"validate_config",
|
|
150
|
+
]
|