fix(auth): bind request auth snapshots

This commit is contained in:
2026-08-17 01:11:25 +02:00
parent 94c2cd3709
commit 09e546c1ef
8 changed files with 308 additions and 58 deletions
+54 -28
View File
@@ -1,4 +1,4 @@
import Fastify, { type FastifyInstance } from "fastify";
import Fastify, { type FastifyInstance, type FastifyRequest } from "fastify";
import cors from "@fastify/cors";
import cookie from "@fastify/cookie";
import rateLimit from "@fastify/rate-limit";
@@ -8,11 +8,11 @@ import type { AppConfig } from "./config.js";
import { ThtRunner } from "./tht/tht-runner.js";
import { PiProcessManager } from "./pi/pi-process-manager.js";
import { SseHub } from "./sse/sse-hub.js";
import { authenticateSession } from "./auth/auth.js";
import { authenticateSession, captureAuthConfigSnapshot, configuredOrigin } from "./auth/auth.js";
import type { PrincipalContext } from "./auth/principal.js";
import type { LoadedAuthConfig } from "./auth/types.js";
import { createCurrentLocalUserRegistryResolver, type LocalUserRegistry } from "./auth/local-registry.js";
import { AuthSessionOperationalError, createFileAuthSessionStore, type AuthSessionStore } from "./auth/session-store.js";
import { AuthSessionOperationalError, createFileAuthSessionStore, type AuthSessionStore, type AuthSessionValidity } from "./auth/session-store.js";
import { registerAuthRoutes } from "./auth/routes.js";
import { sessionRoutes } from "./routes/sessions.js";
import { sqlRoutes } from "./routes/sql.js";
@@ -56,6 +56,9 @@ export interface AppWithAuthSessionStore extends FastifyInstance {
export function buildApp(config: AppConfig, deps?: BuildAppDeps): FastifyInstance {
const app = Fastify({ logger: { level: "warn" }, disableRequestLogging: true });
app.decorateRequest("authConfigSnapshot", undefined);
app.decorateRequest("authConfigSnapshotCaptured", false);
app.decorateRequest("authConfigSnapshotUnavailable", false);
const isolatedTestRoot = process.env.VITEST === "true"
? join(tmpdir(), `thothii-workspace-secrets-vitest-${process.pid}`)
: undefined;
@@ -69,19 +72,18 @@ export function buildApp(config: AppConfig, deps?: BuildAppDeps): FastifyInstanc
const cookieAuth = config.authMode === "local" || config.authMode === "oidc";
app.register(cors, {
origin: cookieAuth
? (origin, callback) => {
try {
const allowed = new URL(config.authentication?.current().value.publicUrl ?? "").origin;
const requested = origin === undefined ? undefined : new URL(origin).origin;
callback(null, requested === allowed ? allowed : false);
} catch {
callback(null, false);
}
}
: true,
credentials: cookieAuth,
methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
// The delegator runs at CORS's onRequest hook. It owns the one request-scoped config load
// which subsequent auth hooks and routes consume, including preflights that end here.
delegator: (request, callback) => {
const snapshot = captureAuthConfigSnapshot(request, config.authentication);
const origin = configuredOrigin(snapshot);
const snapshotUsesCookies = snapshot?.value.mode === "local" || snapshot?.value.mode === "oidc";
callback(null, {
origin: snapshotUsesCookies && origin ? corsOrigin(request, origin) : cookieAuth ? false : true,
credentials: snapshotUsesCookies,
methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
});
},
});
// Cookie parsing and the rate-limit plugin must precede every auth/application route.
app.register(cookie);
@@ -167,6 +169,29 @@ export function buildApp(config: AppConfig, deps?: BuildAppDeps): FastifyInstanc
const resolveLocalUserRegistry = (loaded: LoadedAuthConfig) => {
return deps?.localUserRegistry ?? localRegistryResolver?.resolve(loaded);
};
const localUserForSnapshot = async (loaded: LoadedAuthConfig, subject: string) => {
try {
if (loaded.value.mode !== "local") return { revision: loaded.revision, user: undefined };
const registry = resolveLocalUserRegistry(loaded);
if (!registry) throw new AuthSessionOperationalError();
const user = await registry.findBySubject(subject);
return {
revision: loaded.revision,
user: user === undefined ? undefined : {
enabled: user.enabled,
authRevision: user.authRevision,
roles: user.roles,
},
};
} catch (error) {
if (error instanceof AuthSessionOperationalError) throw error;
throw new AuthSessionOperationalError();
}
};
const sessionValidityForSnapshot = (loaded: LoadedAuthConfig): AuthSessionValidity => ({
currentAuthConfigRevision: () => loaded.revision,
currentLocalUser: (subject) => localUserForSnapshot(loaded, subject),
});
const authSessionStore = deps?.authSessionStore ?? (config.authMode === "local" || config.authMode === "oidc"
? createFileAuthSessionStore(config.authStateRoot, {
currentAuthConfigRevision: () => {
@@ -179,18 +204,8 @@ export function buildApp(config: AppConfig, deps?: BuildAppDeps): FastifyInstanc
currentLocalUser: async (subject) => {
try {
const loaded = config.authentication?.current();
if (!loaded || loaded.value.mode !== "local") return { revision: "", user: undefined };
const registry = resolveLocalUserRegistry(loaded);
if (!registry) throw new AuthSessionOperationalError();
const user = await registry.findBySubject(subject);
return {
revision: loaded.revision,
user: user === undefined ? undefined : {
enabled: user.enabled,
authRevision: user.authRevision,
roles: user.roles,
},
};
if (!loaded) return { revision: "", user: undefined };
return await localUserForSnapshot(loaded, subject);
} catch (error) {
if (error instanceof AuthSessionOperationalError) throw error;
throw new AuthSessionOperationalError();
@@ -204,6 +219,7 @@ export function buildApp(config: AppConfig, deps?: BuildAppDeps): FastifyInstanc
publicExposure: config.publicExposure,
authentication: config.authentication,
sessionStore: authSessionStore,
sessionValidityForSnapshot,
});
app.addHook("preHandler", (req, reply, done) => {
if (isMaintenanceControl(req.url)) {
@@ -284,6 +300,16 @@ export function buildApp(config: AppConfig, deps?: BuildAppDeps): FastifyInstanc
return app;
}
function corsOrigin(request: FastifyRequest, expectedOrigin: string): string | false {
const supplied = request.headers.origin;
if (typeof supplied !== "string") return false;
try {
return new URL(supplied).origin === expectedOrigin ? expectedOrigin : false;
} catch {
return false;
}
}
function isLoopback(ip: string): boolean { return ip === "127.0.0.1" || ip === "::1" || ip === "::ffff:127.0.0.1"; }
function isMaintenanceControl(url: string): boolean {
return /^\/internal\/maintenance\/(?:activate|deactivate|status)(?:\?|$)/.test(url);