apipilot 0.1.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.
- apipilot/__init__.py +42 -0
- apipilot/asgi/__init__.py +49 -0
- apipilot/asgi/csrf.py +275 -0
- apipilot/asgi/csrf_extras.py +164 -0
- apipilot/asgi/diagnostics.py +131 -0
- apipilot/asgi/middleware.py +492 -0
- apipilot/asgi/observability.py +123 -0
- apipilot/asgi/openapi.py +150 -0
- apipilot/asgi/options.py +166 -0
- apipilot/asgi/ratelimit.py +56 -0
- apipilot/asgi/responses.py +143 -0
- apipilot/asgi/serialization.py +146 -0
- apipilot/content_negotiation.py +134 -0
- apipilot/cookie_profile.py +106 -0
- apipilot/correlation.py +83 -0
- apipilot/csrf_binding.py +35 -0
- apipilot/csrf_format.py +85 -0
- apipilot/envelope.py +111 -0
- apipilot/error_codes.py +90 -0
- apipilot/fetch_metadata.py +82 -0
- apipilot/field_key.py +42 -0
- apipilot/origin.py +77 -0
- apipilot/pagination.py +293 -0
- apipilot/wsgi.py +654 -0
- apipilot-0.1.0.dist-info/METADATA +166 -0
- apipilot-0.1.0.dist-info/RECORD +28 -0
- apipilot-0.1.0.dist-info/WHEEL +5 -0
- apipilot-0.1.0.dist-info/top_level.txt +1 -0
apipilot/__init__.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""apipilot — ApiPilot for Python.
|
|
2
|
+
|
|
3
|
+
Framework-neutral core (envelopes, error codes, pagination, validation
|
|
4
|
+
keys, origin, fetch-metadata, cookie rules, CSRF format and binding) plus
|
|
5
|
+
an optional ASGI adapter (``apipilot.asgi``) covering FastAPI, Starlette,
|
|
6
|
+
and ASGI-capable Django.
|
|
7
|
+
|
|
8
|
+
The core has zero dependencies. Install the adapter with::
|
|
9
|
+
|
|
10
|
+
pip install "apipilot[asgi]"
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from . import (
|
|
14
|
+
content_negotiation,
|
|
15
|
+
cookie_profile,
|
|
16
|
+
correlation,
|
|
17
|
+
csrf_binding,
|
|
18
|
+
csrf_format,
|
|
19
|
+
envelope,
|
|
20
|
+
error_codes,
|
|
21
|
+
fetch_metadata,
|
|
22
|
+
field_key,
|
|
23
|
+
origin,
|
|
24
|
+
pagination,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
__version__ = "0.1.0"
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"__version__",
|
|
31
|
+
"content_negotiation",
|
|
32
|
+
"cookie_profile",
|
|
33
|
+
"correlation",
|
|
34
|
+
"csrf_binding",
|
|
35
|
+
"csrf_format",
|
|
36
|
+
"envelope",
|
|
37
|
+
"error_codes",
|
|
38
|
+
"fetch_metadata",
|
|
39
|
+
"field_key",
|
|
40
|
+
"origin",
|
|
41
|
+
"pagination",
|
|
42
|
+
]
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""apipilot.asgi — the ASGI adapter for ApiPilot.
|
|
2
|
+
|
|
3
|
+
Pure ASGI middleware covering FastAPI, Starlette, and any ASGI-capable
|
|
4
|
+
framework (including Django via its ASGI handler). The core logic lives
|
|
5
|
+
in ``apipilot`` (framework-neutral); this subpackage is the HTTP binding.
|
|
6
|
+
|
|
7
|
+
Install with::
|
|
8
|
+
|
|
9
|
+
pip install "apipilot[asgi]"
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from . import csrf_extras, diagnostics, observability, openapi, serialization
|
|
13
|
+
from .csrf import (
|
|
14
|
+
CsrfBindingResolver,
|
|
15
|
+
CsrfKeyRing,
|
|
16
|
+
CsrfProtector,
|
|
17
|
+
CsrfService,
|
|
18
|
+
DefaultCsrfBindingResolver,
|
|
19
|
+
generate_key_material,
|
|
20
|
+
key_ring_from_env,
|
|
21
|
+
)
|
|
22
|
+
from .middleware import ApiPilotASGIMiddleware, ApiPilotOptions
|
|
23
|
+
from .responses import (
|
|
24
|
+
send_error,
|
|
25
|
+
send_paginated,
|
|
26
|
+
send_success,
|
|
27
|
+
send_validation_error,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"ApiPilotASGIMiddleware",
|
|
32
|
+
"ApiPilotOptions",
|
|
33
|
+
"CsrfBindingResolver",
|
|
34
|
+
"CsrfKeyRing",
|
|
35
|
+
"CsrfProtector",
|
|
36
|
+
"CsrfService",
|
|
37
|
+
"DefaultCsrfBindingResolver",
|
|
38
|
+
"csrf_extras",
|
|
39
|
+
"diagnostics",
|
|
40
|
+
"generate_key_material",
|
|
41
|
+
"key_ring_from_env",
|
|
42
|
+
"observability",
|
|
43
|
+
"openapi",
|
|
44
|
+
"send_error",
|
|
45
|
+
"send_paginated",
|
|
46
|
+
"send_success",
|
|
47
|
+
"send_validation_error",
|
|
48
|
+
"serialization",
|
|
49
|
+
]
|
apipilot/asgi/csrf.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
"""CSRF protection for the ASGI adapter — protector, service, binding.
|
|
2
|
+
|
|
3
|
+
Mirrors the TypeScript adapter's csrf/* modules and the C#
|
|
4
|
+
CsrfProtector/CsrfService/CsrfBindingProvider. The cryptographic
|
|
5
|
+
boundary is AES-256-GCM with a shared key ring and purpose isolation —
|
|
6
|
+
the Data-Protection equivalent.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import base64
|
|
12
|
+
import binascii
|
|
13
|
+
import hashlib
|
|
14
|
+
import hmac
|
|
15
|
+
import os
|
|
16
|
+
import time
|
|
17
|
+
from collections.abc import Callable
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from typing import Any, Protocol
|
|
20
|
+
|
|
21
|
+
from cryptography.exceptions import InvalidTag
|
|
22
|
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
23
|
+
|
|
24
|
+
from .. import csrf_binding, csrf_format
|
|
25
|
+
|
|
26
|
+
PURPOSE_DEFAULT = "ApiPilot.Csrf.v1"
|
|
27
|
+
VERSION = "v1"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(slots=True)
|
|
31
|
+
class CsrfKeyRing:
|
|
32
|
+
"""Key ring: active key id + keyId → 32-byte key material."""
|
|
33
|
+
|
|
34
|
+
active_key_id: str
|
|
35
|
+
keys: dict[str, bytes] = field(default_factory=dict)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class CsrfProtector:
|
|
39
|
+
"""Protects/unprotects CSRF token payloads (AES-256-GCM + key ring).
|
|
40
|
+
|
|
41
|
+
Wire format (base64url segments joined by ``.``):
|
|
42
|
+
v1.<keyId>.<iv>.<ciphertext>.<tag>
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def __init__(self, key_ring: CsrfKeyRing, purpose: str = PURPOSE_DEFAULT) -> None:
|
|
46
|
+
self._purpose = purpose
|
|
47
|
+
self._ring = key_ring
|
|
48
|
+
if key_ring.active_key_id not in key_ring.keys:
|
|
49
|
+
raise ValueError(
|
|
50
|
+
"CsrfProtector: active_key_id is not present in the key ring."
|
|
51
|
+
)
|
|
52
|
+
for kid, key in key_ring.keys.items():
|
|
53
|
+
if len(key) != 32:
|
|
54
|
+
raise ValueError(
|
|
55
|
+
f'CsrfProtector: key "{kid}" must be 32 bytes (AES-256).'
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
def protect(self, plaintext: str) -> str:
|
|
59
|
+
"""Encrypts a UTF-8 payload into the wire token."""
|
|
60
|
+
key = self._ring.keys[self._ring.active_key_id]
|
|
61
|
+
iv = os.urandom(12)
|
|
62
|
+
aesgcm = AESGCM(key)
|
|
63
|
+
ct_with_tag = aesgcm.encrypt(
|
|
64
|
+
iv, plaintext.encode("utf-8"), self._purpose.encode("utf-8")
|
|
65
|
+
)
|
|
66
|
+
ct, tag = ct_with_tag[:-16], ct_with_tag[-16:]
|
|
67
|
+
return ".".join(
|
|
68
|
+
[
|
|
69
|
+
VERSION,
|
|
70
|
+
self._ring.active_key_id,
|
|
71
|
+
base64.urlsafe_b64encode(iv).rstrip(b"=").decode("ascii"),
|
|
72
|
+
base64.urlsafe_b64encode(ct).rstrip(b"=").decode("ascii"),
|
|
73
|
+
base64.urlsafe_b64encode(tag).rstrip(b"=").decode("ascii"),
|
|
74
|
+
]
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
def unprotect(self, token: str) -> str | None:
|
|
78
|
+
"""Decrypts a wire token. Returns plaintext or None on ANY failure."""
|
|
79
|
+
parts = token.split(".")
|
|
80
|
+
if len(parts) != 5 or parts[0] != VERSION:
|
|
81
|
+
return None
|
|
82
|
+
_, key_id, iv_b64, ct_b64, tag_b64 = parts
|
|
83
|
+
key = self._ring.keys.get(key_id)
|
|
84
|
+
if key is None:
|
|
85
|
+
return None
|
|
86
|
+
try:
|
|
87
|
+
iv = base64.urlsafe_b64decode(iv_b64 + "=" * (-len(iv_b64) % 4))
|
|
88
|
+
ct = base64.urlsafe_b64decode(ct_b64 + "=" * (-len(ct_b64) % 4))
|
|
89
|
+
tag = base64.urlsafe_b64decode(tag_b64 + "=" * (-len(tag_b64) % 4))
|
|
90
|
+
if len(iv) != 12 or len(tag) != 16:
|
|
91
|
+
return None
|
|
92
|
+
aesgcm = AESGCM(key)
|
|
93
|
+
pt = aesgcm.decrypt(iv, ct + tag, self._purpose.encode("utf-8"))
|
|
94
|
+
return pt.decode("utf-8")
|
|
95
|
+
except (ValueError, binascii.Error, InvalidTag, UnicodeDecodeError):
|
|
96
|
+
return None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def key_ring_from_env(env: dict[str, str] | None = None) -> CsrfKeyRing:
|
|
100
|
+
"""Builds a key ring from APIPILOT_CSRF_KEYS / APIPILOT_CSRF_ACTIVE_KEY.
|
|
101
|
+
|
|
102
|
+
APIPILOT_CSRF_KEYS is a comma-separated list of ``keyId:base64key``
|
|
103
|
+
pairs. All instances sharing the same env config share the same ring.
|
|
104
|
+
"""
|
|
105
|
+
env = env if env is not None else dict(os.environ)
|
|
106
|
+
raw = env.get("APIPILOT_CSRF_KEYS")
|
|
107
|
+
active = env.get("APIPILOT_CSRF_ACTIVE_KEY")
|
|
108
|
+
if not raw or not active:
|
|
109
|
+
raise ValueError(
|
|
110
|
+
"APIPILOT_CSRF_KEYS and APIPILOT_CSRF_ACTIVE_KEY are required for CSRF protection."
|
|
111
|
+
)
|
|
112
|
+
keys: dict[str, bytes] = {}
|
|
113
|
+
for entry in raw.split(","):
|
|
114
|
+
idx = entry.find(":")
|
|
115
|
+
if idx <= 0:
|
|
116
|
+
raise ValueError(f'Malformed APIPILOT_CSRF_KEYS entry: "{entry}".')
|
|
117
|
+
kid = entry[:idx].strip()
|
|
118
|
+
keys[kid] = base64.b64decode(entry[idx + 1 :].strip())
|
|
119
|
+
return CsrfKeyRing(active_key_id=active.strip(), keys=keys)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def generate_key_material() -> str:
|
|
123
|
+
"""Generates a fresh 32-byte key, base64-encoded, for key-ring bootstrap."""
|
|
124
|
+
return base64.b64encode(os.urandom(32)).decode("ascii")
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def safe_equal(a: str, b: str) -> bool:
|
|
128
|
+
"""Constant-time string comparison."""
|
|
129
|
+
return hmac.compare_digest(a.encode("utf-8"), b.encode("utf-8"))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def hmac_sha256(key: bytes, data: str) -> bytes:
|
|
133
|
+
"""HMAC-SHA256 helper retained for binding-adjacent uses."""
|
|
134
|
+
return hmac.new(key, data.encode("utf-8"), hashlib.sha256).digest()
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
# ---------------------------------------------------------------------------
|
|
138
|
+
# Binding resolution
|
|
139
|
+
# ---------------------------------------------------------------------------
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@dataclass(frozen=True, slots=True)
|
|
143
|
+
class CsrfBindingResult:
|
|
144
|
+
"""Resolved binding: fingerprint + raw source + kind."""
|
|
145
|
+
|
|
146
|
+
fingerprint: str
|
|
147
|
+
source: str
|
|
148
|
+
kind: str # "subject" | "session" | "preauth"
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
class CsrfBindingResolver(Protocol):
|
|
152
|
+
"""Resolves the CSRF binding for a request scope."""
|
|
153
|
+
|
|
154
|
+
def resolve(self, scope: dict[str, Any]) -> CsrfBindingResult | None: ...
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@dataclass(slots=True)
|
|
158
|
+
class DefaultCsrfBindingResolver:
|
|
159
|
+
"""Resolution order: subject → session → preauth. Never anonymous."""
|
|
160
|
+
|
|
161
|
+
subject_extractor: Callable[[dict[str, Any]], str | None] | None = None
|
|
162
|
+
session_extractor: Callable[[dict[str, Any]], str | None] | None = None
|
|
163
|
+
pre_auth_source: Callable[[dict[str, Any]], str | None] | None = None
|
|
164
|
+
|
|
165
|
+
def resolve(self, scope: dict[str, Any]) -> CsrfBindingResult | None:
|
|
166
|
+
subject = self.subject_extractor(scope) if self.subject_extractor else None
|
|
167
|
+
if subject:
|
|
168
|
+
return CsrfBindingResult(
|
|
169
|
+
fingerprint=csrf_binding.csrf_binding_fingerprint(subject, "subject"),
|
|
170
|
+
source=subject,
|
|
171
|
+
kind="subject",
|
|
172
|
+
)
|
|
173
|
+
session_id = self.session_extractor(scope) if self.session_extractor else None
|
|
174
|
+
if session_id:
|
|
175
|
+
return CsrfBindingResult(
|
|
176
|
+
fingerprint=csrf_binding.csrf_binding_fingerprint(
|
|
177
|
+
session_id, "session"
|
|
178
|
+
),
|
|
179
|
+
source=session_id,
|
|
180
|
+
kind="session",
|
|
181
|
+
)
|
|
182
|
+
pre_auth = self.pre_auth_source(scope) if self.pre_auth_source else None
|
|
183
|
+
if pre_auth:
|
|
184
|
+
return CsrfBindingResult(
|
|
185
|
+
fingerprint=csrf_binding.csrf_binding_fingerprint(pre_auth, "preauth"),
|
|
186
|
+
source=pre_auth,
|
|
187
|
+
kind="preauth",
|
|
188
|
+
)
|
|
189
|
+
return None
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
# ---------------------------------------------------------------------------
|
|
193
|
+
# Token service
|
|
194
|
+
# ---------------------------------------------------------------------------
|
|
195
|
+
|
|
196
|
+
CsrfValidationOutcome = str # valid | missingToken | invalidSignature | malformedPayload | expired | bindingMismatch | missingBinding | rotated
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
@dataclass(frozen=True, slots=True)
|
|
200
|
+
class CsrfValidationResult:
|
|
201
|
+
"""Validation outcome + optional binding fingerprint."""
|
|
202
|
+
|
|
203
|
+
outcome: CsrfValidationOutcome
|
|
204
|
+
binding_fingerprint: str | None = None
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
class CsrfService:
|
|
208
|
+
"""Issues and validates CSRF tokens. Stateless — validity derives from
|
|
209
|
+
the protected payload (signature + expiry + binding), not server state.
|
|
210
|
+
Mirrors CsrfService.
|
|
211
|
+
"""
|
|
212
|
+
|
|
213
|
+
def __init__(
|
|
214
|
+
self,
|
|
215
|
+
protector: CsrfProtector,
|
|
216
|
+
binding_resolver: CsrfBindingResolver,
|
|
217
|
+
token_lifetime_seconds: int = 7200,
|
|
218
|
+
token_entropy_bytes: int = 32,
|
|
219
|
+
now: Callable[[], float] | None = None,
|
|
220
|
+
) -> None:
|
|
221
|
+
self._protector = protector
|
|
222
|
+
self._binding = binding_resolver
|
|
223
|
+
self._lifetime = token_lifetime_seconds
|
|
224
|
+
self._entropy = token_entropy_bytes
|
|
225
|
+
self._now = now or time.time
|
|
226
|
+
|
|
227
|
+
def issue_token(self, binding_source: str, binding_kind: str) -> str:
|
|
228
|
+
"""Issues a new token bound to the current request context."""
|
|
229
|
+
fingerprint = csrf_binding.csrf_binding_fingerprint(
|
|
230
|
+
binding_source, binding_kind
|
|
231
|
+
)
|
|
232
|
+
issued_at = int(self._now())
|
|
233
|
+
random_part = (
|
|
234
|
+
base64.urlsafe_b64encode(os.urandom(self._entropy))
|
|
235
|
+
.rstrip(b"=")
|
|
236
|
+
.decode("ascii")
|
|
237
|
+
)
|
|
238
|
+
payload = csrf_format.encode_csrf_payload(issued_at, random_part, fingerprint)
|
|
239
|
+
return self._protector.protect(payload)
|
|
240
|
+
|
|
241
|
+
def validate_token(
|
|
242
|
+
self, token: str | None, expected_fingerprint: str
|
|
243
|
+
) -> CsrfValidationResult:
|
|
244
|
+
"""Validates a wire token. Outcome ordering: signature → decode →
|
|
245
|
+
binding → expiry (mirrors CsrfService.ValidateWithMetadata)."""
|
|
246
|
+
if not token:
|
|
247
|
+
return CsrfValidationResult(outcome="missingToken")
|
|
248
|
+
|
|
249
|
+
plaintext = self._protector.unprotect(token)
|
|
250
|
+
if plaintext is None:
|
|
251
|
+
return CsrfValidationResult(outcome="invalidSignature")
|
|
252
|
+
|
|
253
|
+
parts = csrf_format.try_decode_csrf_payload(plaintext)
|
|
254
|
+
if parts is None:
|
|
255
|
+
return CsrfValidationResult(outcome="malformedPayload")
|
|
256
|
+
|
|
257
|
+
if parts.binding_fingerprint != expected_fingerprint:
|
|
258
|
+
return CsrfValidationResult(outcome="bindingMismatch")
|
|
259
|
+
|
|
260
|
+
# Rotation check (optional store attached via csrf_extras).
|
|
261
|
+
store = getattr(self, "_rotation_store", None)
|
|
262
|
+
if store is not None:
|
|
263
|
+
marker = store.get_rotation_marker(parts.binding_fingerprint)
|
|
264
|
+
if marker is not None and parts.issued_at_unix_seconds < marker:
|
|
265
|
+
return CsrfValidationResult(
|
|
266
|
+
outcome="rotated", binding_fingerprint=parts.binding_fingerprint
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
age = int(self._now()) - parts.issued_at_unix_seconds
|
|
270
|
+
if age > self._lifetime:
|
|
271
|
+
return CsrfValidationResult(outcome="expired")
|
|
272
|
+
|
|
273
|
+
return CsrfValidationResult(
|
|
274
|
+
outcome="valid", binding_fingerprint=parts.binding_fingerprint
|
|
275
|
+
)
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""CSRF extras — rotation store, transition listener, endpoint policy resolver.
|
|
2
|
+
|
|
3
|
+
Mirrors ICsrfRotationStore, DefaultCsrfTransitionListener, and
|
|
4
|
+
CsrfEndpointPolicyResolver (C# ApiPilot.Security).
|
|
5
|
+
|
|
6
|
+
A rotation marker is the Unix timestamp of the last rotation for a
|
|
7
|
+
binding. A token whose issue time is before the marker is rejected with
|
|
8
|
+
outcome ``"rotated"``. The store is optional; when absent the service
|
|
9
|
+
operates in expiry-only rotation mode.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
from typing import Any, Protocol
|
|
17
|
+
|
|
18
|
+
from .csrf import CsrfBindingResolver, CsrfService
|
|
19
|
+
|
|
20
|
+
# ---------------------------------------------------------------------------
|
|
21
|
+
# Rotation store
|
|
22
|
+
# ---------------------------------------------------------------------------
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class RotationStore(Protocol):
|
|
26
|
+
"""Persists rotation markers per binding fingerprint.
|
|
27
|
+
|
|
28
|
+
Implementations must be safe for concurrent use across requests.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
def get_rotation_marker(self, binding: str) -> int | None:
|
|
32
|
+
"""Returns the last-rotation Unix timestamp, or None."""
|
|
33
|
+
...
|
|
34
|
+
|
|
35
|
+
def set_rotation_marker(self, binding: str, unix_seconds: int) -> None:
|
|
36
|
+
"""Records a rotation marker for the binding."""
|
|
37
|
+
...
|
|
38
|
+
|
|
39
|
+
def clear_rotation_marker(self, binding: str) -> None:
|
|
40
|
+
"""Removes the marker for the binding."""
|
|
41
|
+
...
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class InMemoryRotationStore:
|
|
45
|
+
"""Process-local RotationStore."""
|
|
46
|
+
|
|
47
|
+
def __init__(self) -> None:
|
|
48
|
+
self._markers: dict[str, int] = {}
|
|
49
|
+
self._lock = threading.Lock()
|
|
50
|
+
|
|
51
|
+
def get_rotation_marker(self, binding: str) -> int | None:
|
|
52
|
+
with self._lock:
|
|
53
|
+
return self._markers.get(binding)
|
|
54
|
+
|
|
55
|
+
def set_rotation_marker(self, binding: str, unix_seconds: int) -> None:
|
|
56
|
+
with self._lock:
|
|
57
|
+
self._markers[binding] = unix_seconds
|
|
58
|
+
|
|
59
|
+
def clear_rotation_marker(self, binding: str) -> None:
|
|
60
|
+
with self._lock:
|
|
61
|
+
self._markers.pop(binding, None)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
# ---------------------------------------------------------------------------
|
|
65
|
+
# Service rotation wiring
|
|
66
|
+
# ---------------------------------------------------------------------------
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def attach_rotation_store(service: CsrfService, store: RotationStore) -> CsrfService:
|
|
70
|
+
"""Attaches a rotation store to the service (monkey-patch free: sets a
|
|
71
|
+
private attribute the service consults when present)."""
|
|
72
|
+
service._rotation_store = store # type: ignore[attr-defined]
|
|
73
|
+
return service
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def check_rotation(service: CsrfService, binding_fingerprint: str, issued_at: int) -> str | None:
|
|
77
|
+
"""Returns ``"rotated"`` when the token predates the binding's rotation
|
|
78
|
+
marker, else None. Called after binding match, before expiry."""
|
|
79
|
+
store = getattr(service, "_rotation_store", None)
|
|
80
|
+
if store is None:
|
|
81
|
+
return None
|
|
82
|
+
marker = store.get_rotation_marker(binding_fingerprint)
|
|
83
|
+
if marker is not None and issued_at < marker:
|
|
84
|
+
return "rotated"
|
|
85
|
+
return None
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def mark_rotated(service: CsrfService, binding_fingerprint: str) -> None:
|
|
89
|
+
"""Records a rotation marker for the binding at the current time."""
|
|
90
|
+
store = getattr(service, "_rotation_store", None)
|
|
91
|
+
if store is not None:
|
|
92
|
+
store.set_rotation_marker(binding_fingerprint, int(time.time()))
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
# ---------------------------------------------------------------------------
|
|
96
|
+
# Transition listener
|
|
97
|
+
# ---------------------------------------------------------------------------
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class CsrfTransitionListener:
|
|
101
|
+
"""Issues fresh tokens on login and clears rotation markers on logout.
|
|
102
|
+
|
|
103
|
+
Never authenticates users or writes cookies — the application owns its
|
|
104
|
+
session lifecycle. Mirrors DefaultCsrfTransitionListener.
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
def __init__(
|
|
108
|
+
self,
|
|
109
|
+
service: CsrfService,
|
|
110
|
+
binding_resolver: CsrfBindingResolver,
|
|
111
|
+
rotation_store: RotationStore | None = None,
|
|
112
|
+
) -> None:
|
|
113
|
+
self._service = service
|
|
114
|
+
self._resolver = binding_resolver
|
|
115
|
+
self._store = rotation_store
|
|
116
|
+
|
|
117
|
+
def on_login(self, scope: dict[str, Any]) -> str | None:
|
|
118
|
+
"""Resolves the binding for the request and issues a fresh token.
|
|
119
|
+
Returns None when no binding can be resolved — fail closed."""
|
|
120
|
+
binding = self._resolver.resolve(scope)
|
|
121
|
+
if binding is None:
|
|
122
|
+
return None
|
|
123
|
+
return self._service.issue_token(binding.source, binding.kind)
|
|
124
|
+
|
|
125
|
+
def on_login_with_binding(self, source: str, kind: str) -> str:
|
|
126
|
+
"""Issues a fresh token for an explicit binding."""
|
|
127
|
+
return self._service.issue_token(source, kind)
|
|
128
|
+
|
|
129
|
+
def on_logout(self, scope: dict[str, Any]) -> None:
|
|
130
|
+
"""Clears the rotation marker for the request's binding when a store
|
|
131
|
+
is registered. Safe before or after session teardown."""
|
|
132
|
+
if self._store is None:
|
|
133
|
+
return
|
|
134
|
+
binding = self._resolver.resolve(scope)
|
|
135
|
+
if binding is not None:
|
|
136
|
+
self._store.clear_rotation_marker(binding.fingerprint)
|
|
137
|
+
|
|
138
|
+
def on_logout_with_fingerprint(self, fingerprint: str) -> None:
|
|
139
|
+
"""Clears the rotation marker for an explicit binding fingerprint."""
|
|
140
|
+
if self._store is not None and fingerprint:
|
|
141
|
+
self._store.clear_rotation_marker(fingerprint)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
# ---------------------------------------------------------------------------
|
|
145
|
+
# Endpoint policy resolver
|
|
146
|
+
# ---------------------------------------------------------------------------
|
|
147
|
+
|
|
148
|
+
POLICY_USE_GLOBAL = "useGlobal"
|
|
149
|
+
POLICY_REQUIRE = "require"
|
|
150
|
+
POLICY_SKIP = "skip"
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def resolve_endpoint_policy(require: bool, skip: bool) -> str:
|
|
154
|
+
"""Combines per-route flags into the effective policy.
|
|
155
|
+
|
|
156
|
+
Precedence: Require > Skip > UseGlobal — mirrors
|
|
157
|
+
CsrfEndpointPolicyResolver. Later flags do not override earlier ones
|
|
158
|
+
of higher precedence.
|
|
159
|
+
"""
|
|
160
|
+
if require:
|
|
161
|
+
return POLICY_REQUIRE
|
|
162
|
+
if skip:
|
|
163
|
+
return POLICY_SKIP
|
|
164
|
+
return POLICY_USE_GLOBAL
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Security diagnostics surface — mirrors ApiPilotSecurityDiagnostics (C#).
|
|
2
|
+
|
|
3
|
+
Reports non-fatal configuration observations. Fatal conditions are
|
|
4
|
+
enforced at middleware construction time, not here. Never exposes
|
|
5
|
+
secrets.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from .csrf import DefaultCsrfBindingResolver
|
|
14
|
+
from .options import ApiPilotOptions
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True, slots=True)
|
|
18
|
+
class Diagnostic:
|
|
19
|
+
"""A non-fatal configuration observation."""
|
|
20
|
+
|
|
21
|
+
code: str
|
|
22
|
+
level: str # "info" | "warning"
|
|
23
|
+
message: str
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _binding_configured(binding: Any) -> bool:
|
|
27
|
+
if binding is None:
|
|
28
|
+
return False
|
|
29
|
+
if isinstance(binding, DefaultCsrfBindingResolver):
|
|
30
|
+
return any(
|
|
31
|
+
(
|
|
32
|
+
binding.subject_extractor,
|
|
33
|
+
binding.session_extractor,
|
|
34
|
+
binding.pre_auth_source,
|
|
35
|
+
)
|
|
36
|
+
)
|
|
37
|
+
return True # custom resolvers are assumed configured
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def diagnostics(options: ApiPilotOptions, binding: Any = None) -> list[Diagnostic]:
|
|
41
|
+
"""Returns non-fatal diagnostics for the resolved options."""
|
|
42
|
+
out: list[Diagnostic] = []
|
|
43
|
+
|
|
44
|
+
if options.csrf.enabled and not _binding_configured(binding):
|
|
45
|
+
out.append(
|
|
46
|
+
Diagnostic(
|
|
47
|
+
code="csrf-no-binding",
|
|
48
|
+
level="warning",
|
|
49
|
+
message=(
|
|
50
|
+
"CSRF is enabled but no binding resolver extractors are "
|
|
51
|
+
"configured; all bindings resolve to null and requests "
|
|
52
|
+
"fail closed."
|
|
53
|
+
),
|
|
54
|
+
)
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
if options.origin.enabled and not options.origin.allowed_origins:
|
|
58
|
+
out.append(
|
|
59
|
+
Diagnostic(
|
|
60
|
+
code="origin-empty-allowlist",
|
|
61
|
+
level="warning",
|
|
62
|
+
message=(
|
|
63
|
+
"Origin policy is enabled with an empty allowlist; all "
|
|
64
|
+
"unsafe requests with an Origin header are rejected."
|
|
65
|
+
),
|
|
66
|
+
)
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
if options.rate_limit.enabled and options.rate_limit.requests_per_window <= 0:
|
|
70
|
+
out.append(
|
|
71
|
+
Diagnostic(
|
|
72
|
+
code="rate-limit-default-limit",
|
|
73
|
+
level="info",
|
|
74
|
+
message=(
|
|
75
|
+
"Rate limiting is enabled with the default limit of 100 "
|
|
76
|
+
"requests per window."
|
|
77
|
+
),
|
|
78
|
+
)
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
return out
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def key_ring_diagnostics(key_ring: Any, csrf_enabled: bool) -> list[Diagnostic]:
|
|
85
|
+
"""Inspects the CSRF key ring for multi-instance safety.
|
|
86
|
+
|
|
87
|
+
Mirrors InstanceSafetyValidator + SharedKeyConfiguration (C#): a single
|
|
88
|
+
key or missing keys are legal but risky at scale — every instance must
|
|
89
|
+
share the same ring or tokens issued by one instance fail on another.
|
|
90
|
+
"""
|
|
91
|
+
out: list[Diagnostic] = []
|
|
92
|
+
if not csrf_enabled:
|
|
93
|
+
return out
|
|
94
|
+
keys = getattr(key_ring, "keys", None) or {}
|
|
95
|
+
active_id = getattr(key_ring, "active_key_id", "")
|
|
96
|
+
if not keys:
|
|
97
|
+
out.append(
|
|
98
|
+
Diagnostic(
|
|
99
|
+
code="csrf-keys-missing",
|
|
100
|
+
level="warning",
|
|
101
|
+
message=(
|
|
102
|
+
"CSRF is enabled but no key ring is configured; tokens "
|
|
103
|
+
"cannot be issued or validated."
|
|
104
|
+
),
|
|
105
|
+
)
|
|
106
|
+
)
|
|
107
|
+
return out
|
|
108
|
+
if len(keys) == 1:
|
|
109
|
+
out.append(
|
|
110
|
+
Diagnostic(
|
|
111
|
+
code="csrf-single-key",
|
|
112
|
+
level="info",
|
|
113
|
+
message=(
|
|
114
|
+
"CSRF key ring has a single key; rotation requires "
|
|
115
|
+
"downtime. Add a second key before rotating in "
|
|
116
|
+
"multi-instance deployments."
|
|
117
|
+
),
|
|
118
|
+
)
|
|
119
|
+
)
|
|
120
|
+
if active_id not in keys:
|
|
121
|
+
out.append(
|
|
122
|
+
Diagnostic(
|
|
123
|
+
code="csrf-active-key-missing",
|
|
124
|
+
level="warning",
|
|
125
|
+
message=(
|
|
126
|
+
"The CSRF active key ID is not present in the key ring; "
|
|
127
|
+
"new tokens cannot be signed."
|
|
128
|
+
),
|
|
129
|
+
)
|
|
130
|
+
)
|
|
131
|
+
return out
|