rn-forge-fastapi 0.4.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.
- rn_forge/fastapi/__init__.py +111 -0
- rn_forge/fastapi/app.py +210 -0
- rn_forge/fastapi/auth/__init__.py +69 -0
- rn_forge/fastapi/auth/authorization.py +62 -0
- rn_forge/fastapi/auth/csrf.py +243 -0
- rn_forge/fastapi/auth/dependencies.py +374 -0
- rn_forge/fastapi/auth/proxies.py +55 -0
- rn_forge/fastapi/auth/rate_limit.py +91 -0
- rn_forge/fastapi/auth/redis.py +88 -0
- rn_forge/fastapi/auth/routes.py +725 -0
- rn_forge/fastapi/auth/sessions.py +504 -0
- rn_forge/fastapi/cors.py +80 -0
- rn_forge/fastapi/dependencies.py +157 -0
- rn_forge/fastapi/deprecation.py +45 -0
- rn_forge/fastapi/health.py +71 -0
- rn_forge/fastapi/idempotency.py +82 -0
- rn_forge/fastapi/merge_patch.py +89 -0
- rn_forge/fastapi/openapi.py +91 -0
- rn_forge/fastapi/problem.py +155 -0
- rn_forge/fastapi/py.typed +0 -0
- rn_forge/fastapi/read_mask.py +86 -0
- rn_forge/fastapi/soft_delete.py +188 -0
- rn_forge/fastapi/transfer.py +936 -0
- rn_forge_fastapi-0.4.0.dist-info/METADATA +165 -0
- rn_forge_fastapi-0.4.0.dist-info/RECORD +27 -0
- rn_forge_fastapi-0.4.0.dist-info/WHEEL +4 -0
- rn_forge_fastapi-0.4.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""FastAPI adapters for :mod:`rn_forge.web` contracts."""
|
|
2
|
+
|
|
3
|
+
from rn_forge.fastapi.app import AppConfig, FastApiApp
|
|
4
|
+
from rn_forge.fastapi.auth import (
|
|
5
|
+
ANONYMOUS_PREFIX,
|
|
6
|
+
ANONYMOUS_TTL,
|
|
7
|
+
CSRF_COOKIE,
|
|
8
|
+
CSRF_HEADER,
|
|
9
|
+
SESSION_COOKIE,
|
|
10
|
+
TRANSACTION_COOKIE,
|
|
11
|
+
ActiveSession,
|
|
12
|
+
AuthRoutesConfig,
|
|
13
|
+
BearerAuth,
|
|
14
|
+
CsrfProtection,
|
|
15
|
+
CsrfStore,
|
|
16
|
+
InMemoryCsrfStore,
|
|
17
|
+
InMemoryRateLimiter,
|
|
18
|
+
PolicyGuard,
|
|
19
|
+
RateLimit,
|
|
20
|
+
RateLimiter,
|
|
21
|
+
SessionMiddleware,
|
|
22
|
+
Sessions,
|
|
23
|
+
active_session,
|
|
24
|
+
auth_router,
|
|
25
|
+
basic_auth,
|
|
26
|
+
bearer_auth,
|
|
27
|
+
current_principal,
|
|
28
|
+
requires,
|
|
29
|
+
requires_permission,
|
|
30
|
+
rotate_session,
|
|
31
|
+
sessions_for,
|
|
32
|
+
)
|
|
33
|
+
from rn_forge.fastapi.cors import CorsPolicy, apply_cors
|
|
34
|
+
from rn_forge.fastapi.dependencies import (
|
|
35
|
+
conditional_get,
|
|
36
|
+
order_by_param,
|
|
37
|
+
page_params,
|
|
38
|
+
require_idempotency_key,
|
|
39
|
+
require_if_match,
|
|
40
|
+
)
|
|
41
|
+
from rn_forge.fastapi.deprecation import deprecated
|
|
42
|
+
from rn_forge.fastapi.health import health_router
|
|
43
|
+
from rn_forge.fastapi.idempotency import idempotent
|
|
44
|
+
from rn_forge.fastapi.merge_patch import (
|
|
45
|
+
merge_into,
|
|
46
|
+
merge_patch_body,
|
|
47
|
+
merge_patch_openapi,
|
|
48
|
+
)
|
|
49
|
+
from rn_forge.fastapi.openapi import operation_id
|
|
50
|
+
from rn_forge.fastapi.problem import Log, register_problem_handlers
|
|
51
|
+
from rn_forge.fastapi.read_mask import masked, read_mask_param
|
|
52
|
+
from rn_forge.fastapi.soft_delete import (
|
|
53
|
+
SoftDeleteState,
|
|
54
|
+
SoftDeleteStore,
|
|
55
|
+
show_deleted_param,
|
|
56
|
+
soft_delete_router,
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
__all__ = [
|
|
60
|
+
"ANONYMOUS_PREFIX",
|
|
61
|
+
"ANONYMOUS_TTL",
|
|
62
|
+
"CSRF_COOKIE",
|
|
63
|
+
"CSRF_HEADER",
|
|
64
|
+
"SESSION_COOKIE",
|
|
65
|
+
"TRANSACTION_COOKIE",
|
|
66
|
+
"ActiveSession",
|
|
67
|
+
"AppConfig",
|
|
68
|
+
"AuthRoutesConfig",
|
|
69
|
+
"BearerAuth",
|
|
70
|
+
"CorsPolicy",
|
|
71
|
+
"CsrfProtection",
|
|
72
|
+
"CsrfStore",
|
|
73
|
+
"FastApiApp",
|
|
74
|
+
"InMemoryCsrfStore",
|
|
75
|
+
"InMemoryRateLimiter",
|
|
76
|
+
"Log",
|
|
77
|
+
"PolicyGuard",
|
|
78
|
+
"RateLimit",
|
|
79
|
+
"RateLimiter",
|
|
80
|
+
"SessionMiddleware",
|
|
81
|
+
"Sessions",
|
|
82
|
+
"SoftDeleteState",
|
|
83
|
+
"SoftDeleteStore",
|
|
84
|
+
"active_session",
|
|
85
|
+
"apply_cors",
|
|
86
|
+
"auth_router",
|
|
87
|
+
"basic_auth",
|
|
88
|
+
"bearer_auth",
|
|
89
|
+
"conditional_get",
|
|
90
|
+
"current_principal",
|
|
91
|
+
"deprecated",
|
|
92
|
+
"health_router",
|
|
93
|
+
"idempotent",
|
|
94
|
+
"masked",
|
|
95
|
+
"merge_into",
|
|
96
|
+
"merge_patch_body",
|
|
97
|
+
"merge_patch_openapi",
|
|
98
|
+
"operation_id",
|
|
99
|
+
"order_by_param",
|
|
100
|
+
"page_params",
|
|
101
|
+
"read_mask_param",
|
|
102
|
+
"register_problem_handlers",
|
|
103
|
+
"require_idempotency_key",
|
|
104
|
+
"require_if_match",
|
|
105
|
+
"requires",
|
|
106
|
+
"requires_permission",
|
|
107
|
+
"rotate_session",
|
|
108
|
+
"sessions_for",
|
|
109
|
+
"show_deleted_param",
|
|
110
|
+
"soft_delete_router",
|
|
111
|
+
]
|
rn_forge/fastapi/app.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"""Construct FastAPI applications with the standard rn-forge adapters."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Collection, Mapping, Sequence
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from fastapi import APIRouter, FastAPI
|
|
10
|
+
from fastapi.responses import JSONResponse
|
|
11
|
+
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
|
|
12
|
+
from opentelemetry.instrumentation.propagators import (
|
|
13
|
+
TraceResponsePropagator,
|
|
14
|
+
get_global_response_propagator,
|
|
15
|
+
set_global_response_propagator, # pyright: ignore[reportUnknownVariableType]
|
|
16
|
+
)
|
|
17
|
+
from rn_forge.fastapi.cors import CorsPolicy, apply_cors
|
|
18
|
+
from rn_forge.fastapi.health import health_router
|
|
19
|
+
from rn_forge.fastapi.openapi import operation_id, repair_problem_schema
|
|
20
|
+
from rn_forge.fastapi.problem import Log, register_problem_handlers
|
|
21
|
+
from rn_forge.web import (
|
|
22
|
+
API_CATALOG_PATH,
|
|
23
|
+
LEGACY_LIVENESS_PATH,
|
|
24
|
+
LINKSET_MEDIA_TYPE,
|
|
25
|
+
LIVENESS_PATH,
|
|
26
|
+
OPENAPI_PATH,
|
|
27
|
+
READINESS_PATH,
|
|
28
|
+
BodySizeLimitMiddleware,
|
|
29
|
+
Check,
|
|
30
|
+
ProblemRegistry,
|
|
31
|
+
api_catalog_body,
|
|
32
|
+
default_registry,
|
|
33
|
+
)
|
|
34
|
+
from rn_forge.web.security import (
|
|
35
|
+
API_SECURITY_HEADERS,
|
|
36
|
+
HSTS_HEADER,
|
|
37
|
+
SecurityHeadersMiddleware,
|
|
38
|
+
)
|
|
39
|
+
from starlette.types import Lifespan
|
|
40
|
+
|
|
41
|
+
__all__ = ["AppConfig", "FastApiApp"]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
45
|
+
class AppConfig:
|
|
46
|
+
"""The standard adapter configuration for :class:`FastApiApp`.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
registry: Domain exception mappings. Register application exceptions
|
|
50
|
+
before constructing this configuration.
|
|
51
|
+
checks: Readiness checks, keyed by their wire-visible names.
|
|
52
|
+
required_checks: Check names whose failure returns 503 from the
|
|
53
|
+
readiness path.
|
|
54
|
+
check_timeout: Maximum seconds a single readiness check may run.
|
|
55
|
+
realm: Optional Bearer authentication realm for problem responses.
|
|
56
|
+
tracing: Instrument the application with
|
|
57
|
+
``FastAPIInstrumentor.instrument_app`` and, when nothing else has,
|
|
58
|
+
set a :class:`~opentelemetry.instrumentation.propagators.TraceResponsePropagator`
|
|
59
|
+
as the global response propagator. This alone decides whether
|
|
60
|
+
server spans are recorded: ``FastApiApp`` turns off FastAPI's
|
|
61
|
+
native tracing unless ``telemetry=`` is passed.
|
|
62
|
+
log: Optional sink for ``problem.server_error`` events, called for
|
|
63
|
+
every 5xx problem response with the exception under ``"exc"``.
|
|
64
|
+
liveness_path: The liveness path.
|
|
65
|
+
readiness_path: The readiness path.
|
|
66
|
+
legacy_liveness_path: An alias of *liveness_path*, marked deprecated
|
|
67
|
+
in the OpenAPI document. ``None`` serves no alias.
|
|
68
|
+
max_body_bytes: The largest request body admitted, per RFC 9110
|
|
69
|
+
§15.5.14. ``None`` disables the limit; uvicorn itself sets none.
|
|
70
|
+
api_catalog: Serve RFC 9727's ``/.well-known/api-catalog``, pointing
|
|
71
|
+
at the OpenAPI document and docs UI.
|
|
72
|
+
security_headers: Install the OWASP REST Security Cheat Sheet response
|
|
73
|
+
headers (``rn_forge.web.security.API_SECURITY_HEADERS``).
|
|
74
|
+
hsts: Also add ``Strict-Transport-Security``. Off by default: sending
|
|
75
|
+
it over plain HTTP tells a browser to refuse a future connection
|
|
76
|
+
that isn't HTTPS, so it is opt-in for deployments that terminate
|
|
77
|
+
TLS themselves rather than at a front end that already sets it.
|
|
78
|
+
cors: A CORS policy to install, or ``None`` (the default) to install
|
|
79
|
+
none — the application owns whether it has a CORS policy at all.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
registry: ProblemRegistry = field(default_factory=default_registry)
|
|
83
|
+
checks: Mapping[str, Check] = field(default_factory=dict[str, Check])
|
|
84
|
+
required_checks: Collection[str] = ()
|
|
85
|
+
check_timeout: float | None = 2.0
|
|
86
|
+
realm: str | None = None
|
|
87
|
+
tracing: bool = True
|
|
88
|
+
log: Log | None = None
|
|
89
|
+
liveness_path: str = LIVENESS_PATH
|
|
90
|
+
readiness_path: str = READINESS_PATH
|
|
91
|
+
legacy_liveness_path: str | None = LEGACY_LIVENESS_PATH
|
|
92
|
+
max_body_bytes: int | None = 1_048_576
|
|
93
|
+
api_catalog: bool = True
|
|
94
|
+
security_headers: bool = True
|
|
95
|
+
hsts: bool = False
|
|
96
|
+
cors: CorsPolicy | None = None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class FastApiApp(FastAPI):
|
|
100
|
+
"""A :class:`fastapi.FastAPI` with the standard rn-forge wiring installed.
|
|
101
|
+
|
|
102
|
+
FastAPI is inherited rather than wrapped, so ``@app.get()``,
|
|
103
|
+
``add_middleware`` and the full :class:`~fastapi.FastAPI` constructor
|
|
104
|
+
keyword set remain available.
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
def __init__(
|
|
108
|
+
self,
|
|
109
|
+
config: AppConfig | None = None,
|
|
110
|
+
*,
|
|
111
|
+
routers: Sequence[APIRouter] = (),
|
|
112
|
+
lifespan: Lifespan[FastAPI] | None = None,
|
|
113
|
+
title: str = "FastAPI",
|
|
114
|
+
description: str = "",
|
|
115
|
+
version: str = "0.1.0",
|
|
116
|
+
**fastapi_kwargs: Any,
|
|
117
|
+
) -> None:
|
|
118
|
+
"""Initialize the application and install the standard adapters.
|
|
119
|
+
|
|
120
|
+
Args:
|
|
121
|
+
config: Standard adapter configuration. Defaults to
|
|
122
|
+
``AppConfig()``.
|
|
123
|
+
routers: Application routers to include in order.
|
|
124
|
+
lifespan: Application startup and shutdown hook.
|
|
125
|
+
title: OpenAPI document title.
|
|
126
|
+
description: OpenAPI document description.
|
|
127
|
+
version: OpenAPI document version.
|
|
128
|
+
**fastapi_kwargs: Forwarded to the :class:`fastapi.FastAPI`
|
|
129
|
+
constructor. ``generate_unique_id_function`` defaults to
|
|
130
|
+
:func:`operation_id` and ``telemetry`` to
|
|
131
|
+
``{"tracing": False}``; both may be overridden here.
|
|
132
|
+
"""
|
|
133
|
+
resolved = config if config is not None else AppConfig()
|
|
134
|
+
fastapi_kwargs.setdefault("generate_unique_id_function", operation_id)
|
|
135
|
+
fastapi_kwargs.setdefault("telemetry", {"tracing": False})
|
|
136
|
+
super().__init__(
|
|
137
|
+
title=title,
|
|
138
|
+
description=description,
|
|
139
|
+
version=version,
|
|
140
|
+
lifespan=lifespan,
|
|
141
|
+
**fastapi_kwargs,
|
|
142
|
+
)
|
|
143
|
+
self.config = resolved
|
|
144
|
+
if resolved.security_headers:
|
|
145
|
+
headers = {**API_SECURITY_HEADERS, **(HSTS_HEADER if resolved.hsts else {})}
|
|
146
|
+
self.add_middleware(SecurityHeadersMiddleware, headers=headers)
|
|
147
|
+
if resolved.max_body_bytes is not None:
|
|
148
|
+
self.add_middleware(
|
|
149
|
+
BodySizeLimitMiddleware, max_bytes=resolved.max_body_bytes
|
|
150
|
+
)
|
|
151
|
+
if resolved.cors is not None:
|
|
152
|
+
apply_cors(self, resolved.cors)
|
|
153
|
+
register_problem_handlers(
|
|
154
|
+
self,
|
|
155
|
+
registry=resolved.registry,
|
|
156
|
+
realm=resolved.realm,
|
|
157
|
+
log=resolved.log,
|
|
158
|
+
)
|
|
159
|
+
if resolved.tracing:
|
|
160
|
+
FastAPIInstrumentor.instrument_app(self)
|
|
161
|
+
if get_global_response_propagator() is None:
|
|
162
|
+
# Process-global state, set only when nobody else set it.
|
|
163
|
+
set_global_response_propagator(TraceResponsePropagator())
|
|
164
|
+
self.include_router(
|
|
165
|
+
health_router(
|
|
166
|
+
checks=resolved.checks,
|
|
167
|
+
required=resolved.required_checks,
|
|
168
|
+
timeout=resolved.check_timeout,
|
|
169
|
+
liveness_path=resolved.liveness_path,
|
|
170
|
+
readiness_path=resolved.readiness_path,
|
|
171
|
+
legacy_liveness_path=resolved.legacy_liveness_path,
|
|
172
|
+
)
|
|
173
|
+
)
|
|
174
|
+
if resolved.api_catalog:
|
|
175
|
+
self.add_api_route(
|
|
176
|
+
API_CATALOG_PATH,
|
|
177
|
+
self._api_catalog,
|
|
178
|
+
methods=["GET", "HEAD"],
|
|
179
|
+
include_in_schema=False,
|
|
180
|
+
)
|
|
181
|
+
for router in routers:
|
|
182
|
+
self.include_router(router)
|
|
183
|
+
|
|
184
|
+
def _api_catalog(self) -> JSONResponse:
|
|
185
|
+
"""Serve RFC 9727's linkset, pointing at this app's own OpenAPI document and docs UI."""
|
|
186
|
+
return JSONResponse(
|
|
187
|
+
api_catalog_body(
|
|
188
|
+
anchor="/",
|
|
189
|
+
service_desc=self.openapi_url or OPENAPI_PATH,
|
|
190
|
+
service_doc=self.docs_url,
|
|
191
|
+
status=self.config.readiness_path,
|
|
192
|
+
),
|
|
193
|
+
media_type=LINKSET_MEDIA_TYPE,
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
def openapi(self) -> dict[str, Any]:
|
|
197
|
+
"""Return the OpenAPI document, repaired for problem-response accuracy.
|
|
198
|
+
|
|
199
|
+
Builds through ``super().openapi()`` — which caches the document the
|
|
200
|
+
way plain :class:`~fastapi.FastAPI` does — and repairs the cached
|
|
201
|
+
document exactly once. A consumer subclass adds further repairs by
|
|
202
|
+
overriding this method and calling ``super().openapi()`` first.
|
|
203
|
+
"""
|
|
204
|
+
if self.openapi_schema:
|
|
205
|
+
return self.openapi_schema
|
|
206
|
+
schema = super().openapi()
|
|
207
|
+
self.openapi_schema = repair_problem_schema(
|
|
208
|
+
schema, registry=self.config.registry
|
|
209
|
+
)
|
|
210
|
+
return self.openapi_schema
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""FastAPI authentication: security dependencies and the ``/auth`` router."""
|
|
2
|
+
|
|
3
|
+
from rn_forge.fastapi.auth.authorization import PolicyGuard
|
|
4
|
+
from rn_forge.fastapi.auth.csrf import (
|
|
5
|
+
ANONYMOUS_PREFIX,
|
|
6
|
+
ANONYMOUS_TTL,
|
|
7
|
+
CSRF_COOKIE,
|
|
8
|
+
CSRF_HEADER,
|
|
9
|
+
CsrfProtection,
|
|
10
|
+
CsrfStore,
|
|
11
|
+
InMemoryCsrfStore,
|
|
12
|
+
)
|
|
13
|
+
from rn_forge.fastapi.auth.dependencies import (
|
|
14
|
+
BearerAuth,
|
|
15
|
+
basic_auth,
|
|
16
|
+
bearer_auth,
|
|
17
|
+
current_principal,
|
|
18
|
+
requires,
|
|
19
|
+
requires_permission,
|
|
20
|
+
)
|
|
21
|
+
from rn_forge.fastapi.auth.rate_limit import (
|
|
22
|
+
InMemoryRateLimiter,
|
|
23
|
+
RateLimit,
|
|
24
|
+
RateLimiter,
|
|
25
|
+
)
|
|
26
|
+
from rn_forge.fastapi.auth.routes import (
|
|
27
|
+
TRANSACTION_COOKIE,
|
|
28
|
+
AuthRoutesConfig,
|
|
29
|
+
auth_router,
|
|
30
|
+
sessions_for,
|
|
31
|
+
)
|
|
32
|
+
from rn_forge.fastapi.auth.sessions import (
|
|
33
|
+
SESSION_COOKIE,
|
|
34
|
+
ActiveSession,
|
|
35
|
+
SessionMiddleware,
|
|
36
|
+
Sessions,
|
|
37
|
+
active_session,
|
|
38
|
+
rotate_session,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
__all__ = [
|
|
42
|
+
"ANONYMOUS_PREFIX",
|
|
43
|
+
"ANONYMOUS_TTL",
|
|
44
|
+
"CSRF_COOKIE",
|
|
45
|
+
"CSRF_HEADER",
|
|
46
|
+
"SESSION_COOKIE",
|
|
47
|
+
"TRANSACTION_COOKIE",
|
|
48
|
+
"ActiveSession",
|
|
49
|
+
"AuthRoutesConfig",
|
|
50
|
+
"BearerAuth",
|
|
51
|
+
"CsrfProtection",
|
|
52
|
+
"CsrfStore",
|
|
53
|
+
"InMemoryCsrfStore",
|
|
54
|
+
"InMemoryRateLimiter",
|
|
55
|
+
"PolicyGuard",
|
|
56
|
+
"RateLimit",
|
|
57
|
+
"RateLimiter",
|
|
58
|
+
"SessionMiddleware",
|
|
59
|
+
"Sessions",
|
|
60
|
+
"active_session",
|
|
61
|
+
"auth_router",
|
|
62
|
+
"basic_auth",
|
|
63
|
+
"bearer_auth",
|
|
64
|
+
"current_principal",
|
|
65
|
+
"requires",
|
|
66
|
+
"requires_permission",
|
|
67
|
+
"rotate_session",
|
|
68
|
+
"sessions_for",
|
|
69
|
+
]
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Object and query checks from a :class:`~rn_forge.auth.ResourcePolicy`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from rn_forge.auth import Principal, ResourcePolicy, audit
|
|
8
|
+
from rn_forge.web import PermissionDenied
|
|
9
|
+
|
|
10
|
+
__all__ = ["PolicyGuard"]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class PolicyGuard[ResourceT, QueryT]:
|
|
14
|
+
"""Apply a :class:`~rn_forge.auth.ResourcePolicy` to queries and objects.
|
|
15
|
+
|
|
16
|
+
The guard is independent of the query type: *QueryT* is whatever the policy
|
|
17
|
+
narrows, such as a SQLAlchemy ``Select``.
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
policy: The policy.
|
|
21
|
+
hides_existence: Report a denied object as 404 instead of 403.
|
|
22
|
+
|
|
23
|
+
Example:
|
|
24
|
+
``rows = guard.scope(principal, "list", select(Order))`` narrows a list
|
|
25
|
+
query, so its rows, counts and pages hold only permitted rows;
|
|
26
|
+
``guard.check(principal, "read", order)`` then returns *order* or raises.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
policy: ResourcePolicy[ResourceT, QueryT],
|
|
32
|
+
*,
|
|
33
|
+
hides_existence: bool = False,
|
|
34
|
+
) -> None:
|
|
35
|
+
self._policy: ResourcePolicy[Any, Any] = policy
|
|
36
|
+
self._hides_existence = hides_existence
|
|
37
|
+
|
|
38
|
+
def scope(self, principal: Principal, action: str, query: QueryT) -> QueryT:
|
|
39
|
+
"""Return *query* narrowed to what *principal* may *action*."""
|
|
40
|
+
return self._policy.scope(principal, action, query)
|
|
41
|
+
|
|
42
|
+
def check(
|
|
43
|
+
self, principal: Principal, action: str, resource: ResourceT
|
|
44
|
+
) -> ResourceT:
|
|
45
|
+
"""Return *resource* if *principal* may *action* it.
|
|
46
|
+
|
|
47
|
+
Raises:
|
|
48
|
+
LookupError: The policy denies it and ``hides_existence`` is true (404).
|
|
49
|
+
PermissionDenied: The policy denies it (403).
|
|
50
|
+
"""
|
|
51
|
+
if self._policy.allows(principal, action, resource):
|
|
52
|
+
return resource
|
|
53
|
+
audit(
|
|
54
|
+
"authorization.denied",
|
|
55
|
+
account_id=principal.subject,
|
|
56
|
+
action=action,
|
|
57
|
+
resource=type(resource).__name__,
|
|
58
|
+
hidden=self._hides_existence,
|
|
59
|
+
)
|
|
60
|
+
if self._hides_existence:
|
|
61
|
+
raise LookupError("Not found")
|
|
62
|
+
raise PermissionDenied("The policy denies the action")
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""Synchronizer-token CSRF protection for the session-authenticated routes.
|
|
2
|
+
|
|
3
|
+
The token is a random value kept server-side under the session ID, and handed
|
|
4
|
+
to the browser in the readable ``XSRF-TOKEN`` cookie. :class:`CsrfProtection`
|
|
5
|
+
compares it in constant time with the ``X-XSRF-TOKEN`` header on an unsafe
|
|
6
|
+
request, which are the names Angular's ``HttpClient`` uses. Before sign-in the
|
|
7
|
+
record is keyed by an anonymous ID behind the ``__Host-session`` cookie, so the
|
|
8
|
+
login request is protected too. ``SessionMiddleware`` decides which requests
|
|
9
|
+
are checked: those that carry the session cookie, and the password-login path.
|
|
10
|
+
|
|
11
|
+
The request's ``Origin`` (``Referer`` over HTTPS when there is no ``Origin``)
|
|
12
|
+
must be its own origin or one of ``trusted_origins``, and
|
|
13
|
+
``Sec-Fetch-Site: cross-site`` is rejected. The request's own scheme and host
|
|
14
|
+
come from ``X-Forwarded-Proto`` and ``X-Forwarded-Host`` only when the peer is
|
|
15
|
+
one of ``trusted_proxies``. A request with a ``Bearer`` ``Authorization`` header
|
|
16
|
+
skips the check.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import hmac
|
|
22
|
+
import secrets
|
|
23
|
+
import threading
|
|
24
|
+
from collections.abc import Callable, Collection, Mapping
|
|
25
|
+
from datetime import UTC, datetime, timedelta
|
|
26
|
+
from typing import Final, Protocol, runtime_checkable
|
|
27
|
+
from urllib.parse import urlsplit
|
|
28
|
+
|
|
29
|
+
from fastapi import Response
|
|
30
|
+
from rn_forge.fastapi.auth.proxies import TrustedProxies
|
|
31
|
+
from rn_forge.web import CsrfFailed, ProblemRegistry, default_registry
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"ANONYMOUS_PREFIX",
|
|
35
|
+
"ANONYMOUS_TTL",
|
|
36
|
+
"CSRF_COOKIE",
|
|
37
|
+
"CSRF_HEADER",
|
|
38
|
+
"CsrfProtection",
|
|
39
|
+
"CsrfStore",
|
|
40
|
+
"InMemoryCsrfStore",
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
CSRF_COOKIE: Final = "XSRF-TOKEN"
|
|
44
|
+
"""The readable cookie that carries the token."""
|
|
45
|
+
|
|
46
|
+
CSRF_HEADER: Final = "X-XSRF-TOKEN"
|
|
47
|
+
"""The request header that must repeat the token."""
|
|
48
|
+
|
|
49
|
+
ANONYMOUS_PREFIX: Final = "anon."
|
|
50
|
+
"""Starts the ID of an anonymous session."""
|
|
51
|
+
|
|
52
|
+
ANONYMOUS_TTL: Final = timedelta(minutes=10)
|
|
53
|
+
"""How long an anonymous session holds its token."""
|
|
54
|
+
|
|
55
|
+
_SAFE_METHODS: Final = frozenset({"GET", "HEAD", "OPTIONS", "TRACE"})
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@runtime_checkable
|
|
59
|
+
class CsrfStore(Protocol):
|
|
60
|
+
"""Holds the CSRF token of each session, keyed by session ID.
|
|
61
|
+
|
|
62
|
+
Every method is synchronous and thread-safe.
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
def save(self, key: str, token: str, *, ttl: timedelta) -> None:
|
|
66
|
+
"""Store *token* under *key*, replacing any token, for *ttl*."""
|
|
67
|
+
...
|
|
68
|
+
|
|
69
|
+
def get(self, key: str) -> str | None:
|
|
70
|
+
"""Return the token stored under *key*, or ``None`` when there is none."""
|
|
71
|
+
...
|
|
72
|
+
|
|
73
|
+
def delete(self, key: str) -> None:
|
|
74
|
+
"""Remove the token stored under *key*, if any."""
|
|
75
|
+
...
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _utc_now() -> datetime:
|
|
79
|
+
return datetime.now(UTC)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class InMemoryCsrfStore:
|
|
83
|
+
""":class:`CsrfStore` held in process memory, for tests and development.
|
|
84
|
+
|
|
85
|
+
Args:
|
|
86
|
+
clock: Returns the current time, aware.
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
def __init__(self, clock: Callable[[], datetime] = _utc_now) -> None:
|
|
90
|
+
self._clock = clock
|
|
91
|
+
self._tokens: dict[str, tuple[str, datetime]] = {}
|
|
92
|
+
self._lock = threading.Lock()
|
|
93
|
+
|
|
94
|
+
def save(self, key: str, token: str, *, ttl: timedelta) -> None:
|
|
95
|
+
"""Store *token* under *key* for *ttl*."""
|
|
96
|
+
with self._lock:
|
|
97
|
+
self._tokens[key] = (token, self._clock() + ttl)
|
|
98
|
+
|
|
99
|
+
def get(self, key: str) -> str | None:
|
|
100
|
+
"""Return the unexpired token under *key*."""
|
|
101
|
+
with self._lock:
|
|
102
|
+
held = self._tokens.get(key)
|
|
103
|
+
if held is None:
|
|
104
|
+
return None
|
|
105
|
+
if held[1] <= self._clock():
|
|
106
|
+
del self._tokens[key]
|
|
107
|
+
return None
|
|
108
|
+
return held[0]
|
|
109
|
+
|
|
110
|
+
def delete(self, key: str) -> None:
|
|
111
|
+
"""Remove the token under *key*."""
|
|
112
|
+
with self._lock:
|
|
113
|
+
self._tokens.pop(key, None)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _origin(value: str) -> str:
|
|
117
|
+
return value.rstrip("/").lower()
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _first(value: str | None) -> str | None:
|
|
121
|
+
if value is None:
|
|
122
|
+
return None
|
|
123
|
+
return value.partition(",")[0].strip() or None
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class CsrfProtection:
|
|
127
|
+
"""The token store and the checks that guard unsafe requests.
|
|
128
|
+
|
|
129
|
+
Args:
|
|
130
|
+
store: Holds the tokens.
|
|
131
|
+
problem_type_base: Prefix of the ``type`` URI of the ``csrf-failed``
|
|
132
|
+
problem; empty for ``about:blank``.
|
|
133
|
+
trusted_origins: Origins, besides the request's own, that may send an
|
|
134
|
+
unsafe request, such as ``https://app.example``.
|
|
135
|
+
trusted_proxies: Peer addresses or CIDR networks whose forwarded scheme
|
|
136
|
+
and host headers are believed.
|
|
137
|
+
"""
|
|
138
|
+
|
|
139
|
+
def __init__(
|
|
140
|
+
self,
|
|
141
|
+
*,
|
|
142
|
+
store: CsrfStore,
|
|
143
|
+
problem_type_base: str,
|
|
144
|
+
trusted_origins: Collection[str] = (),
|
|
145
|
+
trusted_proxies: Collection[str] = (),
|
|
146
|
+
) -> None:
|
|
147
|
+
self.store = store
|
|
148
|
+
self.registry: ProblemRegistry = default_registry(type_base=problem_type_base)
|
|
149
|
+
self._origins = frozenset(_origin(origin) for origin in trusted_origins)
|
|
150
|
+
self._proxies = TrustedProxies(trusted_proxies)
|
|
151
|
+
|
|
152
|
+
@staticmethod
|
|
153
|
+
def is_anonymous(key: str | None) -> bool:
|
|
154
|
+
"""Whether *key* has the shape of an anonymous session ID."""
|
|
155
|
+
return key is not None and key.startswith(ANONYMOUS_PREFIX)
|
|
156
|
+
|
|
157
|
+
@staticmethod
|
|
158
|
+
def new_anonymous_id() -> str:
|
|
159
|
+
"""A new anonymous session ID."""
|
|
160
|
+
return ANONYMOUS_PREFIX + secrets.token_urlsafe(32)
|
|
161
|
+
|
|
162
|
+
def mint(self, key: str, *, ttl: timedelta) -> str:
|
|
163
|
+
"""Store a new random token under *key*, replacing any token, and return it."""
|
|
164
|
+
token = secrets.token_urlsafe(32)
|
|
165
|
+
self.store.save(key, token, ttl=ttl)
|
|
166
|
+
return token
|
|
167
|
+
|
|
168
|
+
@staticmethod
|
|
169
|
+
def set_cookie(response: Response, token: str) -> None:
|
|
170
|
+
"""Set the token cookie on *response*."""
|
|
171
|
+
# Not HttpOnly: client JS reads the token to echo it in a header.
|
|
172
|
+
response.set_cookie( # NOSONAR(S3330)
|
|
173
|
+
CSRF_COOKIE,
|
|
174
|
+
token,
|
|
175
|
+
secure=True,
|
|
176
|
+
httponly=False,
|
|
177
|
+
samesite="lax",
|
|
178
|
+
path="/",
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
def check(
|
|
182
|
+
self,
|
|
183
|
+
*,
|
|
184
|
+
method: str,
|
|
185
|
+
headers: Mapping[str, str],
|
|
186
|
+
scheme: str,
|
|
187
|
+
peer: str | None,
|
|
188
|
+
expected: str | None,
|
|
189
|
+
) -> None:
|
|
190
|
+
"""Check one request.
|
|
191
|
+
|
|
192
|
+
Args:
|
|
193
|
+
method: The HTTP method.
|
|
194
|
+
headers: The request headers, by lowercase name.
|
|
195
|
+
scheme: The scheme the server received the request on.
|
|
196
|
+
peer: The address of the connection's peer.
|
|
197
|
+
expected: The token stored for the request's session, or ``None``
|
|
198
|
+
when it has none.
|
|
199
|
+
|
|
200
|
+
Raises:
|
|
201
|
+
CsrfFailed: The request is unsafe and the origin, fetch-metadata
|
|
202
|
+
or token check fails.
|
|
203
|
+
"""
|
|
204
|
+
if method in _SAFE_METHODS:
|
|
205
|
+
return
|
|
206
|
+
authorization = headers.get("authorization", "")
|
|
207
|
+
if authorization.partition(" ")[0].lower() == "bearer":
|
|
208
|
+
return
|
|
209
|
+
if headers.get("sec-fetch-site") == "cross-site":
|
|
210
|
+
raise CsrfFailed("Sec-Fetch-Site is cross-site")
|
|
211
|
+
self._check_origin(headers, scheme, peer)
|
|
212
|
+
supplied = headers.get(CSRF_HEADER.lower())
|
|
213
|
+
if not supplied or expected is None:
|
|
214
|
+
raise CsrfFailed("CSRF token missing")
|
|
215
|
+
if not hmac.compare_digest(supplied.encode(), expected.encode()):
|
|
216
|
+
raise CsrfFailed("CSRF token mismatch")
|
|
217
|
+
|
|
218
|
+
def _check_origin(
|
|
219
|
+
self, headers: Mapping[str, str], scheme: str, peer: str | None
|
|
220
|
+
) -> None:
|
|
221
|
+
origin = headers.get("origin")
|
|
222
|
+
own = self._own_origin(headers, scheme, peer)
|
|
223
|
+
allowed = self._origins | {own}
|
|
224
|
+
if origin is not None:
|
|
225
|
+
if _origin(origin) not in allowed:
|
|
226
|
+
raise CsrfFailed("Origin checking failed")
|
|
227
|
+
return
|
|
228
|
+
if own.startswith("https://"):
|
|
229
|
+
referer = headers.get("referer")
|
|
230
|
+
parts = urlsplit(referer) if referer else None
|
|
231
|
+
if parts is None or parts.scheme != "https" or not parts.netloc:
|
|
232
|
+
raise CsrfFailed("Referer checking failed")
|
|
233
|
+
if f"{parts.scheme}://{parts.netloc}".lower() not in allowed:
|
|
234
|
+
raise CsrfFailed("Referer checking failed")
|
|
235
|
+
|
|
236
|
+
def _own_origin(
|
|
237
|
+
self, headers: Mapping[str, str], scheme: str, peer: str | None
|
|
238
|
+
) -> str:
|
|
239
|
+
host = headers.get("host", "")
|
|
240
|
+
if self._proxies.trusts(peer):
|
|
241
|
+
scheme = _first(headers.get("x-forwarded-proto")) or scheme
|
|
242
|
+
host = _first(headers.get("x-forwarded-host")) or host
|
|
243
|
+
return f"{scheme}://{host}".lower()
|