Enforce auth in the UI, and fix a header bug that would have broken CSRF
web/README.md promised this was "three lines in router.tsx plus deleting the banner". It was nearly true. Every route is now behind RequireAuth: the gallery for any signed-in user, Devices and System for admin (SPEC 3.1). Roles are listed per route rather than granting admin everything implicitly, so widening one route cannot silently widen another - the same reasoning as api/userauth.require_role. The parts the README did not anticipate: A sign-out control. signOut() existed in AuthProvider and nothing called it, which was fine while the app was ungated and is not fine now: enforcing auth without a way to leave strands whoever signs in. It sits in the header with the theme and language switchers, and only renders when there is a session to end. lib/api.ts now carries the CSRF token, and fixing that surfaced a real bug in the scaffold. The fetch options spread `...init` AFTER `headers:`, so any caller passing headers replaced the whole object instead of merging into it. apiPost always sets Content-Type, so Accept was already being dropped on every POST - harmless, and invisible, because the server does not care. It stops being harmless the moment a header has to be there: the CSRF token would have been dropped on exactly the mutating requests that require one, and every POST would have answered 403 with nothing in the client to explain it. `...init` goes first now, with the reason written next to it. RequireAuth no longer shows the login form for the "unavailable" state. That state means the server answered 404 to /auth/session, which now only happens when a newer UI is served by an older server - so offering a form that 404s is the wrong answer. It says the versions do not match instead. auth.notEnforced is deleted from both catalogues rather than left unused, and .banner went with it, since that notice was its only caller. auth.failed was reworded: the server answers every sign-in failure identically - wrong password, unknown user, bad code, deactivated account - so the message has to cover all of them rather than inventing a distinction the server refuses to make. New keys in both en.ts and de.ts, which is enforced at build time. Verified through the Vite dev proxy, which is the path a browser actually takes rather than the one the tests take: 401 signed out, 401 for an admin without a TOTP code, 200 with one, both cookies arriving through the proxy, 403 on logout without the CSRF header with the session still alive after it, 204 with the header, 401 after. And POST /ingest still answers 401 rather than 403, because a camera sends no cookies and must never need a CSRF token. Docs brought in line: web/README.md said authentication was built but not enforced, which is now the opposite of true, and it now also says the two things needed before anyone can sign in - a user, and POORBIRD_SESSION_COOKIE_SECURE=false for plain-http development. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
0c3fb2d837
commit
79ac1d4632
9 files changed
+186
-62
No files matched your search
@@ -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 <p className="muted centered-page">{t("common.loading")}</p>;
|
||||
}
|
||||
|
||||
if (state.status === "unavailable" || state.status === "anonymous") {
|
||||
if (state.status === "anonymous") {
|
||||
return <LoginPage />;
|
||||
}
|
||||
|
||||
// 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 (
|
||||
<div className="centered-page">
|
||||
<p className="alert alert-danger" role="alert">
|
||||
{t("auth.unavailable")}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (roles !== undefined && !can(...roles)) {
|
||||
return (
|
||||
<div className="centered-page">
|
||||
<p className="alert alert-danger">{t("common.error")}</p>
|
||||
<p className="alert alert-danger" role="alert">
|
||||
{t("auth.forbidden")}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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 (
|
||||
<div className="app">
|
||||
@@ -40,17 +47,22 @@ export function AppLayout() {
|
||||
<div className="header-tools">
|
||||
<LanguageSwitcher />
|
||||
<ThemeSwitcher />
|
||||
{/* 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" && (
|
||||
<>
|
||||
<span className="muted signed-in-as">
|
||||
{t("auth.signedInAs", { username: state.user.username })}
|
||||
</span>
|
||||
<button className="button" type="button" onClick={onSignOut}>
|
||||
{t("auth.signOut")}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* 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" && (
|
||||
<p className="banner" role="status">
|
||||
{t("auth.notEnforced")}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<main className="main">
|
||||
<Outlet />
|
||||
</main>
|
||||
|
||||
+5
-4
@@ -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",
|
||||
|
||||
+11
-4
@@ -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",
|
||||
|
||||
+46
-2
@@ -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<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
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.
|
||||
|
||||
+24
-11
@@ -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 <RequireAuth> (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: () => (
|
||||
<RequireAuth>
|
||||
<GalleryPage />
|
||||
</RequireAuth>
|
||||
),
|
||||
});
|
||||
|
||||
const devicesRoute = createRoute({
|
||||
getParentRoute: () => rootRoute,
|
||||
path: "/devices",
|
||||
component: DevicesPage,
|
||||
component: () => (
|
||||
<RequireAuth roles={["admin"]}>
|
||||
<DevicesPage />
|
||||
</RequireAuth>
|
||||
),
|
||||
});
|
||||
|
||||
const systemRoute = createRoute({
|
||||
getParentRoute: () => rootRoute,
|
||||
path: "/system",
|
||||
component: SystemPage,
|
||||
component: () => (
|
||||
<RequireAuth roles={["admin"]}>
|
||||
<SystemPage />
|
||||
</RequireAuth>
|
||||
),
|
||||
});
|
||||
|
||||
const routeTree = rootRoute.addChildren([galleryRoute, devicesRoute, systemRoute]);
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in new issue
Block a user