Take auth/ whole from boilerplate 09e144d: the lockout claimed before the scrypt, APP_PASSWORD recovery closing every session, Starlette's cookie parser, the rightmost forwarded hop in the log, revoke_all on a password change, a 421 for a non-loopback Host on an open app, API tokens in auth_tokens behind Authorization: Bearer, and sockets closed with their credential

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
WolfandClaude Fable 5.1 committed 2026-10-27 11:51:21 +01:00
1 parent 83e965dfeb
commit 244e57ac29
19 files changed
+2288 -214

No files matched your search

+119 -83
View File
@@ -29,18 +29,20 @@ import os
from pathlib import Path
from urllib.parse import unquote, urlsplit
from fastapi import APIRouter, HTTPException, Request, Response
from fastapi import APIRouter, BackgroundTasks, 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,
claim_attempt, close_ended_sockets, confirm_password, cookie_name, cookie_names,
is_secure, token_from, warn,
)
from auth.models import Account
from auth.schemas import (
LabelBody, LoginBody, PasskeyBody, PasskeyLoginBody, PasswordBody,
LabelBody, LoginBody, Ok, PasskeyAdded, PasskeyBody, PasskeyLoginBody,
PasskeyOptionsBody, PasswordBody, PasswordChanged, SignedOut, TokenBody, TokenCreated,
)
from auth.store import AuthStore
@@ -63,7 +65,7 @@ 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
#: documentation/Password Protection.md — the generated password is sixteen random
#: characters and anything you choose yourself is the weak half.
MIN_LENGTH = 8
@@ -156,19 +158,20 @@ def login_page(request: Request) -> Response:
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.
The attempt is claimed *before* the password is derived, which reads the
lockout and counts the guess in one write, so hammering the button while
locked out does not extend the lockout and concurrent guesses cannot all
slip in under one reading of it; see `AuthStore.claim_attempt`. 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)
claim_attempt(request)
if not _store(request).check_password(body.password):
_warn(request, "wrong password")
if not _store(request).check_password(body.password, claimed=True):
warn(request, "wrong password")
raise HTTPException(401, "That is not the password.")
_open_session(request, response)
@@ -176,17 +179,22 @@ def sign_in(request: Request, response: Response, body: LoginBody) -> dict[str,
@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."""
def sign_out(request: Request, response: Response, tasks: BackgroundTasks) -> Ok:
"""End this session and clear the cookie. Other devices are untouched.
The socket this tab opened is closed too, after the answer; see
`auth.close_ended_sockets`. The same for the four routes below that end
a session or a token."""
token = token_from(request, _config(request))
if token:
_store(request).close_session(token)
tasks.add_task(close_ended_sockets, request.app)
# 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}
return Ok()
# ---------------------------------------------------------------- the account
@@ -205,11 +213,13 @@ def account(request: Request) -> Account:
passkeys=store.passkeys(),
passkeys_available=pk.available(),
passkeys_blocked=pk.blocked(config, request),
tokens=store.tokens(),
)
@router.post("/api/account/password")
def change_password(request: Request, body: PasswordBody) -> dict[str, int]:
def change_password(request: Request, body: PasswordBody,
tasks: BackgroundTasks) -> PasswordChanged:
"""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
@@ -223,6 +233,13 @@ def change_password(request: Request, body: PasswordBody) -> dict[str, int]:
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.
API tokens and passkeys stay by default, because the cron job holding a
token is not what the password was changed against. `revoke_all` deletes
every one of them too, for the case the route exists for: an intruder
who had the password could have minted a token that never expires or
registered a passkey, and either outlives the change. The answer counts
what was closed and what remains, so the screen can say so.
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
@@ -244,32 +261,82 @@ def change_password(request: Request, body: PasswordBody) -> dict[str, int]:
# 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.")
confirm_password(request, body.current)
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}
tokens, keys = store.revoke_credentials() if body.revoke_all else (0, 0)
tokens_left, keys_left = store.counts()
tasks.add_task(close_ended_sockets, request.app)
return PasswordChanged(signed_out=closed, tokens_revoked=tokens, passkeys_revoked=keys,
tokens_left=tokens_left, passkeys_left=keys_left)
@router.delete("/api/account/sessions/{session_id}")
def revoke(session_id: int, request: Request) -> dict[str, bool]:
def revoke(session_id: int, request: Request, tasks: BackgroundTasks) -> Ok:
"""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}
tasks.add_task(close_ended_sockets, request.app)
return Ok()
@router.post("/api/account/sessions/close")
def close_others(request: Request) -> dict[str, int]:
def close_others(request: Request, tasks: BackgroundTasks) -> SignedOut:
"""Sign out everywhere but here. The reason sessions are rows."""
closed = _store(request).close_all(keep=token_from(request, _config(request)))
tasks.add_task(close_ended_sockets, request.app)
return SignedOut(signed_out=closed)
# --------------------------------------------------------------------- tokens
#
# Three routes, all behind a session and none reachable with a token: the
# middleware answers a bearer request under `/api/account` with 403
# (`auth.middleware.ACCOUNT`), so a leaked token cannot mint another, revoke
# the owner's sessions or read the list of ways in. The token is used
# anywhere else as `Authorization: Bearer <token>`.
@router.post("/api/account/tokens")
def create_token(request: Request, body: TokenBody) -> TokenCreated:
"""Mint an API token for a script, once the password is confirmed.
A session is not enough, for the reason it is not enough for a passkey: a
token outlives every session and a password change, so a borrowed
signed-in browser that could mint one would keep a way in for good.
`current` is checked as `change_password` checks it, behind the same
lockout, and on the same condition. The token is in this answer and
nowhere else; the store keeps its hash.
"""
store = _store(request)
return {"signed_out": store.close_all(keep=token_from(request, _config(request)))}
if store.has_password():
confirm_password(request, body.current)
token_id, token = store.create_token(body.label, body.days)
made = next(t for t in store.tokens() if t.id == token_id)
return TokenCreated(id=token_id, token=token, hint=made.hint, label=made.label,
expires_at=made.expires_at)
@router.post("/api/account/tokens/{token_id}/label")
def rename_token(token_id: int, body: LabelBody, request: Request) -> Ok:
if not _store(request).rename_token(token_id, body.label):
raise HTTPException(404, "That token is already gone.")
return Ok()
@router.delete("/api/account/tokens/{token_id}")
def drop_token(token_id: int, request: Request, tasks: BackgroundTasks) -> Ok:
"""Revoke one. The next request carrying it is refused, whatever it holds
open: a token is looked up on every request, like a session, and a socket
it opened is closed as a session's is."""
if not _store(request).delete_token(token_id):
raise HTTPException(404, "That token is already gone.")
tasks.add_task(close_ended_sockets, request.app)
return Ok()
# ------------------------------------------------------------------- passkeys
@@ -281,24 +348,37 @@ def close_others(request: Request) -> dict[str, int]:
@router.post("/api/account/passkeys/options")
def passkey_options(request: Request) -> dict[str, object]:
"""Step one of registering: a challenge for `navigator.credentials.create`."""
def passkey_options(request: Request, body: PasskeyOptionsBody) -> dict[str, object]:
"""Step one of registering: a challenge for `navigator.credentials.create`,
once the password is confirmed.
A session is not enough. A passkey outlives every session and a password
change, so a borrowed signed-in browser that could add one would keep a way
in for good. `current` is checked as `change_password` checks it, behind the
same lockout, and on the same condition: an app with no password (loopback,
never locked) has nothing to confirm and no session to borrow, so
registering there before deploying still works.
"""
_require_passkeys(request)
return pk.register_options(_config(request), request, _store(request))
store = _store(request)
if store.has_password():
confirm_password(request, body.current)
return pk.register_options(_config(request), request, store)
@router.post("/api/account/passkeys")
def add_passkey(request: Request, body: PasskeyBody) -> dict[str, int]:
def add_passkey(request: Request, body: PasskeyBody) -> PasskeyAdded:
"""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.
Requires a session, like everything else under `/api/account`, and a
challenge from `passkey_options`, which only the password gets. The
challenge is single-use and bound to registering, so this step cannot be
reached without the password having been typed for it.
"""
_require_passkeys(request)
try:
return {"id": pk.register_verify(_config(request), request, _store(request),
body.credential, body.label)}
return PasskeyAdded(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
@@ -307,20 +387,20 @@ def add_passkey(request: Request, body: PasskeyBody) -> dict[str, int]:
@router.post("/api/account/passkeys/{passkey_id}/label")
def rename_passkey(passkey_id: int, body: LabelBody, request: Request) -> dict[str, bool]:
def rename_passkey(passkey_id: int, body: LabelBody, request: Request) -> Ok:
"""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}
return Ok()
@router.delete("/api/account/passkeys/{passkey_id}")
def drop_passkey(passkey_id: int, request: Request) -> dict[str, bool]:
def drop_passkey(passkey_id: int, request: Request) -> Ok:
"""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}
return Ok()
@router.post("/login/passkey/options", include_in_schema=False)
@@ -363,7 +443,7 @@ def passkey_login(request: Request, response: Response,
# been wrong about.
raise HTTPException(400, str(exc)) from None
except pk.PasskeyError as exc:
_warn(request, "passkey refused")
warn(request, "passkey refused")
raise HTTPException(401, str(exc)) from None
_open_session(request, response)
@@ -406,44 +486,6 @@ def _open_session(request: Request, response: Response) -> None:
)
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.
@@ -481,9 +523,3 @@ def _local(target: str) -> bool:
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"