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