Files
PacketStation/server/packetstation/main.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

150 lines
5.3 KiB
Python

"""The FastAPI app. `packetstation.main:app` is built on first access so imports need no settings."""
from __future__ import annotations
import asyncio
import contextlib
import logging
from collections.abc import AsyncIterator
from pathlib import Path
from typing import Any
from fastapi import FastAPI
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response
from starlette.concurrency import run_in_threadpool
from . import db, guard
from .api import errors as api_errors
from .api.origin import OriginCheckMiddleware
from .auth.ldap import DirectoryProtocol
from .events import EventHub
from .proxy import TrustedProxies, TrustedProxyMiddleware
from .security import RequestLogMiddleware, SecurityHeadersMiddleware
from .settings import Settings, get_settings
log = logging.getLogger(__name__)
PLACEHOLDER = """<!doctype html>
<html lang="en"><head><meta charset="utf-8"><title>Packet Station</title></head>
<body><h1>Packet Station</h1><p>The web client is not built into this image (STATIC_DIR missing).</p></body></html>
"""
NO_FALLBACK = ("api", "_blob")
def _static_file(static_dir: Path, path: str) -> Path | None:
"""The file under static_dir for a URL path, or None. Never escapes static_dir."""
if not path:
return None
root = static_dir.resolve()
candidate = (root / path).resolve()
if not candidate.is_relative_to(root) or not candidate.is_file():
return None
return candidate
def _load_departments(s: Settings) -> None:
"""Rebuild the group map from the departments table; the built-in seed stays when the DB is not there."""
from .auth import groups
try:
with db.connect_as("app", s, autocommit=True) as conn:
deps = groups.load_departments(conn)
except Exception as e:
log.warning("group map from the built-in departments (database: %s)", type(e).__name__)
return
if deps:
groups.use_departments(deps)
def create_app(
settings: Settings | None = None, *, run_guard: bool = True, directory: DirectoryProtocol | None = None
) -> FastAPI:
s = settings or get_settings()
if run_guard:
guard.startup_checks(s)
trusted = TrustedProxies(s.trusted_proxy_host)
hub = EventHub(connect=lambda: db.connect_as("app", s, autocommit=True))
@contextlib.asynccontextmanager
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
await asyncio.to_thread(trusted.refresh)
task = asyncio.create_task(trusted.run()) if trusted.host else None
deps_task = asyncio.create_task(asyncio.to_thread(_load_departments, s))
hub.start() # connects in its own thread and retries with backoff; never blocks startup
log.info("packetstation app starting", extra={"ps": {"build": s.ps_build, "stack": s.stack}})
try:
yield
finally:
if task:
task.cancel()
deps_task.cancel()
await asyncio.to_thread(hub.stop)
await run_in_threadpool(db.close_pool)
app = FastAPI(
title="Packet Station", version=s.ps_build, lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None
)
app.state.settings = s
app.state.trusted = trusted
app.state.directory = directory # None: built from settings on first use
app.state.events = hub
app.state.session_key = None
app.state.groups_cache = None
api_errors.install(app)
from .api import account, admin, auth, departments
from .api import events as events_api
for module in (auth, account, admin, departments, events_api):
app.include_router(module.router)
@app.get("/healthz")
def healthz() -> dict[str, Any]:
return {"ok": True, "build": s.ps_build}
@app.get("/api/version")
def version() -> dict[str, Any]:
return {"build": s.ps_build, "stack": s.stack, "site_tz": s.site_tz}
@app.get("/api/db-health")
def db_health() -> Response:
try:
db.ping(s)
except db.DatabaseUnavailable:
log.warning("db-health: database unavailable")
return JSONResponse({"ok": False, "error": "database unavailable"}, status_code=503)
return JSONResponse({"ok": True})
@app.api_route("/{path:path}", methods=["GET", "HEAD"], include_in_schema=False)
def static(path: str) -> Response:
if path.split("/", 1)[0] in NO_FALLBACK:
return JSONResponse({"detail": "Not Found"}, status_code=404)
static_dir = s.static_dir
index = static_dir / "index.html"
if not index.is_file():
return HTMLResponse(PLACEHOLDER)
found = _static_file(static_dir, path)
if found is not None:
return FileResponse(found)
return FileResponse(index, headers={"Cache-Control": "no-cache"})
# Last added runs first: proxy rewrite, then the log (sees the real ip), then headers, then the Origin check
app.add_middleware(OriginCheckMiddleware)
app.add_middleware(SecurityHeadersMiddleware)
app.add_middleware(RequestLogMiddleware, build=s.ps_build)
app.add_middleware(TrustedProxyMiddleware, trusted=trusted)
return app
_app: FastAPI | None = None
def __getattr__(name: str) -> Any:
global _app
if name == "app":
if _app is None:
_app = create_app()
return _app
raise AttributeError(name)