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,725 @@
|
|
|
1
|
+
"""The shared HTTP auth surface (``/auth/...``) as a FastAPI router.
|
|
2
|
+
|
|
3
|
+
Mount it with :func:`auth_router`::
|
|
4
|
+
|
|
5
|
+
app.add_middleware(SessionMiddleware, sessions=sessions_for(config))
|
|
6
|
+
app.include_router(auth_router(config))
|
|
7
|
+
|
|
8
|
+
:class:`~rn_forge.fastapi.auth.sessions.SessionMiddleware` resolves the session
|
|
9
|
+
and runs the CSRF check; a router mounted without it is unprotected.
|
|
10
|
+
|
|
11
|
+
The identity providers, account resolver, authorization context provider and
|
|
12
|
+
stores are :mod:`rn_forge.auth` objects the application builds and passes in
|
|
13
|
+
:class:`AuthRoutesConfig`.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
import logging
|
|
20
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
21
|
+
from dataclasses import dataclass, field
|
|
22
|
+
from datetime import UTC, datetime, timedelta
|
|
23
|
+
from http import HTTPStatus
|
|
24
|
+
from typing import TYPE_CHECKING
|
|
25
|
+
from urllib.parse import parse_qsl, urlencode
|
|
26
|
+
|
|
27
|
+
from fastapi import APIRouter, Request, Response
|
|
28
|
+
from fastapi.concurrency import run_in_threadpool
|
|
29
|
+
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
|
|
30
|
+
from rn_forge.auth import (
|
|
31
|
+
AccountRejected,
|
|
32
|
+
AccountResolver,
|
|
33
|
+
AccountStateWriter,
|
|
34
|
+
AuthorizationContextProvider,
|
|
35
|
+
CallbackError,
|
|
36
|
+
DevelopmentIdentityProvider,
|
|
37
|
+
IdentityProvider,
|
|
38
|
+
InMemoryReplayStore,
|
|
39
|
+
InMemorySessionStore,
|
|
40
|
+
InMemoryTransactionStore,
|
|
41
|
+
InvalidReturnTo,
|
|
42
|
+
LoginFailed,
|
|
43
|
+
LoginFlow,
|
|
44
|
+
LoginRequest,
|
|
45
|
+
ReplayStore,
|
|
46
|
+
SessionBody,
|
|
47
|
+
SessionInfo,
|
|
48
|
+
SessionStore,
|
|
49
|
+
TransactionStore,
|
|
50
|
+
audit,
|
|
51
|
+
validate_return_to,
|
|
52
|
+
)
|
|
53
|
+
from rn_forge.fastapi.auth.csrf import CsrfProtection, CsrfStore, InMemoryCsrfStore
|
|
54
|
+
from rn_forge.fastapi.auth.proxies import TrustedProxies
|
|
55
|
+
from rn_forge.fastapi.auth.rate_limit import InMemoryRateLimiter, RateLimit, RateLimiter
|
|
56
|
+
from rn_forge.fastapi.auth.sessions import (
|
|
57
|
+
ActiveSession,
|
|
58
|
+
Sessions,
|
|
59
|
+
refuse_in_memory,
|
|
60
|
+
request_session,
|
|
61
|
+
)
|
|
62
|
+
from rn_forge.web import (
|
|
63
|
+
PROBLEM_MEDIA_TYPE,
|
|
64
|
+
ProblemType,
|
|
65
|
+
SessionRequired,
|
|
66
|
+
TooManyRequests,
|
|
67
|
+
default_registry,
|
|
68
|
+
render_problem,
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
if TYPE_CHECKING:
|
|
72
|
+
from rn_forge.auth.oidc import BackchannelLogout
|
|
73
|
+
|
|
74
|
+
__all__ = ["TRANSACTION_COOKIE", "AuthRoutesConfig", "auth_router", "sessions_for"]
|
|
75
|
+
|
|
76
|
+
_LOGGER = logging.getLogger(__name__)
|
|
77
|
+
|
|
78
|
+
TRANSACTION_COOKIE = "__Host-login-tx"
|
|
79
|
+
"""The cookie that binds a callback to the browser that began the login."""
|
|
80
|
+
|
|
81
|
+
_TRANSACTION_MAX_AGE = 600
|
|
82
|
+
_PASSWORD_PER_CLIENT = RateLimit(30, timedelta(minutes=5))
|
|
83
|
+
_PASSWORD_PER_ACCOUNT = RateLimit(10, timedelta(minutes=5))
|
|
84
|
+
_CALLBACK_PER_CLIENT = RateLimit(60, timedelta(minutes=5))
|
|
85
|
+
_NO_STORE = {"Cache-Control": "max-age=0, no-cache, no-store, must-revalidate, private"}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(frozen=True)
|
|
89
|
+
class AuthRoutesConfig:
|
|
90
|
+
"""What :func:`auth_router` needs to serve the auth routes.
|
|
91
|
+
|
|
92
|
+
Attributes:
|
|
93
|
+
providers: The identity providers, by provider ID. A provider of kind
|
|
94
|
+
``development`` is served only while ``debug`` is true.
|
|
95
|
+
accounts: Links, provisions or rejects each external identity.
|
|
96
|
+
contexts: Supplies each account's authorization context.
|
|
97
|
+
account_state: Persists the account's session version, which
|
|
98
|
+
``/auth/logout/all`` and a back-channel logout by ``sub`` bump.
|
|
99
|
+
return_to_prefixes: Path prefixes a ``return_to`` may lie under.
|
|
100
|
+
default_return_to: Where a password login lands, which has no
|
|
101
|
+
``return_to``.
|
|
102
|
+
error_route: The SPA route a failed callback redirects to, with an
|
|
103
|
+
``error`` query parameter.
|
|
104
|
+
post_logout_redirect: Where the identity provider returns the browser
|
|
105
|
+
after RP-initiated logout.
|
|
106
|
+
provider_names: Display names by provider ID; the ID by default.
|
|
107
|
+
backchannel: Back-channel logout handlers, by provider ID.
|
|
108
|
+
sessions: Holds the login sessions.
|
|
109
|
+
transactions: Holds logins between redirect and callback.
|
|
110
|
+
csrf: Holds each session's CSRF token and the anonymous sessions that
|
|
111
|
+
protect the login request.
|
|
112
|
+
trusted_origins: Origins, besides the request's own, that may send an
|
|
113
|
+
unsafe request.
|
|
114
|
+
trusted_proxies: Peer addresses or CIDR networks whose
|
|
115
|
+
``X-Forwarded-Proto``, ``X-Forwarded-Host`` and
|
|
116
|
+
``X-Forwarded-For`` are believed.
|
|
117
|
+
replay: Holds replayed token IDs and revoked ``sid`` values.
|
|
118
|
+
idle_timeout: How long a session may sit unused.
|
|
119
|
+
absolute_timeout: How long a session lives whatever its use, and how
|
|
120
|
+
long a revoked ``sid`` stays revoked.
|
|
121
|
+
limiter: Counts hits for the rate limits.
|
|
122
|
+
password_client_limit: Password login attempts per client address in a
|
|
123
|
+
window; ``None`` for no limit. The client is the peer, or the
|
|
124
|
+
forwarded client when the peer is in ``trusted_proxies``.
|
|
125
|
+
password_account_limit: Password login attempts per submitted username
|
|
126
|
+
in a window; ``None`` for no limit.
|
|
127
|
+
callback_client_limit: Callback requests per client address in a window.
|
|
128
|
+
Callbacks are limited per client only, because no account is known
|
|
129
|
+
before the response is verified; ``None`` for no limit.
|
|
130
|
+
debug: Serves the ``development`` provider and accepts in-memory
|
|
131
|
+
stores. Otherwise an in-memory sessions, transactions, replay,
|
|
132
|
+
CSRF or rate-limit store is refused.
|
|
133
|
+
clock: Returns the current time, aware.
|
|
134
|
+
problem_type_base: Prefix of the ``type`` URI of the problem responses.
|
|
135
|
+
Required.
|
|
136
|
+
|
|
137
|
+
Raises:
|
|
138
|
+
ValueError: *problem_type_base* is empty.
|
|
139
|
+
"""
|
|
140
|
+
|
|
141
|
+
providers: Mapping[str, IdentityProvider[LoginRequest]]
|
|
142
|
+
accounts: AccountResolver
|
|
143
|
+
contexts: AuthorizationContextProvider
|
|
144
|
+
account_state: AccountStateWriter
|
|
145
|
+
return_to_prefixes: Sequence[str] = ("/",)
|
|
146
|
+
default_return_to: str = "/"
|
|
147
|
+
error_route: str = "/auth/error"
|
|
148
|
+
post_logout_redirect: str = "/"
|
|
149
|
+
provider_names: Mapping[str, str] = field(default_factory=dict[str, str])
|
|
150
|
+
backchannel: Mapping[str, BackchannelLogout] = field(
|
|
151
|
+
default_factory=dict[str, "BackchannelLogout"]
|
|
152
|
+
)
|
|
153
|
+
sessions: SessionStore = field(default_factory=InMemorySessionStore)
|
|
154
|
+
transactions: TransactionStore = field(default_factory=InMemoryTransactionStore)
|
|
155
|
+
replay: ReplayStore = field(default_factory=InMemoryReplayStore)
|
|
156
|
+
csrf: CsrfStore = field(default_factory=InMemoryCsrfStore)
|
|
157
|
+
trusted_origins: Sequence[str] = ()
|
|
158
|
+
trusted_proxies: Sequence[str] = ()
|
|
159
|
+
limiter: RateLimiter = field(default_factory=InMemoryRateLimiter)
|
|
160
|
+
password_client_limit: RateLimit | None = _PASSWORD_PER_CLIENT
|
|
161
|
+
password_account_limit: RateLimit | None = _PASSWORD_PER_ACCOUNT
|
|
162
|
+
callback_client_limit: RateLimit | None = _CALLBACK_PER_CLIENT
|
|
163
|
+
idle_timeout: timedelta = timedelta(minutes=30)
|
|
164
|
+
absolute_timeout: timedelta = timedelta(hours=12)
|
|
165
|
+
debug: bool = False
|
|
166
|
+
clock: Callable[[], datetime] = lambda: datetime.now(UTC)
|
|
167
|
+
problem_type_base: str = ""
|
|
168
|
+
|
|
169
|
+
def __post_init__(self) -> None:
|
|
170
|
+
if not self.problem_type_base:
|
|
171
|
+
raise ValueError(
|
|
172
|
+
"problem_type_base must be set: without it csrf-failed and "
|
|
173
|
+
"forbidden differ only in detail"
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
@dataclass(frozen=True)
|
|
178
|
+
class _Request:
|
|
179
|
+
query: Mapping[str, str]
|
|
180
|
+
form: Mapping[str, str]
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
@dataclass(frozen=True)
|
|
184
|
+
class _Started:
|
|
185
|
+
"""A completed login: the session to hand the browser and where to send it."""
|
|
186
|
+
|
|
187
|
+
return_to: str
|
|
188
|
+
session_id: str
|
|
189
|
+
csrf_token: str
|
|
190
|
+
info: SessionInfo
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class _Views:
|
|
194
|
+
def __init__(self, config: AuthRoutesConfig) -> None:
|
|
195
|
+
self._config = config
|
|
196
|
+
self._registry = default_registry(type_base=config.problem_type_base)
|
|
197
|
+
if not config.debug:
|
|
198
|
+
refuse_in_memory(
|
|
199
|
+
transaction_store=config.transactions, rate_limiter=config.limiter
|
|
200
|
+
)
|
|
201
|
+
self._proxies = TrustedProxies(config.trusted_proxies)
|
|
202
|
+
self.sessions = sessions_for(config)
|
|
203
|
+
self._flow = LoginFlow[LoginRequest](
|
|
204
|
+
config.providers,
|
|
205
|
+
config.transactions,
|
|
206
|
+
return_to_prefixes=config.return_to_prefixes,
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
# Routes -----------------------------------------------------------------
|
|
210
|
+
|
|
211
|
+
# Starlette handler: the signature is imposed, the body needs no await.
|
|
212
|
+
async def providers(self, request: Request) -> Response: # NOSONAR(S1172,S7503)
|
|
213
|
+
names = self._config.provider_names
|
|
214
|
+
return JSONResponse(
|
|
215
|
+
[
|
|
216
|
+
{"id": p.id, "name": names.get(p.id, p.id), "kind": p.kind}
|
|
217
|
+
for p in self._config.providers.values()
|
|
218
|
+
if self._served(p)
|
|
219
|
+
]
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
async def login(self, request: Request, provider_id: str) -> Response:
|
|
223
|
+
if provider_id == "password":
|
|
224
|
+
return Response(
|
|
225
|
+
status_code=HTTPStatus.METHOD_NOT_ALLOWED, headers={"Allow": "POST"}
|
|
226
|
+
)
|
|
227
|
+
provider = self._navigable(provider_id)
|
|
228
|
+
if provider is None:
|
|
229
|
+
return self._not_found(request)
|
|
230
|
+
query = dict(request.query_params)
|
|
231
|
+
login_request = _Request(query=query, form={})
|
|
232
|
+
development = provider.kind == "development"
|
|
233
|
+
if development and "account" not in query:
|
|
234
|
+
return self._account_list(request, provider)
|
|
235
|
+
return_to = query.get("return_to", self._config.default_return_to)
|
|
236
|
+
try:
|
|
237
|
+
start = await run_in_threadpool(
|
|
238
|
+
self._flow.begin, provider_id, login_request, return_to=return_to
|
|
239
|
+
)
|
|
240
|
+
if development:
|
|
241
|
+
return await self._signed_in(
|
|
242
|
+
request, provider_id, login_request, start.transaction.id
|
|
243
|
+
)
|
|
244
|
+
except LoginFailed as exc:
|
|
245
|
+
self._audit_failure(provider_id, exc)
|
|
246
|
+
return self._redirect(self._error_url(exc.code))
|
|
247
|
+
if start.redirect_url is None:
|
|
248
|
+
return self._not_found(request)
|
|
249
|
+
response = _no_store(RedirectResponse(start.redirect_url, status_code=302))
|
|
250
|
+
response.set_cookie(
|
|
251
|
+
TRANSACTION_COOKIE,
|
|
252
|
+
start.transaction.id,
|
|
253
|
+
max_age=_TRANSACTION_MAX_AGE,
|
|
254
|
+
secure=True,
|
|
255
|
+
httponly=True,
|
|
256
|
+
samesite="lax",
|
|
257
|
+
path="/",
|
|
258
|
+
)
|
|
259
|
+
return response
|
|
260
|
+
|
|
261
|
+
async def callback(self, request: Request, provider_id: str) -> Response:
|
|
262
|
+
if self._navigable(provider_id) is None:
|
|
263
|
+
return self._not_found(request)
|
|
264
|
+
limited = await self._limit(
|
|
265
|
+
request,
|
|
266
|
+
"callback",
|
|
267
|
+
("client", self._client(request), self._config.callback_client_limit),
|
|
268
|
+
)
|
|
269
|
+
if limited is not None:
|
|
270
|
+
return limited
|
|
271
|
+
try:
|
|
272
|
+
response = await self._signed_in(
|
|
273
|
+
request,
|
|
274
|
+
provider_id,
|
|
275
|
+
_Request(query=dict(request.query_params), form={}),
|
|
276
|
+
self._transaction_cookie(request),
|
|
277
|
+
)
|
|
278
|
+
except LoginFailed as exc:
|
|
279
|
+
self._audit_failure(provider_id, exc)
|
|
280
|
+
response = self._redirect(self._error_url(exc.code))
|
|
281
|
+
response.delete_cookie(
|
|
282
|
+
TRANSACTION_COOKIE, path="/", secure=True, httponly=True, samesite="lax"
|
|
283
|
+
)
|
|
284
|
+
return response
|
|
285
|
+
|
|
286
|
+
async def password_login(self, request: Request) -> Response:
|
|
287
|
+
provider = next(
|
|
288
|
+
(p for p in self._config.providers.values() if p.kind == "password"), None
|
|
289
|
+
)
|
|
290
|
+
if provider is None:
|
|
291
|
+
return self._not_found(request)
|
|
292
|
+
login_request = _Request(query={}, form=await _credentials(request))
|
|
293
|
+
username = login_request.form.get("username", "").strip().lower()
|
|
294
|
+
limited = await self._limit(
|
|
295
|
+
request,
|
|
296
|
+
"password",
|
|
297
|
+
("client", self._client(request), self._config.password_client_limit),
|
|
298
|
+
("account", username, self._config.password_account_limit),
|
|
299
|
+
)
|
|
300
|
+
if limited is not None:
|
|
301
|
+
return limited
|
|
302
|
+
try:
|
|
303
|
+
started = await run_in_threadpool(
|
|
304
|
+
self._begin_and_complete, provider.id, login_request, request
|
|
305
|
+
)
|
|
306
|
+
except LoginFailed as exc:
|
|
307
|
+
self._audit_failure(provider.id, exc)
|
|
308
|
+
# Every failure answers alike, so the response cannot tell which
|
|
309
|
+
# accounts exist.
|
|
310
|
+
return self._unauthorized(request)
|
|
311
|
+
return await self._session_response(request, started=started)
|
|
312
|
+
|
|
313
|
+
async def session(self, request: Request) -> Response:
|
|
314
|
+
response = await self._session_response(request)
|
|
315
|
+
_, active = await self._resolve(request)
|
|
316
|
+
token, anonymous_id = await run_in_threadpool(
|
|
317
|
+
self.sessions.ensure_csrf, self.sessions.session_id(request), active
|
|
318
|
+
)
|
|
319
|
+
if anonymous_id is not None:
|
|
320
|
+
self.sessions.set_anonymous_cookie(response, anonymous_id)
|
|
321
|
+
self.sessions.csrf.set_cookie(response, token)
|
|
322
|
+
return response
|
|
323
|
+
|
|
324
|
+
async def logout(self, request: Request) -> Response:
|
|
325
|
+
session_id, active = await self._resolve(request)
|
|
326
|
+
if active is None:
|
|
327
|
+
return self._unauthorized(request)
|
|
328
|
+
info = active.info
|
|
329
|
+
provider = self._config.providers.get(info.provider)
|
|
330
|
+
redirect = (
|
|
331
|
+
provider.logout_redirect(
|
|
332
|
+
info, post_logout_redirect=self._config.post_logout_redirect
|
|
333
|
+
)
|
|
334
|
+
if provider is not None
|
|
335
|
+
else None
|
|
336
|
+
)
|
|
337
|
+
response = _no_store(JSONResponse({"redirect": redirect}))
|
|
338
|
+
await self._end(response, session_id)
|
|
339
|
+
audit("logout", account_id=info.account_id, provider=info.provider)
|
|
340
|
+
return response
|
|
341
|
+
|
|
342
|
+
async def logout_all(self, request: Request) -> Response:
|
|
343
|
+
session_id, active = await self._resolve(request)
|
|
344
|
+
if active is None:
|
|
345
|
+
return self._unauthorized(request)
|
|
346
|
+
await run_in_threadpool(
|
|
347
|
+
self._config.account_state.bump_session_version, active.info.account_id
|
|
348
|
+
)
|
|
349
|
+
response = _no_store(JSONResponse({"redirect": None}))
|
|
350
|
+
await self._end(response, session_id)
|
|
351
|
+
audit(
|
|
352
|
+
"logout.all",
|
|
353
|
+
account_id=active.info.account_id,
|
|
354
|
+
provider=active.info.provider,
|
|
355
|
+
)
|
|
356
|
+
return response
|
|
357
|
+
|
|
358
|
+
async def _end(self, response: Response, session_id: str | None) -> None:
|
|
359
|
+
"""End the session and hand the browser a fresh anonymous session and token."""
|
|
360
|
+
|
|
361
|
+
def end() -> tuple[str, str]:
|
|
362
|
+
self.sessions.end(session_id)
|
|
363
|
+
return self.sessions.start_anonymous()
|
|
364
|
+
|
|
365
|
+
anonymous_id, token = await run_in_threadpool(end)
|
|
366
|
+
self.sessions.set_anonymous_cookie(response, anonymous_id)
|
|
367
|
+
self.sessions.csrf.set_cookie(response, token)
|
|
368
|
+
|
|
369
|
+
async def backchannel_logout(self, request: Request, provider_id: str) -> Response:
|
|
370
|
+
from rn_forge.auth.oidc import TokenVerificationError # needs the oidc extra
|
|
371
|
+
|
|
372
|
+
handler = self._config.backchannel.get(provider_id)
|
|
373
|
+
if handler is None:
|
|
374
|
+
return self._not_found(request)
|
|
375
|
+
form = _form(await request.body())
|
|
376
|
+
try:
|
|
377
|
+
revocation = await run_in_threadpool(
|
|
378
|
+
handler.handle, form.get("logout_token", "")
|
|
379
|
+
)
|
|
380
|
+
except TokenVerificationError as exc:
|
|
381
|
+
_LOGGER.warning("Back-channel logout from %s refused: %s", provider_id, exc)
|
|
382
|
+
return _no_store(Response(status_code=HTTPStatus.BAD_REQUEST))
|
|
383
|
+
if revocation.sid is not None:
|
|
384
|
+
await run_in_threadpool(
|
|
385
|
+
self._config.replay.revoke_sid,
|
|
386
|
+
revocation.issuer,
|
|
387
|
+
revocation.sid,
|
|
388
|
+
ttl=self._config.absolute_timeout,
|
|
389
|
+
)
|
|
390
|
+
audit("logout.backchannel", provider=provider_id, scope="session")
|
|
391
|
+
elif revocation.account_id is not None:
|
|
392
|
+
await run_in_threadpool(
|
|
393
|
+
self._config.account_state.bump_session_version, revocation.account_id
|
|
394
|
+
)
|
|
395
|
+
audit(
|
|
396
|
+
"logout.backchannel",
|
|
397
|
+
provider=provider_id,
|
|
398
|
+
scope="account",
|
|
399
|
+
account_id=revocation.account_id,
|
|
400
|
+
)
|
|
401
|
+
return _no_store(Response())
|
|
402
|
+
|
|
403
|
+
# Login ------------------------------------------------------------------
|
|
404
|
+
|
|
405
|
+
async def _signed_in(
|
|
406
|
+
self,
|
|
407
|
+
request: Request,
|
|
408
|
+
provider_id: str,
|
|
409
|
+
login_request: LoginRequest,
|
|
410
|
+
transaction_id: str | None,
|
|
411
|
+
) -> Response:
|
|
412
|
+
started = await run_in_threadpool(
|
|
413
|
+
self._complete,
|
|
414
|
+
provider_id,
|
|
415
|
+
login_request,
|
|
416
|
+
transaction_id,
|
|
417
|
+
self.sessions.session_id(request),
|
|
418
|
+
)
|
|
419
|
+
response = self._redirect(started.return_to)
|
|
420
|
+
self._start_cookies(response, started)
|
|
421
|
+
return response
|
|
422
|
+
|
|
423
|
+
def _begin_and_complete(
|
|
424
|
+
self, provider_id: str, login_request: LoginRequest, request: Request
|
|
425
|
+
) -> _Started:
|
|
426
|
+
start = self._flow.begin(
|
|
427
|
+
provider_id, login_request, return_to=self._config.default_return_to
|
|
428
|
+
)
|
|
429
|
+
return self._complete(
|
|
430
|
+
provider_id,
|
|
431
|
+
login_request,
|
|
432
|
+
start.transaction.id,
|
|
433
|
+
self.sessions.session_id(request),
|
|
434
|
+
)
|
|
435
|
+
|
|
436
|
+
def _complete(
|
|
437
|
+
self,
|
|
438
|
+
provider_id: str,
|
|
439
|
+
login_request: LoginRequest,
|
|
440
|
+
transaction_id: str | None,
|
|
441
|
+
previous_session_id: str | None,
|
|
442
|
+
) -> _Started:
|
|
443
|
+
"""Finish a login and start the session; runs in the thread pool."""
|
|
444
|
+
completed = self._flow.complete(
|
|
445
|
+
provider_id, login_request, transaction_id=transaction_id
|
|
446
|
+
)
|
|
447
|
+
identity = completed.identity
|
|
448
|
+
try:
|
|
449
|
+
account_id = self._config.accounts.resolve(identity)
|
|
450
|
+
except AccountRejected as exc:
|
|
451
|
+
audit("account.rejected", provider=provider_id, reason=exc.reason)
|
|
452
|
+
raise self._refused("account_not_provisioned", provider_id, exc.reason)
|
|
453
|
+
context = self._config.contexts.resolve(account_id)
|
|
454
|
+
if not context.active:
|
|
455
|
+
audit("account.disabled", account_id=account_id, provider=provider_id)
|
|
456
|
+
raise self._refused("access_denied", provider_id, "account is not active")
|
|
457
|
+
moment = self.sessions.now()
|
|
458
|
+
info = SessionInfo(
|
|
459
|
+
account_id=account_id,
|
|
460
|
+
session_version=context.session_version,
|
|
461
|
+
provider=identity.provider,
|
|
462
|
+
issuer=identity.issuer,
|
|
463
|
+
external_subject=identity.subject,
|
|
464
|
+
created_at=moment,
|
|
465
|
+
expires_at=moment + self._config.absolute_timeout,
|
|
466
|
+
auth_time=identity.auth_time,
|
|
467
|
+
amr=identity.amr,
|
|
468
|
+
session_ref=identity.session_ref,
|
|
469
|
+
id_token=identity.id_token,
|
|
470
|
+
)
|
|
471
|
+
session_id, token = self.sessions.start(info, previous=previous_session_id)
|
|
472
|
+
audit("login.success", account_id=account_id, provider=provider_id)
|
|
473
|
+
return _Started(self._return_to(completed.return_to), session_id, token, info)
|
|
474
|
+
|
|
475
|
+
def _return_to(self, return_to: str) -> str:
|
|
476
|
+
try:
|
|
477
|
+
return validate_return_to(
|
|
478
|
+
return_to, prefixes=self._config.return_to_prefixes
|
|
479
|
+
)
|
|
480
|
+
except InvalidReturnTo:
|
|
481
|
+
return self._config.default_return_to
|
|
482
|
+
|
|
483
|
+
@staticmethod
|
|
484
|
+
def _audit_failure(provider_id: str, exc: LoginFailed) -> None:
|
|
485
|
+
audit("login.failure", provider=provider_id, code=exc.code, reason=exc.reason)
|
|
486
|
+
|
|
487
|
+
def _client(self, request: Request) -> str:
|
|
488
|
+
peer = request.client.host if request.client else None
|
|
489
|
+
return self._proxies.client(peer, request.headers.getlist("x-forwarded-for"))
|
|
490
|
+
|
|
491
|
+
async def _limit(
|
|
492
|
+
self,
|
|
493
|
+
request: Request,
|
|
494
|
+
scope: str,
|
|
495
|
+
*counters: tuple[str, str, RateLimit | None],
|
|
496
|
+
) -> Response | None:
|
|
497
|
+
"""Count one hit on each counter; answer ``429`` for the first one over."""
|
|
498
|
+
for by, subject, rate in counters:
|
|
499
|
+
if rate is None:
|
|
500
|
+
continue
|
|
501
|
+
retry_after = await run_in_threadpool(
|
|
502
|
+
self._config.limiter.hit, f"{scope}:{by}", subject, rate
|
|
503
|
+
)
|
|
504
|
+
if retry_after is not None:
|
|
505
|
+
audit("rate_limited", scope=scope, by=by, retry_after=retry_after)
|
|
506
|
+
return _no_store(
|
|
507
|
+
self._problem(
|
|
508
|
+
request,
|
|
509
|
+
TooManyRequests("Too many requests", retry_after=retry_after),
|
|
510
|
+
)
|
|
511
|
+
)
|
|
512
|
+
return None
|
|
513
|
+
|
|
514
|
+
@staticmethod
|
|
515
|
+
def _refused(code: CallbackError, provider_id: str, reason: str) -> LoginFailed:
|
|
516
|
+
_LOGGER.warning("Login with %s refused: %s", provider_id, reason)
|
|
517
|
+
return LoginFailed(code, reason)
|
|
518
|
+
|
|
519
|
+
@staticmethod
|
|
520
|
+
def _transaction_cookie(request: Request) -> str | None:
|
|
521
|
+
# Starlette's cookie parsing keeps one value per name, so duplicates
|
|
522
|
+
# are counted in the raw header.
|
|
523
|
+
values = [
|
|
524
|
+
value.strip()
|
|
525
|
+
for name, _, value in (
|
|
526
|
+
part.partition("=")
|
|
527
|
+
for header in request.headers.getlist("cookie")
|
|
528
|
+
for part in header.split(";")
|
|
529
|
+
)
|
|
530
|
+
if name.strip() == TRANSACTION_COOKIE
|
|
531
|
+
]
|
|
532
|
+
if len(values) > 1:
|
|
533
|
+
raise LoginFailed("login_failed", "more than one transaction cookie")
|
|
534
|
+
return values[0] if values else None
|
|
535
|
+
|
|
536
|
+
# Providers --------------------------------------------------------------
|
|
537
|
+
|
|
538
|
+
def _served(self, provider: IdentityProvider[LoginRequest]) -> bool:
|
|
539
|
+
return provider.kind != "development" or self._config.debug
|
|
540
|
+
|
|
541
|
+
def _navigable(self, provider_id: str) -> IdentityProvider[LoginRequest] | None:
|
|
542
|
+
"""The provider for a browser-navigated route, or ``None`` if there is none."""
|
|
543
|
+
provider = self._config.providers.get(provider_id)
|
|
544
|
+
if provider is None or provider.kind == "password":
|
|
545
|
+
return None
|
|
546
|
+
return provider if self._served(provider) else None
|
|
547
|
+
|
|
548
|
+
def _account_list(
|
|
549
|
+
self, request: Request, provider: IdentityProvider[LoginRequest]
|
|
550
|
+
) -> Response:
|
|
551
|
+
if not isinstance(provider, DevelopmentIdentityProvider):
|
|
552
|
+
return Response(status_code=HTTPStatus.NOT_FOUND)
|
|
553
|
+
return _no_store(
|
|
554
|
+
HTMLResponse(provider.render_accounts(login_url=request.url.path))
|
|
555
|
+
)
|
|
556
|
+
|
|
557
|
+
# Responses --------------------------------------------------------------
|
|
558
|
+
|
|
559
|
+
async def _resolve(
|
|
560
|
+
self, request: Request
|
|
561
|
+
) -> tuple[str | None, ActiveSession | None]:
|
|
562
|
+
"""The request's session: the middleware's, else a read that does not extend it."""
|
|
563
|
+
resolved = request_session(request)
|
|
564
|
+
if resolved is not None:
|
|
565
|
+
return resolved
|
|
566
|
+
session_id = self.sessions.session_id(request)
|
|
567
|
+
return session_id, await run_in_threadpool(
|
|
568
|
+
self.sessions.read, session_id, touch=False
|
|
569
|
+
)
|
|
570
|
+
|
|
571
|
+
async def _session_response(
|
|
572
|
+
self,
|
|
573
|
+
request: Request,
|
|
574
|
+
*,
|
|
575
|
+
started: _Started | None = None,
|
|
576
|
+
) -> Response:
|
|
577
|
+
if started is not None:
|
|
578
|
+
active = await run_in_threadpool(
|
|
579
|
+
self.sessions.read, started.session_id, touch=False
|
|
580
|
+
)
|
|
581
|
+
else:
|
|
582
|
+
_, active = await self._resolve(request)
|
|
583
|
+
if active is None:
|
|
584
|
+
return self._unauthorized(request)
|
|
585
|
+
body = SessionBody.build(active.info, active.context)
|
|
586
|
+
response = _no_store(JSONResponse(body.to_json()))
|
|
587
|
+
if started is not None:
|
|
588
|
+
self._start_cookies(response, started)
|
|
589
|
+
return response
|
|
590
|
+
|
|
591
|
+
def _start_cookies(self, response: Response, started: _Started) -> None:
|
|
592
|
+
self.sessions.set_cookie(response, started.session_id, started.info)
|
|
593
|
+
self.sessions.csrf.set_cookie(response, started.csrf_token)
|
|
594
|
+
|
|
595
|
+
def _error_url(self, code: str) -> str:
|
|
596
|
+
return f"{self._config.error_route}?{urlencode({'error': code})}"
|
|
597
|
+
|
|
598
|
+
@staticmethod
|
|
599
|
+
def _redirect(url: str) -> Response:
|
|
600
|
+
return _no_store(RedirectResponse(url, status_code=302))
|
|
601
|
+
|
|
602
|
+
def _unauthorized(self, request: Request) -> Response:
|
|
603
|
+
return _no_store(self._problem(request, SessionRequired("no session")))
|
|
604
|
+
|
|
605
|
+
def _not_found(self, request: Request) -> Response:
|
|
606
|
+
row = self._registry.problem_for_status(HTTPStatus.NOT_FOUND)
|
|
607
|
+
return self._problem(
|
|
608
|
+
request, LookupError("no such auth route"), problem=row, detail=row.title
|
|
609
|
+
)
|
|
610
|
+
|
|
611
|
+
def _problem(
|
|
612
|
+
self,
|
|
613
|
+
request: Request,
|
|
614
|
+
exc: BaseException,
|
|
615
|
+
*,
|
|
616
|
+
problem: ProblemType | None = None,
|
|
617
|
+
detail: str | None = None,
|
|
618
|
+
) -> Response:
|
|
619
|
+
rendered = render_problem(
|
|
620
|
+
self._registry,
|
|
621
|
+
exc,
|
|
622
|
+
instance=request.url.path,
|
|
623
|
+
problem=problem,
|
|
624
|
+
detail=detail,
|
|
625
|
+
)
|
|
626
|
+
return JSONResponse(
|
|
627
|
+
rendered.body,
|
|
628
|
+
status_code=rendered.status,
|
|
629
|
+
media_type=PROBLEM_MEDIA_TYPE,
|
|
630
|
+
headers=dict(rendered.headers),
|
|
631
|
+
)
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def sessions_for(config: AuthRoutesConfig) -> Sessions:
|
|
635
|
+
"""A :class:`Sessions` with the stores and timeouts of *config*.
|
|
636
|
+
|
|
637
|
+
Pass it to :class:`~rn_forge.fastapi.auth.sessions.SessionMiddleware` so the
|
|
638
|
+
middleware and the routes of ``auth_router(config)`` agree.
|
|
639
|
+
|
|
640
|
+
Raises:
|
|
641
|
+
RuntimeError: ``config.debug`` is false and a store is held in memory.
|
|
642
|
+
"""
|
|
643
|
+
return Sessions(
|
|
644
|
+
store=config.sessions,
|
|
645
|
+
contexts=config.contexts,
|
|
646
|
+
replay=config.replay,
|
|
647
|
+
csrf=CsrfProtection(
|
|
648
|
+
store=config.csrf,
|
|
649
|
+
problem_type_base=config.problem_type_base,
|
|
650
|
+
trusted_origins=config.trusted_origins,
|
|
651
|
+
trusted_proxies=config.trusted_proxies,
|
|
652
|
+
),
|
|
653
|
+
idle_timeout=config.idle_timeout,
|
|
654
|
+
absolute_timeout=config.absolute_timeout,
|
|
655
|
+
debug=config.debug,
|
|
656
|
+
clock=config.clock,
|
|
657
|
+
)
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
def _no_store[ResponseT: Response](response: ResponseT) -> ResponseT:
|
|
661
|
+
response.headers.update(_NO_STORE)
|
|
662
|
+
return response
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
def _form(body: bytes) -> dict[str, str]:
|
|
666
|
+
return dict(parse_qsl(body.decode("utf-8", errors="replace")))
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
async def _credentials(request: Request) -> dict[str, str]:
|
|
670
|
+
"""The ``username`` and ``password`` of a JSON or form-encoded login request."""
|
|
671
|
+
body = await request.body()
|
|
672
|
+
media_type = request.headers.get("content-type", "").partition(";")[0].strip()
|
|
673
|
+
if media_type == "application/json":
|
|
674
|
+
try:
|
|
675
|
+
document: object = json.loads(body)
|
|
676
|
+
except ValueError:
|
|
677
|
+
return {}
|
|
678
|
+
if not isinstance(document, dict):
|
|
679
|
+
return {}
|
|
680
|
+
fields = document # pyright: ignore[reportUnknownVariableType]
|
|
681
|
+
return {
|
|
682
|
+
str(name): value # pyright: ignore[reportUnknownArgumentType]
|
|
683
|
+
for name, value in fields.items() # pyright: ignore[reportUnknownVariableType]
|
|
684
|
+
if isinstance(value, str)
|
|
685
|
+
}
|
|
686
|
+
return _form(body)
|
|
687
|
+
|
|
688
|
+
|
|
689
|
+
def auth_router(config: AuthRoutesConfig, *, prefix: str = "/auth") -> APIRouter:
|
|
690
|
+
"""Return a router serving every auth route under *prefix*.
|
|
691
|
+
|
|
692
|
+
| Method | Path |
|
|
693
|
+
| -- | -- |
|
|
694
|
+
| ``GET`` | ``providers`` |
|
|
695
|
+
| ``GET`` | ``login/{provider}`` |
|
|
696
|
+
| ``GET`` | ``callback/{provider}`` |
|
|
697
|
+
| ``GET`` | ``session`` |
|
|
698
|
+
| ``POST`` | ``logout`` |
|
|
699
|
+
| ``POST`` | ``logout/all`` |
|
|
700
|
+
| ``POST`` | ``backchannel-logout/{provider}`` |
|
|
701
|
+
| ``POST`` | ``login/password`` |
|
|
702
|
+
|
|
703
|
+
Args:
|
|
704
|
+
config: The providers and collaborators the routes use.
|
|
705
|
+
prefix: The URL prefix, with a leading slash and none at the end;
|
|
706
|
+
empty for none.
|
|
707
|
+
|
|
708
|
+
Returns:
|
|
709
|
+
The router, to pass to ``FastAPI.include_router``.
|
|
710
|
+
"""
|
|
711
|
+
views = _Views(config)
|
|
712
|
+
router = APIRouter(prefix=prefix.rstrip("/"), include_in_schema=False)
|
|
713
|
+
router.add_api_route("/providers", views.providers, methods=["GET"])
|
|
714
|
+
router.add_api_route("/login/password", views.password_login, methods=["POST"])
|
|
715
|
+
router.add_api_route("/login/{provider_id}", views.login, methods=["GET"])
|
|
716
|
+
router.add_api_route("/callback/{provider_id}", views.callback, methods=["GET"])
|
|
717
|
+
router.add_api_route("/session", views.session, methods=["GET"])
|
|
718
|
+
router.add_api_route("/logout", views.logout, methods=["POST"])
|
|
719
|
+
router.add_api_route("/logout/all", views.logout_all, methods=["POST"])
|
|
720
|
+
router.add_api_route(
|
|
721
|
+
"/backchannel-logout/{provider_id}",
|
|
722
|
+
views.backchannel_logout,
|
|
723
|
+
methods=["POST"],
|
|
724
|
+
)
|
|
725
|
+
return router
|