526 lines
23 KiB
Python
526 lines
23 KiB
Python
"""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, 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 (
|
|
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, Ok, PasskeyAdded, PasskeyBody, PasskeyLoginBody,
|
|
PasskeyOptionsBody, PasswordBody, PasswordChanged, SignedOut, TokenBody, TokenCreated,
|
|
)
|
|
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
|
|
#: documentation/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 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.")
|
|
|
|
claim_attempt(request)
|
|
|
|
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)
|
|
return {"next": _safe_next(body.next)}
|
|
|
|
|
|
@router.post("/logout", include_in_schema=False)
|
|
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()
|
|
|
|
|
|
# ---------------------------------------------------------------- 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),
|
|
tokens=store.tokens(),
|
|
)
|
|
|
|
|
|
@router.post("/api/account/password")
|
|
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
|
|
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.
|
|
|
|
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
|
|
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():
|
|
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))
|
|
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, 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.")
|
|
tasks.add_task(close_ended_sockets, request.app)
|
|
return Ok()
|
|
|
|
|
|
@router.post("/api/account/sessions/close")
|
|
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)
|
|
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
|
|
#
|
|
# 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, 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)
|
|
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) -> PasskeyAdded:
|
|
"""Step two: check what the authenticator signed, and keep the public key.
|
|
|
|
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 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
|
|
# 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) -> 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()
|
|
|
|
|
|
@router.delete("/api/account/passkeys/{passkey_id}")
|
|
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()
|
|
|
|
|
|
@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 _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
|