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.
@@ -0,0 +1,504 @@
1
+ """The login session, kept in an ``rn-forge-auth`` :class:`~rn_forge.auth.SessionStore`.
2
+
3
+ The session ID travels in the ``__Host-session`` cookie. Every store call is
4
+ synchronous; :class:`Sessions` methods are blocking and async code runs them
5
+ in the thread pool. :class:`SessionMiddleware` resolves the session once per
6
+ request and keeps its cookie current.
7
+
8
+ ``GET`` requests to the paths in ``untouched_paths`` read the session without
9
+ extending it; every other request moves the idle expiry forward.
10
+
11
+ The middleware also runs the :class:`~rn_forge.fastapi.auth.csrf.CsrfProtection`
12
+ check on an unsafe request that carries the session cookie, or that goes to the
13
+ password-login path, so the application's own session-authenticated routes are
14
+ protected as well as the ``/auth`` routes. A request with no session cookie
15
+ reaches the application unchecked.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import logging
21
+ from collections.abc import Callable, Collection, MutableMapping
22
+ from dataclasses import dataclass
23
+ from datetime import UTC, datetime, timedelta
24
+ from typing import TYPE_CHECKING, Any, Final
25
+
26
+ from fastapi import Request, Response
27
+ from fastapi.concurrency import run_in_threadpool
28
+ from fastapi.responses import JSONResponse
29
+ from rn_forge.auth import (
30
+ AuthorizationContext,
31
+ AuthorizationContextProvider,
32
+ InMemoryReplayStore,
33
+ InMemorySessionStore,
34
+ InMemoryTransactionStore,
35
+ ReplayStore,
36
+ SessionInfo,
37
+ SessionStore,
38
+ TransactionStore,
39
+ )
40
+ from rn_forge.fastapi.auth.csrf import (
41
+ ANONYMOUS_TTL,
42
+ CsrfProtection,
43
+ CsrfStore,
44
+ InMemoryCsrfStore,
45
+ )
46
+ from rn_forge.fastapi.auth.rate_limit import InMemoryRateLimiter, RateLimiter
47
+ from rn_forge.web import PROBLEM_MEDIA_TYPE, CsrfFailed, render_problem
48
+ from starlette.datastructures import Headers, MutableHeaders
49
+
50
+ if TYPE_CHECKING:
51
+ from starlette.types import ASGIApp, Message, Receive, Scope, Send
52
+
53
+ __all__ = [
54
+ "SESSION_COOKIE",
55
+ "ActiveSession",
56
+ "SessionMiddleware",
57
+ "Sessions",
58
+ "active_session",
59
+ "refuse_in_memory",
60
+ "rotate_session",
61
+ ]
62
+
63
+ _LOGGER = logging.getLogger(__name__)
64
+
65
+ _STATE_KEY: Final = "rn_forge_session"
66
+
67
+ SESSION_COOKIE: Final = "__Host-session"
68
+ """The cookie that carries the session ID."""
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class ActiveSession:
73
+ """A session with its account's current authorization context.
74
+
75
+ Attributes:
76
+ info: The session's content.
77
+ context: The account's authorization context.
78
+ """
79
+
80
+ info: SessionInfo
81
+ context: AuthorizationContext
82
+
83
+
84
+ def _utc_now() -> datetime:
85
+ return datetime.now(UTC)
86
+
87
+
88
+ class Sessions:
89
+ """Starts, reads, rotates and ends login sessions.
90
+
91
+ Args:
92
+ store: Holds the sessions.
93
+ contexts: Supplies the account's current context for the checks.
94
+ replay: Says which ``(issuer, sid)`` pairs are revoked.
95
+ csrf: Holds each session's CSRF token and checks unsafe requests.
96
+ idle_timeout: How long a session may sit unused.
97
+ absolute_timeout: How long a session lives whatever its use.
98
+ debug: Allow in-memory stores.
99
+ clock: Returns the current time, aware.
100
+
101
+ Raises:
102
+ RuntimeError: *debug* is false and *store*, *replay* or the CSRF store
103
+ is held in process memory.
104
+ """
105
+
106
+ def __init__(
107
+ self,
108
+ *,
109
+ store: SessionStore,
110
+ contexts: AuthorizationContextProvider,
111
+ replay: ReplayStore,
112
+ csrf: CsrfProtection,
113
+ idle_timeout: timedelta,
114
+ absolute_timeout: timedelta,
115
+ debug: bool = False,
116
+ clock: Callable[[], datetime] = _utc_now,
117
+ ) -> None:
118
+ if not debug:
119
+ refuse_in_memory(
120
+ session_store=store, replay_store=replay, csrf_store=csrf.store
121
+ )
122
+ self.csrf = csrf
123
+ self._store = store
124
+ self._contexts = contexts
125
+ self._replay = replay
126
+ self._idle = idle_timeout
127
+ self.absolute_timeout = absolute_timeout
128
+ self._clock = clock
129
+
130
+ def now(self) -> datetime:
131
+ """The current time, aware."""
132
+ return self._clock()
133
+
134
+ @staticmethod
135
+ def session_id(request: Request) -> str | None:
136
+ """The session ID the request's cookie carries, if any."""
137
+ return request.cookies.get(SESSION_COOKIE)
138
+
139
+ def start(
140
+ self, info: SessionInfo, *, previous: str | None = None
141
+ ) -> tuple[str, str]:
142
+ """Store *info* under a new session ID with a new CSRF token.
143
+
144
+ The session or anonymous session *previous* is deleted with its token.
145
+
146
+ Returns:
147
+ The new session ID and its CSRF token.
148
+ """
149
+ if previous is not None:
150
+ self.end(previous)
151
+ session_id = self._store.create(info, idle_ttl=self._idle)
152
+ return session_id, self.csrf.mint(session_id, ttl=self.absolute_timeout)
153
+
154
+ def start_anonymous(self) -> tuple[str, str]:
155
+ """Start a short-lived anonymous session that holds only a CSRF token.
156
+
157
+ Returns:
158
+ The anonymous session ID and its CSRF token.
159
+ """
160
+ session_id = self.csrf.new_anonymous_id()
161
+ return session_id, self.csrf.mint(session_id, ttl=ANONYMOUS_TTL)
162
+
163
+ def csrf_state(
164
+ self, cookie_id: str | None, active: ActiveSession | None
165
+ ) -> tuple[str | None, str | None]:
166
+ """The CSRF key and stored token of a request.
167
+
168
+ Args:
169
+ cookie_id: The session ID from the cookie.
170
+ active: The session that ID names, if it names one.
171
+
172
+ Returns:
173
+ The key the token is stored under and the token. The key is
174
+ ``None`` when the cookie names neither a session nor a live
175
+ anonymous session; the token is ``None`` when none is stored.
176
+ """
177
+ if cookie_id and (active is not None or self.csrf.is_anonymous(cookie_id)):
178
+ return cookie_id, self.csrf.store.get(cookie_id)
179
+ return None, None
180
+
181
+ def ensure_csrf(
182
+ self, cookie_id: str | None, active: ActiveSession | None
183
+ ) -> tuple[str, str | None]:
184
+ """Return the request's CSRF token, minting a session or anonymous one if needed.
185
+
186
+ Returns:
187
+ The token, and the ID of a new anonymous session when one was
188
+ started, which the caller must send as the session cookie.
189
+ """
190
+ key, token = self.csrf_state(cookie_id, active)
191
+ if token is not None:
192
+ return token, None
193
+ if active is not None and key is not None:
194
+ return self.csrf.mint(key, ttl=self.absolute_timeout), None
195
+ anonymous_id, token = self.start_anonymous()
196
+ return token, anonymous_id
197
+
198
+ def read(
199
+ self, session_id: str | None, *, touch: bool = True
200
+ ) -> ActiveSession | None:
201
+ """Return the session with ID *session_id*, or ``None`` when there is none.
202
+
203
+ A session past its absolute timeout, whose recorded version differs
204
+ from its account's, whose account is inactive, or whose ``session_ref``
205
+ is revoked, is deleted and read as absent.
206
+
207
+ Args:
208
+ session_id: The session ID from the cookie.
209
+ touch: Move the idle expiry forward. ``False`` reads without
210
+ extending the session.
211
+ """
212
+ if not session_id:
213
+ return None
214
+ info = self._store.get(session_id)
215
+ if info is None:
216
+ return None
217
+ context = self._contexts.resolve(info.account_id)
218
+ if (
219
+ self.now() >= info.expires_at
220
+ or not context.active
221
+ or context.session_version != info.session_version
222
+ or (
223
+ info.session_ref is not None
224
+ and self._replay.is_sid_revoked(info.issuer, info.session_ref)
225
+ )
226
+ ):
227
+ self.end(session_id)
228
+ return None
229
+ # A touch that finds the session gone means a concurrent logout won.
230
+ if touch and not self._store.touch(session_id, idle_ttl=self._idle):
231
+ return None
232
+ return ActiveSession(info, context)
233
+
234
+ def rotate(self, session_id: str) -> str | None:
235
+ """Move the session to a new ID; the old ID is unreadable afterwards.
236
+
237
+ The CSRF token moves with the session.
238
+
239
+ Returns:
240
+ The new session ID, or ``None`` when the session is absent.
241
+ """
242
+ new_id = self._store.rotate(session_id, idle_ttl=self._idle)
243
+ token = self.csrf.store.get(session_id)
244
+ self.csrf.store.delete(session_id)
245
+ if new_id is not None and token is not None:
246
+ self.csrf.store.save(new_id, token, ttl=self.absolute_timeout)
247
+ return new_id
248
+
249
+ def end(self, session_id: str | None) -> None:
250
+ """Delete the session or anonymous session with ID *session_id*, with its token."""
251
+ if session_id:
252
+ self._store.delete(session_id)
253
+ self.csrf.store.delete(session_id)
254
+
255
+ def set_cookie(
256
+ self, response: Response, session_id: str, info: SessionInfo
257
+ ) -> None:
258
+ """Set the session cookie on *response*."""
259
+ remaining = min(self._idle, info.expires_at - self.now())
260
+ response.set_cookie(
261
+ SESSION_COOKIE,
262
+ session_id,
263
+ max_age=max(1, int(remaining.total_seconds())),
264
+ secure=True,
265
+ httponly=True,
266
+ samesite="lax",
267
+ path="/",
268
+ )
269
+
270
+ @staticmethod
271
+ def set_anonymous_cookie(response: Response, session_id: str) -> None:
272
+ """Set the cookie that carries an anonymous session's ID."""
273
+ response.set_cookie(
274
+ SESSION_COOKIE,
275
+ session_id,
276
+ max_age=int(ANONYMOUS_TTL.total_seconds()),
277
+ secure=True,
278
+ httponly=True,
279
+ samesite="lax",
280
+ path="/",
281
+ )
282
+
283
+ @staticmethod
284
+ def clear_cookie(response: Response) -> None:
285
+ """Delete the session cookie on *response*."""
286
+ response.delete_cookie(
287
+ SESSION_COOKIE, path="/", secure=True, httponly=True, samesite="lax"
288
+ )
289
+
290
+
291
+ def refuse_in_memory(
292
+ *,
293
+ session_store: SessionStore | None = None,
294
+ replay_store: ReplayStore | None = None,
295
+ transaction_store: TransactionStore | None = None,
296
+ csrf_store: CsrfStore | None = None,
297
+ rate_limiter: RateLimiter | None = None,
298
+ ) -> None:
299
+ """Refuse stores held in process memory, which processes do not share.
300
+
301
+ Raises:
302
+ RuntimeError: A given store is an in-memory store.
303
+ """
304
+ for name, store, kind in (
305
+ ("sessions", session_store, InMemorySessionStore),
306
+ ("replay", replay_store, InMemoryReplayStore),
307
+ ("transactions", transaction_store, InMemoryTransactionStore),
308
+ ("CSRF", csrf_store, InMemoryCsrfStore),
309
+ ("rate limiter", rate_limiter, InMemoryRateLimiter),
310
+ ):
311
+ if isinstance(store, kind):
312
+ raise RuntimeError( # noqa: TRY004 # a configuration error
313
+ f"The {name} store is held in process memory, which is not shared "
314
+ "between processes and loses revocations; use the Redis store "
315
+ "(or set debug=True for development)"
316
+ )
317
+
318
+
319
+ @dataclass
320
+ class _Held:
321
+ """What the middleware resolved for one request."""
322
+
323
+ sessions: Sessions
324
+ session_id: str | None
325
+ active: ActiveSession | None
326
+ cookie_sent: bool
327
+ touched: bool
328
+ anonymous: bool = False
329
+ csrf_token: str | None = None
330
+ rotated: bool = False
331
+
332
+
333
+ def _held(request: Request) -> _Held | None:
334
+ state: dict[str, Any] = request.scope.get("state", {})
335
+ held = state.get(_STATE_KEY)
336
+ return held if isinstance(held, _Held) else None
337
+
338
+
339
+ def request_session(request: Request) -> tuple[str | None, ActiveSession | None] | None:
340
+ """The ``(session_id, session)`` the middleware resolved, or ``None`` without it."""
341
+ held = _held(request)
342
+ return None if held is None else (held.session_id, held.active)
343
+
344
+
345
+ def active_session(request: Request) -> ActiveSession | None:
346
+ """The request's session as :class:`SessionMiddleware` resolved it.
347
+
348
+ Returns:
349
+ The session, or ``None`` when the request has none.
350
+
351
+ Raises:
352
+ RuntimeError: :class:`SessionMiddleware` is not installed.
353
+ """
354
+ resolved = request_session(request)
355
+ if resolved is None:
356
+ raise RuntimeError("SessionMiddleware is not installed")
357
+ return resolved[1]
358
+
359
+
360
+ async def rotate_session(request: Request) -> None:
361
+ """Give the request's session a new ID and keep its content.
362
+
363
+ Call it after a change of the account's privileges, so a session ID that
364
+ was seen before the change is useless afterwards. The middleware sets the
365
+ new cookie on the response. A request with no session is left alone.
366
+
367
+ Raises:
368
+ RuntimeError: :class:`SessionMiddleware` is not installed.
369
+ """
370
+ held = _held(request)
371
+ if held is None:
372
+ raise RuntimeError("SessionMiddleware is not installed")
373
+ if held.session_id is None or held.active is None:
374
+ return
375
+ new_id = await run_in_threadpool(held.sessions.rotate, held.session_id)
376
+ held.session_id = new_id
377
+ held.rotated = True
378
+ if new_id is None:
379
+ held.active = None
380
+
381
+
382
+ class SessionMiddleware:
383
+ """Resolve the login session once per request and keep its cookie current.
384
+
385
+ The session is available through :func:`active_session`. Every request
386
+ except a ``GET`` to *untouched_paths* extends the idle expiry and refreshes
387
+ the cookie's ``Max-Age``; a request whose cookie names no valid session
388
+ or anonymous session gets the cookie cleared, unless its response sets the
389
+ cookie itself.
390
+
391
+ An unsafe request is then checked with ``sessions.csrf`` when it carries the
392
+ session cookie, whether it names a live session, a live anonymous session or
393
+ nothing known, or when its path is *login_path*, which a browser can reach
394
+ with no cookie. A failure is answered with the ``403`` ``csrf-failed``
395
+ problem. A request to a path under *csrf_exempt_prefixes* is not checked.
396
+
397
+ Args:
398
+ app: The wrapped ASGI application.
399
+ sessions: Reads and extends the sessions.
400
+ untouched_paths: Paths whose ``GET`` requests do not extend the session.
401
+ login_path: The password-login path, checked even with no session cookie.
402
+ csrf_exempt_prefixes: Path prefixes whose requests skip the CSRF check:
403
+ the back-channel logout routes, which carry a signed token.
404
+ """
405
+
406
+ def __init__(
407
+ self,
408
+ app: ASGIApp,
409
+ *,
410
+ sessions: Sessions,
411
+ untouched_paths: Collection[str] = ("/auth/session",),
412
+ login_path: str = "/auth/login/password",
413
+ csrf_exempt_prefixes: Collection[str] = ("/auth/backchannel-logout/",),
414
+ ) -> None:
415
+ self.app = app
416
+ self._sessions = sessions
417
+ self._untouched = frozenset(untouched_paths)
418
+ self._login_path = login_path
419
+ self._exempt = tuple(csrf_exempt_prefixes)
420
+
421
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
422
+ if scope["type"] != "http":
423
+ await self.app(scope, receive, send)
424
+ return
425
+ session_id = Sessions.session_id(Request(scope))
426
+ touch = not (scope["method"] == "GET" and scope["path"] in self._untouched)
427
+ active = await run_in_threadpool(self._sessions.read, session_id, touch=touch)
428
+ held = _Held(
429
+ self._sessions,
430
+ session_id if active else None,
431
+ active,
432
+ cookie_sent=bool(session_id),
433
+ touched=touch,
434
+ )
435
+ state: MutableMapping[str, Any] = scope.setdefault("state", {})
436
+ state[_STATE_KEY] = held
437
+ key, held.csrf_token = await run_in_threadpool(
438
+ self._sessions.csrf_state, session_id, active
439
+ )
440
+ held.anonymous = (
441
+ key is not None and held.csrf_token is not None and active is None
442
+ )
443
+ path = scope["path"]
444
+ if not path.startswith(self._exempt) and (
445
+ session_id is not None or path == self._login_path
446
+ ):
447
+ try:
448
+ self._check_csrf(scope, held)
449
+ except CsrfFailed as exc:
450
+ await self._reject(scope, receive, send, exc)
451
+ return
452
+
453
+ async def send_with_cookie(message: Message) -> None:
454
+ if message["type"] == "http.response.start":
455
+ self._set_cookie(held, MutableHeaders(scope=message))
456
+ await send(message)
457
+
458
+ await self.app(scope, receive, send_with_cookie)
459
+
460
+ def _check_csrf(self, scope: Scope, held: _Held) -> None:
461
+ peer = scope["client"][0] if scope.get("client") else None
462
+ self._sessions.csrf.check(
463
+ method=scope["method"],
464
+ headers=Headers(scope=scope),
465
+ scheme=scope["scheme"],
466
+ peer=peer,
467
+ expected=held.csrf_token,
468
+ )
469
+
470
+ async def _reject(
471
+ self, scope: Scope, receive: Receive, send: Send, exc: CsrfFailed
472
+ ) -> None:
473
+ _LOGGER.warning("CSRF check failed: %s", exc)
474
+ rendered = render_problem(
475
+ self._sessions.csrf.registry, exc, instance=scope["path"]
476
+ )
477
+ response = JSONResponse(
478
+ rendered.body,
479
+ status_code=rendered.status,
480
+ media_type=PROBLEM_MEDIA_TYPE,
481
+ headers=dict(rendered.headers),
482
+ )
483
+ await response(scope, receive, send)
484
+
485
+ def _set_cookie(self, held: _Held, headers: MutableHeaders) -> None:
486
+ prefix = f"{SESSION_COOKIE}="
487
+ if any(value.startswith(prefix) for value in headers.getlist("set-cookie")):
488
+ return
489
+ carrier = Response()
490
+ if (
491
+ held.active is not None
492
+ and held.session_id
493
+ and (held.touched or held.rotated)
494
+ ):
495
+ self._sessions.set_cookie(carrier, held.session_id, held.active.info)
496
+ elif (
497
+ held.active is None
498
+ and not held.anonymous
499
+ and (held.cookie_sent or held.rotated)
500
+ ):
501
+ self._sessions.clear_cookie(carrier)
502
+ for name, value in carrier.raw_headers:
503
+ if name == b"set-cookie":
504
+ headers.append("set-cookie", value.decode("latin-1"))
@@ -0,0 +1,80 @@
1
+ """An opt-in CORS module over Starlette's own ``CORSMiddleware``.
2
+
3
+ **The application owns its CORS policy** — which origins, and whether there is
4
+ one at all. What this module adds is not a policy but the one default only
5
+ this kit can supply: a browser cannot read ``ETag`` or ``Link`` unless they
6
+ are named in ``Access-Control-Expose-Headers``, and an application-owned CORS
7
+ block does not know what headers the kit emits. ``traceresponse`` needs no
8
+ entry here — the OpenTelemetry response propagator exposes it itself.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import dataclass, field
14
+
15
+ from fastapi import FastAPI
16
+ from rn_forge.web import EXPOSED_HEADERS, WebError
17
+ from starlette.middleware.cors import CORSMiddleware
18
+
19
+ __all__ = ["CorsPolicy", "apply_cors"]
20
+
21
+
22
+ @dataclass(frozen=True, slots=True, kw_only=True)
23
+ class CorsPolicy:
24
+ """A CORS policy: the application's origins, and this kit's own defaults.
25
+
26
+ Args:
27
+ allow_origins: The origins this API allows. No default — naming them
28
+ is the application's decision.
29
+ allow_credentials: Whether to allow cookies/credentials.
30
+ allow_methods: The methods a preflight may approve.
31
+ allow_headers: The request headers a preflight may approve.
32
+ expose_headers: The response headers a browser may read. Defaults to
33
+ :data:`rn_forge.web.EXPOSED_HEADERS`.
34
+ max_age: How long, in seconds, a preflight result may be cached.
35
+
36
+ Raises:
37
+ WebError: *allow_credentials* is set and *allow_origins* contains
38
+ ``"*"`` — a combination browsers reject outright.
39
+ """
40
+
41
+ allow_origins: tuple[str, ...]
42
+ allow_credentials: bool = False
43
+ allow_methods: tuple[str, ...] = (
44
+ "GET",
45
+ "POST",
46
+ "PUT",
47
+ "PATCH",
48
+ "DELETE",
49
+ "OPTIONS",
50
+ )
51
+ allow_headers: tuple[str, ...] = (
52
+ "Authorization",
53
+ "Content-Type",
54
+ "If-Match",
55
+ "Idempotency-Key",
56
+ )
57
+ expose_headers: tuple[str, ...] = field(default_factory=lambda: EXPOSED_HEADERS)
58
+ max_age: int = 600
59
+
60
+ def __post_init__(self) -> None:
61
+ if self.allow_credentials and "*" in self.allow_origins:
62
+ raise WebError("CorsPolicy cannot allow credentials with a wildcard origin")
63
+
64
+
65
+ def apply_cors(app: FastAPI, policy: CorsPolicy) -> None:
66
+ """Install Starlette's ``CORSMiddleware`` configured from *policy*.
67
+
68
+ Args:
69
+ app: The application to install onto.
70
+ policy: The CORS policy.
71
+ """
72
+ app.add_middleware(
73
+ CORSMiddleware,
74
+ allow_origins=list(policy.allow_origins),
75
+ allow_credentials=policy.allow_credentials,
76
+ allow_methods=list(policy.allow_methods),
77
+ allow_headers=list(policy.allow_headers),
78
+ expose_headers=list(policy.expose_headers),
79
+ max_age=policy.max_age,
80
+ )