Files
PacketStation/server/packetstation/api/errors.py
T
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

69 lines
2.2 KiB
Python

"""Every API error is JSON `{"detail": "<message>", "code": "<snake_code>"}`, with extra fields when useful."""
from __future__ import annotations
from typing import Any
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
HTTP_CODES = {
400: "bad_request",
401: "no_session",
403: "forbidden",
404: "not_found",
405: "method_not_allowed",
409: "conflict",
413: "too_large",
429: "rate_limited",
503: "unavailable",
}
class ApiError(Exception):
def __init__(
self,
status: int,
code: str,
detail: str,
*,
headers: dict[str, str] | None = None,
extra: dict[str, Any] | None = None,
):
super().__init__(detail)
self.status = status
self.code = code
self.detail = detail
self.headers = headers or {}
self.extra = extra or {}
def body(self) -> dict[str, Any]:
return {"detail": self.detail, "code": self.code, **self.extra}
def error_response(err: ApiError) -> JSONResponse:
return JSONResponse(err.body(), status_code=err.status, headers=err.headers)
def install(app: FastAPI) -> None:
@app.exception_handler(ApiError)
async def _api_error(_: Request, exc: ApiError) -> JSONResponse:
return error_response(exc)
@app.exception_handler(RequestValidationError)
async def _invalid(_: Request, exc: RequestValidationError) -> JSONResponse:
errors = [{"loc": [str(x) for x in e.get("loc", ())], "msg": str(e.get("msg", ""))} for e in exc.errors()]
where = ", ".join(".".join(e["loc"][1:]) or e["loc"][0] for e in errors if e["loc"]) or "request"
return JSONResponse(
{"detail": f"Invalid request: {where}", "code": "invalid_request", "errors": errors}, status_code=422
)
@app.exception_handler(StarletteHTTPException)
async def _http(_: Request, exc: StarletteHTTPException) -> JSONResponse:
code = HTTP_CODES.get(exc.status_code, "http_error")
return JSONResponse(
{"detail": str(exc.detail), "code": code}, status_code=exc.status_code, headers=exc.headers or None
)