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,374 @@
1
+ """FastAPI security dependencies for the authentication contracts.
2
+
3
+ Framework credential parsers run with ``auto_error=False`` so failures use the
4
+ shared problem response and challenge behavior.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import inspect
10
+ from collections.abc import Awaitable, Callable, Mapping
11
+ from dataclasses import replace
12
+ from typing import cast
13
+
14
+ from fastapi import Depends, Request, Security
15
+ from fastapi.concurrency import run_in_threadpool
16
+ from fastapi.security import (
17
+ HTTPAuthorizationCredentials,
18
+ HTTPBasic,
19
+ HTTPBasicCredentials,
20
+ HTTPBearer,
21
+ )
22
+ from rn_forge.auth import (
23
+ AccountResolver,
24
+ AsyncAuthenticator,
25
+ Authenticator,
26
+ AuthorizationContext,
27
+ AuthorizationContextProvider,
28
+ Authorizer,
29
+ Principal,
30
+ Requirement,
31
+ ScopeAuthorizer,
32
+ audit,
33
+ effective_permissions,
34
+ requirement_for,
35
+ )
36
+ from rn_forge.fastapi.auth.sessions import ActiveSession, active_session
37
+ from rn_forge.fastapi.problem import Log
38
+ from rn_forge.web import (
39
+ AuthenticationFailed,
40
+ Credentials,
41
+ PermissionDenied,
42
+ SessionRequired,
43
+ parse_authorization,
44
+ )
45
+
46
+ __all__ = [
47
+ "BearerAuth",
48
+ "basic_auth",
49
+ "bearer_auth",
50
+ "current_principal",
51
+ "requires",
52
+ "requires_permission",
53
+ ]
54
+
55
+ _NO_CREDENTIALS = "No credentials were supplied"
56
+ _BEARER = HTTPBearer(auto_error=False)
57
+
58
+ type PrincipalDependency = Callable[..., Awaitable[Principal]]
59
+
60
+
61
+ class BearerAuth:
62
+ """A dependency yielding the :class:`rn_forge.auth.Principal` for a Bearer token.
63
+
64
+ Build it with :func:`bearer_auth`; use the instance as a dependency, or pass
65
+ it to :func:`current_principal`.
66
+ """
67
+
68
+ def __init__(
69
+ self,
70
+ *,
71
+ authenticator: Authenticator | AsyncAuthenticator,
72
+ accounts: AccountResolver,
73
+ contexts: AuthorizationContextProvider,
74
+ scope_map: Mapping[str, frozenset[str]],
75
+ log: Log | None,
76
+ ) -> None:
77
+ self._authenticator = authenticator
78
+ self._accounts = accounts
79
+ self._contexts = contexts
80
+ self._scope_map = scope_map
81
+ self._log = log
82
+
83
+ async def authenticate(self, request: Request) -> Principal:
84
+ """Return the principal for the request's Bearer token.
85
+
86
+ Raises:
87
+ AuthenticationFailed: The token is absent, invalid or has no linked
88
+ active account.
89
+ """
90
+ credentials = parse_authorization(
91
+ request.headers.get("Authorization"), "Bearer"
92
+ )
93
+ if credentials is None or not credentials.token:
94
+ raise AuthenticationFailed(_NO_CREDENTIALS, error_code=401)
95
+ verified = await _authenticate(self._authenticator, credentials, self._log)
96
+ try:
97
+ return await run_in_threadpool(self._link, verified)
98
+ except AuthenticationFailed as exc:
99
+ if self._log is not None:
100
+ self._log(
101
+ "authentication.failed",
102
+ {"scheme": "Bearer", "reason": exc.message},
103
+ )
104
+ raise
105
+
106
+ def _link(self, principal: Principal) -> Principal:
107
+ account_id = (
108
+ self._accounts.lookup(principal.issuer, principal.subject)
109
+ if principal.issuer
110
+ else None
111
+ )
112
+ if account_id is None:
113
+ raise AuthenticationFailed("No account is linked to the token subject")
114
+ context = self._contexts.resolve(account_id)
115
+ if not context.active:
116
+ raise AuthenticationFailed("The account is not active")
117
+ return replace(
118
+ principal,
119
+ subject=account_id,
120
+ external_subject=principal.subject,
121
+ permissions=effective_permissions(
122
+ context.permissions,
123
+ mechanism="bearer",
124
+ scopes=principal.scopes,
125
+ scope_map=self._scope_map,
126
+ ),
127
+ roles=context.roles,
128
+ tenant=_tenant(context),
129
+ attributes=context.attributes,
130
+ )
131
+
132
+ async def __call__(
133
+ self,
134
+ request: Request,
135
+ _credentials: HTTPAuthorizationCredentials | None = Security(_BEARER),
136
+ ) -> Principal:
137
+ return await self.authenticate(request)
138
+
139
+
140
+ def bearer_auth(
141
+ *,
142
+ authenticator: Authenticator | AsyncAuthenticator,
143
+ accounts: AccountResolver,
144
+ contexts: AuthorizationContextProvider,
145
+ scope_map: Mapping[str, frozenset[str]] | None = None,
146
+ log: Log | None = None,
147
+ ) -> BearerAuth:
148
+ """Return a dependency yielding the :class:`rn_forge.auth.Principal` for a Bearer token.
149
+
150
+ The verified token's ``(issuer, subject)`` is looked up with
151
+ ``accounts.lookup``, which never provisions. A token with no linked
152
+ account, or whose account is inactive, is a 401. The principal's
153
+ ``subject`` is then the account ID (``external_subject`` keeps the token's);
154
+ its roles, tenant and attributes come from the account's authorization
155
+ context, and its permissions are the context's limited by the token's
156
+ scopes through *scope_map*.
157
+
158
+ Args:
159
+ authenticator: Verifies ``Credentials(scheme="Bearer", token=...)``.
160
+ accounts: Links the token's identity to an account.
161
+ contexts: Supplies the account's authorization context.
162
+ scope_map: The permissions each accepted scope allows; a scope it does
163
+ not name allows nothing.
164
+ log: Receives ``authentication.failed`` with the failure's reason.
165
+ The 401 body never carries it.
166
+ """
167
+ return BearerAuth(
168
+ authenticator=authenticator,
169
+ accounts=accounts,
170
+ contexts=contexts,
171
+ scope_map=scope_map if scope_map is not None else {},
172
+ log=log,
173
+ )
174
+
175
+
176
+ def current_principal(*, bearer: BearerAuth | None = None) -> PrincipalDependency:
177
+ """Return a dependency yielding the session or bearer principal.
178
+
179
+ A request with an ``Authorization`` header is authenticated by *bearer*
180
+ alone: an invalid token is a 401 even with a valid session cookie, and
181
+ without *bearer* the header makes the request unauthenticated. Any other
182
+ request is authenticated by the login session that
183
+ :class:`~rn_forge.fastapi.SessionMiddleware` resolved, whose principal has
184
+ ``mechanism="session"``, the context's roles and permissions, and the
185
+ session's ``auth_time`` and ``amr``. CSRF checks for session requests are
186
+ the middleware's.
187
+
188
+ An unauthenticated request is a 401 with the ``Bearer`` challenge when
189
+ *bearer* is given, and without a challenge otherwise.
190
+
191
+ Args:
192
+ bearer: From :func:`bearer_auth`.
193
+
194
+ Raises:
195
+ RuntimeError: At request time, :class:`~rn_forge.fastapi.SessionMiddleware`
196
+ is not installed and the request carries no ``Authorization`` header.
197
+ """
198
+
199
+ async def resolve(request: Request) -> Principal:
200
+ if "Authorization" in request.headers:
201
+ if bearer is None:
202
+ raise SessionRequired("Authorization header without bearer auth")
203
+ return await bearer.authenticate(request)
204
+ active = active_session(request)
205
+ if active is None:
206
+ if bearer is None:
207
+ raise SessionRequired("No session")
208
+ raise AuthenticationFailed(_NO_CREDENTIALS, error_code=401)
209
+ return _session_principal(active)
210
+
211
+ if bearer is None:
212
+
213
+ async def session_dependency(request: Request) -> Principal:
214
+ return await resolve(request)
215
+
216
+ return session_dependency
217
+
218
+ async def dependency(
219
+ request: Request,
220
+ _credentials: HTTPAuthorizationCredentials | None = Security(_BEARER),
221
+ ) -> Principal:
222
+ return await resolve(request)
223
+
224
+ return dependency
225
+
226
+
227
+ def _tenant(context: AuthorizationContext) -> str | None:
228
+ tenant = context.attributes.get("tenant")
229
+ return tenant if isinstance(tenant, str) else None
230
+
231
+
232
+ def _session_principal(active: ActiveSession) -> Principal:
233
+ info, context = active.info, active.context
234
+ return Principal(
235
+ subject=info.account_id,
236
+ issuer=info.issuer,
237
+ external_subject=info.external_subject,
238
+ permissions=context.permissions,
239
+ roles=context.roles,
240
+ tenant=_tenant(context),
241
+ attributes=context.attributes,
242
+ mechanism="session",
243
+ auth_time=info.auth_time,
244
+ amr=info.amr,
245
+ )
246
+
247
+
248
+ def basic_auth(
249
+ *, authenticator: Authenticator | AsyncAuthenticator, log: Log | None = None
250
+ ) -> PrincipalDependency:
251
+ """Return a dependency yielding a principal for HTTP Basic credentials.
252
+
253
+ Args:
254
+ authenticator: Verifies ``Credentials(scheme="Basic", token=...)``, where
255
+ the token is the base64 parameter exactly as sent (RFC 7617).
256
+ log: Receives ``authentication.failed`` with the authenticator's reason.
257
+ """
258
+ scheme = HTTPBasic(auto_error=False)
259
+
260
+ async def dependency(
261
+ request: Request,
262
+ basic: HTTPBasicCredentials | None = Security(scheme),
263
+ ) -> Principal:
264
+ credentials = parse_authorization(request.headers.get("Authorization"), "Basic")
265
+ if basic is None or credentials is None:
266
+ raise AuthenticationFailed(_NO_CREDENTIALS, error_code=401)
267
+ return await _authenticate(authenticator, credentials, log)
268
+
269
+ return dependency
270
+
271
+
272
+ def requires(
273
+ authenticate: PrincipalDependency,
274
+ requirement: Requirement,
275
+ *,
276
+ authorizer: Authorizer | None = None,
277
+ ) -> PrincipalDependency:
278
+ """Return a dependency that authenticates, then enforces *requirement*.
279
+
280
+ Insufficient access produces 403 without an authentication challenge.
281
+
282
+ Args:
283
+ authenticate: A dependency from :func:`bearer_auth`, :func:`basic_auth`
284
+ or :func:`current_principal`.
285
+ requirement: Evaluated by :class:`rn_forge.auth.Requirement`'s own rule.
286
+ authorizer: Defaults to :class:`rn_forge.auth.ScopeAuthorizer`.
287
+ """
288
+ resolved = authorizer if authorizer is not None else ScopeAuthorizer()
289
+
290
+ # Async to satisfy PrincipalDependency, though it awaits nothing.
291
+ async def dependency( # NOSONAR(S7503)
292
+ principal: Principal = Depends(authenticate),
293
+ ) -> Principal:
294
+ try:
295
+ resolved.authorize(principal, requires=requirement)
296
+ except PermissionDenied:
297
+ audit("authorization.denied", account_id=principal.subject)
298
+ raise
299
+ return principal
300
+
301
+ return dependency
302
+
303
+
304
+ def requires_permission(
305
+ authenticate: PrincipalDependency,
306
+ permission_key: str,
307
+ action: str,
308
+ *,
309
+ action_map: Mapping[str, str] | None = None,
310
+ authorizer: Authorizer | None = None,
311
+ ) -> PrincipalDependency:
312
+ """Return a dependency that authenticates, then enforces a permission key.
313
+
314
+ The requirement is :func:`rn_forge.auth.requirement_for` of *permission_key*
315
+ and the action. Insufficient access produces 403 without a challenge.
316
+
317
+ Args:
318
+ authenticate: A dependency such as :func:`current_principal`'s.
319
+ permission_key: The resource's base permission key, such as ``orders``.
320
+ action: The action to check, such as ``list``, ``retrieve`` or
321
+ ``partial_update``.
322
+ action_map: Overrides of ``DEFAULT_PERMISSION_ACTION_MAP``.
323
+ authorizer: Defaults to :class:`rn_forge.auth.ScopeAuthorizer`.
324
+ """
325
+ resolved = authorizer if authorizer is not None else ScopeAuthorizer()
326
+
327
+ requirement = requirement_for(permission_key, action, action_map=action_map)
328
+
329
+ # Async to satisfy PrincipalDependency, though it awaits nothing.
330
+ async def dependency( # NOSONAR(S7503)
331
+ principal: Principal = Depends(authenticate),
332
+ ) -> Principal:
333
+ try:
334
+ resolved.authorize(principal, requires=requirement)
335
+ except PermissionDenied:
336
+ audit(
337
+ "authorization.denied",
338
+ account_id=principal.subject,
339
+ permission_key=permission_key,
340
+ action=action,
341
+ )
342
+ raise
343
+ return principal
344
+
345
+ return dependency
346
+
347
+
348
+ async def _authenticate(
349
+ authenticator: Authenticator | AsyncAuthenticator,
350
+ credentials: Credentials,
351
+ log: Log | None,
352
+ ) -> Principal:
353
+ """Run a sync or async authenticator, logging the reason for a refusal.
354
+
355
+ A synchronous authenticator runs in the threadpool, as FastAPI runs a sync
356
+ dependency, so its network I/O (a JWKS fetch, say) does not block the loop.
357
+ """
358
+ try:
359
+ if inspect.iscoroutinefunction(authenticator.authenticate):
360
+ outcome = authenticator.authenticate(credentials=credentials)
361
+ else:
362
+ authenticate = cast(
363
+ Callable[..., Principal | Awaitable[Principal]],
364
+ authenticator.authenticate,
365
+ )
366
+ outcome = await run_in_threadpool(authenticate, credentials=credentials)
367
+ return outcome if isinstance(outcome, Principal) else await outcome
368
+ except AuthenticationFailed as exc:
369
+ if log is not None:
370
+ log(
371
+ "authentication.failed",
372
+ {"scheme": credentials.scheme, "reason": exc.message},
373
+ )
374
+ raise
@@ -0,0 +1,55 @@
1
+ """Which peers may speak for a client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ipaddress
6
+ from collections.abc import Collection
7
+
8
+ __all__ = ["TrustedProxies"]
9
+
10
+
11
+ class TrustedProxies:
12
+ """Peer addresses or CIDR networks whose forwarded headers are believed.
13
+
14
+ Args:
15
+ proxies: Addresses or CIDR networks, such as ``10.0.0.0/8``.
16
+ """
17
+
18
+ def __init__(self, proxies: Collection[str] = ()) -> None:
19
+ self._networks = tuple(
20
+ ipaddress.ip_network(proxy, strict=False) for proxy in proxies
21
+ )
22
+
23
+ def trusts(self, peer: str | None) -> bool:
24
+ """Whether *peer* is one of the proxies."""
25
+ if peer is None:
26
+ return False
27
+ try:
28
+ address = ipaddress.ip_address(peer.strip())
29
+ except ValueError:
30
+ return False
31
+ return any(address in network for network in self._networks)
32
+
33
+ def client(self, peer: str | None, forwarded_for: Collection[str]) -> str:
34
+ """The address of the client behind *peer*.
35
+
36
+ Args:
37
+ peer: The address of the connection's peer.
38
+ forwarded_for: The ``X-Forwarded-For`` header values, in order.
39
+
40
+ Returns:
41
+ *peer* unless it is a trusted proxy; then the nearest address in
42
+ the forwarded chain that is not itself a trusted proxy.
43
+ """
44
+ if not self.trusts(peer):
45
+ return peer or ""
46
+ chain = [
47
+ hop.strip()
48
+ for value in forwarded_for
49
+ for hop in value.split(",")
50
+ if hop.strip()
51
+ ]
52
+ for hop in reversed(chain):
53
+ if not self.trusts(hop):
54
+ return hop
55
+ return peer or ""
@@ -0,0 +1,91 @@
1
+ """Fixed-window rate limiting for the login and callback routes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import math
7
+ import threading
8
+ import time
9
+ from collections.abc import Callable
10
+ from dataclasses import dataclass
11
+ from datetime import timedelta
12
+ from typing import Protocol, runtime_checkable
13
+
14
+ __all__ = [
15
+ "InMemoryRateLimiter",
16
+ "RateLimit",
17
+ "RateLimiter",
18
+ "window_key",
19
+ "window_seconds",
20
+ ]
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class RateLimit:
25
+ """At most *limit* hits in each *window*.
26
+
27
+ Attributes:
28
+ limit: The hits one window allows.
29
+ window: The length of a window.
30
+ """
31
+
32
+ limit: int
33
+ window: timedelta
34
+
35
+
36
+ @runtime_checkable
37
+ class RateLimiter(Protocol):
38
+ """Counts hits per scope and subject in fixed windows.
39
+
40
+ Windows are aligned to the clock, so a client can use a limit twice around
41
+ a window boundary. Every method is synchronous and thread-safe.
42
+ """
43
+
44
+ def hit(self, scope: str, subject: str, rate: RateLimit) -> int | None:
45
+ """Count one hit of *subject* in *scope*.
46
+
47
+ Returns:
48
+ ``None`` while within *rate*, otherwise the seconds until the
49
+ window ends.
50
+ """
51
+ ...
52
+
53
+
54
+ def window_seconds(rate: RateLimit) -> int:
55
+ """The length of *rate*'s window in whole seconds, at least one."""
56
+ return max(1, math.ceil(rate.window.total_seconds()))
57
+
58
+
59
+ def window_key(scope: str, subject: str, rate: RateLimit, now: float) -> str:
60
+ """The counter key for a hit at *now*: a digest, so *subject* is never stored."""
61
+ digest = hashlib.sha256(f"{scope}\0{subject}".encode()).hexdigest()
62
+ return f"{digest}:{int(now // window_seconds(rate))}"
63
+
64
+
65
+ class InMemoryRateLimiter:
66
+ """:class:`RateLimiter` held in process memory, for tests and development.
67
+
68
+ Args:
69
+ clock: Returns the current time in seconds.
70
+ """
71
+
72
+ def __init__(self, clock: Callable[[], float] = time.time) -> None:
73
+ self._clock = clock
74
+ self._counts: dict[str, tuple[int, float]] = {}
75
+ self._lock = threading.Lock()
76
+
77
+ def hit(self, scope: str, subject: str, rate: RateLimit) -> int | None:
78
+ """Count one hit of *subject* in *scope*."""
79
+ window = window_seconds(rate)
80
+ now = self._clock()
81
+ key = window_key(scope, subject, rate, now)
82
+ ends = (int(now // window) + 1) * window
83
+ with self._lock:
84
+ self._counts = {
85
+ k: held for k, held in self._counts.items() if held[1] > now
86
+ }
87
+ count = self._counts.get(key, (0, ends))[0] + 1
88
+ self._counts[key] = (count, ends)
89
+ if count <= rate.limit:
90
+ return None
91
+ return max(1, math.ceil(ends - now))
@@ -0,0 +1,88 @@
1
+ """Redis implementations of the CSRF token store and the rate limiter.
2
+
3
+ Requires the ``redis`` extra and Redis 6.2 or later. Not imported by
4
+ ``rn_forge.fastapi``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ import time
11
+ from collections.abc import Callable
12
+ from datetime import timedelta
13
+
14
+ from redis import Redis
15
+ from rn_forge.fastapi.auth.rate_limit import RateLimit, window_key, window_seconds
16
+
17
+ __all__ = ["RedisCsrfStore", "RedisRateLimiter"]
18
+
19
+ DEFAULT_PREFIX = "rn-forge-fastapi:"
20
+
21
+
22
+ class RedisCsrfStore:
23
+ """:class:`~rn_forge.fastapi.auth.csrf.CsrfStore` over Redis.
24
+
25
+ Each token is one key written with ``SET ... EX``.
26
+
27
+ Args:
28
+ client: The Redis client.
29
+ prefix: Prepended to every key.
30
+ """
31
+
32
+ def __init__(self, client: Redis, *, prefix: str = DEFAULT_PREFIX) -> None:
33
+ self._client = client
34
+ self._prefix = f"{prefix}csrf:"
35
+
36
+ def save(self, key: str, token: str, *, ttl: timedelta) -> None:
37
+ """Store *token* under *key* with ``SET ... EX``."""
38
+ self._client.set(
39
+ self._prefix + key, token, ex=max(1, math.ceil(ttl.total_seconds()))
40
+ )
41
+
42
+ def get(self, key: str) -> str | None:
43
+ """Return the token under *key*."""
44
+ value: object = self._client.get(self._prefix + key)
45
+ if value is None:
46
+ return None
47
+ return value.decode() if isinstance(value, bytes) else str(value)
48
+
49
+ def delete(self, key: str) -> None:
50
+ """Remove the token under *key*."""
51
+ self._client.delete(self._prefix + key)
52
+
53
+
54
+ class RedisRateLimiter:
55
+ """:class:`~rn_forge.fastapi.auth.rate_limit.RateLimiter` over Redis.
56
+
57
+ Each window is one key, counted with ``INCR`` and given a lifetime of one
58
+ window with ``EXPIRE``, in one transaction.
59
+
60
+ Args:
61
+ client: The Redis client.
62
+ prefix: Prepended to every key.
63
+ clock: Returns the current time in seconds.
64
+ """
65
+
66
+ def __init__(
67
+ self,
68
+ client: Redis,
69
+ *,
70
+ prefix: str = DEFAULT_PREFIX,
71
+ clock: Callable[[], float] = time.time,
72
+ ) -> None:
73
+ self._client = client
74
+ self._prefix = f"{prefix}rate:"
75
+ self._clock = clock
76
+
77
+ def hit(self, scope: str, subject: str, rate: RateLimit) -> int | None:
78
+ """Count one hit of *subject* in *scope*."""
79
+ window = window_seconds(rate)
80
+ now = self._clock()
81
+ key = self._prefix + window_key(scope, subject, rate, now)
82
+ pipeline = self._client.pipeline() # pyright: ignore[reportUnknownMemberType] # redis-py leaves shard_hint untyped
83
+ pipeline.incr(key)
84
+ pipeline.expire(key, window)
85
+ count = int(pipeline.execute()[0])
86
+ if count <= rate.limit:
87
+ return None
88
+ return max(1, math.ceil((int(now // window) + 1) * window - now))