Files
spencermandClaude Fable 5.1 97b0973130 Phase 1: identity, sessions, audit, frontend shell
AD sign-in over LDAPS (search with the service account, bind as the user,
nested groups through LDAP_MATCHING_RULE_IN_CHAIN, disabled accounts refused),
roles as the union of PS-* groups mapped by a table derived from the seeded
departments. Server-side sessions with idle, lock and absolute timeouts, Origin
and X-Requested-With check, step-up unlock. Optional Argon2id PIN set with the
domain password; PIN sign-in by employee ID on registered devices only; five
wrong attempts disable the PIN, three wrong at unlock or signature end the
session. Rate limits per account and per address before any bind. Devices,
signatures table and sign helper, audit rows for every identity event, SSE over
LISTEN/NOTIFY with presence. Account settings and Admin APIs and screens
(AD view, devices, PIN clearing, group map with missing-group flags, refresh
from AD now). CLI ad-groups --list and ad-refresh. Migration 0002.

Frontend: real sign-in (password tab, PIN keypad on registered devices), lock
screen, role switcher, Account settings, Admin shell, screen placeholders.

CI: Samba AD DC container (PSTEST.LOCAL) with a generated CA, 49 of the 50
groups plus one extra, 17 test users; wired into the CI compose overlay and
the Gitea workflow; Playwright sign-in scenario.

Verified on docker-1: 171 server tests green inside the CI stack against
PostgreSQL and the Samba DC, 48 frontend tests, 8 Playwright scenarios against
the live stack (password and PIN sign-in, lock and unlock, Admin group map).
Findings recorded in the docs: the DC needs CAP_SYS_ADMIN, a hidden tab locks
only after a minute as the old build did,
and the app uses the alias ps-app for Playwright because "app" is on
Chromium's HSTS preload list.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-10-16 07:40:29 -06:00

65 lines
2.2 KiB
Python

"""Origin check for state-changing API requests (CSRF defence on top of SameSite=Strict cookies)."""
from __future__ import annotations
import json
from urllib.parse import urlsplit
from starlette.types import ASGIApp, Receive, Scope, Send
UNSAFE = frozenset({"POST", "PUT", "PATCH", "DELETE"})
MARKER = "PacketStation"
REFUSED = {"detail": "Cross-origin request refused", "code": "bad_origin"}
def _origin_of(url: str) -> str | None:
try:
parts = urlsplit(url)
except ValueError:
return None
if not parts.scheme or not parts.netloc:
return None
return f"{parts.scheme}://{parts.netloc}".lower()
def allowed(scope: Scope) -> bool:
"""True when the request is safe, not under /api, or carries a same-origin Origin and the marker header."""
if scope.get("method", "GET").upper() not in UNSAFE or not scope.get("path", "").startswith("/api"):
return True
headers = {k.decode("latin-1").lower(): v.decode("latin-1") for k, v in scope.get("headers", [])}
if headers.get("x-requested-with", "") != MARKER:
return False
host = headers.get("host", "").strip().lower()
if not host:
return False
expected = f"{scope.get('scheme', 'http')}://{host}"
origin = headers.get("origin")
if origin and origin != "null":
got = _origin_of(origin)
elif headers.get("referer"):
got = _origin_of(headers["referer"])
else:
got = None
return got == expected
class OriginCheckMiddleware:
"""Runs after TrustedProxyMiddleware so the scheme is the client's."""
def __init__(self, app: ASGIApp):
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http" or allowed(scope):
await self.app(scope, receive, send)
return
body = json.dumps(REFUSED).encode("utf-8")
await send(
{
"type": "http.response.start",
"status": 403,
"headers": [(b"content-type", b"application/json"), (b"content-length", str(len(body)).encode())],
}
)
await send({"type": "http.response.body", "body": body})