feat(portal-bff): helmet + env-driven CORS allowlist + double-submit CSRF
phase-2 security baseline the main.ts placeholder has been
advertising since the auth track started. three independent
middlewares + their spa counterparts shipped together because
they only become meaningful as a set.
helmet on the bff:
helmet() with three overrides matching our specific shape:
- HSTS only in production (dev runs on plain http)
- crossOriginResourcePolicy: 'cross-origin' (SPA needs to read
bff json from a different origin)
- CSP disabled in non-prod (bff doesn't render html; default CSP
just adds devtools noise)
cors allowlist env-driven:
CORS_ALLOWED_ORIGINS is now mandatory at boot. readCorsAllowlist()
parses + validates (http(s) only, bare origins, no path/query),
same boot-time validator family as assertSessionSecret etc. the
previous hardcoded localhost fallback is removed — silent
cors misconfiguration is exactly the "works in dev breaks in
prod" trap this guard catches.
double-submit CSRF (session-bound):
- bff mints a 256-bit csrfToken at /auth/callback, stored on
req.session.csrfToken AND mirrored to a js-readable cookie
(__Host-portal_csrf prod / portal_csrf dev). cookie is the
spa's read-only view; session is the source of truth.
- createCsrfMiddleware compares X-CSRF-Token header to the
session token via crypto.timingSafeEqual. skips: safe methods,
anonymous requests, /auth/login + /auth/callback.
- mismatch → 403 {"error":"csrf"} + structured pino warn.
- spa csrfInterceptor reads the cookie via document.cookie and
copies into X-CSRF-Token on mutating bff requests. omitted on
GET/HEAD/OPTIONS and on non-bff origins.
- logout + absolute-timeout middleware now clear the csrf cookie
alongside the session cookie.
notable choices:
- session-bound double-submit, not pure cookie-vs-header. an
attacker who plants a cookie via subdomain takeover would
still need to know the server-side session token. tying the
check to req.session.csrfToken instead of the cookie itself
is what makes this stronger than the canonical recipe.
- csrfInterceptor sits between bffCredentialsInterceptor (which
sets withCredentials) and bffUnauthorizedInterceptor (which
handles 401s). forward order, no surprises.
- no CSRF for anonymous mutating routes in v1 — none exist today
and generating tokens for anonymous sessions conflicts with
express-session's saveUninitialized: false.
specs:
- 239 / 239 pass under the clean-env repro (env -u every config
var including the new CORS_ALLOWED_ORIGINS).
- +42 specs across check-cors-allowlist, csrf-cookie, csrf
middleware, csrf interceptor, and extended auth.controller /
absolute-timeout coverage for the csrf cookie mirror/clear.
out of scope, landing in follow-ups:
- rate limiting + structured error filter (remaining phase-2
todos)
- CSP fine-tuning for the portal-shell + portal-admin static
bundles
- csrf token rotation on idle-extension (current token lives
the session lifetime)
This commit is contained in:
@@ -55,6 +55,7 @@ interface SessionStub {
|
||||
user?: AuthenticatedUser;
|
||||
createdAt?: number;
|
||||
absoluteExpiresAt?: number;
|
||||
csrfToken?: string;
|
||||
save: jest.Mock;
|
||||
destroy: jest.Mock;
|
||||
}
|
||||
@@ -261,6 +262,34 @@ describe('AuthController.callback', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('mints a CSRF token, writes it to the session, and mirrors it to the JS-readable cookie', async () => {
|
||||
const { controller } = makeController();
|
||||
const res = makeResStub();
|
||||
const session = makeSessionStub();
|
||||
const req = makeReqStub({
|
||||
signedCookies: { [PRE_AUTH_COOKIE_NAME]: JSON.stringify(PRE_AUTH) },
|
||||
session,
|
||||
});
|
||||
|
||||
await controller.callback(req, res, 'auth-code', PRE_AUTH.state);
|
||||
|
||||
// Server-side source of truth lives on the session.
|
||||
expect(typeof session.csrfToken).toBe('string');
|
||||
expect((session.csrfToken as string).length).toBeGreaterThan(20);
|
||||
|
||||
// Cookie mirror — name picked from sessionCookieName's twin
|
||||
// (NODE_ENV-conditional). In the test default (development),
|
||||
// it's the unprefixed variant.
|
||||
const csrfCookieCall = res.cookie.mock.calls.find(
|
||||
(c) => c[0] === 'portal_csrf' || c[0] === '__Host-portal_csrf',
|
||||
);
|
||||
expect(csrfCookieCall).toBeDefined();
|
||||
expect(csrfCookieCall?.[1]).toBe(session.csrfToken);
|
||||
// Must NOT be HttpOnly — the SPA reads it to echo back via the
|
||||
// X-CSRF-Token header.
|
||||
expect(csrfCookieCall?.[2]).toMatchObject({ httpOnly: false });
|
||||
});
|
||||
|
||||
it('registers the new session in the user_sessions index after save', async () => {
|
||||
const { controller, userSessionIndex } = makeController();
|
||||
const res = makeResStub();
|
||||
@@ -501,6 +530,7 @@ describe('AuthController.logout', () => {
|
||||
});
|
||||
expect(session.destroy).toHaveBeenCalledTimes(1);
|
||||
expect(res.clearCookie).toHaveBeenCalledWith('portal_session', { path: '/' });
|
||||
expect(res.clearCookie).toHaveBeenCalledWith('portal_csrf', { path: '/' });
|
||||
expect(logger.log).toHaveBeenCalledWith(
|
||||
{ event: 'auth.signed_out', wasAuthenticated: true },
|
||||
'AuthLogout',
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { Controller, Get, Inject, Query, Req, Res } from '@nestjs/common';
|
||||
import type { Request, Response } from 'express';
|
||||
import { Logger } from 'nestjs-pino';
|
||||
import { AuditWriter } from '../audit/audit.service';
|
||||
import { csrfCookieName, csrfCookieOptions } from '../security/csrf-cookie';
|
||||
import { readSessionTimeouts, sessionCookieName } from '../session/session-cookie';
|
||||
import { UserSessionIndexService } from '../session/user-session-index.service';
|
||||
import {
|
||||
@@ -117,19 +119,30 @@ export class AuthController {
|
||||
try {
|
||||
const user = await this.authService.completeAuthCodeFlow(code, state, preAuth);
|
||||
const now = Date.now();
|
||||
const { absoluteSeconds } = readSessionTimeouts();
|
||||
const { idleSeconds, absoluteSeconds } = readSessionTimeouts();
|
||||
const csrfToken = randomBytes(32).toString('base64url');
|
||||
req.session.user = user;
|
||||
req.session.createdAt = now;
|
||||
// Hard ceiling per ADR-0010 §"TTL policy" — checked on every
|
||||
// request by the absolute-timeout middleware, independent of
|
||||
// idle TTL.
|
||||
req.session.absoluteExpiresAt = now + absoluteSeconds * 1000;
|
||||
// CSRF token per ADR-0009 §"Double-submit CSRF". Server-side
|
||||
// source of truth lives on the session; the cookie below is
|
||||
// the SPA's read-only mirror used to echo the value in the
|
||||
// X-CSRF-Token header.
|
||||
req.session.csrfToken = csrfToken;
|
||||
// Force the save before the redirect: express-session writes
|
||||
// on response end, but the 302 we're about to emit closes the
|
||||
// response before the async store-write would otherwise
|
||||
// complete. Without this, the browser hits the SPA before
|
||||
// Redis carries the new payload.
|
||||
await saveSession(req);
|
||||
// Mirror the CSRF token to a JS-readable cookie. maxAge
|
||||
// matches the session's idle TTL so the cookie expires at
|
||||
// the same time as the session (rolling, refreshed on each
|
||||
// request alongside express-session's own cookie).
|
||||
res.cookie(csrfCookieName(), csrfToken, csrfCookieOptions(idleSeconds * 1000));
|
||||
// Register the freshly-minted session id in the per-user
|
||||
// index so a future admin "logout everywhere" can enumerate
|
||||
// and revoke. Best-effort: a Redis hiccup here doesn't fail
|
||||
@@ -232,6 +245,7 @@ export class AuthController {
|
||||
}
|
||||
|
||||
res.clearCookie(sessionCookieName(), { path: '/' });
|
||||
res.clearCookie(csrfCookieName(), { path: '/' });
|
||||
this.logger.log({ event: 'auth.signed_out', wasAuthenticated }, 'AuthLogout');
|
||||
res.redirect(302, logoutUrl);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user