Files
WolfandClaude Opus 5.5 9d666d0937 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>
2026-09-23 12:29:16 +02:00

247 lines
11 KiB
Python

"""The lock on the door: is there a session, and what happens when there isn't.
Three things live here — when the door is locked at all, who gets past it, and
the cookie that says so. The password itself is `auth/store.py`; this module
never sees a hash.
## Why a middleware and not a dependency
The FastAPI-shaped answer is `Depends(current_session)` on every route, and it
is the wrong one here for two reasons.
The first is the WebSocket. `/ws/jobs` is a real socket, and route dependencies
on a WebSocket endpoint are awkward at best — but a cookie rides the handshake
like any other request, so one ASGI middleware in front of everything covers
the socket and the JSON with the same six lines.
The second is the failure mode. A dependency is opt-in: protection is applied
by remembering to apply it, and the cost of forgetting is not a broken page but
a quiet hole — an API served to the internet, and nothing on screen different.
An app adds routers regularly, and the next one should be safe because it
exists, not because someone remembered. So the rule is inverted: everything is
shut, and the few things that must be open are named in one list you can read
at a glance.
## What being locked means
`auto` decides from the bind address, which is the only setting that ever
mattered: bound to loopback, the door is already the machine's own login, and a
password is a second lock on it; bound to anything else, the app is on a
network and needs its own. The alternative — default off, switch it on when you
deploy — fails silently in the exact case it exists for, because an app serving
the internet with no password looks and behaves precisely like one that is fine.
"""
from __future__ import annotations
import asyncio
import ipaddress
import logging
from http.cookies import SimpleCookie
from typing import Any
from urllib.parse import quote
from starlette.requests import HTTPConnection
from starlette.responses import JSONResponse, RedirectResponse, Response
from starlette.types import ASGIApp, Receive, Scope, Send
from auth.config import AuthConfig
from auth.store import AuthStore
log = logging.getLogger(__name__)
#: Reachable without a session, and nothing else is. `/login` has to be, or
#: there is no way in, and the passkey ceremony under `/login/` with it;
#: `/_auth/` carries the two scripts the login page and the account element
#: are; `/health` is for a proxy probe that has no session to offer. The app
#: adds its own — `/static/`, normally, or the login page arrives unstyled.
#:
#: A name ending in `/` is a prefix, any other is matched whole, so `/health`
#: does not open `/healthz` and `/login` does not open `/loginx`. Matched
#: against the path only — a query string cannot widen this.
OPEN: tuple[str, ...] = ("/login", "/login/", "/_auth/", "/health")
def locked(config: AuthConfig, host: str) -> bool:
"""Whether this app should ask for a password. See `AuthConfig.enabled`.
`host` is the address the server binds, which is the app's own
`server.host` setting and not anything a request carries: a `Host` header
is written by whoever is talking, and a door that could be talked out of
being a door is not one.
"""
if config.enabled == "always":
return True
if config.enabled == "never":
return False
return not _loopback(host)
def _loopback(host: str) -> bool:
"""Whether binding here means "this machine only".
`localhost` by name, and anything in 127.0.0.0/8 or ::1 by number. An empty
host, or `0.0.0.0`, or a LAN address is not loopback — and an unparseable
one is treated as not loopback too, because the failure to be careful about
is guessing "private" and being wrong.
"""
if host in ("localhost", "::1"):
return True
try:
return ipaddress.ip_address(host).is_loopback
except ValueError:
return False
def cookie_name(config: AuthConfig, scope_secure: bool) -> str:
"""`__Host-` when the cookie will be Secure, plain otherwise.
That prefix is a promise to the browser that the cookie is Secure,
path-scoped to `/` and carries no Domain, and a browser will refuse to
store one that is not — which presents as a login that appears to succeed
and lands you back on the login page, with nothing in any log. So the name
is chosen per deployment rather than fixed.
"""
return f"__Host-{config.cookie}" if is_secure(config, scope_secure) else config.cookie
def cookie_names(config: AuthConfig) -> tuple[str, str]:
"""Both names, secure first. Read and cleared together, because which one
was set depends on `secure_cookie` and on the scheme the login happened
over — and clearing only one leaves a cookie the browser goes on offering."""
return f"__Host-{config.cookie}", config.cookie
def is_secure(config: AuthConfig, scope_secure: bool) -> bool:
setting = config.secure_cookie
if setting == "always":
return True
if setting == "never":
return False
return scope_secure
def token_from(conn: HTTPConnection | Scope, config: AuthConfig) -> str:
"""The session token this request carries, or "".
Both cookie names are looked for, so flipping `secure_cookie` or moving
behind TLS does not strand a live session under the other name.
"""
scope: Any = conn.scope if isinstance(conn, HTTPConnection) else conn
for key, value in scope.get("headers", ()):
if key == b"cookie":
jar = SimpleCookie()
try:
jar.load(value.decode("latin-1"))
except Exception: # a cookie header that is not one
return ""
for name in cookie_names(config):
if name in jar:
return jar[name].value
return ""
def client_address(conn: HTTPConnection | Scope) -> str:
"""Who is asking, as well as it can be known, for the log to say so.
Behind a reverse proxy the peer is a container on the same Docker network
and says nothing about who is at the other end; the address worth writing
down is the first hop of `X-Forwarded-For`, which the proxy sets. Both are
reported when they differ, because the header is only as trustworthy as
whoever sent it — which is why nothing is *decided* from this, only logged.
See `AuthStore.check_password` for that argument in full.
That header is also the one piece of a stranger's own writing that ends up
in the log, so only the characters an address is made of survive the trip:
a line in this log is something fail2ban reads and a person believes, and
neither should be forgeable by whoever is knocking.
"""
scope: Any = conn.scope if isinstance(conn, HTTPConnection) else conn
peer = (scope.get("client") or ("", 0))[0] or "unknown"
for key, value in scope.get("headers", ()):
if key == b"x-forwarded-for":
first = value.decode("latin-1").split(",")[0]
claimed = "".join(c for c in first if c.isalnum() or c in ".:%-")[:45]
if claimed and claimed != peer:
return f"{claimed} via {peer}"
return peer
#: Prefixes whose refusal is JSON rather than a redirect. A caller that asked
#: for data and is sent a login page reads it as a 200 full of HTML where its
#: JSON should be; `{"detail": ...}` with a 401 is something it can act on.
JSON_PREFIXES = ("/api", "/ws", "/_jobs", "/_auth")
class RequireLogin:
"""Everything is shut except the open list. Raw ASGI, so it covers sockets.
Deliberately not `BaseHTTPMiddleware`, which only sees `http` scopes — a
WebSocket would pass straight under it, and `/ws/jobs` streams the state of
every job in the app.
Whether the door is locked at all is decided once, at construction, from
the config and the bind address: neither changes while the process runs,
and deciding per request would mean re-deriving the same answer a thousand
times a minute and having no single place to read it off.
"""
def __init__(self, app: ASGIApp, store: AuthStore, config: AuthConfig,
open: tuple[str, ...] = (), host: str = "") -> None:
self.app = app
self.store = store
self.config = config
self.open = OPEN + tuple(open)
self.locked = locked(config, host)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] not in ("http", "websocket") or not self.locked:
return await self.app(scope, receive, send)
path = scope.get("path", "")
if any(path == p.rstrip("/") or (p.endswith("/") and path.startswith(p))
for p in self.open):
return await self.app(scope, receive, send)
token = token_from(scope, self.config)
# `to_thread`, because the store is SQLite and this is the event loop.
session = await asyncio.to_thread(self.store.touch, token) if token else None
if session is not None:
# Parked on the scope so `/api/account` can flag which row in the
# sessions list is the browser asking, and `/logout` can end the
# right one. Not a header and not a dependency: the middleware is
# the only thing that has verified it.
scope["auth_token"] = token
return await self.app(scope, receive, send)
await self._refuse(scope, receive, send, path)
async def _refuse(self, scope: Scope, receive: Receive, send: Send,
path: str) -> None:
"""No session. Say so in whatever the caller can understand."""
if scope["type"] == "websocket":
# Sent before accepting, which the ASGI server turns into an HTTP
# 403 on the handshake. The reconnect backoff in `<desk-jobs>` then
# does the right thing by itself.
await send({"type": "websocket.close", "code": 1008})
return
response: Response
# A GET of anything that is not an API path is a page being asked for,
# whatever the caller put in `Accept` — curl and a browser want the
# same thing there, and a 401 in place of the login page is a worse
# answer to both. Everything else is JSON, including a POST to a page
# path: a form submitted without a session has nowhere useful to land.
if scope.get("method") == "GET" and not path.startswith(JSON_PREFIXES):
# Carry where they were going, so a bookmarked deep link survives
# the login. Only ever a path from this app's own scope — but it is
# being written into a query string, and the scope has already
# decoded it, so a path holding a `&` or a `%` would arrive at the
# login page as a different path or as nothing. `quote` puts it back
# the way `URLSearchParams` will read it.
target = "/login" + (f"?next={quote(path)}" if path not in ("/", "") else "")
response = RedirectResponse(target, status_code=303)
else:
response = JSONResponse({"detail": "Not signed in"}, status_code=401)
await response(scope, receive, send)