Files
FabledSteward/steward/auth/csrf.py
T
bvandeusenandClaude Opus 5.5 e8b75143f1
CI / lint (push) Successful in 3s
CI / integration (push) Successful in 1m23s
CI / unit (push) Successful in 1m37s
CI / publish (push) Successful in 1m8s
feat(backup): check a backup against what is in place, changing nothing (#5823)
#5823 "Check a backup: compare what it would restore with what is in
place, without restoring".

- steward/backup/check.py: pg_restore writes the backup's rows as COPY
  text with no database involved. The rows in place go out through COPY in
  the same form. Tables are compared on their primary keys, over the columns
  both sides have, and grouped by area.
- Sealed values are opened with each side's own key and compared as
  plaintext digests, so a secret sealed twice still matches. They are never
  shown. A backup whose key can't open its own secrets fails the check.
- What Steward records as it runs (last-seen times, a schedule's last run,
  backup history, scraped UniFi fields) is left out of the comparison:
  contents.ACTIVITY, STATE_SETTINGS and HAND_SET_ONLY.
- Settings → Backups:
  - a Check button on each sent backup, which fetches it from the bucket
    (new s3.get_file);
  - "Check a file" to upload one, with the size limit raised before the
    CSRF check reads the form;
  - a results page.
- Each backup Steward sends checks itself once written, and its history
  row says how that went.
- New CLI command `steward check-backup FILE`. CI's image smoke step checks a
  real backup against its source and expects a match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 10:48:48 -04:00

74 lines
2.7 KiB
Python

"""Forged-request (CSRF) protection for the browser side of Steward.
A page on another site can make a logged-in browser POST to Steward, and the
browser sends Steward's session cookie with it. Every state-changing request
from a browser therefore has to carry a token that only Steward's own pages
know: a random value kept in the session, written into each form by
`csrf_field()` and sent by HTMX and fetch() as the `X-CSRF-Token` header (set
once on <body> in base.html).
One check in a before_request covers every route, so a new route cannot
forget it. Callers that authenticate with a bearer token instead of the
session cookie (the host agent's ingest; /mcp never reaches Quart) are exempt:
a forged browser request cannot carry their token.
"""
from __future__ import annotations
import hmac
import secrets
from markupsafe import Markup, escape
from quart import Response, request, session
SESSION_KEY = "_csrf"
FORM_FIELD = "csrf_token"
HEADER = "X-CSRF-Token"
UNSAFE_METHODS = ("POST", "PUT", "PATCH", "DELETE")
# Bearer-authenticated endpoints: no session cookie, nothing to forge.
EXEMPT_PATHS = frozenset({"/plugins/host_agent/ingest"})
def csrf_token() -> str:
"""This session's token, created on first use."""
token = session.get(SESSION_KEY)
if not token:
token = session[SESSION_KEY] = secrets.token_urlsafe(32)
return token
def csrf_field() -> Markup:
"""The hidden input every POST form carries."""
return Markup(f'<input type="hidden" name="{FORM_FIELD}" value="{escape(csrf_token())}">')
def rotate() -> None:
"""Drop the token, so a new one is issued — at login, where the session
changes hands."""
session.pop(SESSION_KEY, None)
# Forms that send a file past the app's default body limit (16 MiB). This
# check reads the form first, so the limit is raised here, before it does:
# a backup file (settings only is small; an older one carries the audit log).
UPLOAD_LIMITS: dict[str, int] = {
"/settings/backups/check/file/": 512 * 1024 * 1024,
}
async def check_request() -> Response | None:
"""before_request hook: refuse an unsafe request without the session's token."""
if request.method not in UNSAFE_METHODS or request.path in EXEMPT_PATHS:
return None
if request.path in UPLOAD_LIMITS:
request.max_content_length = UPLOAD_LIMITS[request.path]
expected = session.get(SESSION_KEY)
sent = request.headers.get(HEADER, "")
if not sent:
form = await request.form
sent = form.get(FORM_FIELD, "")
if expected and sent and hmac.compare_digest(expected, sent):
return None
return Response(
"This form has expired or did not come from Steward. Reload the page and try again.",
status=400, content_type="text/plain; charset=utf-8")