Files
apf_portal/apps/portal-bff/src/auth/auth.controller.spec.ts
T
julien aca9e8d155
CI / check (push) Successful in 3m2s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m54s
CI / a11y (push) Successful in 1m25s
CI / perf (push) Successful in 4m23s
feat(portal-bff): user directory upserted at sign-in (#140)
## Summary

First PR of the **portal-admin User-list chantier** per [ADR-0020](docs/decisions/0020-portal-admin-app.md) §"v1 scope — User list (read-only)". Ships the **write side** only:

1. A new `public.users` table that holds the BFF's local cache of identities seen sign in to either portal-shell or portal-admin.
2. A `UserDirectoryService.recordSignIn(user)` upsert called from `SessionEstablisher.establish` after the blocking audit write.

The read side (`GET /api/admin/users` + the admin viewer SPA screen) lands in two follow-up PRs of the same chantier.

## Schema

[`prisma/schema.prisma`](apps/portal-bff/prisma/schema.prisma) gains a `User` model in the `public` schema:

| Column | Type | Notes |
| --- | --- | --- |
| `oid` | TEXT, PK | Entra's stable per-user identifier inside the tenant. Per-tenant uniqueness is sufficient for v1's single-workforce-tenant design (ADR-0008). |
| `tid` | TEXT | Tenant id. Updated on every upsert because a dual-audience future may legitimately change it. |
| `audience` | TEXT | `'workforce'` \| `'customer'`. Hardcoded to `workforce` in v1 per ADR-0008's simplification; will read from session/claims when External ID activates. |
| `username` | TEXT | Updated on every upsert (Entra-side rename possible). |
| `display_name` | TEXT | Same. |
| `first_seen_at` | TIMESTAMPTZ | Set once at first sign-in via DEFAULT NOW(); **never overwritten** thereafter. Enables "users since <date>" without joining anything. |
| `last_seen_at` | TIMESTAMPTZ | Updated on every upsert. Enables "most recently active" without scanning `audit.events`. |

Indexes:
- `last_seen_at DESC` — admin default sort.
- `username` — prefix filtering.

Migration in [`prisma/migrations/20260514192014_users_directory/`](apps/portal-bff/prisma/migrations/20260514192014_users_directory/migration.sql).

## [`UserDirectoryService`](apps/portal-bff/src/users/user-directory.service.ts)

```ts
async recordSignIn(entry): Promise<void> {
  try {
    await prisma.user.upsert({
      where: { oid },
      create: { oid, tid, audience, username, displayName },
      update: { tid, audience, username, displayName, lastSeenAt: new Date() },
    });
  } catch (err) {
    // logged, never propagated
  }
}
```

**Best-effort write.** Catches its own errors, logs a Pino warn (`user_directory.record_sign_in_failed`), returns `undefined`. The directory is a convenience for admin browsing, not a security boundary — a Postgres hiccup must not lock a user out of sign-in. ADR-0013's "no audit ⇒ no action" applies to the audit module only.

## [`SessionEstablisher`](apps/portal-bff/src/auth/session-establisher.service.ts) wiring

The directory call lands right after the existing audit emission:

```ts
await this.audit.signIn({ actor: user, sessionId: req.sessionID }); // blocking per ADR-0013
await this.userDirectory.recordSignIn({ ...user, audience: 'workforce' }); // best-effort
this.logger.log(...);
```

Two invariants the tests pin:

1. **Audit-first**: when `audit.signIn` throws, `userDirectory.recordSignIn` is NOT called. The directory never holds a row for a sign-in the audit log doesn't carry.
2. **Awaited**: an admin who just signed in sees themselves on the user list immediately — no race between the upsert and the response.

## Module wiring

[`UsersModule`](apps/portal-bff/src/users/users.module.ts) is declared `@Global()` so `SessionEstablisher` (which lives in `AuthModule`) injects `UserDirectoryService` without forcing `AuthModule` to import `UsersModule`. The directory is a true cross-cutting concern: one writer (the auth callback) and one future reader (the admin endpoint).

Wired into [`AppModule`](apps/portal-bff/src/app/app.module.ts) alongside the other v1 modules. `auth.module.spec.ts` updated to also import `UsersModule` in its slice-of-graph compile (otherwise the test fails to resolve the new `SessionEstablisher` dep).

## Notes for the reviewer

- The directory write **awaits** (not fire-and-forget). The cost is one round-trip per sign-in on the response-critical path; the benefit is the no-race property called out above. If sign-in p95 becomes an issue we can revisit (e.g. background job) but the simpler shape is correct first.
- `firstSeenAt` is intentionally absent from the `update` payload. The Prisma upsert's `update` block is precisely what changes on conflict; omitting the field leaves it untouched at the column level (Postgres-side default doesn't refire on UPDATE).
- The model lives in `public`, not in a dedicated `identity` or `cms` schema. ADR-0020 enumerates `cms.*` for editorial data and `audit.*` for the audit ledger but doesn't require a separate schema for user-directory data. We can promote it to its own schema later if a role-isolation need emerges; the migration would be a `ALTER TABLE users SET SCHEMA …`.
- `audit.events.actor_id_hash` is **not** stored on `public.users`. A future admin endpoint that joins sign-in counts from `audit.events` can compute the hash on-the-fly via `HashUserIdService` — keeping the salted-hash invariant from ADR-0013 intact (the salt stays inside the audit module).

## Test plan

- [x] `pnpm nx test portal-bff` — **365 specs pass** (was 358; +7: UserDirectoryService 4, SessionEstablisher integration 3).
- [x] `pnpm exec nx affected -t format:check lint test build --base=origin/main` — clean (the pre-existing rate-limit warnings + one unused-eslint-disable from PR #137 are unrelated).
- [x] Prisma `migrate diff` confirms the model matches the migration SQL.
- [ ] e2e — after merge: sign in via portal-shell or portal-admin, expect a row in `public.users` with the right `oid` / `last_seen_at`; sign in again, expect the same row's `last_seen_at` to advance and `first_seen_at` to stay put.

## What's next

The chantier sequence:

1. **This PR** — write side: schema + service + sign-in upsert.
2. **PR 2** — BFF `GET /api/admin/users` (paginated + filterable, gated by `@RequireAdmin`, emits `admin.users.query` audit).
3. **PR 3** — portal-admin `/users` screen (table + filter form), promote the sidebar entry from "Soon" badge to live link.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #140
2026-05-14 19:30:12 +02:00

667 lines
24 KiB
TypeScript

import type { Request, Response } from 'express';
import type { Logger } from 'nestjs-pino';
import type { AuditWriter } from '../audit/audit.service';
import type { UserSessionIndexService } from '../session/user-session-index.service';
import type { UserDirectoryService } from '../users/user-directory.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';
import { SessionEstablisher } from './session-establisher.service';
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/',
adminRedirectUri: 'http://localhost:3000/api/admin/auth/callback',
adminPostLogoutRedirectUri: 'http://localhost:4300/',
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'],
roles: [],
};
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;
csrfToken?: string;
mfaVerifiedAt?: 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 };
audit: {
signIn: jest.Mock;
signInFailed: jest.Mock;
signOut: jest.Mock;
sessionExpired: 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 audit = {
signIn: jest.fn().mockResolvedValue(undefined),
signInFailed: jest.fn().mockResolvedValue(undefined),
signOut: jest.fn().mockResolvedValue(undefined),
sessionExpired: jest.fn().mockResolvedValue(undefined),
};
const logger = makeLoggerStub();
// The directory service is a best-effort dependency — a noop mock
// is sufficient for the controller's behavioural assertions.
const userDirectory = { recordSignIn: jest.fn().mockResolvedValue(undefined) };
// Real SessionEstablisher with the same mocks the legacy tests
// already wire — keeps the behavioural assertions on session
// fields / audit calls untouched after the controller refactor.
const sessionEstablisher = new SessionEstablisher(
logger as unknown as Logger,
userSessionIndex as unknown as UserSessionIndexService,
audit as unknown as AuditWriter,
userDirectory as unknown as UserDirectoryService,
);
return {
controller: new AuthController(
service,
logger as unknown as Logger,
ENTRA,
audit as unknown as AuditWriter,
sessionEstablisher,
),
beginAuthCodeFlow,
completeAuthCodeFlow,
logger,
userSessionIndex,
audit,
};
}
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,
ENTRA.redirectUri,
);
// 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',
surface: 'user',
oid: USER.oid,
username: USER.username,
amr: USER.amr,
}),
'AuthCallback',
);
expect(res.redirect).toHaveBeenCalledWith(302, ENTRA.postLogoutRedirectUri);
});
it('records mfaVerifiedAt on the session (ADR-0011 §"Confirmation")', 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.mfaVerifiedAt).toBeGreaterThanOrEqual(before);
expect(session.mfaVerifiedAt).toBeLessThanOrEqual(after);
// Posted at the same moment as createdAt — the callback grabs
// `now` once and writes both fields, so the freshness anchor
// and the absolute-timeout anchor share a clock reading.
expect(session.mfaVerifiedAt).toBe(session.createdAt);
});
it('records createdAt + absoluteExpiresAt on the session (ADR-0010 §"TTL policy")', async () => {
// Force the ADR-0010 default for this test — apps/portal-bff/.env
// may have a custom SESSION_ABSOLUTE_TIMEOUT_SECONDS for local
// experiments and Nx auto-loads it. Asserting on the default in
// a test that doesn't override it then fails non-deterministically.
const originalAbsolute = process.env['SESSION_ABSOLUTE_TIMEOUT_SECONDS'];
delete process.env['SESSION_ABSOLUTE_TIMEOUT_SECONDS'];
try {
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);
} finally {
if (originalAbsolute === undefined) {
delete process.env['SESSION_ABSOLUTE_TIMEOUT_SECONDS'];
} else {
process.env['SESSION_ABSOLUTE_TIMEOUT_SECONDS'] = originalAbsolute;
}
}
});
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();
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('emits an auth.sign_in audit event on the happy path', async () => {
const { controller, audit } = makeController();
const res = makeResStub();
const req = makeReqStub({
signedCookies: { [PRE_AUTH_COOKIE_NAME]: JSON.stringify(PRE_AUTH) },
session: makeSessionStub(),
sessionID: 'fresh-sid',
});
await controller.callback(req, res, 'auth-code', PRE_AUTH.state);
expect(audit.signIn).toHaveBeenCalledWith({
actor: USER,
sessionId: 'fresh-sid',
});
expect(audit.signInFailed).not.toHaveBeenCalled();
});
it('emits auth.sign_in.failed on the Entra-error branch', async () => {
const { controller, audit } = 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(audit.signInFailed).toHaveBeenCalledWith({
failureKind: 'entra-error',
payload: { entraError: 'access_denied', entraErrorDescription: 'user cancelled' },
});
expect(audit.signIn).not.toHaveBeenCalled();
});
it('emits auth.sign_in.failed (no-pre-auth-cookie) when the cookie is missing', async () => {
const { controller, audit } = makeController();
const res = makeResStub();
const req = makeReqStub();
await controller.callback(req, res, 'code', 'state');
expect(audit.signInFailed).toHaveBeenCalledWith({ failureKind: 'no-pre-auth-cookie' });
});
it('emits auth.sign_in.failed with the discriminator kind on AuthCodeFlowException', async () => {
const completeAuthCodeFlow = jest
.fn()
.mockRejectedValue(new AuthCodeFlowException({ kind: 'state-mismatch' }));
const { controller, audit } = 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(audit.signInFailed).toHaveBeenCalledWith({ failureKind: 'state-mismatch' });
});
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('throws UnauthorizedException with code=unauthenticated when no user is on the session', () => {
// Controller now relies on the global StructuredErrorFilter to
// serialise the response. The `code` lives on the
// HttpException's response object so the filter picks it up
// verbatim into the `{ error: { code } }` envelope.
const { controller } = makeController();
const res = makeResStub();
const req = makeReqStub();
expect(() => controller.me(req, res)).toThrow(
expect.objectContaining({
status: 401,
response: expect.objectContaining({
code: 'unauthenticated',
message: 'Unauthenticated',
}),
}),
);
expect(res.json).not.toHaveBeenCalled();
});
});
describe('AuthController.logout', () => {
it('destroys the session, clears the session cookie, logs + audits sign-out, redirects to Entra logout', async () => {
const { controller, logger, userSessionIndex, audit } = 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(audit.signOut).toHaveBeenCalledWith({
actor: USER,
sessionId: 'logged-out-sid',
});
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', surface: 'user', 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 (no audit row either)', async () => {
const { controller, logger, userSessionIndex, audit } = 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). The audit row is also
// skipped: an "anonymous user logged out" event is noise.
expect(userSessionIndex.remove).not.toHaveBeenCalled();
expect(audit.signOut).not.toHaveBeenCalled();
expect(session.destroy).toHaveBeenCalledTimes(1);
expect(logger.log).toHaveBeenCalledWith(
{ event: 'auth.signed_out', surface: 'user', 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();
});
});