fjkit 0.1.0.dev0__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.
Files changed (127) hide show
  1. fjkit/__init__.py +49 -0
  2. fjkit/auth/__init__.py +54 -0
  3. fjkit/auth/csrf.py +88 -0
  4. fjkit/auth/errors.py +31 -0
  5. fjkit/auth/plugin.py +496 -0
  6. fjkit/auth/sources.py +24 -0
  7. fjkit/auth/stores.py +141 -0
  8. fjkit/auth/types.py +141 -0
  9. fjkit/cli/__init__.py +67 -0
  10. fjkit/cli/build_css.py +135 -0
  11. fjkit/cli/check.py +193 -0
  12. fjkit/cli/eject.py +562 -0
  13. fjkit/cli/ejected.py +202 -0
  14. fjkit/cli/vocabulary.py +85 -0
  15. fjkit/config.py +130 -0
  16. fjkit/errors.py +156 -0
  17. fjkit/flash.py +189 -0
  18. fjkit/forms.py +145 -0
  19. fjkit/htmx.py +76 -0
  20. fjkit/icons.py +60 -0
  21. fjkit/messages.py +227 -0
  22. fjkit/mounting.py +72 -0
  23. fjkit/plugins.py +223 -0
  24. fjkit/py.typed +0 -0
  25. fjkit/rendering.py +554 -0
  26. fjkit/signing.py +63 -0
  27. fjkit/static/brand/torii-bolt.png +0 -0
  28. fjkit/static/dist/fjkit-luma.css +2 -0
  29. fjkit/static/dist/fjkit-lyra.css +2 -0
  30. fjkit/static/dist/fjkit-maia.css +2 -0
  31. fjkit/static/dist/fjkit-mira.css +2 -0
  32. fjkit/static/dist/fjkit-nova.css +2 -0
  33. fjkit/static/dist/fjkit-rhea.css +2 -0
  34. fjkit/static/dist/fjkit-sera.css +2 -0
  35. fjkit/static/dist/fjkit-vega.css +2 -0
  36. fjkit/static/icons/lucide.json +1 -0
  37. fjkit/static/js/errors.js +117 -0
  38. fjkit/static/js/multiselect.js +126 -0
  39. fjkit/static/js/reveal.js +51 -0
  40. fjkit/static/js/select.js +113 -0
  41. fjkit/static/src/fjkit.css +385 -0
  42. fjkit/static/vendor/basecoat/base/base.css +136 -0
  43. fjkit/static/vendor/basecoat/basecoat-base.css +2 -0
  44. fjkit/static/vendor/basecoat/basecoat-components.css +39 -0
  45. fjkit/static/vendor/basecoat/basecoat-luma.css +2 -0
  46. fjkit/static/vendor/basecoat/basecoat-lyra.css +2 -0
  47. fjkit/static/vendor/basecoat/basecoat-maia.css +2 -0
  48. fjkit/static/vendor/basecoat/basecoat-mira.css +2 -0
  49. fjkit/static/vendor/basecoat/basecoat-nova.css +2 -0
  50. fjkit/static/vendor/basecoat/basecoat-rhea.css +2 -0
  51. fjkit/static/vendor/basecoat/basecoat-sera.css +2 -0
  52. fjkit/static/vendor/basecoat/basecoat-vega.css +2 -0
  53. fjkit/static/vendor/basecoat/basecoat.all.css +1 -0
  54. fjkit/static/vendor/basecoat/basecoat.css +1 -0
  55. fjkit/static/vendor/basecoat/components/accordion.css +27 -0
  56. fjkit/static/vendor/basecoat/components/alert.css +38 -0
  57. fjkit/static/vendor/basecoat/components/avatar.css +47 -0
  58. fjkit/static/vendor/basecoat/components/badge.css +6 -0
  59. fjkit/static/vendor/basecoat/components/breadcrumb.css +30 -0
  60. fjkit/static/vendor/basecoat/components/button-group.css +54 -0
  61. fjkit/static/vendor/basecoat/components/button.css +6 -0
  62. fjkit/static/vendor/basecoat/components/card.css +26 -0
  63. fjkit/static/vendor/basecoat/components/chart.css +56 -0
  64. fjkit/static/vendor/basecoat/components/checkbox.css +12 -0
  65. fjkit/static/vendor/basecoat/components/collapsible.css +21 -0
  66. fjkit/static/vendor/basecoat/components/combobox.css +99 -0
  67. fjkit/static/vendor/basecoat/components/command.css +140 -0
  68. fjkit/static/vendor/basecoat/components/dialog.css +101 -0
  69. fjkit/static/vendor/basecoat/components/drawer.css +89 -0
  70. fjkit/static/vendor/basecoat/components/dropdown-menu.css +56 -0
  71. fjkit/static/vendor/basecoat/components/empty.css +26 -0
  72. fjkit/static/vendor/basecoat/components/field.css +82 -0
  73. fjkit/static/vendor/basecoat/components/form.css +9 -0
  74. fjkit/static/vendor/basecoat/components/input-group.css +74 -0
  75. fjkit/static/vendor/basecoat/components/input.css +32 -0
  76. fjkit/static/vendor/basecoat/components/item.css +50 -0
  77. fjkit/static/vendor/basecoat/components/kbd.css +6 -0
  78. fjkit/static/vendor/basecoat/components/label.css +13 -0
  79. fjkit/static/vendor/basecoat/components/native-select.css +12 -0
  80. fjkit/static/vendor/basecoat/components/popover.css +107 -0
  81. fjkit/static/vendor/basecoat/components/progress.css +14 -0
  82. fjkit/static/vendor/basecoat/components/radio.css +11 -0
  83. fjkit/static/vendor/basecoat/components/range.css +50 -0
  84. fjkit/static/vendor/basecoat/components/scrollbar.css +46 -0
  85. fjkit/static/vendor/basecoat/components/select.css +64 -0
  86. fjkit/static/vendor/basecoat/components/sidebar.css +101 -0
  87. fjkit/static/vendor/basecoat/components/skeleton.css +6 -0
  88. fjkit/static/vendor/basecoat/components/switch.css +8 -0
  89. fjkit/static/vendor/basecoat/components/table.css +34 -0
  90. fjkit/static/vendor/basecoat/components/tabs.css +31 -0
  91. fjkit/static/vendor/basecoat/components/textarea.css +7 -0
  92. fjkit/static/vendor/basecoat/components/toast.css +57 -0
  93. fjkit/static/vendor/basecoat/components/tooltip.css +82 -0
  94. fjkit/static/vendor/basecoat/js/all.min.js +1 -0
  95. fjkit/static/vendor/basecoat/styles/luma.css +1376 -0
  96. fjkit/static/vendor/basecoat/styles/lyra.css +1379 -0
  97. fjkit/static/vendor/basecoat/styles/maia.css +1364 -0
  98. fjkit/static/vendor/basecoat/styles/mira.css +1373 -0
  99. fjkit/static/vendor/basecoat/styles/nova.css +1387 -0
  100. fjkit/static/vendor/basecoat/styles/rhea.css +1381 -0
  101. fjkit/static/vendor/basecoat/styles/sera.css +1397 -0
  102. fjkit/static/vendor/basecoat/styles/vega.css +1386 -0
  103. fjkit/static/vendor/htmx/htmx.min.js +1 -0
  104. fjkit/static/vendor/htmx/json-enc.js +38 -0
  105. fjkit/styles.py +30 -0
  106. fjkit/templates/errors/page.html +92 -0
  107. fjkit/templates/ui/attrs.html +18 -0
  108. fjkit/templates/ui/button.html +64 -0
  109. fjkit/templates/ui/data.html +362 -0
  110. fjkit/templates/ui/disclosure.html +89 -0
  111. fjkit/templates/ui/feedback.html +313 -0
  112. fjkit/templates/ui/form.html +595 -0
  113. fjkit/templates/ui/icon.html +13 -0
  114. fjkit/templates/ui/layout.html +189 -0
  115. fjkit/templates/ui/nav.html +110 -0
  116. fjkit/templates/ui/overlay.html +624 -0
  117. fjkit/templates/ui/shell.html +170 -0
  118. fjkit/templates/ui/sidebar.html +170 -0
  119. fjkit/templates/ui/table.html +427 -0
  120. fjkit/templates/ui/tabs.html +133 -0
  121. fjkit/templating.py +365 -0
  122. fjkit/vendored.py +46 -0
  123. fjkit-0.1.0.dev0.dist-info/METADATA +119 -0
  124. fjkit-0.1.0.dev0.dist-info/RECORD +127 -0
  125. fjkit-0.1.0.dev0.dist-info/WHEEL +4 -0
  126. fjkit-0.1.0.dev0.dist-info/entry_points.txt +2 -0
  127. fjkit-0.1.0.dev0.dist-info/licenses/LICENSE +21 -0
fjkit/auth/plugin.py ADDED
@@ -0,0 +1,496 @@
1
+ """`AuthPlugin` — the cookie the browser holds, the token the server keeps.
2
+
3
+ The browser gets one opaque, signed, HttpOnly cookie. The access token, the
4
+ refresh token and the app's claims stay in a `SessionStore` on the server. This
5
+ is the token-handler shape, also called a backend for frontend (BFF): a page
6
+ carries a session without JavaScript reading, storing or attaching a credential,
7
+ so an htmx app needs no `htmx:configRequest` hook, no refresh-and-retry glue and
8
+ no token in `<body>`.
9
+
10
+ The cookie carries a random 32-byte id and a hash-based message authentication
11
+ code (HMAC) of it. Signing an already-unguessable id is not about secrecy: it
12
+ rejects a forged or corrupted cookie without a round trip to the store.
13
+
14
+ The trade: a cookie is an ambient credential, so cross-site request forgery
15
+ (CSRF) comes back. `fjkit.auth.csrf` explains why this plugin handles it rather
16
+ than leaving it to the app.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import asyncio
22
+ import base64
23
+ import hashlib
24
+ import hmac
25
+ import secrets
26
+ import warnings
27
+ from dataclasses import dataclass
28
+ from datetime import UTC, datetime, timedelta
29
+ from typing import TYPE_CHECKING, Any, Literal
30
+ from urllib.parse import quote
31
+
32
+ from fastapi import Request, Response
33
+ from fastapi.responses import JSONResponse
34
+ from starlette.middleware.base import BaseHTTPMiddleware
35
+
36
+ from fjkit.auth.csrf import NoCsrf, OriginCsrf
37
+ from fjkit.auth.errors import AuthError, CsrfRejected, NotAuthenticated, RefreshFailed
38
+ from fjkit.auth.sources import LocalSource
39
+ from fjkit.auth.stores import MemoryStore
40
+ from fjkit.auth.types import Csrf, Session, SessionStore, TokenSource, decode, encode
41
+ from fjkit.htmx import is_htmx
42
+ from fjkit.plugins import AppSetup, EnvSetup, PluginWarning
43
+
44
+ if TYPE_CHECKING:
45
+ from fjkit.flash import FlashPlugin
46
+
47
+ __all__ = ["AuthPlugin", "CookieSpec", "safe_next"]
48
+
49
+ #: How often a request that lost the refresh race looks for the winner's work.
50
+ _POLL_SECONDS = 0.05
51
+
52
+ #: What the user is told, per reason. Two entries, because they are different
53
+ #: events: never signed in here, versus signed in and the session ran out. Only
54
+ #: the second is worth interrupting someone about.
55
+ _FLASH_TEXT = {
56
+ "required": ("Sign in to continue", "That page needs a session."),
57
+ "expired": ("You were signed out", "Your session expired. Sign in again to carry on."),
58
+ }
59
+
60
+
61
+ def _full_path(request) -> str:
62
+ """Join the path and its query string, so a filtered view survives the trip.
63
+
64
+ `request.url.path` alone drops the query, and the user returns from the
65
+ login form to an unfiltered list with their search gone.
66
+ """
67
+ query = request.url.query
68
+ return f"{request.url.path}?{query}" if query else request.url.path
69
+
70
+
71
+ def _is_navigation(request) -> bool:
72
+ """Report whether a person is looking at this, rather than a program.
73
+
74
+ Two signals, either one sufficient. `Sec-Fetch-Mode: navigate` is the
75
+ purpose-built one: every current browser sends it when the address bar
76
+ moves, and nothing else sends it. `Accept` is the fallback for browsers
77
+ predating it — a navigation asks for `text/html`, while curl, `fetch()` and
78
+ HTTP clients send `*/*`, which states no preference and counts as none.
79
+ """
80
+ if request.headers.get("sec-fetch-mode") == "navigate":
81
+ return True
82
+ return "text/html" in request.headers.get("accept", "")
83
+
84
+
85
+ @dataclass(frozen=True, slots=True)
86
+ class CookieSpec:
87
+ """The one cookie this plugin sets.
88
+
89
+ `httponly` is not a field. This plugin exists so no script can read the
90
+ credential, and a setting to turn that off would only ever be turned off by
91
+ mistake.
92
+ """
93
+
94
+ name: str = "fjkit_session"
95
+ max_age: timedelta = timedelta(hours=8)
96
+ path: str = "/"
97
+ domain: str | None = None
98
+ secure: bool = True
99
+ #: `"lax"` still sends the cookie on a top-level navigation from another
100
+ #: site, so a link into the app keeps the user logged in while a cross-site
101
+ #: write gets nothing. `"none"` drops that protection and leaves the
102
+ #: `Origin` check alone; use it only for an app embedded in another site's
103
+ #: iframe.
104
+ same_site: Literal["lax", "strict", "none"] = "lax"
105
+
106
+
107
+ class AuthPlugin:
108
+ """Sessions for a fjkit app. Register it in `FjkitConfig.plugins`.
109
+
110
+ auth = AuthPlugin(
111
+ secret=os.environ["FJKIT_SECRET"],
112
+ store=RedisStore(redis.from_url(REDIS_URL)),
113
+ source=MyOIDCSource(),
114
+ trusted_origins=["https://app.example.com"],
115
+ )
116
+ config = FjkitConfig(template_dir=..., plugins=(auth,))
117
+ mount_fjkit(app, config)
118
+
119
+ Every request costs one store read. That buys revoking a session by deleting
120
+ a row, and keeping refresh tokens off the wire; a self-contained encrypted
121
+ cookie gives neither.
122
+
123
+ Routes see none of it. Put `Depends(auth.required)` on a router and its
124
+ handlers keep their signatures; the session is on `request.state.auth`, and
125
+ in every template as `session`.
126
+ """
127
+
128
+ name = "auth"
129
+
130
+ def __init__(
131
+ self,
132
+ *,
133
+ secret: str | bytes,
134
+ store: SessionStore | None = None,
135
+ source: TokenSource | None = None,
136
+ cookie: CookieSpec | None = None,
137
+ csrf: Csrf | None = None,
138
+ trusted_origins: tuple[str, ...] | list[str] = (),
139
+ flash: FlashPlugin | None = None,
140
+ login_url: str = "/login",
141
+ refresh_leeway: timedelta = timedelta(seconds=60),
142
+ refresh_lock_ttl: timedelta = timedelta(seconds=10),
143
+ refresh_wait: timedelta = timedelta(seconds=10),
144
+ ) -> None:
145
+ self.secret = secret.encode("utf-8") if isinstance(secret, str) else secret
146
+ self.store: SessionStore = store if store is not None else MemoryStore()
147
+ self.source: TokenSource = source if source is not None else LocalSource()
148
+ self.cookie = cookie or CookieSpec()
149
+ #: Optional, and injected rather than imported: this kit has no rule
150
+ #: letting one plugin depend on another. The app registers both and
151
+ #: hands one to the other, so auth works without flash and flash stays
152
+ #: useful to routes unrelated to auth.
153
+ self.flash = flash
154
+ self.login_url = login_url
155
+ self.refresh_leeway = refresh_leeway
156
+ self.refresh_lock_ttl = refresh_lock_ttl
157
+ self.refresh_wait = refresh_wait
158
+ self._warned_no_refresh = False
159
+
160
+ if csrf is None:
161
+ if not trusted_origins:
162
+ raise ValueError(
163
+ "AuthPlugin needs `trusted_origins=[...]` for its Origin check. "
164
+ "They are named explicitly rather than read from the Host header, "
165
+ "which a request controls. Pass `csrf=NoCsrf()` to opt out on purpose."
166
+ )
167
+ csrf = OriginCsrf(trusted_origins)
168
+ elif trusted_origins:
169
+ raise ValueError("Pass either `csrf=` or `trusted_origins=`, not both.")
170
+ self.csrf = csrf
171
+
172
+ # ---------------------------------------------------------------- plugin
173
+
174
+ def mount(self, setup: AppSetup) -> None:
175
+ setup.add_middleware(_SessionMiddleware, plugin=self)
176
+ setup.add_exception_handler(NotAuthenticated, self._handle)
177
+ setup.add_exception_handler(CsrfRejected, self._handle)
178
+
179
+ if isinstance(self.store, MemoryStore) and not setup.config.auto_reload:
180
+ setup.warn(
181
+ "MemoryStore under a production config: with more than one worker a "
182
+ "request can land on a process that has never seen the session, and "
183
+ "users are logged out at random. Use RedisStore, or a store of your own."
184
+ )
185
+ if self.cookie.same_site == "none" and not self.cookie.secure:
186
+ setup.warn("SameSite=None requires Secure; browsers will drop this cookie.")
187
+ if isinstance(self.csrf, NoCsrf):
188
+ setup.warn("CSRF checking is off. Every cookie-authenticated write is unprotected.")
189
+
190
+ def extend(self, setup: EnvSetup) -> None:
191
+ setup.add_context_processor(
192
+ lambda request: {"session": getattr(request.state, "auth", None)},
193
+ provides=["session"],
194
+ )
195
+
196
+ # ------------------------------------------------------------- app-facing
197
+
198
+ async def issue(self, request: Request, response: Response, credentials: Any) -> Session:
199
+ """Log in: exchange `credentials`, store the session, set the cookie.
200
+
201
+ Takes `request` so it can drop the caller's previous session; an id that
202
+ survives a login is a session-fixation hole. This is the only point the
203
+ id changes — a refresh keeps it (see `_refresh`).
204
+
205
+ The login route is therefore `async def`, which is correct because it
206
+ does network I/O. Every rendering route stays `def`.
207
+ """
208
+ session = await self.source.exchange(credentials)
209
+
210
+ previous = self._read_cookie(request)
211
+ if previous is not None:
212
+ await self.store.delete(previous)
213
+
214
+ sid = secrets.token_urlsafe(32)
215
+ await self._write(sid, session)
216
+ self._set_cookie(response, sid)
217
+ self.csrf.on_issue(response, sid)
218
+ # So a login that renders rather than redirects sees the session it
219
+ # just created.
220
+ request.state.auth = session
221
+ return session
222
+
223
+ async def revoke(self, request: Request, response: Response) -> None:
224
+ """Log out: forget the session server-side and clear the cookie."""
225
+ sid = self._read_cookie(request)
226
+ if sid is not None:
227
+ await self.store.delete(sid)
228
+ response.delete_cookie(
229
+ self.cookie.name,
230
+ path=self.cookie.path,
231
+ domain=self.cookie.domain,
232
+ )
233
+ request.state.auth = None
234
+
235
+ async def required(self, request: Request) -> Session:
236
+ """Dependency. Refuse an anonymous request.
237
+
238
+ router = APIRouter(dependencies=[Depends(auth.required)])
239
+
240
+ Returns the session as well as raising, so a handler can take it as a
241
+ parameter instead of reading `request.state`.
242
+ """
243
+ session = getattr(request.state, "auth", None)
244
+ if session is None:
245
+ raise NotAuthenticated(f"{request.url.path} needs a session")
246
+ return session
247
+
248
+ async def optional(self, request: Request) -> Session | None:
249
+ """Dependency. The session, or `None`."""
250
+ return getattr(request.state, "auth", None)
251
+
252
+ # -------------------------------------------------------------- internals
253
+
254
+ async def load(self, request: Request) -> Session | None:
255
+ """Return the session for this request, refreshed if it is near expiry.
256
+
257
+ Called by the middleware. Raises `NotAuthenticated` only for a session
258
+ that existed and could not be renewed; an absent or unreadable cookie is
259
+ an anonymous request, not an error.
260
+ """
261
+ sid = self._read_cookie(request)
262
+ if sid is None:
263
+ return None
264
+
265
+ payload = await self.store.get(sid)
266
+ if payload is None:
267
+ return None
268
+ try:
269
+ session = decode(payload)
270
+ except (ValueError, TypeError):
271
+ # A payload this process cannot read is not a session. Drop it,
272
+ # rather than answer 500 to every request until the user clears
273
+ # their cookies.
274
+ await self.store.delete(sid)
275
+ return None
276
+
277
+ return await self._refresh(sid, session)
278
+
279
+ async def _refresh(self, sid: str, session: Session) -> Session:
280
+ """Renew the token once, however many requests notice at the same time.
281
+
282
+ Self-guarding: a session that is not near expiry, or a source that
283
+ cannot renew, is returned unchanged, so callers need not know which case
284
+ they are in.
285
+
286
+ The session id does not change here. Rotating it would give several
287
+ concurrent swaps a different `Set-Cookie` each; the last wins, the rest
288
+ become orphans, and the mechanism meant to keep the user signed in logs
289
+ them out.
290
+ """
291
+ if not self._expiring(session):
292
+ return session
293
+
294
+ if not hasattr(self.source, "refresh"):
295
+ # Reported here rather than at startup, where it is not yet true: a
296
+ # source with no `refresh` and no `expires_at` is an ordinary
297
+ # configuration, and warning about it would train people to ignore
298
+ # the warning that matters. Warned once, so a busy app does not
299
+ # write this line on every request.
300
+ if not self._warned_no_refresh:
301
+ self._warned_no_refresh = True
302
+ warnings.warn(
303
+ f"[fjkit:{self.name}] {type(self.source).__name__} hands out tokens with an "
304
+ "`expires_at` but has no `refresh()`, so sessions end when the token does.",
305
+ PluginWarning,
306
+ stacklevel=2,
307
+ )
308
+ return session
309
+
310
+ if not await self.store.acquire_refresh_lock(sid, int(self.refresh_lock_ttl.total_seconds())):
311
+ return await self._await_refresh(sid, session)
312
+
313
+ try:
314
+ # Read again now that the lock is held. Another request may have
315
+ # finished renewing since this one's first read, and the token held
316
+ # here is single-use: spending it twice makes an upstream with
317
+ # rotation revoke the whole family.
318
+ payload = await self.store.get(sid)
319
+ current = decode(payload) if payload is not None else session
320
+ if not self._expiring(current):
321
+ return current
322
+
323
+ try:
324
+ fresh = await self.source.refresh(current) # type: ignore[attr-defined]
325
+ except Exception as exc:
326
+ # Only the upstream refusing ends a session. Otherwise a store
327
+ # that failed a moment ago logs every user out over a blip,
328
+ # which is worse than one retried request.
329
+ await self.store.delete(sid)
330
+ raise RefreshFailed(f"could not renew the session: {exc}") from exc
331
+
332
+ await self._write(sid, fresh)
333
+ return fresh
334
+ finally:
335
+ await self.store.release_refresh_lock(sid)
336
+
337
+ async def _await_refresh(self, sid: str, stale: Session) -> Session:
338
+ """Wait for whoever won the lock, then read what they wrote."""
339
+ deadline = asyncio.get_running_loop().time() + self.refresh_wait.total_seconds()
340
+ while asyncio.get_running_loop().time() < deadline:
341
+ await asyncio.sleep(_POLL_SECONDS)
342
+ payload = await self.store.get(sid)
343
+ if payload is None:
344
+ raise RefreshFailed("the session was dropped while its token was being renewed")
345
+ session = decode(payload)
346
+ if not self._expiring(session):
347
+ return session
348
+ raise RefreshFailed(
349
+ "timed out waiting for another request to renew this session; "
350
+ "raise `refresh_wait` if the upstream is slower than that"
351
+ )
352
+
353
+ def _expiring(self, session: Session) -> bool:
354
+ """Report whether the token is inside the leeway, or already past it.
355
+
356
+ `expires_at is None` means the source reported no expiry, so there is
357
+ nothing to act on and the session is left alone.
358
+ """
359
+ if session.expires_at is None:
360
+ return False
361
+ return session.expires_at - datetime.now(UTC) <= self.refresh_leeway
362
+
363
+ async def _write(self, sid: str, session: Session) -> None:
364
+ await self.store.put(sid, encode(session), int(self.cookie.max_age.total_seconds()))
365
+
366
+ # ------------------------------------------------------------- the cookie
367
+
368
+ def _sign(self, sid: str) -> str:
369
+ mac = hmac.new(self.secret, sid.encode("ascii"), hashlib.sha256).digest()
370
+ return f"{sid}.{base64.urlsafe_b64encode(mac).decode('ascii').rstrip('=')}"
371
+
372
+ def _read_cookie(self, request: Request) -> str | None:
373
+ raw = request.cookies.get(self.cookie.name)
374
+ if not raw:
375
+ return None
376
+ sid, _, _ = raw.partition(".")
377
+ if not sid or not hmac.compare_digest(raw, self._sign(sid)):
378
+ return None
379
+ return sid
380
+
381
+ def _set_cookie(self, response: Response, sid: str) -> None:
382
+ response.set_cookie(
383
+ self.cookie.name,
384
+ self._sign(sid),
385
+ max_age=int(self.cookie.max_age.total_seconds()),
386
+ path=self.cookie.path,
387
+ domain=self.cookie.domain,
388
+ secure=self.cookie.secure,
389
+ httponly=True,
390
+ samesite=self.cookie.same_site,
391
+ )
392
+
393
+ # ------------------------------------------------------------- responses
394
+
395
+ def _handle(self, request: Request, exc: Exception) -> Response:
396
+ """Build the refusal for both entry points.
397
+
398
+ Registered as an exception handler and called from the middleware,
399
+ because Starlette's `ExceptionMiddleware` sits inside the user
400
+ middleware stack, so an error raised in middleware never reaches a
401
+ registered handler. Sharing this function stops the two paths drifting
402
+ into different answers.
403
+ """
404
+ if isinstance(exc, CsrfRejected):
405
+ # No redirect to the login page: the browser is where it belongs,
406
+ # and the request is what is wrong.
407
+ return Response(status_code=403)
408
+
409
+ # Three kinds of caller, three answers — the same question `@render`
410
+ # asks about what to put on the wire, asked about how to refuse.
411
+ #
412
+ # 401 everywhere reads the spec tidily and is wrong for one of the
413
+ # three: a plain navigation cannot act on it and lands on a blank page.
414
+ # The other two get 401, and the htmx one still moves — see below.
415
+ vary = {"vary": "HX-Request, Accept, Sec-Fetch-Mode"}
416
+ # `safe="/"` and nothing else. Leaving `?`, `=` or `&` raw lets the
417
+ # value's own query string break out into extra parameters of the login
418
+ # URL, so `next` arrives truncated at the first `?`.
419
+ target = f"{self.login_url}?next={quote(_full_path(request), safe='/')}"
420
+ reason = "expired" if isinstance(exc, RefreshFailed) else "required"
421
+
422
+ if is_htmx(request):
423
+ # 401 and a redirect together: htmx acts on `HX-Redirect` before it
424
+ # reads the status code, so the status stays accurate while the
425
+ # browser still moves the whole page.
426
+ #
427
+ # It has to move the whole page. htmx's own fetch would follow a
428
+ # 303 and swap the login form into whatever element the click
429
+ # targeted; a bare 401 would swap nothing, because htmx ignores a
430
+ # 4xx body, and the click would appear to do nothing.
431
+ response: Response = Response(status_code=401, headers={"HX-Redirect": target, **vary})
432
+ elif _is_navigation(request):
433
+ response = Response(status_code=303, headers={"location": target, **vary})
434
+ else:
435
+ # A script, curl, another service. Under `render_mode="auto"` a
436
+ # route answers this caller in JSON, so refusing with a redirect to
437
+ # an HTML login form answers a question it did not ask, and
438
+ # following that redirect hands it a login page with a 200, which
439
+ # reads as success.
440
+ #
441
+ # No `WWW-Authenticate`: RFC 9110 requires the field, and every
442
+ # registered scheme is wrong here. `Basic` makes the browser open
443
+ # its own credential dialog, which is the login form this plugin
444
+ # replaces.
445
+ return JSONResponse(
446
+ {"detail": "authentication required", "reason": reason, "login_url": self.login_url},
447
+ status_code=401,
448
+ headers=vary,
449
+ )
450
+
451
+ # Both branches above end in a new page load, which `HX-Trigger` cannot
452
+ # survive: the document it would fire into is gone. A cookie crosses
453
+ # that gap.
454
+ if self.flash is not None:
455
+ self.flash.add(response, *_FLASH_TEXT[reason], category="warning")
456
+ return response
457
+
458
+
459
+ class _SessionMiddleware(BaseHTTPMiddleware):
460
+ """Verify, load and renew — before the handler, so routes see a plain session."""
461
+
462
+ def __init__(self, app: Any, *, plugin: AuthPlugin) -> None:
463
+ super().__init__(app)
464
+ self.plugin = plugin
465
+
466
+ async def dispatch(self, request: Request, call_next: Any) -> Response:
467
+ plugin = self.plugin
468
+ request.state.auth = None
469
+ try:
470
+ if plugin._read_cookie(request) is not None:
471
+ # Only when the browser attached a credential. A public POST
472
+ # carrying no session has nothing for CSRF to steal, and
473
+ # refusing it would break endpoints meant to be open.
474
+ await plugin.csrf.verify(request)
475
+ request.state.auth = await plugin.load(request)
476
+ except AuthError as exc:
477
+ return plugin._handle(request, exc)
478
+ return await call_next(request)
479
+
480
+
481
+ def safe_next(value: str | None, fallback: str = "/") -> str:
482
+ """Return the `next=` value, or `fallback` when it points off this site.
483
+
484
+ The plugin only ever writes a path here, so nothing it produced points
485
+ off-site. What arrives back is a query string, which anyone can type, and a
486
+ login page that redirects to whatever it is handed is an open redirect: a
487
+ link to your own domain, your own login form, then a hop to the attacker's
488
+ site at the moment someone has typed their password.
489
+
490
+ The rule is positional rather than a blocklist. One leading slash, not two:
491
+ `//evil.example.com` is a protocol-relative URL that a browser reads as a
492
+ different site, and a naive `startswith("/")` lets it through.
493
+ """
494
+ if not value or not value.startswith("/") or value.startswith("//"):
495
+ return fallback
496
+ return value
fjkit/auth/sources.py ADDED
@@ -0,0 +1,24 @@
1
+ """The source for an app with no upstream, and the default source."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from typing import Any
7
+
8
+ from fjkit.auth.types import Session
9
+
10
+ __all__ = ["LocalSource"]
11
+
12
+
13
+ class LocalSource:
14
+ """No token exchange: the claims passed in are the session.
15
+
16
+ Puts a plain login and an upstream OAuth token on one code path. Without it,
17
+ `AuthPlugin` would need a `source is None` branch in `issue`, in the refresh
18
+ check and in every message about either.
19
+
20
+ await auth.issue(request, response, {"user_id": user.id})
21
+ """
22
+
23
+ async def exchange(self, credentials: Mapping[str, Any]) -> Session:
24
+ return Session(claims=dict(credentials))
fjkit/auth/stores.py ADDED
@@ -0,0 +1,141 @@
1
+ """The two backends that ship, and an adapter for a blocking third.
2
+
3
+ Neither imports a database driver. `RedisStore` takes a client the app already
4
+ built, which keeps fjkit's runtime dependencies at two (CHARTER §7) and also
5
+ works with Valkey, fakeredis, or anything else exposing the same four methods.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from time import monotonic
11
+ from typing import Any, Protocol
12
+
13
+ from starlette.concurrency import run_in_threadpool
14
+
15
+ __all__ = ["MemoryStore", "RedisStore", "SyncStore"]
16
+
17
+
18
+ class MemoryStore:
19
+ """A dict with expiry. Correct for one process, wrong for more than one.
20
+
21
+ `AuthPlugin` warns when it sees this under a production config. The symptom
22
+ otherwise is users logged out at random on a machine running four workers,
23
+ with nothing in the traceback pointing here.
24
+
25
+ No locking primitives: an event loop runs one task at a time between awaits,
26
+ and no method below awaits anything, so the check-then-set in
27
+ `acquire_refresh_lock` cannot be interleaved.
28
+ """
29
+
30
+ __slots__ = ("_items", "_locks")
31
+
32
+ def __init__(self) -> None:
33
+ self._items: dict[str, tuple[bytes, float]] = {}
34
+ self._locks: dict[str, float] = {}
35
+
36
+ async def get(self, sid: str) -> bytes | None:
37
+ entry = self._items.get(sid)
38
+ if entry is None:
39
+ return None
40
+ payload, expires = entry
41
+ if expires <= monotonic():
42
+ del self._items[sid]
43
+ return None
44
+ return payload
45
+
46
+ async def put(self, sid: str, payload: bytes, ttl: int) -> None:
47
+ self._items[sid] = (payload, monotonic() + ttl)
48
+
49
+ async def delete(self, sid: str) -> None:
50
+ self._items.pop(sid, None)
51
+ self._locks.pop(sid, None)
52
+
53
+ async def acquire_refresh_lock(self, sid: str, ttl: int) -> bool:
54
+ now = monotonic()
55
+ held = self._locks.get(sid)
56
+ if held is not None and held > now:
57
+ return False
58
+ self._locks[sid] = now + ttl
59
+ return True
60
+
61
+ async def release_refresh_lock(self, sid: str) -> None:
62
+ self._locks.pop(sid, None)
63
+
64
+
65
+ class _AsyncRedis(Protocol):
66
+ """The client calls `RedisStore` makes. Structural, so no import is needed."""
67
+
68
+ async def get(self, name: str) -> Any: ...
69
+ async def set(self, name: str, value: Any, **kwargs: Any) -> Any: ...
70
+ async def delete(self, *names: str) -> Any: ...
71
+
72
+
73
+ class RedisStore:
74
+ """Store sessions in Redis, through a client the app owns.
75
+
76
+ Expects an async client: `redis.asyncio.Redis` or equivalent. Put a blocking
77
+ client behind `SyncStore`, so the threadpool hop stays visible in the app's
78
+ wiring instead of hidden here.
79
+
80
+ The refresh lock is `SET NX EX`, which is what lets several workers share
81
+ this store and still refresh a token exactly once.
82
+ """
83
+
84
+ __slots__ = ("_client", "_prefix")
85
+
86
+ def __init__(self, client: _AsyncRedis, *, prefix: str = "fjkit:sess:") -> None:
87
+ self._client = client
88
+ self._prefix = prefix
89
+
90
+ def _key(self, sid: str) -> str:
91
+ return f"{self._prefix}{sid}"
92
+
93
+ def _lock_key(self, sid: str) -> str:
94
+ return f"{self._prefix}refresh:{sid}"
95
+
96
+ async def get(self, sid: str) -> bytes | None:
97
+ value = await self._client.get(self._key(sid))
98
+ if value is None:
99
+ return None
100
+ return value if isinstance(value, bytes) else str(value).encode("utf-8")
101
+
102
+ async def put(self, sid: str, payload: bytes, ttl: int) -> None:
103
+ await self._client.set(self._key(sid), payload, ex=ttl)
104
+
105
+ async def delete(self, sid: str) -> None:
106
+ await self._client.delete(self._key(sid), self._lock_key(sid))
107
+
108
+ async def acquire_refresh_lock(self, sid: str, ttl: int) -> bool:
109
+ return bool(await self._client.set(self._lock_key(sid), b"1", nx=True, ex=ttl))
110
+
111
+ async def release_refresh_lock(self, sid: str) -> None:
112
+ await self._client.delete(self._lock_key(sid))
113
+
114
+
115
+ class SyncStore:
116
+ """Run a blocking store's five methods in the threadpool.
117
+
118
+ For a backend with no async driver: a synchronous Redis client, a database
119
+ session, a file. The hop costs a thread per call, so it is an explicit
120
+ wrapper rather than something the plugin applies on its own.
121
+ """
122
+
123
+ __slots__ = ("_inner",)
124
+
125
+ def __init__(self, store: Any) -> None:
126
+ self._inner = store
127
+
128
+ async def get(self, sid: str) -> bytes | None:
129
+ return await run_in_threadpool(self._inner.get, sid)
130
+
131
+ async def put(self, sid: str, payload: bytes, ttl: int) -> None:
132
+ await run_in_threadpool(self._inner.put, sid, payload, ttl)
133
+
134
+ async def delete(self, sid: str) -> None:
135
+ await run_in_threadpool(self._inner.delete, sid)
136
+
137
+ async def acquire_refresh_lock(self, sid: str, ttl: int) -> bool:
138
+ return await run_in_threadpool(self._inner.acquire_refresh_lock, sid, ttl)
139
+
140
+ async def release_refresh_lock(self, sid: str) -> None:
141
+ await run_in_threadpool(self._inner.release_refresh_lock, sid)