dorfteich/apps/api/src/auth/auth.guard.ts
Claude Fable 5 13f0311d8e
Some checks failed
CI / Lint, typecheck, test (pull_request) Successful in 6m55s
CI / Build container images (pull_request) Successful in 4m43s
CI / Auth e2e pack (pull_request) Successful in 9m13s
CI / Import/export fidelity gate (pull_request) Successful in 1m4s
CD / Deploy to Test (push) Blocked by required conditions
CD / Smoke tests against Test (push) Blocked by required conditions
CD / Promote to Int (push) Blocked by required conditions
CI / Auth e2e pack (push) Blocked by required conditions
CI / Import/export fidelity gate (push) Blocked by required conditions
CI / Build container images (push) Blocked by required conditions
CI / Lint, typecheck, test (push) Has been cancelled
CD / Build and push images (push) Has been cancelled
#216: hard AUTH_LOCAL_ENABLED switch over every local credential flow
The deploy-level realization of auth.local.enabled (ADR 0021): FALSE
answers 404 on every local credential flow — login, signup, e-mail
verification, resend, password forgot/reset/change — enforced centrally
in the auth guard via the @LocalCredentialFlow() marker before any
session or CSRF logic runs. Deploy-level on purpose: a compromised Site
Admin cannot reopen the local path, so the runtime-flip residual risk
from ADR 0021 does not materialize (R-02 closed in the risk list).

An enumeration fence fails when an auth route is neither marked nor on
the reviewed allowlist, so a new credential flow cannot ship unswitched.
Stated decisions, each tested: sessions/logout keep working for
externally authenticated users; PAT and feed-token issuance stays
available (API authorization under its own switches, not interactive
sign-in). Bootstrap: complete setup (or SETUP_ADMIN_* pre-seed) before
flipping; the api warns at boot when local auth is off with neither OIDC
nor proxy auth configured. GET /auth/methods reports local:false and the
login page hides the local form and credential links.

Hardening guide: the planned auth.local.enabled row moves from 1.3 into
the live deploy table with the bootstrap ordering, and the verification
checklist gains the login-404 probe.

Refs #216.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AUtYMxwTCMHG9mVHnwbFg8
2026-07-31 12:58:07 +02:00

176 lines
6.3 KiB
TypeScript

import {
CanActivate,
ExecutionContext,
ForbiddenException,
Injectable,
NotFoundException,
SetMetadata,
UnauthorizedException,
createParamDecorator,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import type { CurrentUser as CurrentUserShape } from '@dorfteich/shared';
import type { User } from '@prisma/client';
import type { Request, Response } from 'express';
import { AppConfig } from '../config/app-config.service';
import { ProxyIdentityService } from './proxy-identity.service';
import { SessionsService } from './sessions.service';
export const SESSION_COOKIE = 'dt_session';
const IS_PUBLIC_KEY = 'isPublic';
/** Marks a route as reachable without a session (login, signup, healthz…). */
export const Public = (): MethodDecorator & ClassDecorator => SetMetadata(IS_PUBLIC_KEY, true);
export const LOCAL_CREDENTIAL_KEY = 'isLocalCredentialFlow';
/**
* Marks a route as part of the LOCAL credential machinery (issue #216,
* ADR 0021): password login, signup, e-mail verification, password
* forgot/reset/change. With `AUTH_LOCAL_ENABLED=false` every marked route
* answers 404 (existence hidden, the switch precedent) — and the
* enumeration fence in `local-auth-switch.e2e.db.test.ts` fails when an
* auth route is neither marked nor on its reviewed allowlist, so a new
* credential flow cannot ship unswitched by accident.
*/
export const LocalCredentialFlow = (): MethodDecorator => SetMetadata(LOCAL_CREDENTIAL_KEY, true);
export interface AuthedRequest extends Request {
user?: User;
sessionId?: string;
sessionToken?: string;
}
/** Injects the authenticated Prisma user into a handler parameter. */
export const CurrentUser = createParamDecorator((_data: unknown, context: ExecutionContext) => {
return context.switchToHttp().getRequest<AuthedRequest>().user;
});
export function toCurrentUser(user: User): CurrentUserShape {
return {
id: user.id,
username: user.username,
email: user.email,
displayName: user.displayName,
locale: user.locale === 'de' ? 'de' : 'en',
isSiteAdmin: user.isSiteAdmin,
autoWatchOwnPages: user.autoWatchOwnPages,
autoWatchOnComment: user.autoWatchOnComment,
digestFrequency:
user.digestFrequency === 'daily' || user.digestFrequency === 'off'
? user.digestFrequency
: 'hourly',
};
}
/**
* Session cookie contract shared by login and the setup wizard (issue #80).
* `maxAgeMs` follows the configured absolute session bound (#190) — the
* server-side idle/absolute checks are authoritative, the cookie merely
* stops outliving them.
*/
export function setSessionCookie(
response: Response,
token: string,
production: boolean,
maxAgeMs: number,
): void {
response.cookie(SESSION_COOKIE, token, {
httpOnly: true,
sameSite: 'lax',
secure: production,
maxAge: maxAgeMs,
path: '/',
});
}
const MUTATING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
/**
* Global authentication guard: routes are protected by default and opt
* out with @Public(). Also enforces the CSRF origin check on mutating
* requests that carry a session cookie — SameSite=Lax is the first line
* of defense, this is the second (security.md).
*/
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private readonly reflector: Reflector,
private readonly sessions: SessionsService,
private readonly config: AppConfig,
private readonly proxyIdentity: ProxyIdentityService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<AuthedRequest>();
// The hard local-auth switch (issue #216): marked credential routes
// disappear entirely — before any session or CSRF logic runs.
if (!this.config.env.AUTH_LOCAL_ENABLED) {
const isLocalFlow = this.reflector.getAllAndOverride<boolean>(LOCAL_CREDENTIAL_KEY, [
context.getHandler(),
context.getClass(),
]);
if (isLocalFlow) throw new NotFoundException();
}
const rawToken = (request.cookies as Record<string, string> | undefined)?.[SESSION_COOKIE];
if (rawToken && MUTATING_METHODS.has(request.method)) {
this.assertSameOrigin(request);
}
// Trusted-proxy identity first (issue #215): when the perimeter
// authenticates, its header IS the identity for this request — a
// session cookie riding along never escalates beyond it, and an
// untrusted peer carrying the header is rejected inside resolve().
const proxyUser = await this.proxyIdentity.resolve(request);
if (proxyUser) {
request.user = proxyUser;
} else if (rawToken) {
// Attach the user whenever the cookie is valid — public routes may
// still want to know who is asking.
const validated = await this.sessions.validate(rawToken);
if (validated) {
request.user = validated.user;
request.sessionId = validated.session.id;
request.sessionToken = rawToken;
}
}
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
]);
if (isPublic) return true;
if (!request.user) throw new UnauthorizedException();
return true;
}
/**
* Fail closed (#189): a cookie-carrying mutation must prove its origin —
* browsers always send `Origin` on cross- and same-origin mutations, so a
* missing header means "not a browser page of ours" and is rejected like a
* mismatch. Non-browser clients (curl, scripts) either send a matching
* `Origin` explicitly or authenticate with a PAT/bearer token and no
* cookie, which never reaches this check — the exception for them is
* structural (bound to the cookie), never a header loophole.
*/
private assertSameOrigin(request: Request): void {
const origin = request.headers.origin ?? request.headers.referer;
if (!origin) throw new ForbiddenException({ code: 'csrf_origin_mismatch' });
const expected = new URL(this.config.env.APP_BASE_URL).origin;
let actual: string;
try {
actual = new URL(origin).origin;
} catch {
// An unparsable Origin/Referer is a broken or hostile client, not ours.
throw new ForbiddenException({ code: 'csrf_origin_mismatch' });
}
if (actual !== expected) {
throw new ForbiddenException({ code: 'csrf_origin_mismatch' });
}
}
}