dorfteich/apps/api/src/auth/auth.guard.ts
Claude Fable 5 4c7f001cab
Some checks failed
CI / Lint, typecheck, test (pull_request) Successful in 6m44s
CI / Build container images (pull_request) Successful in 4m42s
CI / Auth e2e pack (pull_request) Successful in 9m15s
CI / Import/export fidelity gate (pull_request) Successful in 59s
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
CD / Build and push images (push) Has been cancelled
CI / Lint, typecheck, test (push) Has been cancelled
#215: trusted reverse-proxy header / mTLS client-certificate path
For perimeters that authenticate before the application (ADR 0021 §4).
Off unless BOTH AUTH_PROXY_HEADER and AUTH_PROXY_TRUSTED_PEERS are set —
nothing about the header is guessed. The peer check runs against the TCP
peer address only (a forwarded header is attacker-influenced): a request
carrying the header from any other peer is rejected outright and audited
as auth.proxy_rejected (catalogue v1.4) — that is a spoof attempt, not a
misconfiguration — even when a valid session cookie rides along. From a
trusted peer the header IS the identity; a session cookie never
escalates beyond it; with the feature off the header is inert.

Mapping is explicit (AUTH_PROXY_MAP: username or e-mail); deliberately
no just-in-time creation — the header carries no verified address. The
mTLS variant (AUTH_PROXY_MODE=mtls-dn) maps the configured attribute
(default CN) out of the certificate subject DN the TLS terminator
forwards, under the same peer rules. Session-less proxy requests key the
read trail per user (user:<id>).

The trust boundary is stated in security.md (the section an assessor
reads closest), the VS-NfD security documentation and the hardening
guide's deploy table. Tests cover all four decisions: off = inert,
trusted peer authenticates (username and DN mapping), untrusted peer
rejected + audited, no escalation past a session cookie.

Refs #215.

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

152 lines
5.2 KiB
TypeScript

import {
CanActivate,
ExecutionContext,
ForbiddenException,
Injectable,
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 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>();
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' });
}
}
}