Files
apf_portal/apps/portal-bff/src/auth/auth.controller.spec.ts
T
Julien Gautier 5c346820ea
CI / commits (pull_request) Successful in 1m25s
CI / scan (pull_request) Successful in 1m30s
CI / check (pull_request) Failing after 1m34s
CI / a11y (pull_request) Successful in 1m6s
CI / perf (pull_request) Successful in 3m30s
feat(portal-bff): absolute-timeout middleware + user_sessions index per ADR-0010
closes the ttl-policy + revocation pieces left from #110.

absolute-timeout middleware:
  every request that survives express-session runs through a new
  middleware that checks req.session.absoluteExpiresAt. past the
  12 h hard ceiling, it destroys the redis-side session, clears the
  portal_session cookie, drops the entry from the per-user index,
  and lets the request keep flowing anonymously. route-level
  guards (/me today, future @requireauth) turn that into a 401
  where auth is actually needed — public routes stay accessible.
  not the "every route returns 401" reading of adr-0010 §"ttl
  policy" (validated with the project lead): "returns 401" is
  interpreted as "the user eventually sees a 401 when they touch
  something that needs auth", not as a hard refusal on the
  current in-flight request.

user_sessions:{userId} secondary index (adr-0010 §"revocation"):
  a new UserSessionIndexService maintains a redis set of active
  session ids per user. wired on /auth/callback (sadd at sign-in,
  after session.save() so the session row exists before the index
  points at it) and on /auth/logout + the absolute-timeout
  middleware (srem on destroy). best-effort: a failed sadd/srem
  logs a pino warning and the auth flow continues — the index is
  a convenience for admin operations, not a security invariant.
  orphans (entries whose session:<id> redis key has expired on
  idle ttl) are tolerated per the adr; future consumer code
  filters them out.

  no in-product consumer ships in this pr — the admin "logout
  everywhere" endpoint lands with the admin module (+ @requireadmin
  / @requiremfa guards). today the index is write-only on the bff
  side.

session payload extension:
  createdAt and absoluteExpiresAt are now set on the session at
  the same moment as req.session.user, in /auth/callback. the
  session.types.ts declaration merging exposes them as optional
  SessionData fields so every consumer sees a typed payload.

wiring:
  - SessionModule provides UserSessionIndexService and a
    SESSION_ABSOLUTE_TIMEOUT_MIDDLEWARE token whose factory builds
    the middleware via createAbsoluteTimeoutMiddleware(index,
    logger). same pattern as the existing SESSION_MIDDLEWARE token.
  - AuthModule now imports SessionModule so AuthController can
    inject UserSessionIndexService.
  - main.ts mounts the absolute-timeout middleware immediately
    after the session middleware.

per-user identifier is the entra `oid` claim (stable per-user
inside the tenant, matches req.session.user.oid). future
multi-tenant scenarios may want `${tid}:${oid}` — easy refactor
when external id activation lands (adr-0008). not in scope here.

out of scope, landing in follow-ups:
- admin "logout everywhere" endpoint consuming
  UserSessionIndexService.list(userId)
- audit-pipeline first-class events for session.absolute_timeout
  + user_session_index.* (adr-0013)
- token blob persistence (id_token / access_token / refresh_token)
  in the encrypted session — adr-0014 dependency

123/123 tests pass (was 110); +13 specs across the two new files
and the auth controller spec.
2026-05-12 23:22:08 +02:00

488 lines
16 KiB
TypeScript

import type { Request, Response } from 'express';
import type { Logger } from 'nestjs-pino';
import type { UserSessionIndexService } from '../session/user-session-index.service';
import { AuthController } from './auth.controller';
import { PRE_AUTH_COOKIE_NAME, PRE_AUTH_COOKIE_TTL_MS } from './auth.cookie';
import { AuthCodeFlowException } from './auth.errors';
import type { AuthService, AuthenticatedUser, PreAuthPayload } from './auth.service';
import type { EntraConfig } from './entra-config.token';
const ENTRA: EntraConfig = {
instanceUrl: 'https://login.microsoftonline.com/',
tenantId: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',
clientId: '11111111-2222-3333-4444-555555555555',
clientSecret: 's3cret',
redirectUri: 'http://localhost:3000/api/auth/callback',
postLogoutRedirectUri: 'http://localhost:4200/',
authority: 'https://login.microsoftonline.com/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',
};
const PRE_AUTH: PreAuthPayload = {
state: 'state-nonce',
codeVerifier: 'verifier-secret',
createdAt: 1_000,
};
const USER: AuthenticatedUser = {
oid: 'user-oid',
tid: ENTRA.tenantId,
username: 'jane.doe@apf.example',
displayName: 'Jane Doe',
amr: ['pwd', 'mfa'],
};
function makeResStub() {
const res = {
cookie: jest.fn(),
clearCookie: jest.fn(),
redirect: jest.fn(),
status: jest.fn(),
json: jest.fn(),
};
// status/json/cookie/clearCookie/redirect all return the response
// in Express for chaining. Wire `mockReturnThis` after the object
// exists so `this` resolves to the same stub.
res.cookie.mockReturnValue(res);
res.clearCookie.mockReturnValue(res);
res.redirect.mockReturnValue(res);
res.status.mockReturnValue(res);
res.json.mockReturnValue(res);
return res as unknown as Response & typeof res;
}
interface SessionStub {
user?: AuthenticatedUser;
createdAt?: number;
absoluteExpiresAt?: number;
save: jest.Mock;
destroy: jest.Mock;
}
function makeSessionStub(opts?: {
user?: AuthenticatedUser;
saveError?: Error;
destroyError?: Error;
}): SessionStub {
return {
...(opts?.user !== undefined ? { user: opts.user } : {}),
save: jest.fn((cb: (err?: Error) => void) => cb(opts?.saveError)),
destroy: jest.fn((cb: (err?: Error) => void) => cb(opts?.destroyError)),
};
}
function makeReqStub(opts?: {
signedCookies?: Record<string, unknown>;
session?: SessionStub;
sessionID?: string;
}): Request & { session: SessionStub; sessionID: string } {
return {
signedCookies: opts?.signedCookies ?? {},
session: opts?.session ?? makeSessionStub(),
sessionID: opts?.sessionID ?? 'sid-test',
} as unknown as Request & { session: SessionStub; sessionID: string };
}
function makeLoggerStub() {
return {
log: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
debug: jest.fn(),
} as unknown as Logger & {
log: jest.Mock;
warn: jest.Mock;
error: jest.Mock;
debug: jest.Mock;
};
}
interface ControllerFixture {
controller: AuthController;
beginAuthCodeFlow: jest.Mock;
completeAuthCodeFlow: jest.Mock;
logger: ReturnType<typeof makeLoggerStub>;
userSessionIndex: { add: jest.Mock; remove: jest.Mock; list: jest.Mock };
}
const LOGOUT_URL = `${ENTRA.authority}/oauth2/v2.0/logout?post_logout_redirect_uri=${encodeURIComponent(ENTRA.postLogoutRedirectUri)}`;
function makeController(opts?: { completeAuthCodeFlow?: jest.Mock }): ControllerFixture {
const beginAuthCodeFlow = jest.fn().mockResolvedValue({
authUrl: 'https://entra.example/authorize?state=state-nonce',
preAuthPayload: PRE_AUTH,
});
const completeAuthCodeFlow = opts?.completeAuthCodeFlow ?? jest.fn().mockResolvedValue(USER);
const buildLogoutUrl = jest.fn().mockReturnValue(LOGOUT_URL);
const service = {
beginAuthCodeFlow,
completeAuthCodeFlow,
buildLogoutUrl,
} as unknown as AuthService;
const userSessionIndex = {
add: jest.fn().mockResolvedValue(undefined),
remove: jest.fn().mockResolvedValue(undefined),
list: jest.fn().mockResolvedValue([]),
};
const logger = makeLoggerStub();
return {
controller: new AuthController(
service,
logger as unknown as Logger,
ENTRA,
userSessionIndex as unknown as UserSessionIndexService,
),
beginAuthCodeFlow,
completeAuthCodeFlow,
logger,
userSessionIndex,
};
}
describe('AuthController.login', () => {
it('writes the pre-auth cookie and 302s to the Entra auth URL', async () => {
const { controller } = makeController();
const res = makeResStub();
await controller.login(res);
expect(res.cookie).toHaveBeenCalledTimes(1);
const call = res.cookie.mock.calls[0] ?? [];
const [name, value, options] = call;
expect(name).toBe(PRE_AUTH_COOKIE_NAME);
expect(JSON.parse(value as string)).toEqual(PRE_AUTH);
expect(options).toMatchObject({
signed: true,
httpOnly: true,
sameSite: 'lax',
path: '/',
maxAge: PRE_AUTH_COOKIE_TTL_MS,
});
expect(res.redirect).toHaveBeenCalledWith(
302,
'https://entra.example/authorize?state=state-nonce',
);
});
it('toggles cookie `secure` based on NODE_ENV', async () => {
const originalNodeEnv = process.env['NODE_ENV'];
try {
process.env['NODE_ENV'] = 'production';
const { controller } = makeController();
const res = makeResStub();
await controller.login(res);
const call = res.cookie.mock.calls[0] ?? [];
const options = call[2] as { secure: boolean };
expect(options.secure).toBe(true);
} finally {
if (originalNodeEnv === undefined) {
delete process.env['NODE_ENV'];
} else {
process.env['NODE_ENV'] = originalNodeEnv;
}
}
});
});
describe('AuthController.callback', () => {
it('clears the pre-auth cookie, persists the user in the session, logs success, redirects to the SPA on the happy path', async () => {
const { controller, completeAuthCodeFlow, logger } = 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);
expect(res.clearCookie).toHaveBeenCalledWith(PRE_AUTH_COOKIE_NAME, expect.any(Object));
expect(completeAuthCodeFlow).toHaveBeenCalledWith('auth-code', PRE_AUTH.state, PRE_AUTH);
// The resolved user must be on the session before the redirect
// so the subsequent /me call sees a populated payload.
expect(session.user).toEqual(USER);
expect(session.save).toHaveBeenCalledTimes(1);
expect(logger.log).toHaveBeenCalledWith(
expect.objectContaining({
event: 'auth.signed_in',
oid: USER.oid,
username: USER.username,
amr: USER.amr,
}),
'AuthCallback',
);
expect(res.redirect).toHaveBeenCalledWith(302, ENTRA.postLogoutRedirectUri);
});
it('records createdAt + absoluteExpiresAt on the session (ADR-0010 §"TTL policy")', async () => {
const before = Date.now();
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);
const after = Date.now();
expect(session.createdAt).toBeGreaterThanOrEqual(before);
expect(session.createdAt).toBeLessThanOrEqual(after);
// Default absoluteSeconds = 43200 (12 h) per ADR-0010.
expect(session.absoluteExpiresAt).toBe((session.createdAt as number) + 43_200 * 1000);
});
it('registers the new session in the user_sessions index after save', async () => {
const { controller, userSessionIndex } = makeController();
const res = makeResStub();
const session = makeSessionStub();
const req = makeReqStub({
signedCookies: { [PRE_AUTH_COOKIE_NAME]: JSON.stringify(PRE_AUTH) },
session,
sessionID: 'fresh-sid',
});
await controller.callback(req, res, 'auth-code', PRE_AUTH.state);
expect(userSessionIndex.add).toHaveBeenCalledWith(USER.oid, 'fresh-sid');
// Order matters: the Redis session row must be written before
// the index points at it. We can't enforce a strict
// `toHaveBeenCalledBefore` ordering across jest mocks without
// a plugin — assert at least that the index entry was added.
expect(session.save).toHaveBeenCalled();
});
it('propagates a session.save() error as an exception (so the SPA never sees a successful redirect with no session)', async () => {
const { controller } = makeController();
const res = makeResStub();
const session = makeSessionStub({ saveError: new Error('redis down') });
const req = makeReqStub({
signedCookies: { [PRE_AUTH_COOKIE_NAME]: JSON.stringify(PRE_AUTH) },
session,
});
await expect(controller.callback(req, res, 'auth-code', PRE_AUTH.state)).rejects.toThrow(
/redis down/,
);
expect(res.redirect).not.toHaveBeenCalledWith(302, ENTRA.postLogoutRedirectUri);
});
it('redirects with ?auth_error=token-exchange-failed when Entra returns error', async () => {
const { controller, completeAuthCodeFlow } = makeController();
const res = makeResStub();
const req = makeReqStub({
signedCookies: { [PRE_AUTH_COOKIE_NAME]: JSON.stringify(PRE_AUTH) },
});
await controller.callback(req, res, undefined, undefined, 'access_denied', 'user cancelled');
expect(completeAuthCodeFlow).not.toHaveBeenCalled();
expect(res.clearCookie).toHaveBeenCalled();
expect(res.redirect).toHaveBeenCalledWith(
302,
expect.stringContaining('auth_error=token-exchange-failed'),
);
});
it('redirects with ?auth_error=flow-expired when the pre-auth cookie is missing', async () => {
const { controller, completeAuthCodeFlow, logger } = makeController();
const res = makeResStub();
const req = makeReqStub();
await controller.callback(req, res, 'code', 'state');
expect(completeAuthCodeFlow).not.toHaveBeenCalled();
expect(logger.warn).toHaveBeenCalledWith(
expect.objectContaining({ event: 'auth.no_pre_auth_cookie' }),
'AuthCallback',
);
expect(res.redirect).toHaveBeenCalledWith(
302,
expect.stringContaining('auth_error=flow-expired'),
);
});
it('redirects with the typed error from AuthCodeFlowException', async () => {
const completeAuthCodeFlow = jest
.fn()
.mockRejectedValue(new AuthCodeFlowException({ kind: 'state-mismatch' }));
const { controller, logger } = makeController({ completeAuthCodeFlow });
const res = makeResStub();
const req = makeReqStub({
signedCookies: { [PRE_AUTH_COOKIE_NAME]: JSON.stringify(PRE_AUTH) },
});
await controller.callback(req, res, 'code', 'state');
expect(logger.warn).toHaveBeenCalledWith(
expect.objectContaining({
event: 'auth.flow_error',
failure: { kind: 'state-mismatch' },
}),
'AuthCallback',
);
expect(res.redirect).toHaveBeenCalledWith(
302,
expect.stringContaining('auth_error=state-mismatch'),
);
});
it('redirects with ?auth_error=token-exchange-failed when query is missing code/state', async () => {
const { controller } = makeController();
const res = makeResStub();
const req = makeReqStub({
signedCookies: { [PRE_AUTH_COOKIE_NAME]: JSON.stringify(PRE_AUTH) },
});
await controller.callback(req, res); // no code, no state
expect(res.redirect).toHaveBeenCalledWith(
302,
expect.stringContaining('auth_error=token-exchange-failed'),
);
});
it('rejects a malformed pre-auth cookie as flow-expired', async () => {
const { controller, completeAuthCodeFlow } = makeController();
const res = makeResStub();
const req = makeReqStub({ signedCookies: { [PRE_AUTH_COOKIE_NAME]: 'not-json' } });
await controller.callback(req, res, 'code', 'state');
expect(completeAuthCodeFlow).not.toHaveBeenCalled();
expect(res.redirect).toHaveBeenCalledWith(
302,
expect.stringContaining('auth_error=flow-expired'),
);
});
});
describe('AuthController.me', () => {
it('returns the curated public user when the session is populated', () => {
const { controller } = makeController();
const res = makeResStub();
const req = makeReqStub({ session: makeSessionStub({ user: USER }) });
controller.me(req, res);
expect(res.status).not.toHaveBeenCalledWith(401);
expect(res.json).toHaveBeenCalledWith({
oid: USER.oid,
tid: USER.tid,
username: USER.username,
displayName: USER.displayName,
});
});
it('strips amr (internal claim) from the response payload', () => {
const { controller } = makeController();
const res = makeResStub();
const req = makeReqStub({ session: makeSessionStub({ user: USER }) });
controller.me(req, res);
const payload = res.json.mock.calls[0]?.[0] as Record<string, unknown>;
expect(payload).not.toHaveProperty('amr');
});
it('returns 401 when no user is on the session', () => {
const { controller } = makeController();
const res = makeResStub();
const req = makeReqStub();
controller.me(req, res);
expect(res.status).toHaveBeenCalledWith(401);
expect(res.json).toHaveBeenCalledWith({ error: 'unauthenticated' });
});
});
describe('AuthController.logout', () => {
it('destroys the session, clears the session cookie, logs success, redirects to Entra logout', async () => {
const { controller, logger, userSessionIndex } = makeController();
const res = makeResStub();
const session = makeSessionStub({ user: USER });
const req = makeReqStub({ session, sessionID: 'logged-out-sid' });
await controller.logout(req, res);
expect(userSessionIndex.remove).toHaveBeenCalledWith(USER.oid, 'logged-out-sid');
expect(session.destroy).toHaveBeenCalledTimes(1);
expect(res.clearCookie).toHaveBeenCalledWith('portal_session', { path: '/' });
expect(logger.log).toHaveBeenCalledWith(
{ event: 'auth.signed_out', wasAuthenticated: true },
'AuthLogout',
);
// Authority + /oauth2/v2.0/logout?post_logout_redirect_uri=…
expect(res.redirect).toHaveBeenCalledWith(
302,
expect.stringContaining(`${ENTRA.authority}/oauth2/v2.0/logout`),
);
expect(res.redirect).toHaveBeenCalledWith(
302,
expect.stringContaining(
`post_logout_redirect_uri=${encodeURIComponent(ENTRA.postLogoutRedirectUri)}`,
),
);
});
it('uses the __Host- prefixed cookie name in production', async () => {
const originalNodeEnv = process.env['NODE_ENV'];
try {
process.env['NODE_ENV'] = 'production';
const { controller } = makeController();
const res = makeResStub();
const req = makeReqStub({ session: makeSessionStub({ user: USER }) });
await controller.logout(req, res);
expect(res.clearCookie).toHaveBeenCalledWith('__Host-portal_session', { path: '/' });
} finally {
if (originalNodeEnv === undefined) {
delete process.env['NODE_ENV'];
} else {
process.env['NODE_ENV'] = originalNodeEnv;
}
}
});
it('still clears the cookie and redirects when the user was already anonymous', async () => {
const { controller, logger, userSessionIndex } = makeController();
const res = makeResStub();
const session = makeSessionStub();
const req = makeReqStub({ session });
await controller.logout(req, res);
// Nothing was ever added to the index for an anonymous request —
// skip the SREM (cheaper + avoids racing the cleanup of a
// future user's session id collision).
expect(userSessionIndex.remove).not.toHaveBeenCalled();
expect(session.destroy).toHaveBeenCalledTimes(1);
expect(logger.log).toHaveBeenCalledWith(
{ event: 'auth.signed_out', wasAuthenticated: false },
'AuthLogout',
);
expect(res.redirect).toHaveBeenCalled();
});
it('logs but does not throw when session.destroy fails — still clears cookie and redirects', async () => {
const { controller, logger } = makeController();
const res = makeResStub();
const session = makeSessionStub({ user: USER, destroyError: new Error('redis down') });
const req = makeReqStub({ session });
await controller.logout(req, res);
expect(logger.error).toHaveBeenCalledWith(
expect.objectContaining({
event: 'session.destroy_failed',
message: 'redis down',
}),
'AuthLogout',
);
expect(res.clearCookie).toHaveBeenCalled();
expect(res.redirect).toHaveBeenCalled();
});
});