Files
apf_portal/apps/portal-bff/src/admin/admin-auth.controller.spec.ts
T
julien 77343e3113
CI / check (push) Successful in 3m6s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m11s
CI / a11y (push) Successful in 1m5s
CI / perf (push) Successful in 3m59s
fix(portal-bff): use the real portal-admin dev port (4300) in admin-flow references (#131)
## Summary

PR #129 (`feat(portal-bff): distinct admin session + /api/admin/auth flow`) baked `4201` into a handful of comments, test fixtures, and the `.env.example` as the portal-admin dev port. The actual port wired in [apps/portal-admin/project.json](apps/portal-admin/project.json#L87) `serve.options.port` is **4300** — that's what `pnpm nx serve portal-admin` listens on.

This PR aligns the references so a contributor copying values from `.env.example` (or reading the test fixtures) sees the same port their browser is going to hit.

It also drops `http://localhost:4300` into `CORS_ALLOWED_ORIGINS` — the portal-admin SPA will hit the BFF with credentials as soon as the admin auth flow is exercised end-to-end, and without the origin in the allowlist the browser blocks the call. Better to set the right example now than have the next contributor chase a CORS error.

## Touched

- [apps/portal-bff/.env.example](apps/portal-bff/.env.example):
  - `ENTRA_ADMIN_POST_LOGOUT_REDIRECT_URI` default + the surrounding comment now point at `http://localhost:4300/`.
  - `CORS_ALLOWED_ORIGINS` example lists both `:4200` (portal-shell) and `:4300` (portal-admin).
  - Both sections cite `apps/<app>/project.json` `serve.options.port` as the source of truth so a future reader doesn't have to grep.
- [apps/portal-bff/src/config/check-cors-allowlist.ts](apps/portal-bff/src/config/check-cors-allowlist.ts) — stale doc-comment that pre-dated the portal-admin scaffolding, now matches reality.
- Test-fixture `adminPostLogoutRedirectUri` values in `auth.module.spec.ts`, `auth.controller.spec.ts`, `auth.service.spec.ts`, `admin-auth.controller.spec.ts`, `check-entra-config.spec.ts` — tests don't depend on the port; aligned for clarity only.

## Test plan

- [x] `grep -rn 4201 apps/ libs/` → empty.
- [x] `pnpm nx test portal-bff` — **278 specs pass** (unchanged from #129; this PR only touches strings).
- [x] No behaviour change in the BFF; only the example values shift. Developers must update their local `.env` to pick up the new port + origin.

## Notes for the reviewer

The two new env vars from #129 (`ENTRA_ADMIN_REDIRECT_URI`, `ENTRA_ADMIN_POST_LOGOUT_REDIRECT_URI`) plus the existing `CORS_ALLOWED_ORIGINS` are mandatory at boot. If your local `apps/portal-bff/.env` still has the `4201` value, the BFF will still start (any valid URL passes the validators) — but admin logout will 302 you to a port nothing is listening on, and the admin SPA's BFF calls will fail CORS. Update to `4300` to match the actual portal-admin dev server.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #131
2026-05-14 15:40:07 +02:00

283 lines
9.7 KiB
TypeScript

import type { Request, Response } from 'express';
import type { Logger } from 'nestjs-pino';
import type { AuditWriter } from '../audit/audit.service';
import { PRE_AUTH_COOKIE_NAME } from '../auth/auth.cookie';
import { AuthCodeFlowException } from '../auth/auth.errors';
import type { AuthService, PreAuthPayload } from '../auth/auth.service';
import type { EntraConfig } from '../auth/entra-config.token';
import type { SessionEstablisher } from '../auth/session-establisher.service';
import { AdminAuthController } from './admin-auth.controller';
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 USER = {
oid: 'admin-oid',
tid: ENTRA.tenantId,
username: 'admin@apf.example',
displayName: 'Admin Smith',
amr: ['pwd', 'mfa'],
roles: ['admin'],
};
const PRE_AUTH: PreAuthPayload = {
state: 'state-nonce',
codeVerifier: 'verifier-secret',
createdAt: 1_000,
};
const ADMIN_LOGOUT_URL = `${ENTRA.authority}/oauth2/v2.0/logout?post_logout_redirect_uri=${encodeURIComponent(ENTRA.adminPostLogoutRedirectUri)}`;
function makeResStub() {
const res = {
cookie: jest.fn(),
clearCookie: jest.fn(),
redirect: jest.fn(),
status: jest.fn(),
json: jest.fn(),
};
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;
}
function makeReqStub(opts?: {
signedCookies?: Record<string, unknown>;
sessionUser?: typeof USER;
}): Request {
return {
signedCookies: opts?.signedCookies ?? {},
session: opts?.sessionUser !== undefined ? { user: opts.sessionUser } : {},
sessionID: 'sid-admin',
} as unknown as Request;
}
function makeFixture(opts?: { completeAuthCodeFlow?: jest.Mock }) {
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(ADMIN_LOGOUT_URL);
const authService = {
beginAuthCodeFlow,
completeAuthCodeFlow,
buildLogoutUrl,
} as unknown as AuthService;
const audit = {
signIn: jest.fn().mockResolvedValue(undefined),
signInFailed: jest.fn().mockResolvedValue(undefined),
signOut: jest.fn().mockResolvedValue(undefined),
};
const establisher = {
establish: jest.fn().mockResolvedValue(undefined),
destroy: jest.fn().mockResolvedValue(undefined),
};
const logger = { log: jest.fn(), warn: jest.fn(), error: jest.fn() };
return {
controller: new AdminAuthController(
authService,
logger as unknown as Logger,
ENTRA,
audit as unknown as AuditWriter,
establisher as unknown as SessionEstablisher,
),
beginAuthCodeFlow,
completeAuthCodeFlow,
buildLogoutUrl,
audit,
establisher,
logger,
};
}
describe('AdminAuthController.login', () => {
it('passes the admin redirect URI to beginAuthCodeFlow', async () => {
const { controller, beginAuthCodeFlow } = makeFixture();
await controller.login(makeResStub());
expect(beginAuthCodeFlow).toHaveBeenCalledWith(ENTRA.adminRedirectUri);
});
it('writes the pre-auth cookie and 302s to the Entra auth URL', async () => {
const { controller } = makeFixture();
const res = makeResStub();
await controller.login(res);
expect(res.cookie).toHaveBeenCalledWith(
PRE_AUTH_COOKIE_NAME,
expect.any(String),
expect.objectContaining({ signed: true, httpOnly: true }),
);
expect(res.redirect).toHaveBeenCalledWith(302, expect.stringContaining('entra.example'));
});
});
describe('AdminAuthController.callback', () => {
it('passes the admin redirect URI to completeAuthCodeFlow and establishes a surface=admin session', async () => {
const { controller, completeAuthCodeFlow, establisher } = makeFixture();
const res = makeResStub();
const req = makeReqStub({
signedCookies: { [PRE_AUTH_COOKIE_NAME]: JSON.stringify(PRE_AUTH) },
});
await controller.callback(req, res, 'auth-code', PRE_AUTH.state);
expect(completeAuthCodeFlow).toHaveBeenCalledWith(
'auth-code',
PRE_AUTH.state,
PRE_AUTH,
ENTRA.adminRedirectUri,
);
expect(establisher.establish).toHaveBeenCalledWith({
user: USER,
req,
res,
surface: 'admin',
});
expect(res.redirect).toHaveBeenCalledWith(302, ENTRA.adminPostLogoutRedirectUri);
});
it('redirects with ?auth_error=token-exchange-failed when Entra returns error', async () => {
const { controller } = makeFixture();
const res = makeResStub();
const req = makeReqStub({
signedCookies: { [PRE_AUTH_COOKIE_NAME]: JSON.stringify(PRE_AUTH) },
});
await controller.callback(req, res, undefined, undefined, 'access_denied', 'consent declined');
expect(res.redirect).toHaveBeenCalledWith(
302,
expect.stringContaining('auth_error=token-exchange-failed'),
);
// Error redirect lands on the admin post-logout target, not the user-portal one.
expect(res.redirect).toHaveBeenCalledWith(
302,
expect.stringContaining(ENTRA.adminPostLogoutRedirectUri),
);
});
it('redirects with ?auth_error=flow-expired when the pre-auth cookie is missing', async () => {
const { controller, audit } = makeFixture();
const res = makeResStub();
const req = makeReqStub({ signedCookies: {} });
await controller.callback(req, res, 'auth-code', PRE_AUTH.state);
expect(res.redirect).toHaveBeenCalledWith(
302,
expect.stringContaining('auth_error=flow-expired'),
);
expect(audit.signInFailed).toHaveBeenCalledWith(
expect.objectContaining({
failureKind: 'no-pre-auth-cookie',
payload: expect.objectContaining({ surface: 'admin' }),
}),
);
});
it('redirects with the typed error from AuthCodeFlowException', async () => {
const completeAuthCodeFlow = jest
.fn()
.mockRejectedValue(new AuthCodeFlowException({ kind: 'state-mismatch' }));
const { controller, audit } = makeFixture({ completeAuthCodeFlow });
const res = makeResStub();
const req = makeReqStub({
signedCookies: { [PRE_AUTH_COOKIE_NAME]: JSON.stringify(PRE_AUTH) },
});
await controller.callback(req, res, 'auth-code', PRE_AUTH.state);
expect(res.redirect).toHaveBeenCalledWith(
302,
expect.stringContaining('auth_error=state-mismatch'),
);
expect(audit.signInFailed).toHaveBeenCalledWith(
expect.objectContaining({
failureKind: 'state-mismatch',
payload: expect.objectContaining({ surface: 'admin' }),
}),
);
});
});
describe('AdminAuthController.me', () => {
it('returns the public payload with roles when the admin session is populated', () => {
const { controller } = makeFixture();
const res = makeResStub();
const req = makeReqStub({ sessionUser: USER });
controller.me(req, res);
expect(res.json).toHaveBeenCalledWith({
oid: USER.oid,
tid: USER.tid,
username: USER.username,
displayName: USER.displayName,
roles: USER.roles,
});
});
it('throws UnauthorizedException when no user is on the admin session', () => {
const { controller } = makeFixture();
const res = makeResStub();
const req = makeReqStub();
expect(() => controller.me(req, res)).toThrow(/Unauthenticated/);
});
});
describe('AdminAuthController.logout', () => {
it('destroys the admin session, clears the admin cookie + CSRF cookie, redirects to Entra logout', async () => {
const { controller, establisher, buildLogoutUrl } = makeFixture();
const res = makeResStub();
const req = makeReqStub({ sessionUser: USER });
await controller.logout(req, res);
expect(establisher.destroy).toHaveBeenCalledWith({ actor: USER, req });
expect(buildLogoutUrl).toHaveBeenCalledWith(ENTRA.adminPostLogoutRedirectUri);
expect(res.clearCookie).toHaveBeenCalledWith('portal_admin_session', { path: '/' });
expect(res.clearCookie).toHaveBeenCalledWith('portal_csrf', { path: '/' });
expect(res.redirect).toHaveBeenCalledWith(302, ADMIN_LOGOUT_URL);
});
it('uses the __Host- prefixed admin cookie name in production', async () => {
const originalNodeEnv = process.env['NODE_ENV'];
try {
process.env['NODE_ENV'] = 'production';
const { controller } = makeFixture();
const res = makeResStub();
const req = makeReqStub({ sessionUser: USER });
await controller.logout(req, res);
expect(res.clearCookie).toHaveBeenCalledWith('__Host-portal_admin_session', {
path: '/',
});
} finally {
if (originalNodeEnv === undefined) {
delete process.env['NODE_ENV'];
} else {
process.env['NODE_ENV'] = originalNodeEnv;
}
}
});
it('still clears cookies and redirects for an anonymous admin sign-out', async () => {
const { controller, establisher } = makeFixture();
const res = makeResStub();
const req = makeReqStub();
await controller.logout(req, res);
expect(establisher.destroy).toHaveBeenCalledWith({ actor: undefined, req });
expect(res.clearCookie).toHaveBeenCalledWith('portal_admin_session', { path: '/' });
expect(res.redirect).toHaveBeenCalled();
});
});