Bring in pipeline, auth, deploy and docs from the boilerplate
roledesk is built on the boilerplate from here on: pipeline 2.0 (queue and scheduler), auth (one password, sessions, passkeys), the deploy kit and its docs, plus the coupling and packaging tests. Downstream copies, unedited. Refreshed from boilerplate/d56949f7d0f6c0bfe5745478e09007bfad67ae87 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1f436104f3
commit
9d666d0937
76 files changed
+15235
No files matched your search
+489
@@ -0,0 +1,489 @@
|
||||
"""Signing in, signing out, and the one account there is.
|
||||
|
||||
The middleware in `auth/middleware.py` decides who gets past the door; this is
|
||||
the door itself, plus the small screen for changing the key. Everything here is
|
||||
deliberately about *this* user's own credential — there is no user to create,
|
||||
none to list, and none to delete, because there is one.
|
||||
|
||||
Nothing is read from a module-level global: the store, the config and whether
|
||||
the door is locked all come off `app.state`, where `connect` put them. That is
|
||||
what lets two apps in one test process each have their own, and what keeps this
|
||||
router importable by an app that never calls `connect` at all.
|
||||
|
||||
## Why the cookie is `SameSite=Lax` and there is no CSRF token
|
||||
|
||||
A CSRF token defends a cookie-authenticated app against another origin
|
||||
submitting a form on your behalf. `SameSite=Lax` already refuses to send this
|
||||
cookie on any cross-site request that is not a top-level navigation, and no
|
||||
`GET` in this package changes anything — so the attack the token would stop
|
||||
cannot be mounted. Adding one anyway would mean a second secret, a second thing
|
||||
to rotate, and a second way for a request to fail for reasons the UI has to
|
||||
explain. Where that reasoning stops being true is a browser old enough to
|
||||
ignore `SameSite` entirely, which is not one that will run the login page.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from urllib.parse import unquote, urlsplit
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, Response
|
||||
from fastapi.responses import FileResponse, HTMLResponse, RedirectResponse
|
||||
from starlette.requests import HTTPConnection
|
||||
|
||||
from auth import passkeys as pk
|
||||
from auth.config import AuthConfig
|
||||
from auth.middleware import (
|
||||
client_address, cookie_name, cookie_names, is_secure, token_from,
|
||||
)
|
||||
from auth.models import Account
|
||||
from auth.schemas import (
|
||||
LabelBody, LoginBody, PasskeyBody, PasskeyLoginBody, PasswordBody,
|
||||
)
|
||||
from auth.store import AuthStore
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(tags=["auth"])
|
||||
|
||||
#: The page and the two scripts, shipped with the package. Served from routes
|
||||
#: rather than mounted as a static directory because a router cannot mount one
|
||||
#: — only an app can — and needing the app to mount something is exactly the
|
||||
#: line of setup `connect` exists to remove. The same deal `/_jobs/jobs.js`
|
||||
#: makes in `pipeline/web/jobs.py`.
|
||||
TEMPLATES = Path(__file__).resolve().parent / "templates"
|
||||
STATIC = Path(__file__).resolve().parent / "static"
|
||||
|
||||
#: The login page must never be cached: a proxy or a browser holding on to it
|
||||
#: is a form posting to a door that has since been opened, or a page shown to
|
||||
#: the next person at this machine.
|
||||
NO_STORE = {"Cache-Control": "no-store"}
|
||||
|
||||
#: The shortest new password the account screen will take. Low, deliberately:
|
||||
#: it is a floor against a typo, not a password policy. The honest advice is in
|
||||
#: docs/password-protection.md — the generated password is sixteen random
|
||||
#: characters and anything you choose yourself is the weak half.
|
||||
MIN_LENGTH = 8
|
||||
|
||||
|
||||
# ------------------------------------------------------- what connect left us
|
||||
|
||||
def _store(conn: HTTPConnection) -> AuthStore:
|
||||
return conn.app.state.auth
|
||||
|
||||
|
||||
def _config(conn: HTTPConnection) -> AuthConfig:
|
||||
return conn.app.state.auth_config
|
||||
|
||||
|
||||
def _locked(conn: HTTPConnection) -> bool:
|
||||
"""Whether this app is running with the door locked.
|
||||
|
||||
Read off `app.state`, where `connect` put it, rather than recomputed: the
|
||||
answer depends on the bind address, which the config alone does not know
|
||||
and a request cannot be asked for.
|
||||
"""
|
||||
return bool(conn.app.state.auth_locked)
|
||||
|
||||
|
||||
def _pinned(conn: HTTPConnection) -> str:
|
||||
"""The password from the environment, or "". See `auth.bootstrap`."""
|
||||
return os.environ.get(_config(conn).password_env, "")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the scripts
|
||||
|
||||
@router.get("/_auth/passkey.js", include_in_schema=False)
|
||||
def passkey_js() -> FileResponse:
|
||||
"""The browser half of WebAuthn, shared by the login page and the element."""
|
||||
return _script("passkey.js")
|
||||
|
||||
|
||||
@router.get("/_auth/account.js", include_in_schema=False)
|
||||
def account_js() -> FileResponse:
|
||||
"""`<auth-account>`: the account screen, for an app with no UI for it yet.
|
||||
|
||||
<script type="module" src="/_auth/account.js"></script>
|
||||
<auth-account></auth-account>
|
||||
"""
|
||||
return _script("account.js")
|
||||
|
||||
|
||||
def _script(name: str) -> FileResponse:
|
||||
"""Cached for an hour rather than forever. These change when the package is
|
||||
copied into a project and then hardly ever, and an app that wants them
|
||||
fingerprinted can serve the files itself from `STATIC`."""
|
||||
return FileResponse(STATIC / name, media_type="text/javascript",
|
||||
headers={"Cache-Control": "public, max-age=3600"})
|
||||
|
||||
|
||||
# ------------------------------------------------------------------- the door
|
||||
|
||||
@router.get("/login", response_class=HTMLResponse, include_in_schema=False)
|
||||
def login_page(request: Request) -> Response:
|
||||
"""The one page served without a session.
|
||||
|
||||
Sent only if you ask for it directly with no session cookie; with one,
|
||||
there is nothing here to do, so it bounces to the front page rather than
|
||||
offering a form that would replace a session you have.
|
||||
"""
|
||||
if not _locked(request):
|
||||
return RedirectResponse("/", status_code=303)
|
||||
token = token_from(request, _config(request))
|
||||
if token and _store(request).touch(token):
|
||||
return RedirectResponse("/", status_code=303)
|
||||
|
||||
config = _config(request)
|
||||
store = _store(request)
|
||||
# Whether to draw the passkey button at all. Decided here rather than by
|
||||
# the page asking, because a button that appears and then discovers there
|
||||
# is nothing to press is worse than one that was never drawn — and the page
|
||||
# has no session, so it cannot ask anything else about the account.
|
||||
offer = "true" if (pk.available() and store.passkey_ids()) else "false"
|
||||
sheet = request.app.state.auth_stylesheet
|
||||
html = (TEMPLATES / "login.html").read_text(encoding="utf-8")
|
||||
html = (html
|
||||
.replace("{stylesheet}",
|
||||
f'<link rel="stylesheet" href="{sheet}">' if sheet else "")
|
||||
.replace("{name}", config.rp_name)
|
||||
.replace("{passkeys}", offer))
|
||||
return HTMLResponse(html, headers=NO_STORE)
|
||||
|
||||
|
||||
@router.post("/login", include_in_schema=False)
|
||||
def sign_in(request: Request, response: Response, body: LoginBody) -> dict[str, str]:
|
||||
"""Check the password, and if it is right, open a session.
|
||||
|
||||
The lockout is read *before* the password is checked, so hammering the
|
||||
button while locked out does not extend the lockout — see
|
||||
`AuthStore.locked_for`. A wrong password and an unknown one are the same
|
||||
answer here for the usual reason, which is thin cover with one account but
|
||||
costs nothing to keep.
|
||||
"""
|
||||
if not _locked(request):
|
||||
raise HTTPException(400, "This app is not password-protected.")
|
||||
|
||||
_refuse_while_locked(request)
|
||||
|
||||
if not _store(request).check_password(body.password):
|
||||
_warn(request, "wrong password")
|
||||
raise HTTPException(401, "That is not the password.")
|
||||
|
||||
_open_session(request, response)
|
||||
return {"next": _safe_next(body.next)}
|
||||
|
||||
|
||||
@router.post("/logout", include_in_schema=False)
|
||||
def sign_out(request: Request, response: Response) -> dict[str, bool]:
|
||||
"""End this session and clear the cookie. Other devices are untouched."""
|
||||
token = token_from(request, _config(request))
|
||||
if token:
|
||||
_store(request).close_session(token)
|
||||
# Both names, because which one was set depends on `secure_cookie` and on
|
||||
# the scheme the login happened over — and clearing only one of them leaves
|
||||
# a cookie the browser will keep offering.
|
||||
for name in cookie_names(_config(request)):
|
||||
response.delete_cookie(name, path="/")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the account
|
||||
|
||||
@router.get("/api/account")
|
||||
def account(request: Request) -> Account:
|
||||
"""What there is to know and what can be changed."""
|
||||
store = _store(request)
|
||||
config = _config(request)
|
||||
return Account(
|
||||
locked=_locked(request),
|
||||
pinned=bool(_pinned(request)),
|
||||
pinned_by=config.password_env,
|
||||
password_set_at=store.changed_at(),
|
||||
sessions=store.sessions(token_from(request, config)),
|
||||
passkeys=store.passkeys(),
|
||||
passkeys_available=pk.available(),
|
||||
passkeys_blocked=pk.blocked(config, request),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/account/password")
|
||||
def change_password(request: Request, body: PasswordBody) -> dict[str, int]:
|
||||
"""Change it, having proved you know the current one — or set the first.
|
||||
|
||||
Asking for the current password matters even though you are already signed
|
||||
in: it is what makes a borrowed unlocked laptop not equal to a permanent
|
||||
takeover of the account. It is asked for whenever there is one, which on a
|
||||
locked app is always; see the body of the function for the one case where
|
||||
there is not.
|
||||
|
||||
Every *other* session is closed on success. If the reason you are changing
|
||||
the password is that someone may have it, leaving their session open makes
|
||||
the change ceremonial — and the cost when that is not the reason is signing
|
||||
in again on your phone, which is the right way round.
|
||||
|
||||
Which is also why this is behind the same lockout as the front door, and not
|
||||
only behind a session. `current` is the password, guessed here rather than
|
||||
at `/login`, and a borrowed unlocked laptop is exactly the situation the
|
||||
field exists for — so leaving it ungated would leave one door counted and
|
||||
one door open, at scrypt speed, ending in a password change that signs the
|
||||
owner out everywhere.
|
||||
"""
|
||||
config = _config(request)
|
||||
if _pinned(request):
|
||||
raise HTTPException(
|
||||
409, f"The password is pinned by {config.password_env}. Change it there.")
|
||||
store = _store(request)
|
||||
|
||||
# The first one is set without proving anything, because there is nothing
|
||||
# to prove: an app with no password is one nothing was asked for, and the
|
||||
# only way to reach this route is from a session it never demanded. That
|
||||
# is the unlocked laptop, and setting a password *there* — before the
|
||||
# thing is ever deployed — is the order this should encourage. A locked
|
||||
# app never lands here: `auth.bootstrap` gives it a password at startup,
|
||||
# so `current` is always required for the app that has a door.
|
||||
if store.has_password():
|
||||
_refuse_while_locked(request)
|
||||
if not store.check_password(body.current):
|
||||
_warn(request, "wrong current password")
|
||||
raise HTTPException(403, "That is not the current password.")
|
||||
if len(body.new) < MIN_LENGTH:
|
||||
raise HTTPException(400, f"Use at least {MIN_LENGTH} characters.")
|
||||
|
||||
store.set_password(body.new)
|
||||
closed = store.close_all(keep=token_from(request, config))
|
||||
return {"signed_out": closed}
|
||||
|
||||
|
||||
@router.delete("/api/account/sessions/{session_id}")
|
||||
def revoke(session_id: int, request: Request) -> dict[str, bool]:
|
||||
"""Drop one session. Revoking your own is allowed — it is a logout with an
|
||||
extra click, and refusing it would be a rule to explain for no gain."""
|
||||
if not _store(request).close_by_id(session_id):
|
||||
raise HTTPException(404, "That session is already gone.")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/api/account/sessions/close")
|
||||
def close_others(request: Request) -> dict[str, int]:
|
||||
"""Sign out everywhere but here. The reason sessions are rows."""
|
||||
store = _store(request)
|
||||
return {"signed_out": store.close_all(keep=token_from(request, _config(request)))}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------- passkeys
|
||||
#
|
||||
# Four routes behind the session (register in two steps, rename, revoke) and two
|
||||
# in front of it (sign in). The ceremony itself is `auth/passkeys.py`; these are
|
||||
# the round trips it needs, and the translation of its two exceptions into
|
||||
# status codes.
|
||||
|
||||
|
||||
@router.post("/api/account/passkeys/options")
|
||||
def passkey_options(request: Request) -> dict[str, object]:
|
||||
"""Step one of registering: a challenge for `navigator.credentials.create`."""
|
||||
_require_passkeys(request)
|
||||
return pk.register_options(_config(request), request, _store(request))
|
||||
|
||||
|
||||
@router.post("/api/account/passkeys")
|
||||
def add_passkey(request: Request, body: PasskeyBody) -> dict[str, int]:
|
||||
"""Step two: check what the authenticator signed, and keep the public key.
|
||||
|
||||
Requires a session, like everything else under `/api/account`. Registering a
|
||||
passkey is granting a new way in, so it is gated on already being in — the
|
||||
password is what proves that, and the ceremony does not replace it.
|
||||
"""
|
||||
_require_passkeys(request)
|
||||
try:
|
||||
return {"id": pk.register_verify(_config(request), request, _store(request),
|
||||
body.credential, body.label)}
|
||||
except pk.PasskeyError as exc:
|
||||
# `PasskeyMalformed` is one of these and answers the same way: from
|
||||
# behind a session, a body that is not a ceremony and a ceremony that
|
||||
# did not check out are both "that did not work, press it again".
|
||||
raise HTTPException(400, str(exc)) from None
|
||||
|
||||
|
||||
@router.post("/api/account/passkeys/{passkey_id}/label")
|
||||
def rename_passkey(passkey_id: int, body: LabelBody, request: Request) -> dict[str, bool]:
|
||||
"""Name it. A key you cannot name is one you will never dare revoke."""
|
||||
if not _store(request).rename_passkey(passkey_id, body.label):
|
||||
raise HTTPException(404, "That passkey is already gone.")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.delete("/api/account/passkeys/{passkey_id}")
|
||||
def drop_passkey(passkey_id: int, request: Request) -> dict[str, bool]:
|
||||
"""Revoke one. The password is still there, so this cannot lock you out —
|
||||
which is exactly why the password is still there."""
|
||||
if not _store(request).delete_passkey(passkey_id):
|
||||
raise HTTPException(404, "That passkey is already gone.")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/login/passkey/options", include_in_schema=False)
|
||||
def passkey_login_options(request: Request) -> dict[str, object]:
|
||||
"""Step one of signing in. Open, necessarily — there is no session yet.
|
||||
|
||||
Handing out a challenge to anyone who asks costs nothing: it is a random
|
||||
number, single-use, and worth nothing without a private key that never left
|
||||
the authenticator.
|
||||
"""
|
||||
_require_passkeys(request)
|
||||
store = _store(request)
|
||||
if not store.passkey_ids():
|
||||
raise HTTPException(404, "No passkeys are registered on this app.")
|
||||
return pk.login_options(_config(request), request, store)
|
||||
|
||||
|
||||
@router.post("/login/passkey", include_in_schema=False)
|
||||
def passkey_login(request: Request, response: Response,
|
||||
body: PasskeyLoginBody) -> dict[str, str]:
|
||||
"""Step two: a good signature from a registered key opens a session.
|
||||
|
||||
The same session a password opens — one kind of session, whichever door it
|
||||
came through, so revoking and expiry have one implementation.
|
||||
|
||||
Deliberately not behind the password lockout. An attacker hammering the
|
||||
front door locks it for the owner too (see `AuthStore.check_password` on
|
||||
why there is one counter), and a passkey that skips that queue is what
|
||||
makes it survivable. It is safe to skip: there is nothing to guess here,
|
||||
only a signature to produce.
|
||||
"""
|
||||
if not _locked(request):
|
||||
raise HTTPException(400, "This app is not password-protected.")
|
||||
_require_passkeys(request)
|
||||
try:
|
||||
pk.login_verify(_config(request), request, _store(request), body.credential)
|
||||
except pk.PasskeyMalformed as exc:
|
||||
# Not a failed sign-in — a request that was never a ceremony. 400 rather
|
||||
# than 401, and no warning, because there is no credential here to have
|
||||
# been wrong about.
|
||||
raise HTTPException(400, str(exc)) from None
|
||||
except pk.PasskeyError as exc:
|
||||
_warn(request, "passkey refused")
|
||||
raise HTTPException(401, str(exc)) from None
|
||||
|
||||
_open_session(request, response)
|
||||
return {"next": "/"}
|
||||
|
||||
|
||||
def _require_passkeys(request: Request) -> None:
|
||||
"""501 rather than 500 when the extra is not installed, and a sentence
|
||||
saying what to install.
|
||||
|
||||
"Not implemented" is the honest reading: the route exists and this build
|
||||
cannot perform it. The account element watches for exactly this status and
|
||||
takes the passkey section off the screen, so a missing optional dependency
|
||||
costs a paragraph rather than a broken page.
|
||||
|
||||
Only the package is checked here — an insecure origin blocks *registration*
|
||||
in the browser, not these endpoints, and the account screen has already
|
||||
said so.
|
||||
"""
|
||||
if not pk.available():
|
||||
raise HTTPException(501, pk.blocked(_config(request), request))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- helpers
|
||||
|
||||
def _open_session(request: Request, response: Response) -> None:
|
||||
"""One session, one cookie, whichever door was used."""
|
||||
config = _config(request)
|
||||
token = _store(request).open_session(
|
||||
request.headers.get("user-agent", ""), config.session_days)
|
||||
https = request.url.scheme == "https"
|
||||
response.set_cookie(
|
||||
cookie_name(config, https),
|
||||
token,
|
||||
max_age=config.session_days * 86400,
|
||||
httponly=True, # JavaScript cannot read it, so an XSS cannot post it on
|
||||
secure=is_secure(config, https),
|
||||
samesite="lax", # see the module docstring on why there is no CSRF token
|
||||
path="/",
|
||||
)
|
||||
|
||||
|
||||
def _refuse_while_locked(request: Request) -> None:
|
||||
"""The lockout, in front of every place a password can be guessed.
|
||||
|
||||
Read *before* the guess is looked at, so hammering while locked out does not
|
||||
extend the lockout — see `AuthStore.locked_for`. Called from both doors
|
||||
rather than living inside `check_password`, because the store counts and
|
||||
this decides: the same wrong answer is a refusal here and a bootstrap
|
||||
comparison in `auth.bootstrap`, which must not be able to lock anyone out of
|
||||
their own restart.
|
||||
"""
|
||||
wait = _store(request).locked_for()
|
||||
if wait:
|
||||
_warn(request, "attempt while locked out")
|
||||
raise HTTPException(429, f"Too many attempts. Try again in {_spell(wait)}.",
|
||||
headers={"Retry-After": str(wait)})
|
||||
|
||||
|
||||
def _warn(request: Request, what: str) -> None:
|
||||
"""Write down that someone got it wrong, and who.
|
||||
|
||||
The whole record of who is knocking. There is no access log worth the name —
|
||||
uvicorn is run quietly — and no table of attempts, because the log is the
|
||||
record and a second copy of it would only ever disagree. WARNING so it
|
||||
survives that level, one line per refusal, and the address first after
|
||||
`from` so a fail2ban filter is one regex; see docs/password-protection.md.
|
||||
|
||||
The message does not name the package, because the logger already does:
|
||||
with the usual `%(name)s: %(message)s` this module is `auth.router`, and a
|
||||
line reading `auth.router: auth: wrong password` says it twice and reads
|
||||
like a bug in the logging.
|
||||
|
||||
Nothing is *decided* from the address — `AuthStore.check_password` says why
|
||||
it cannot be — so this is where it earns its keep: at the layer that can
|
||||
drop the connection instead of answering it.
|
||||
"""
|
||||
log.warning("%s from %s", what, client_address(request))
|
||||
|
||||
|
||||
def _safe_next(target: str) -> str:
|
||||
r"""Where to go after signing in — only ever inside this app.
|
||||
|
||||
The classic open redirect: a real login page, a real successful sign-in, and
|
||||
someone else's site afterwards. So this accepts one shape only — a path
|
||||
beginning with a single `/`, with no host in it — and turns everything else
|
||||
into `/`.
|
||||
|
||||
A backslash is refused because a browser treats it as a slash in exactly
|
||||
this position: `/\evil.com` is parsed as `//evil.com` and is a host, which
|
||||
is how a version of this that rejected only a literal `//` sent people to
|
||||
another site. And the value is checked decoded as well as raw, because it
|
||||
reaches here through a query string that `URLSearchParams` has already
|
||||
unescaped once — `%5C` is a backslash to everything downstream of the
|
||||
address bar, and no `next` this app produces needs an escaped slash to
|
||||
survive.
|
||||
"""
|
||||
if not _local(target) or not _local(unquote(target)):
|
||||
return "/"
|
||||
return target
|
||||
|
||||
|
||||
def _local(target: str) -> bool:
|
||||
r"""Whether this is a path inside this app and nothing else.
|
||||
|
||||
`urlsplit` rather than more string tests, because it is the parser the
|
||||
browser's own rules are written against — it strips the tabs and newlines a
|
||||
browser strips, so `/\t/evil.com` is seen the way the browser will see it,
|
||||
as a host, and not as the local path a naive `startswith` reads.
|
||||
"""
|
||||
if not target.startswith("/") or target.startswith("//") or "\\" in target:
|
||||
return False
|
||||
try:
|
||||
parts = urlsplit(target)
|
||||
except ValueError: # an unparseable authority, e.g. `//[`
|
||||
return False
|
||||
return not parts.scheme and not parts.netloc
|
||||
|
||||
|
||||
def _spell(seconds: int) -> str:
|
||||
if seconds < 60:
|
||||
return f"{seconds} seconds"
|
||||
return f"{round(seconds / 60)} minutes"
|
||||
Reference in new issue
Block a user