Files
TREK/server/tests/unit/nest/oidc-backchannel.controller.test.ts
T
Maurice 06aaddc34d feat(oidc): end TREK sessions when the identity provider signs a user out
OpenID Connect Back-Channel Logout 1.0: the provider calls
POST /api/auth/oidc/backchannel-logout with a logout token when a user signs
out there or an admin ends their session, and TREK ends the matching
sessions. Until now a session lived on for up to 30 days after access was
taken away at the provider.

- The token is checked as section 2.6 asks, through the verifier the login
  uses for the id_token (provider JWKS, issuer incl. a custom discovery URL,
  client id in aud), plus a recent iat, the logout event, a sub or sid, no
  nonce, an accepted typ and a jti not seen before (in-memory, bounded replay
  store; a jti whose sessions failed to end is released for the retry).
- The id_token's sid is stored on the session the SSO sign-in creates
  (nullable user_sessions.oidc_sid, both engines), and an app session handed
  off from that browser sign-in carries it too. A token with a sid ends those
  sessions only; a token with only a sub ends every session of the account.
- A valid token answers 200 with no-store also when it names nobody here; an
  invalid one 400 invalid_request, never 500, with the reason only in the
  server log. Public route with its allow-list entry, rate limited, audited
  as oidc.backchannel_logout.
- Always active: nothing changes until an admin enters the URL at the
  provider. Wiki: the URL, where it goes in Authentik, Keycloak and Pocket ID,
  and Keycloak's single token when an admin signs a user out.

Addresses discussion #3124.
2026-11-27 22:24:21 +01:00

135 lines
6.0 KiB
TypeScript

/**
* OidcBackchannelController over a stub service: the parity of section 2.8
* (status, Cache-Control, body) for success and each kind of refusal, the form
* field it reads, the rate limit, and the route metadata (public, POST, 200).
*/
import { IS_PUBLIC } from '../../../src/nest/auth-core/public.decorator';
import { DomainError } from '../../../src/nest/common/domain-error';
import type { RateLimitService } from '../../../src/nest/common/rate-limit.service';
import { RESPONSE_CONTRACT_KEY } from '../../../src/nest/common/response-contract';
import { PUBLIC_ROUTE_ALLOW_LIST } from '../../../src/nest/common/validate-route-guards';
import {
BACKCHANNEL_LOGOUT_RATE_LIMIT,
OidcBackchannelController,
} from '../../../src/nest/oidc/oidc-backchannel.controller';
import type { OidcBackchannelService } from '../../../src/nest/oidc/oidc-backchannel.service';
import { RequestMethod } from '@nestjs/common';
import { HTTP_CODE_METADATA, METHOD_METADATA, PATH_METADATA } from '@nestjs/common/constants';
import { oidcBackchannelLogoutErrorSchema, oidcBackchannelLogoutResponseSchema } from '@trek/shared';
import type { Request, Response } from 'express';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const logout = vi.fn();
const check = vi.fn();
const service = { logout } as unknown as OidcBackchannelService;
const rl = { check } as unknown as RateLimitService;
const controller = () => new OidcBackchannelController(service, rl);
function makeRes() {
const headers: Record<string, string> = {};
const res = {
headers,
set: vi.fn((name: string, value: string) => {
headers[name.toLowerCase()] = value;
return res;
}),
};
return res as unknown as Response & { headers: Record<string, string> };
}
const req = (body: unknown, ip = '198.51.100.7') => ({ body, ip, socket: {} }) as unknown as Request;
/** What the global filter makes of a thrown refusal: its status and body. */
async function refused(call: Promise<unknown>): Promise<{ status: number; body: Record<string, unknown> }> {
const err = await call.then(
() => null,
(e: unknown) => e,
);
expect(err).toBeInstanceOf(DomainError);
return { status: (err as DomainError).getStatus(), body: (err as DomainError).toBody() };
}
beforeEach(() => {
vi.clearAllMocks();
check.mockResolvedValue(true);
logout.mockResolvedValue(undefined);
});
describe('OidcBackchannelController POST /api/auth/oidc/backchannel-logout', () => {
it('BCL-CTL-001: a valid token answers 200 {} with Cache-Control no-store and is handed to the service with the caller ip', async () => {
const res = makeRes();
const body = await controller().logout(req({ logout_token: 'a.b.c' }), res);
expect(body).toEqual({});
expect(oidcBackchannelLogoutResponseSchema.safeParse(body).success).toBe(true);
expect(res.headers['cache-control']).toBe('no-store');
expect(res.headers['pragma']).toBe('no-cache');
expect(logout).toHaveBeenCalledWith('a.b.c', '198.51.100.7');
});
it('BCL-CTL-002: a missing logout_token is the 400 invalid_request of section 2.8, with no-store', async () => {
const res = makeRes();
const result = await refused(controller().logout(req({}), res));
expect(result).toEqual({
status: 400,
body: { error: 'invalid_request', error_description: 'The logout_token parameter is missing or malformed.' },
});
expect(oidcBackchannelLogoutErrorSchema.safeParse(result.body).success).toBe(true);
expect(res.headers['cache-control']).toBe('no-store');
expect(logout).not.toHaveBeenCalled();
});
it.each([
{ label: 'a repeated form field (an array)', body: { logout_token: ['a', 'b'] } },
{ label: 'an empty one', body: { logout_token: '' } },
{ label: 'no body at all', body: undefined },
])('BCL-CTL-003: $label is refused the same way', async ({ body }) => {
expect((await refused(controller().logout(req(body), makeRes()))).status).toBe(400);
expect(logout).not.toHaveBeenCalled();
});
it('BCL-CTL-004: a token the service refuses keeps its 400 body, and the header is already set', async () => {
logout.mockRejectedValue(
new DomainError(400, 'invalid_request', {
code: 'stale_iat',
details: { error_description: 'The logout token is missing or invalid.' },
}),
);
const res = makeRes();
expect(await refused(controller().logout(req({ logout_token: 'a.b.c' }), res))).toEqual({
status: 400,
body: { error: 'invalid_request', error_description: 'The logout token is missing or invalid.' },
});
expect(res.headers['cache-control']).toBe('no-store');
});
it('BCL-CTL-005: past the flood limit the answer is 429, before the body is read', async () => {
check.mockResolvedValue(false);
const res = makeRes();
expect(await refused(controller().logout(req({ logout_token: 'a.b.c' }), res))).toEqual({
status: 429,
body: { error: 'too_many_requests', error_description: 'Too many requests. Please try again later.' },
});
expect(check).toHaveBeenCalledWith(
'oidc_backchannel',
'198.51.100.7',
BACKCHANNEL_LOGOUT_RATE_LIMIT,
60_000,
expect.any(Number),
);
expect(logout).not.toHaveBeenCalled();
expect(res.headers['cache-control']).toBe('no-store');
});
it('BCL-CTL-006: the route is a public POST that answers 200 under the OIDC prefix', () => {
const handler = OidcBackchannelController.prototype.logout;
expect(Reflect.getMetadata(PATH_METADATA, OidcBackchannelController)).toBe('api/auth/oidc');
expect(Reflect.getMetadata(PATH_METADATA, handler)).toBe('backchannel-logout');
expect(Reflect.getMetadata(METHOD_METADATA, handler)).toBe(RequestMethod.POST);
expect(Reflect.getMetadata(HTTP_CODE_METADATA, handler)).toBe(200);
expect(Reflect.getMetadata(RESPONSE_CONTRACT_KEY, handler)).toBe(oidcBackchannelLogoutResponseSchema);
expect(PUBLIC_ROUTE_ALLOW_LIST).toContain('OidcBackchannelController.logout');
expect(Reflect.getMetadata(IS_PUBLIC, OidcBackchannelController)).toEqual({ reason: expect.any(String) });
});
});