diff --git a/TODO.md b/TODO.md index 47f7df1..db70982 100644 --- a/TODO.md +++ b/TODO.md @@ -162,9 +162,10 @@ and the System page reads live data through the Vite proxy. - [x] Three themes as design tokens, `data-theme` on ``, no flash of the wrong theme - [x] `npm run check:contrast` — asserts WCAG AA across all three themes; caught three failing `--border-strong` values on its first run - [x] i18n de/en with a build-time-complete catalogue -- [x] Auth shell: provider, login form with TOTP field, `RequireAuth` — **written, deliberately not enforcing** (no endpoints yet, and no dev bypass on purpose) +- [x] Auth shell: provider, login form with TOTP field, `RequireAuth` (no dev bypass, on purpose) - [x] System page on live `/health` — the end-to-end proof browser → proxy → FastAPI → Postgres -- [ ] Wire `RequireAuth` into `router.tsx` and delete the "not enforced" banner, once `/auth/*` exists +- [x] Wire `RequireAuth` into `router.tsx` and delete the "not enforced" banner — gallery needs + any signed-in user, Devices and System need `admin`. Sign-out is in the header. - [ ] ESLint (skipped during scaffolding; `tsc --noEmit` covers the important cases for now) - [ ] Virtualised gallery grid; filters for date range, taxon, device, tag, reviewed, kept - [ ] Observation editor — `captures` 1—n `observations`, so a photo can hold two species or none @@ -172,9 +173,16 @@ and the System page reads live data through the Vite proxy. - [ ] Tags, favourite/reject (`kept`), review flag - [ ] Persist the theme choice **per user** (`users.theme`) rather than in localStorage — the tokens and the switcher are done (above); this is the half that needs accounts to exist -- [ ] Auth: session cookies, Argon2id, CSRF, RBAC per SPEC §3.1 (viewer / editor / admin), `audit_log` on every mutation +- [x] Auth: session cookies, Argon2id, CSRF, RBAC per SPEC §3.1 (viewer / editor / admin), + `audit_log` on login, failed login and logout. Sessions are rows, so logout is immediate; + only the SHA-256 of the cookie is stored; CSRF is bound to the session, not just + double-submitted. Accounts come from `poorbird user add` — there is no sign-up endpoint. +- [ ] Extend `audit_log` to the *content* mutations (observations, tags, device config) as each + endpoint lands. Auth events are covered; nothing else writes to it yet. - [ ] **Auth-checked image serving** — the app authorizes, Caddy serves the bytes. An unguessable URL is not access control -- [ ] TOTP 2FA — see 3.0 for the policy +- [x] TOTP 2FA — enforced at account creation for `admin` rather than at login, because a + login-time check can lock the only admin out of their own account. Codes required whenever + the account has a secret. Replay inside the ~90s window is documented, not closed. - [ ] **Revisit CORS.** Deliberately not configured in Phase 2: Caddy serves the built UI and the API from one origin, so there is no cross-origin request to permit, and adding permissive headers "for the UI" would only weaken that. The Vite dev server proxies `/api` for the diff --git a/web/README.md b/web/README.md index 83aa6fb..b95162a 100644 --- a/web/README.md +++ b/web/README.md @@ -15,6 +15,22 @@ too (see [`../server/README.md`](../server/README.md)). Both must be running or the System page shows "cannot reach the server", which is the honest answer rather than a blank screen. +**Two things the server side needs before you can sign in:** + +```bash +cd ../server +# 1. Secure cookies are dropped over plain http, and this dev server is http. +# Without this, login returns 200 and you are never signed in. +echo 'POORBIRD_SESSION_COOKIE_SECURE=false' >> .env + +# 2. There is no sign-up page. Accounts are created on the server. +.venv/Scripts/poorbird user add me --role admin +``` + +`--role admin` enables TOTP and prints an `otpauth://` URI once — scan it +before pressing on, because the app will ask for a code and the URI is not +shown again. `--no-totp` skips it and says why that is a bad idea. + | Script | Does | |---|---| | `npm run dev` | Vite dev server with HMR | @@ -29,26 +45,28 @@ answer rather than a blank screen. ## What is real and what is not -Only `GET /api/v1/health` exists on the server today, so only the **System** -page shows live data. It is the end-to-end proof: browser → Vite proxy → -FastAPI → PostgreSQL. +**Authentication is real and enforced.** `/auth/session`, `/auth/login` and +`/auth/logout` exist, so every route is now behind `RequireAuth`: + +- the gallery needs any signed-in user; **Devices and System need `admin`** + (SPEC §3.1), so a `viewer` account sees a "no access" message there +- TOTP is required whenever the account has a secret, which `user add --role + admin` sets up by default +- signing out is in the header, next to the theme and language switchers +- **there is still no development bypass**, and there never was one — a bypass + that works is the kind of code that survives into production + +The guard here decides what to *render*. It is not access control: the server +authorises every request on its own, and deleting `RequireAuth.tsx` would +expose no data, it would only render pages whose requests then 401. + +**Only `GET /health` and `/auth/*` return real data.** So the **System** page +shows live values and the others do not yet: Gallery and Devices render an honest empty state. They are deliberately not filled with mock rows — fake data hides exactly the layout problems that real -data exposes, and Phase 2 is what brings real captures. - -**Authentication is built but not enforced.** `/auth/session`, `/auth/login` -and `/auth/logout` are Phase 3 server work and do not exist yet. So: - -- `AuthProvider` and `RequireAuth` are written and typechecked -- `router.tsx` does **not** wrap routes in `RequireAuth` yet, and says why -- a banner in the layout states plainly that sign-in is not enforced -- **there is no development bypass**, on purpose — a bypass that works is the - kind of code that survives into production, and an auth bypass that works is - the worst possible bug - -Wiring it up when the endpoints land is three lines in `router.tsx` plus -deleting the banner. +data exposes. The capture and device listing endpoints are the next server +work; the six captures already in the dev database have nothing to serve them. --- @@ -64,6 +82,12 @@ tokens, which is what makes a fourth theme a single CSS block. Run `npm run check:contrast` after touching any colour — it caught three failing `--border-strong` values the first time it ran. +**`lib/api.ts` is the only place that calls `fetch`,** and the only place that +knows about CSRF. It reads the `poorbird_csrf` cookie and echoes it in +`X-CSRF-Token` on every POST/PUT/PATCH/DELETE; the server compares it against +the token stored on the session row. A new mutating call needs nothing extra, +which is the point of there being one such place. + **Themes** are `data-theme` on ``: `light`, `dark`, `blue` (dark navy). An inline script in `index.html` applies the stored choice before first paint to avoid a flash of the wrong theme; it must stay in sync with diff --git a/web/src/auth/RequireAuth.tsx b/web/src/auth/RequireAuth.tsx index 9d49344..cca8578 100644 --- a/web/src/auth/RequireAuth.tsx +++ b/web/src/auth/RequireAuth.tsx @@ -5,13 +5,14 @@ import { LoginPage } from "./LoginPage"; import { useAuth } from "./AuthProvider"; import type { Role } from "./AuthProvider"; -/* Route guard. Written now, wired in when Phase 3 lands the endpoints -- - * see router.tsx for why it is not used yet. +/* Route guard, now wired into router.tsx. * * This is the client-side half only. It decides what to *render*; it is not * access control. The server authorises every request independently, and the * image bytes go through the auth-checked handoff (SPEC 3.3), because an - * unguessable URL is not access control either. */ + * unguessable URL is not access control either. Deleting this file would + * expose no data -- it would only make the app render pages whose requests + * then 401. */ export function RequireAuth({ children, roles, @@ -27,14 +28,29 @@ export function RequireAuth({ return

{t("common.loading")}

; } - if (state.status === "unavailable" || state.status === "anonymous") { + if (state.status === "anonymous") { return ; } + // Now that /auth/* exists this should not happen. When it does, it means a + // newer UI is being served by an older server, so showing the login form + // would be offering a form that 404s. Say what is actually wrong instead. + if (state.status === "unavailable") { + return ( +
+

+ {t("auth.unavailable")} +

+
+ ); + } + if (roles !== undefined && !can(...roles)) { return (
-

{t("common.error")}

+

+ {t("auth.forbidden")} +

); } diff --git a/web/src/components/AppLayout.tsx b/web/src/components/AppLayout.tsx index 026ba86..407dfed 100644 --- a/web/src/components/AppLayout.tsx +++ b/web/src/components/AppLayout.tsx @@ -7,7 +7,14 @@ import { ThemeSwitcher } from "./ThemeSwitcher"; export function AppLayout() { const t = useT(); - const { state } = useAuth(); + const { state, signOut } = useAuth(); + + // Signing out clears the cookies server-side and the cached session here. + // A failure is not worth interrupting anyone for: the button is pressed + // again, or the session expires on its own. + function onSignOut() { + void signOut(); + } return (
@@ -40,17 +47,22 @@ export function AppLayout() {
+ {/* Only once there is a session to end. Rendering it while signed + out would be a button that does nothing, and the login form is + already the whole page in that state. */} + {state.status === "authenticated" && ( + <> + + {t("auth.signedInAs", { username: state.user.username })} + + + + )}
- {/* Visible for as long as the app is ungated. It disappears by - deleting this block when RequireAuth is wired into the router. */} - {state.status !== "authenticated" && ( -

- {t("auth.notEnforced")} -

- )} -
diff --git a/web/src/i18n/de.ts b/web/src/i18n/de.ts index 880ab12..df99b18 100644 --- a/web/src/i18n/de.ts +++ b/web/src/i18n/de.ts @@ -27,17 +27,18 @@ export const de: Catalogue = { "lang.en": "Englisch", "lang.de": "Deutsch", - "auth.notEnforced": - "Die Anmeldung ist noch nicht aktiv — die Auth-Endpunkte kommen in Phase 3.", "auth.signIn": "Anmelden", + "auth.signOut": "Abmelden", + "auth.signedInAs": "Angemeldet als {username}", "auth.username": "Benutzername", "auth.password": "Passwort", "auth.totp": "Bestätigungscode", "auth.totpHint": "Sechs Ziffern aus deiner Authenticator-App", "auth.signingIn": "Anmeldung läuft…", - "auth.failed": "Anmeldung fehlgeschlagen. Benutzername und Passwort prüfen.", + "auth.failed": "Anmeldung fehlgeschlagen. Benutzername, Passwort und Code prüfen.", + "auth.forbidden": "Dein Konto hat keinen Zugriff auf diese Seite.", "auth.unavailable": - "Den Anmelde-Endpunkt gibt es noch nicht. Diese Seite ist die Hülle dafür.", + "Dieser Server hat keinen Anmelde-Endpunkt. UI- und Server-Version passen nicht zusammen.", "gallery.title": "Galerie", "gallery.empty.title": "Noch keine Aufnahmen", diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts index c14a633..fbf19db 100644 --- a/web/src/i18n/en.ts +++ b/web/src/i18n/en.ts @@ -27,17 +27,24 @@ export const en = { "lang.en": "English", "lang.de": "German", - "auth.notEnforced": - "Sign-in is not enforced yet — the auth endpoints arrive in Phase 3.", "auth.signIn": "Sign in", + "auth.signOut": "Sign out", + "auth.signedInAs": "Signed in as {username}", "auth.username": "Username", "auth.password": "Password", "auth.totp": "Authentication code", "auth.totpHint": "Six digits from your authenticator app", "auth.signingIn": "Signing in…", - "auth.failed": "Sign-in failed. Check your username and password.", + // The server answers every sign-in failure identically, so this message has + // to cover all of them: wrong password, unknown user, wrong or missing + // authentication code, deactivated account. Being more specific here would + // invent a distinction the server deliberately refuses to make. + "auth.failed": "Sign-in failed. Check your username, password and code.", + "auth.forbidden": "Your account does not have access to this page.", + // Should now be unreachable: /auth/* exists. Kept for the one case that + // still produces it -- a new UI build served against an older server. "auth.unavailable": - "The sign-in endpoint does not exist yet. This screen is the shell it will use.", + "This server has no sign-in endpoint. The UI and the server versions do not match.", "gallery.title": "Gallery", "gallery.empty.title": "No captures yet", diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index 6a39efe..4ff3fa1 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -23,13 +23,57 @@ export class ApiError extends Error { } } +/* CSRF, the browser half. + * + * The server sets `poorbird_csrf` as a readable cookie alongside the HttpOnly + * session cookie, and requires this header to match the token on the session + * row for every mutating request. Reading a cookie is exactly what an attacker + * on another origin cannot do, which is what makes echoing it meaningful. + * + * Deliberately read fresh on each call rather than cached: signing out and back + * in issues a new token, and a stale one in a module variable would produce a + * 403 that looks like a server bug. */ +const CSRF_COOKIE = "poorbird_csrf"; + +/** Methods the server requires a CSRF token for. Must match UNSAFE_METHODS. */ +const UNSAFE = new Set(["POST", "PUT", "PATCH", "DELETE"]); + +function csrfToken(): string | null { + // document.cookie is a flat "a=1; b=2" string; there is no read API for one + // cookie. Split rather than regex so a token containing no special + // characters cannot be mangled by an over-clever pattern. + for (const part of document.cookie.split("; ")) { + const eq = part.indexOf("="); + if (eq > 0 && part.slice(0, eq) === CSRF_COOKIE) { + return decodeURIComponent(part.slice(eq + 1)); + } + } + return null; +} + async function request(path: string, init?: RequestInit): Promise { + const method = (init?.method ?? "GET").toUpperCase(); + const csrf = UNSAFE.has(method) ? csrfToken() : null; + let response: Response; try { response = await fetch(`/api/v1${path}`, { - credentials: "same-origin", - headers: { Accept: "application/json", ...init?.headers }, + // `...init` FIRST, then the values that must win. It used to come last, + // which meant a caller passing any headers at all replaced this whole + // object rather than merging into it -- so apiPost, which always sets + // Content-Type, was silently dropping Accept. Harmless then. Not + // harmless now: it would have dropped the CSRF header on exactly the + // mutating requests that require one, and every POST would answer 403. ...init, + credentials: "same-origin", + headers: { + Accept: "application/json", + // Omitted when there is no cookie, which is the case for the very + // first request of all: logging in. The server exempts it for the + // same reason -- there is no session to protect yet. + ...(csrf === null ? {} : { "X-CSRF-Token": csrf }), + ...init?.headers, + }, }); } catch (cause) { // fetch only rejects on a network-level failure: server down, DNS, CORS. diff --git a/web/src/router.tsx b/web/src/router.tsx index 95c067a..2e5373e 100644 --- a/web/src/router.tsx +++ b/web/src/router.tsx @@ -11,6 +11,7 @@ import { createRouter, } from "@tanstack/react-router"; +import { RequireAuth } from "./auth/RequireAuth"; import { AppLayout } from "./components/AppLayout"; import { DevicesPage } from "./pages/DevicesPage"; import { GalleryPage } from "./pages/GalleryPage"; @@ -18,31 +19,43 @@ import { SystemPage } from "./pages/SystemPage"; const rootRoute = createRootRoute({ component: AppLayout }); -/* NOT GATED YET. +/* Every route is gated. This is the client-side half only -- it decides what + * to render, and the server authorises each request independently. A guard + * here that the server did not also enforce would be decoration. * - * Once Phase 3 lands /auth/session, /auth/login and /auth/logout, wrap these - * components in (and pass `roles={["admin"]}` for the device - * and system routes, per SPEC 3.1). The component is written and waiting in - * auth/RequireAuth.tsx. - * - * Doing it now would leave the app unusable behind a login form that cannot - * succeed, so instead it is ungated and says so in a banner. */ + * Roles follow SPEC 3.1: the gallery is what a viewer is for, while devices + * and system expose operational state and belong to admins. Listing the roles + * per route rather than granting admin everything implicitly means widening + * one route cannot silently widen another -- the same reasoning as + * api/userauth.require_role. */ const galleryRoute = createRoute({ getParentRoute: () => rootRoute, path: "/", - component: GalleryPage, + component: () => ( + + + + ), }); const devicesRoute = createRoute({ getParentRoute: () => rootRoute, path: "/devices", - component: DevicesPage, + component: () => ( + + + + ), }); const systemRoute = createRoute({ getParentRoute: () => rootRoute, path: "/system", - component: SystemPage, + component: () => ( + + + + ), }); const routeTree = rootRoute.addChildren([galleryRoute, devicesRoute, systemRoute]); diff --git a/web/src/styles/global.css b/web/src/styles/global.css index 62cced8..10125f5 100644 --- a/web/src/styles/global.css +++ b/web/src/styles/global.css @@ -121,16 +121,15 @@ code, .header-tools { display: flex; + align-items: center; gap: var(--space-2); } -.banner { - margin: 0; - padding: var(--space-2) var(--space-4); - background: var(--accent-subtle); - color: var(--text); - border-bottom: 1px solid var(--border); +/* Replaced .banner, which existed only for the "sign-in is not enforced" + notice and went away with it. */ +.signed-in-as { font-size: var(--text-sm); + white-space: nowrap; } .main {