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:
1 parent
83e965dfeb
commit
244e57ac29
19 files changed
+2288
-214
No files matched your search
+511
-28
@@ -1,8 +1,10 @@
|
||||
"""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.
|
||||
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
|
||||
|
||||
@@ -30,6 +32,66 @@ 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
|
||||
@@ -37,11 +99,11 @@ 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 urllib.parse import quote, urlsplit
|
||||
|
||||
from starlette.requests import HTTPConnection
|
||||
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
|
||||
|
||||
@@ -61,6 +123,22 @@ log = logging.getLogger(__name__)
|
||||
#: 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`.
|
||||
@@ -126,47 +204,113 @@ def token_from(conn: HTTPConnection | Scope, config: AuthConfig) -> str:
|
||||
|
||||
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 = SimpleCookie()
|
||||
try:
|
||||
jar.load(value.decode("latin-1"))
|
||||
except Exception: # a cookie header that is not one
|
||||
return ""
|
||||
jar = cookie_parser(value.decode("latin-1"))
|
||||
for name in cookie_names(config):
|
||||
if name in jar:
|
||||
return jar[name].value
|
||||
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 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.
|
||||
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.
|
||||
|
||||
That header is also the one piece of a stranger's own writing that ends up
|
||||
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.
|
||||
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":
|
||||
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}"
|
||||
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.
|
||||
@@ -187,20 +331,35 @@ class RequireLogin:
|
||||
"""
|
||||
|
||||
def __init__(self, app: ASGIApp, store: AuthStore, config: AuthConfig,
|
||||
open: tuple[str, ...] = (), host: str = "") -> None:
|
||||
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") or not self.locked:
|
||||
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 any(path == p.rstrip("/") or (p.endswith("/") and path.startswith(p))
|
||||
for p in self.open):
|
||||
if matches(path, self.open):
|
||||
return await self.app(scope, receive, send)
|
||||
|
||||
token = token_from(scope, self.config)
|
||||
@@ -214,8 +373,34 @@ class RequireLogin:
|
||||
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."""
|
||||
@@ -244,3 +429,301 @@ class RequireLogin:
|
||||
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
|
||||
Reference in new issue
Block a user