Files
jobboard/auth/middleware.py
T

730 lines
35 KiB
Python

"""The lock on the door: is there a session, and what happens when there isn't.
Six things live here — when the door is locked at all, who gets past it, the
cookie and the bearer header that say so, the rule that another site's page
gets nothing changed, the password asked again from behind a session
(`confirm_password`, and `confirm_current` for a header), and the closing of a socket whose credential has ended.
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.
A reverse proxy on the same machine defeats the bind address, so an app `auto`
left open refuses any request a proxy forwarded; see
`RequireLogin._refuse_proxied`.
## Three credentials, two carriers
A session cookie is what the password and a passkey open, and it is what a
browser carries. An API token (`AuthStore.create_token`) is what a script
carries, as `Authorization: Bearer <token>`, and it is looked up on every
request the way a session is, so revoking it takes effect on the next call.
The cookie is read first and wins; the header is read only when there is no
live session. A token opens every door the session does except the account:
a request carrying one for `/api/account` or `/logout` is answered 403
(`ACCOUNT`), so a token that leaked cannot mint another, revoke the owner's
sessions or read the list of ways in. An app adds its own session-only routes
through `connect(session_only=...)`: anything that reads or replaces the
database as a file belongs there, since the file holds the password hash and
these rows, and a token that could fetch or swap it would hold the account
after all. A token that is not live is a 401 and a
WARNING line, like a wrong password; it is not counted against the lockout,
since 256 random bits are not guessed and the counter would only hand a
stranger a way to lock the owner out.
## Another site's page
`SameSite=Lax` keeps the session cookie off a cross-site `POST`, which covers
a locked app. An unlocked one on loopback has no cookie to withhold, so a page
open in the same browser could `POST` to `http://127.0.0.1:8787/api/...` with
a `text/plain` body, which needs no preflight, and every route that takes no
body acted on it; a WebSocket handshake is not subject to CORS at all, so the
same page could open `/ws/jobs` and read every job and notice. So a request
that changes something is refused when the browser says it came from another
site (`Sec-Fetch-Site`, else `Origin` against `Host` or `AuthConfig.origin`),
and a body of a type another site could send without a preflight is refused
whoever sent it: the API is JSON. Locked or not, because the rule costs two
header reads and a locked app with `secure_cookie: never` on a LAN is a real
deployment. See `cross_site`.
That comparison is against the request's own `Host`, and a page served from
`rebind.example` whose name is pointed at 127.0.0.1 arrives with a `Host` and
an `Origin` that agree. So an app `auto` left open also refuses any request
whose `Host` is not a loopback name, a `.localhost` name or the host of
`AuthConfig.origin`, with the same 421 as a forwarded one, whatever else it
carries: a browser that sends no fetch metadata and no `Origin` on a read is
still a rebound page. A loopback app is reached as `localhost` or
`127.0.0.1`, and a request that names another host for it came through a
proxy or a rebinding, neither of which the bind address can see. A test
client names the host it is given (`base_url="http://127.0.0.1"`).
## A socket outlives its handshake
The door is checked when a socket opens, and the socket stays open for the
life of the tab. So a route that ends a credential (`/logout`, a password
change, a revoked session or token) runs `close_ended_sockets` after its
answer, which asks the store about every open socket's cookie or bearer header
and closes the ones it no longer knows with 1008. Expiry ends no request, so
`connect` also runs `sweep_ended_sockets`, which does the same every `SWEEP`
seconds. A tab's reconnect then meets the door. The sockets are the app's:
`app.state.bus`, which `pipeline.web.connect` sets, and an app without one has
nothing to close.
"""
from __future__ import annotations
import asyncio
import ipaddress
import logging
from typing import Any
from urllib.parse import quote, urlsplit
from fastapi import HTTPException
from starlette.requests import HTTPConnection, cookie_parser
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")
#: What a bearer token cannot reach: the account, which is managed from a
#: browser with a session, and the sign-out of a session a token has not got.
#: Matched as `OPEN` is. Everything else a session opens, a token opens.
ACCOUNT: tuple[str, ...] = ("/api/account", "/api/account/", "/logout")
#: What a request carrying a token for the account is told.
TOKEN_NOT_HERE = ("An API token opens the API, not the account. Sign in with the "
"password or a passkey to manage it.")
def matches(path: str, names: tuple[str, ...]) -> bool:
"""Whether `path` is one of `names`: a name ending in `/` is a prefix, any
other is matched whole. The one rule for `OPEN` and `ACCOUNT`."""
return any(path == name.rstrip("/") or (name.endswith("/") and path.startswith(name))
for name in names)
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.
Parsed per `;`-separated pair by Starlette's `cookie_parser`, as a browser
does, and not by `http.cookies.SimpleCookie`, whose `load` returns an
empty jar for the whole header when one cookie in it has a space or JSON
in its value: a sibling app on the parent domain setting `theme=dark mode`
signed the owner out on every request. A pair that is not a cookie is
skipped, so a garbage header is no cookie rather than a 500.
"""
scope: Any = conn.scope if isinstance(conn, HTTPConnection) else conn
for key, value in scope.get("headers", ()):
if key == b"cookie":
jar = cookie_parser(value.decode("latin-1"))
for name in cookie_names(config):
if jar.get(name):
return jar[name]
return ""
def bearer_from(conn: HTTPConnection | Scope) -> str:
"""The API token this request carries in `Authorization: Bearer`, or "".
Only that header and only that scheme: a token in a query string would
land in every access log between the script and the app, and `Basic` is
a password, which has its own door.
"""
value = _header(conn, b"authorization")
scheme, _, token = value.strip().partition(" ")
if scheme.lower() != "bearer":
return ""
return token.strip()
def _header(conn: HTTPConnection | Scope, name: bytes) -> str:
scope: Any = conn.scope if isinstance(conn, HTTPConnection) else conn
for key, value in scope.get("headers", ()):
if key == name:
return value.decode("latin-1")
return ""
def credential_live(store: AuthStore, config: AuthConfig,
conn: HTTPConnection | Scope) -> bool:
"""Whether what this request carries still opens the door: its cookie's
session, else its bearer token. What `RequireLogin` decides from, asked
again of an open socket by `close_ended_sockets`."""
token = token_from(conn, config)
if token and store.touch(token) is not None:
return True
bearer = bearer_from(conn)
return bool(bearer) and store.touch_token(bearer) is not None
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 rightmost hop of `X-Forwarded-For`, the one the proxy in front
of this app appended for the connection it accepted; every hop left of it
was in the request when it arrived and is whatever the caller wrote. nginx's
`$proxy_add_x_forwarded_for` appends rather than replaces, so the first hop
let an attacker name the address a fail2ban filter on this line bans.
Without that header, `X-Real-IP`, which such a proxy sets outright. The
claimed address and the peer are both reported when they differ, because a
header is only as trustworthy as the proxy that set it, which is why
nothing is *decided* from this, only logged. See
`AuthStore.check_password` for that argument in full.
The header is also the one piece of a stranger's writing that can end 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. The address stays the
first word after `from`, so a filter is one regex.
"""
scope: Any = conn.scope if isinstance(conn, HTTPConnection) else conn
peer = (scope.get("client") or ("", 0))[0] or "unknown"
forwarded = real = ""
for key, value in scope.get("headers", ()):
# The last of each, should a header arrive twice: a proxy that adds
# one rather than appending writes it after the caller's.
if key == b"x-forwarded-for":
forwarded = value.decode("latin-1")
elif key == b"x-real-ip":
real = value.decode("latin-1")
hop = forwarded.split(",")[-1] if forwarded.strip() else real
claimed = "".join(c for c in hop if c.isalnum() or c in ".:%-")[:45]
if claimed and claimed != peer:
return f"{claimed} via {peer}"
return peer
#: Headers a reverse proxy adds. Any one of them on a request to an app that
#: `auto` left open because it binds loopback means the bind address is not the
#: whole story: a proxy on this machine is passing on someone else.
FORWARDED = frozenset({b"forwarded", b"x-forwarded-for", b"x-forwarded-proto",
b"x-forwarded-host"})
#: What such a request is answered with, for whoever runs the proxy.
PROXIED = ("This app binds loopback and so asks for no password, but this request "
"came through a proxy. Set auth.enabled: always in config.yaml and restart.")
#: What a browser script's request naming another host is answered with.
REBOUND = ("This app binds loopback and so asks for no password, but this request "
"names a host that is not localhost. Open the app as http://localhost, or "
"set auth.enabled: always in config.yaml and restart.")
#: 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 = "",
session_only: tuple[str, ...] = ()) -> None:
self.app = app
self.store = store
self.config = config
self.open = OPEN + tuple(open)
#: What a token may not reach: the account, and whatever the app adds.
self.session_only = (*ACCOUNT, *session_only)
self.locked = locked(config, host)
#: Open only because `auto` saw loopback; see `_refuse_proxied`.
self.watch_proxy = config.enabled == "auto" and not self.locked
self.warned = False
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] not in ("http", "websocket"):
return await self.app(scope, receive, send)
# Another site's page, locked or not: see the module docstring.
refused = cross_site(scope, self.config.origin)
if refused is not None:
return await self._answer(scope, receive, send, *refused)
if not self.locked:
if self.watch_proxy and _forwarded(scope):
return await self._refuse_proxied(scope, receive, send, PROXIED)
if self.watch_proxy and _rebound(scope, self.config.origin):
return await self._refuse_proxied(scope, receive, send, REBOUND)
return await self.app(scope, receive, send)
path = scope.get("path", "")
if matches(path, 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)
bearer = bearer_from(scope)
if bearer:
held = await asyncio.to_thread(self.store.touch_token, bearer)
if held is not None:
if matches(path, self.session_only):
return await self._answer(scope, receive, send, 403, TOKEN_NOT_HERE)
# The row, for a route that wants to know it was a script.
scope["auth_bearer"] = held.id
return await self.app(scope, receive, send)
# The same line a wrong password writes, for the same reader. A
# script with a bad token gets JSON whatever it asked for: a
# redirect to the login page is for a browser, and a browser does
# not send this header.
log.warning("bad token from %s", client_address(scope))
return await self._answer(scope, receive, send, 401,
"That token is not valid here.")
await self._refuse(scope, receive, send, path)
async def _answer(self, scope: Scope, receive: Receive, send: Send,
status: int, detail: str) -> None:
"""A refusal in the shape the caller can act on: `{"detail"}` with the
status, or a 1008 close before the socket is accepted."""
if scope["type"] == "websocket":
await send({"type": "websocket.close", "code": 1008})
return
await JSONResponse({"detail": detail}, status_code=status)(scope, receive, send)
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)
async def _refuse_proxied(self, scope: Scope, receive: Receive, send: Send,
detail: str) -> None:
"""421 for a forwarded request to an app `auto` left open, and for a
request that names a host it is not reached under (`_rebound`).
`auto` reads loopback as "this machine only", and a reverse proxy on
the same machine makes that false while every request still arrives
from 127.0.0.1. The peer cannot tell the proxy from a local browser,
only the headers the proxy adds can, so a request carrying one is
refused rather than served unlocked. A client can add the headers
itself, which only gets it refused. The Vite dev server's proxy adds
none (`xfwd` is off) and forwards `Host` unchanged, so `npm run dev`
is unaffected. Logged once at WARNING, since every request through
the proxy would repeat it.
"""
if not self.warned:
self.warned = True
log.warning("refused a proxied or rebound request to an unlocked app (%s): %s",
client_address(scope), detail)
if scope["type"] == "websocket":
await send({"type": "websocket.close", "code": 1008})
return
await JSONResponse({"detail": detail}, status_code=421)(scope, receive, send)
def _forwarded(scope: Scope) -> bool:
return any(key in FORWARDED for key, _ in scope.get("headers", ()))
def _rebound(scope: Scope, configured_origin: str) -> bool:
"""Whether a request reaches this loopback app under a name that is not
loopback: the shape of a DNS rebinding, where the page's own `Origin` and
the `Host` it sends agree and `_from_here` cannot tell.
Every request is judged, whatever headers it carries. A browser that sends
neither `Sec-Fetch-Site` nor `Origin` on a read is still a page on the
rebound name reading the API, and the only names a loopback app is reached
under are a loopback address, `localhost` and its subdomains, and the host
of `AuthConfig.origin`. A missing or unparseable `Host` names none of
them and is refused too.
"""
try:
host = urlsplit("//" + _header(scope, b"host")).hostname or ""
except ValueError: # an unparseable authority, e.g. `[`
return True
if _loopback(host) or host.endswith(".localhost"):
return False
allowed = urlsplit(configured_origin).hostname if configured_origin else ""
return not host or host != (allowed or "").lower()
# ------------------------------------------------------ the password again
def claim_attempt(conn: HTTPConnection) -> None:
"""The lockout, in front of every place a password can be guessed: 429
while it holds, else the guess is counted before it is derived.
`AuthStore.claim_attempt` decides and counts in one write transaction, so
concurrent guesses each see the ones before them and a window admits five
of them, not a threadpool's worth. A refused claim counts nothing, so
hammering while locked out does not extend the lockout. The caller then
checks with `check_password(..., claimed=True)`, which clears the count
when the guess was right. Called from both doors rather than living inside
`check_password`, because the same comparison is a counted guess here and
a bootstrap comparison in `auth.bootstrap`, which must not be able to lock
anyone out of their own restart.
"""
wait = conn.app.state.auth.claim_attempt()
if wait:
warn(conn, "attempt while locked out")
raise HTTPException(429, f"Too many attempts. Try again in {_spell(wait)}.",
headers={"Retry-After": str(wait)})
def confirm_password(conn: HTTPConnection, current: str) -> None:
"""The password again, from someone already signed in: changing it, adding
a passkey, minting a token, and any app route that must not be one
borrowed browser away from the account (`connect(session_only=...)`).
Counted and gated like the front door, because `current` is a guess at the
password made from behind a session: 429 while locked out, 403 when wrong.
It has nothing to confirm on an app with no password yet, which refuses
every guess, so a route that can run there asks `has_password()` first, as
the account routes do."""
claim_attempt(conn)
if not conn.app.state.auth.check_password(current, claimed=True):
warn(conn, "wrong current password")
raise HTTPException(403, "That is not the current password.")
#: Where a route whose body is a file takes the current password. A header and
#: not a field, because the body is the file itself; read before the first byte
#: of that body, so a refusal costs no upload.
CURRENT_HEADER = "x-current-password"
def confirm_current(conn: HTTPConnection) -> None:
"""The current password from the `X-Current-Password` header, for a route
that hands out or replaces the database as a file (`connect(session_only=...)`).
A session is not enough for a route that replaces the credentials: the
restored file brings its own password hash, passkeys and tokens, so a
borrowed signed-in browser that could restore a doctored backup would own
the account. Call it before reading the body. A missing or empty header is
a WARNING line and a 403 that counts nothing against the lockout, since a
missing field is not a guess; a wrong one goes through `confirm_password`,
which counts it, warns and answers 403, or 429 while locked out. An app
that never had a password (loopback, never locked) has nothing to confirm.
The check is a deliberately slow derivation, so a coroutine route runs it
in the threadpool. newsdesk's `/api/restore` is the caller.
"""
if not conn.app.state.auth.has_password():
return
current = conn.headers.get(CURRENT_HEADER, "")
if not current:
warn(conn, f"no current password for {conn.scope.get('method', '')} "
f"{conn.scope.get('path', '')}")
raise HTTPException(403, "This takes the current password in X-Current-Password.")
confirm_password(conn, current)
def warn(conn: HTTPConnection, 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 documentation/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.middleware`,
and a line reading `auth.middleware: 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(conn))
def _spell(seconds: int) -> str:
if seconds < 60:
return f"{seconds} seconds"
return f"{round(seconds / 60)} minutes"
# --------------------------------------------- sockets whose credential ended
#: How often, in seconds, `sweep_ended_sockets` asks about every open socket:
#: the longest an expired session or token keeps the socket it opened.
SWEEP = 60.0
async def close_ended_sockets(app: Any) -> int:
"""Close every open socket whose session or token has ended. Returns how
many it closed.
The door is checked at the handshake, and a socket stays open for the
life of the tab. So signing out, changing the password or revoking a
session or a token left the socket it had opened streaming to whoever
held it. Run after each of those, as a background task of the route, and
on a clock by `sweep_ended_sockets`, this asks the store about every
socket's cookie or bearer header (`credential_live`) and closes the ones
it no longer knows with 1008; a tab's reconnect then meets the door.
The sockets are `app.state.bus`: what `pipeline.web.connect` puts there,
or anything with a `sockets` tuple and an async `close(sockets, code,
reason)`. Nothing to do on an unlocked app, which has no sessions to
end, or on one without a bus.
"""
if not getattr(app.state, "auth_locked", False):
return 0
bus = getattr(app.state, "bus", None)
if bus is None:
return 0
store, config = app.state.auth, app.state.auth_config
sockets = bus.sockets
def ended() -> list[Any]:
return [ws for ws in sockets if not credential_live(store, config, ws)]
# `to_thread`, because the store is SQLite and this is the event loop.
gone = await asyncio.to_thread(ended)
return await bus.close(gone, 1008, "signed out") if gone else 0
async def sweep_ended_sockets(app: Any, every: float = SWEEP) -> None:
"""`close_ended_sockets` every `every` seconds, until cancelled.
The door is checked at the handshake only, and the routes that end a
credential close its sockets themselves. Expiry is seen by no route: a
session or token that runs out ends no request, so its socket streamed
until the tab reconnected. This closes it within `every` seconds.
`connect` starts it on a locked app and cancels it at shutdown. A sweep
that fails is logged and the next one runs, since a loop that died on
one busy database would leave every later expiry open.
"""
while True:
await asyncio.sleep(every)
try:
await close_ended_sockets(app)
except Exception:
log.warning("the socket sweep failed", exc_info=True)
# ------------------------------------------------------------ another site
#: The methods that change something. No `GET` here changes anything (see the
#: module docstring of `auth/router.py`), so these are the ones to guard.
UNSAFE = frozenset({"POST", "PUT", "PATCH", "DELETE"})
#: The bodies another site's page may send without the browser asking first:
#: the three CORS-safelisted types, and a body with no type at all. A
#: cross-site request with any other type is preflighted, and nothing here
#: answers a preflight, so it never leaves the browser.
SIMPLE_BODIES = frozenset({"", "text/plain", "application/x-www-form-urlencoded",
"multipart/form-data"})
CROSS_SITE = ("This request came from another site's page, and nothing here "
"changes on another site's say-so.")
def cross_site(scope: Scope, configured_origin: str = "") -> tuple[int, str] | None:
"""Why a request that changes something is refused, or None.
Two checks, the first for the socket too:
- **Where it came from.** `Sec-Fetch-Site` when the browser sends it,
which a page cannot set; otherwise `Origin`, which must name this host
or `configured_origin` (`AuthConfig.origin`, for a proxy that rewrites
`Host`). No `Origin` at all is a client that is not a browser page
(`curl`, a script with a token, a test) and passes.
- **What the body is.** A body of a type another site could send without
a preflight is refused, whoever sent it: the API is JSON.
A read is never refused, wherever it came from.
"""
if scope["type"] == "websocket":
if not _from_here(scope, configured_origin):
return 403, "another site's page cannot open this socket"
return None
if scope.get("method") not in UNSAFE:
return None
if not _from_here(scope, configured_origin):
return 403, CROSS_SITE
kind = _header(scope, b"content-type").split(";")[0].strip().lower()
if _has_body(scope) and kind in SIMPLE_BODIES:
return 415, ("Send the body as application/json, not "
f"{kind or 'without a content type'}.")
return None
def _from_here(scope: Scope, configured: str) -> bool:
"""Whether the page that sent this is this app's own, as far as the
browser says.
`Sec-Fetch-Site` decides when present: the browser sets it and a page
cannot, and it stays right behind a proxy that rewrites `Host`, where an
`Origin` comparison would refuse the app's own page. `none` is a request
the user made by typing or from a bookmark. Without it, `Origin` against
`Host` (the Vite dev server forwards `Host` unchanged) or against the
configured origin. `null` is a sandboxed frame or a `file://` page and is
never this app.
"""
site = _header(scope, b"sec-fetch-site")
if site:
return site in ("same-origin", "none")
origin = _header(scope, b"origin")
if not origin:
return True
if origin == "null":
return False
if configured and origin.rstrip("/") == configured.rstrip("/"):
return True
parts = urlsplit(origin)
host = _header(scope, b"host")
return bool(host) and (_authority(parts.scheme, parts.netloc)
== _authority(parts.scheme, host))
def _authority(scheme: str, netloc: str) -> str:
"""`host[:port]`, lowercased, without the scheme's default port, so
`Host: app.example.com:443` and `Origin: https://app.example.com` agree."""
netloc = netloc.lower()
default = {"http": ":80", "ws": ":80", "https": ":443", "wss": ":443"}.get(scheme, "")
return netloc[: -len(default)] if default and netloc.endswith(default) else netloc
def _has_body(scope: Scope) -> bool:
length = _header(scope, b"content-length")
# The header's presence, not its value, says a body follows; an empty value
# is malformed and is not given the benefit of the doubt.
chunked = any(key == b"transfer-encoding" for key, _ in scope.get("headers", ()))
return (length.isdigit() and int(length) > 0) or chunked