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.
This commit is contained in:
Maurice
2026-11-27 22:24:19 +01:00
parent 6f669920f1
commit 06aaddc34d
28 changed files with 1824 additions and 26 deletions
+2 -2
View File
@@ -142,11 +142,11 @@ SQLite is the default engine and Postgres the second (`TREK_DB_URL`, see Engines
- **`src/nest/common/`**: the global exception filter (error envelope), the Zod validation pipe, the idempotency interceptor (`X-Idempotency-Key` replay), and `validate-route-guards.ts` (boot-time ratchet refusing any public route not on its allow-list).
- **Response contracts** (`src/nest/common/response-contract.ts`): `@ResponseContract(schema)` names the `@trek/shared` response schema a handler answers with. Under `NODE_ENV=test` it adds an interceptor that parses every response of that handler against the schema and turns a body the schema does not describe into a logged 500 naming the handler and the first issues, so every e2e and integration test that reaches the route is a drift check; in production it only records the schema and adds nothing to the request path. The parse never replaces the body. When a check fails, fix the schema to describe what the route really sends, or the test stub to return what the service really returns, never the response. Rows keep their storage spelling in these schemas (0/1 flags, TEXT or epoch times) wherever the route has always answered that way.
- **Auth is default-deny**: the global auth guard and the MFA policy guard run as `APP_GUARD`s, followed by the managed-install guard (`managed.guard.ts`), which refuses the routes a centrally administered install withholds from its own admin — it runs last so strangers still get a 401, never a route-revealing 403. Routes opt out with `@Public()`/`@OptionalAuth()`. The global guard stands down for routes declaring their own guard chain, so `@UseGuards(JwtAuthGuard, TripAccessGuard)` + `@RequirePermission` stacks work. Session is a cookie (`trek_session`); `@CurrentUser()` reads the user. Every session token carries a `jti` naming its `user_sessions` row, and `verifyJwtAndLoadUser` refuses one whose row is revoked, expired or gone (logout, `/api/auth/sessions`, a password change or reset, an MFA disable all end rows; `session-purge.job.ts` deletes the expired ones nightly; a revoked row waits for its own expiry, because for a session renewed from a pre-`jti` token, whose id is derived from that token, the revoked row is all that keeps the token from inserting it again). A token without a `jti` predates the table and passes until it expires, so an upgrade signs nobody out. The `token` field in the login-type JSON bodies and in the SSO exchange (`GET /api/auth/oidc/exchange`, which also answers `success: true`) is deprecated: kept for API clients, read by nothing of ours. **Never gate a multipart upload with a guard** — guards run before the parser and the client sees ECONNRESET instead of your 403; check in the handler.
- **Auth is default-deny**: the global auth guard and the MFA policy guard run as `APP_GUARD`s, followed by the managed-install guard (`managed.guard.ts`), which refuses the routes a centrally administered install withholds from its own admin — it runs last so strangers still get a 401, never a route-revealing 403. Routes opt out with `@Public()`/`@OptionalAuth()`. The global guard stands down for routes declaring their own guard chain, so `@UseGuards(JwtAuthGuard, TripAccessGuard)` + `@RequirePermission` stacks work. Session is a cookie (`trek_session`); `@CurrentUser()` reads the user. Every session token carries a `jti` naming its `user_sessions` row, and `verifyJwtAndLoadUser` refuses one whose row is revoked, expired or gone (logout, `/api/auth/sessions`, a password change or reset, an MFA disable and an OIDC back-channel logout all end rows; `session-purge.job.ts` deletes the expired ones nightly; a revoked row waits for its own expiry, because for a session renewed from a pre-`jti` token, whose id is derived from that token, the revoked row is all that keeps the token from inserting it again). A token without a `jti` predates the table and passes until it expires, so an upgrade signs nobody out. The `token` field in the login-type JSON bodies and in the SSO exchange (`GET /api/auth/oidc/exchange`, which also answers `success: true`) is deprecated: kept for API clients, read by nothing of ours. **Never gate a multipart upload with a guard** — guards run before the parser and the client sees ECONNRESET instead of your 403; check in the handler.
- **Logging**: `src/nest/audit/audit-log.logger.ts` (`logInfo`/`logWarn`/`logError`/`logDebug`) prints each line to the console and queues it for `data/logs/trek.log`, which `log-file.ts` appends in batches off the event loop and rotates at 10 MB over five files; `index.ts` flushes what is queued on exit. Never write the log file synchronously from a request path.
- **Request correlation** (`src/nest/common/request-correlation.ts`): every HTTP request runs under an id (a well-formed incoming `X-Request-Id`, else a fresh UUID) that the response carries in `X-Request-Id`, and every log line written inside it is tagged `[http <id>]`. The exception filter leaves a 5xx on `res.locals` so the access log writes the request line and the stack as one entry. The other entry points (MCP tool/resource/prompt calls via the registry's `around` seam, WebSocket messages in `TrekWsAdapter`, plugin RPC dispatches in the supervisor, cron ticks in `CronRegistrarService`) each run under their own id through `traceEntry()` (`nest/audit/entry-trace.logger.ts`), which logs one line per call: debug on success, debug as `skipped` when the call declines its work on purpose (a cron tick whose lease another process holds), warn or error with the reason on failure. A new entry point goes through `traceEntry()` too.
- **Process safety nets** (`src/index.ts`, `src/shutdown.ts`): `unhandledRejection` and `uncaughtException` are logged to trek.log and end in the same orderly shutdown as SIGTERM, with exit code 1; a second fatal error during it exits at once. A shutdown first marks `ReadinessService` (`nest/health/`) as draining, so `/api/health/ready` answers 503 for the whole drain. The HTTP server keeps idle keep-alive connections for `HTTP_KEEP_ALIVE_TIMEOUT_MS` (95 s, above the 60 s of nginx and the 90 s of Traefik) with the headers timeout one second above it (`applyProxyTimeouts` in `bootstrap.ts`).
- **Process-local state sits behind injectable ports**, each with an in-memory implementation that keeps today's behaviour: `RateLimitStore` (`nest/common/rate-limit.store.ts`, provided by `RateLimitModule`), `PendingCodeStore` (`nest/oauth/oauth.pending-codes.ts`), `OidcFlowStore` (`nest/oidc/oidc-flow.store.ts`), `PermissionsCacheStore` (`nest/permissions/permissions-cache.ts`) and `RoomRegistry` (`nest/realtime/ws-state.ts`). The owning module provides the implementation. Every port a shared store could back returns promises (a store in the database or on the network is async); `RoomRegistry` stays synchronous because membership holds live sockets, and several processes would need a fan-out in front of `broadcast()` instead. The process-wide ports (`PendingCodeStore`, `PermissionsCacheStore`, `RoomRegistry`) also have readers outside the container (the pending-code sweep, the backup restore's cache flush, the broadcast functions, hand-built consumers), so their module installs the store the container resolved in a `ProcessStoreSlot` (`nest/common/process-store-slot.ts`) those readers use: overriding the provider changes every reader. New process-local state follows the same shape; TREK still runs as one process.
- **Process-local state sits behind injectable ports**, each with an in-memory implementation that keeps today's behaviour: `RateLimitStore` (`nest/common/rate-limit.store.ts`, provided by `RateLimitModule`), `PendingCodeStore` (`nest/oauth/oauth.pending-codes.ts`), `OidcFlowStore` (`nest/oidc/oidc-flow.store.ts`), `OidcLogoutReplayStore` (`nest/oidc/oidc-logout-replay.store.ts`), `PermissionsCacheStore` (`nest/permissions/permissions-cache.ts`) and `RoomRegistry` (`nest/realtime/ws-state.ts`). The owning module provides the implementation. Every port a shared store could back returns promises (a store in the database or on the network is async); `RoomRegistry` stays synchronous because membership holds live sockets, and several processes would need a fan-out in front of `broadcast()` instead. The process-wide ports (`PendingCodeStore`, `PermissionsCacheStore`, `RoomRegistry`) also have readers outside the container (the pending-code sweep, the backup restore's cache flush, the broadcast functions, hand-built consumers), so their module installs the store the container resolved in a `ProcessStoreSlot` (`nest/common/process-store-slot.ts`) those readers use: overriding the provider changes every reader. New process-local state follows the same shape; TREK still runs as one process.
- **`src/middleware/globalMiddleware.ts`** is the only Express middleware left (helmet/CSP, CORS, HSTS, forced-HTTPS, logging, cookies).
## Tests
@@ -13,6 +13,7 @@ export class UserSessions {
expires_at!: string;
revoked_at?: string | null;
user_agent?: string | null;
oidc_sid?: string | null;
}
export const UserSessionsSchema = defineEntity({
@@ -27,5 +28,6 @@ export const UserSessionsSchema = defineEntity({
expires_at: p.type(DbTimestampType).index('idx_user_sessions_expires'),
revoked_at: p.type(DbTimestampType).nullable(),
user_agent: p.text().nullable(),
oidc_sid: p.text().nullable().index('idx_user_sessions_oidc_sid'),
},
});
@@ -10,4 +10,5 @@ export interface UserSessionsTable {
expires_at: string;
revoked_at: InsertOptional<string | null>;
user_agent: InsertOptional<string | null>;
oidc_sid: InsertOptional<string | null>;
}
@@ -0,0 +1,35 @@
import { engineDdl } from '../migration-utils';
import { Migration } from '@mikro-orm/migrations';
/**
* A session started through SSO remembers the identity provider's session it
* came from, so the provider can end it again (OpenID Connect Back-Channel
* Logout 1.0).
*
* `user_sessions.oidc_sid` holds the `sid` claim of the verified id_token the
* login was made with. A logout token naming that `sid` ends only the TREK
* sessions carrying it; one naming only the subject ends every session of the
* account. The column is empty for every other way in (password, passkey,
* demo, a renewal from a token issued before sessions were tracked) and for a
* provider that sends no `sid`, and every existing row starts empty, so nothing
* changes for a session that is already there.
*
* The index serves the logout token that names a `sid` without a subject: it is
* looked up across every account of the provider.
*/
export class Migration20200101046510_a_session_knows_its_provider_session extends Migration {
override name = 'Migration20200101046510_a_session_knows_its_provider_session';
override up(): void {
engineDdl(this, {
sqlite: [
'ALTER TABLE user_sessions ADD COLUMN oidc_sid TEXT',
'CREATE INDEX idx_user_sessions_oidc_sid ON user_sessions(oidc_sid)',
],
postgres: [
'alter table "user_sessions" add column "oidc_sid" text null',
'create index "idx_user_sessions_oidc_sid" on "user_sessions" ("oidc_sid")',
],
});
}
}
@@ -13,12 +13,13 @@ export interface UserSessionRow {
expires_at: string;
revoked_at: string | null;
user_agent: string | null;
oidc_sid: string | null;
}
const _userSessionRowKeys: AssertRowKeys<UserSessionRow, UserSessions> = true;
/** What a session list shows: the row without its owner, who is the caller. */
export type UserSessionListRow = Omit<UserSessionRow, 'user_id' | 'revoked_at'>;
/** What a session list shows: the row without its owner, who is the caller, and without the provider's session id. */
export type UserSessionListRow = Omit<UserSessionRow, 'user_id' | 'revoked_at' | 'oidc_sid'>;
/**
* An active session read before a database file swap, with the email its
@@ -35,6 +36,8 @@ export interface NewUserSessionRow {
created_at: string;
expires_at: string;
user_agent: string | null;
/** The `sid` claim of the id_token an SSO sign-in was made with; left out for every other way in. */
oidc_sid?: string | null;
}
/**
@@ -45,7 +48,10 @@ export interface NewUserSessionRow {
* a test can pin a clock for.
*/
export class UserSessionsRepository extends TrekRepository<UserSessions> {
/** `INSERT INTO user_sessions (id, user_id, created_at, last_seen_at, expires_at, user_agent) VALUES (?, ?, ?, ?, ?, ?)`. */
/**
* `INSERT INTO user_sessions (id, user_id, created_at, last_seen_at, expires_at, user_agent, oidc_sid)
* VALUES (?, ?, ?, ?, ?, ?, ?)`.
*/
async insertSession(row: NewUserSessionRow): Promise<void> {
await this.insert({
id: row.id,
@@ -54,6 +60,7 @@ export class UserSessionsRepository extends TrekRepository<UserSessions> {
last_seen_at: row.created_at,
expires_at: row.expires_at,
user_agent: row.user_agent,
oidc_sid: row.oidc_sid ?? null,
});
}
@@ -92,6 +99,20 @@ export class UserSessionsRepository extends TrekRepository<UserSessions> {
return row ? { id: row.id, last_seen_at: row.last_seen_at } : null;
}
/**
* The same match as `findActive`, answering the provider session the row was
* signed in with: `SELECT oidc_sid FROM user_sessions WHERE id = ? AND user_id = ?
* AND revoked_at IS NULL AND expires_at > ?`. A session minted from this one
* carries that `sid` on, so a back-channel logout naming it ends both.
*/
async findActiveOidcSid(id: string, userId: number, now: string): Promise<{ oidc_sid: string | null } | null> {
const row = await this.findOne(
{ id, user: userId, revoked_at: null, expires_at: { $gt: now } },
{ fields: ['id', 'oidc_sid'] },
);
return row ? { oidc_sid: row.oidc_sid ?? null } : null;
}
/** `UPDATE user_sessions SET last_seen_at = ? WHERE id = ?`. */
async touchLastSeen(id: string, now: string): Promise<void> {
await this.nativeUpdate({ id }, { last_seen_at: now });
@@ -155,6 +176,27 @@ export class UserSessionsRepository extends TrekRepository<UserSessions> {
);
}
/**
* A back-channel logout naming the provider's session:
* `UPDATE user_sessions SET revoked_at = ? WHERE oidc_sid = ? AND revoked_at IS NULL
* AND user_id IN (SELECT id FROM users WHERE oidc_issuer = ?) [AND user_id = ?]
* RETURNING user_id`. Only accounts linked to that issuer match, and with
* `userId` only that account. Answers the owner of every session it ended,
* one entry per session.
*/
async revokeByOidcSid(sid: string, issuer: string, now: string, userId?: number): Promise<number[]> {
const db = this.kysely<Pick<DB, 'user_sessions' | 'users'>>();
let update = db
.updateTable('user_sessions')
.set({ revoked_at: now })
.where('oidc_sid', '=', sid)
.where('revoked_at', 'is', null)
.where('user_id', 'in', db.selectFrom('users').select('id').where('oidc_issuer', '=', issuer));
if (userId !== undefined) update = update.where('user_id', '=', userId);
const rows = await update.returning('user_id').execute();
return rows.map((row) => Number(row.user_id));
}
/**
* `SELECT user_id, MAX(last_seen_at) FROM user_sessions GROUP BY user_id`: when
* each account last made an authenticated request, over every row the nightly
@@ -191,6 +233,7 @@ export class UserSessionsRepository extends TrekRepository<UserSessions> {
last_seen_at: row.last_seen_at,
expires_at: row.expires_at,
user_agent: row.user_agent ?? null,
oidc_sid: row.oidc_sid ?? null,
});
}
return carried;
@@ -219,6 +262,7 @@ export class UserSessionsRepository extends TrekRepository<UserSessions> {
expires_at: row.expires_at,
revoked_at: null,
user_agent: row.user_agent,
oidc_sid: row.oidc_sid,
})),
{ onConflictFields: ['id'], onConflictAction: 'ignore' },
);
+1
View File
@@ -39,6 +39,7 @@ const ACTION_LABELS: Record<string, string> = {
'admin.places_contribute_withdraw': 'withdrew the place details this installation shared',
'immich.private_ip_configured': 'configured Immich with private IP',
'oidc.role_change': 'role changed by OIDC claim mapping',
'oidc.backchannel_logout': 'signed out by the identity provider',
};
/**
+13 -4
View File
@@ -1,6 +1,5 @@
import { Users } from '../../db/entities/Users.entity';
import type { UsersRepository } from '../../db/repositories/Users.repository';
import { dbNow } from '../../db/types/db-timestamp.type';
import { UnitOfWork } from '../database/unit-of-work';
import { SessionsService, type SessionClient } from '../sessions/sessions.service';
import { AuthService } from './auth.service';
@@ -39,16 +38,26 @@ export class LoginSessionService {
* longer stands: the account is gone, the password changed since, or that
* session ended (a sign-out, a revocation, a password reset). A credential
* the account took back cannot mint a new one this way.
*
* The new session keeps the identity provider's `sid` of the one it comes
* from, so a back-channel logout of that provider session ends both.
*/
async signIn(origin: SessionOrigin, remember: boolean | undefined, client?: SessionClient): Promise<string | null> {
return this.uow.transactional(async () => {
const passwordVersion = await this.users.getPasswordVersion(origin.userId);
if (passwordVersion === null || passwordVersion !== origin.passwordVersion) return null;
if (origin.sessionId !== null && !(await this.sessions.findActive(origin.sessionId, origin.userId, dbNow()))) {
return null;
let oidcSid: string | null = null;
if (origin.sessionId !== null) {
const from = await this.sessions.findActiveOrigin(origin.sessionId, origin.userId);
if (!from) return null;
oidcSid = from.oidcSid;
}
await this.users.touchLastLogin(origin.userId);
return this.auth.generateToken({ id: origin.userId, password_version: passwordVersion }, remember, client);
return this.auth.generateToken(
{ id: origin.userId, password_version: passwordVersion },
remember,
oidcSid !== null ? { ...client, oidcSid } : client,
);
});
}
}
@@ -155,6 +155,9 @@ export const PUBLIC_ROUTE_ALLOW_LIST: string[] = [
'OauthPublicController.revoke',
'OauthPublicController.token',
'OauthPublicController.userinfo',
// OpenID Connect Back-Channel Logout: the identity provider posts here server
// to server, so no session exists; the signed logout token is the credential.
'OidcBackchannelController.logout',
// The OIDC handshake, before a TREK session exists.
'OidcController.callback',
'OidcController.exchange',
@@ -0,0 +1,84 @@
import { getClientIp } from '../audit/client-ip';
import { Public } from '../auth-core/public.decorator';
import { DomainError } from '../common/domain-error';
import { RateLimitService } from '../common/rate-limit.service';
import { ResponseContract } from '../common/response-contract';
import { OidcBackchannelService } from './oidc-backchannel.service';
import { Controller, HttpCode, Post, Req, Res } from '@nestjs/common';
import {
oidcBackchannelLogoutRequestSchema,
oidcBackchannelLogoutResponseSchema,
type OidcBackchannelLogoutResponse,
} from '@trek/shared';
import type { Request, Response } from 'express';
/**
* Requests one address may send in a minute. An identity provider sends one
* request per signed-out session, and an admin ending every session of a realm
* sends a burst of them from one address, so the limit sits far above any real
* logout traffic and only caps a flood of tokens that each cost a signature
* check.
*/
export const BACKCHANNEL_LOGOUT_RATE_LIMIT = 600;
const RATE_WINDOW_MS = 60_000;
/**
* POST /api/auth/oidc/backchannel-logout: OpenID Connect Back-Channel Logout
* 1.0. The identity provider posts the signed `logout_token` here, server to
* server, when a user signs out there; the admin enters this URL as the
* client's back-channel logout URL in the provider.
*
* Always mounted: without a provider configured, or before the admin enters
* the URL there, nothing ever posts a valid token and every request is a 400.
*
* The answers are the ones section 2.8 prescribes, all with
* `Cache-Control: no-store`: 200 when the token was valid (also when it named
* no account or session here), 400 `{"error":"invalid_request"}` for a missing
* or invalid token and while OIDC is not configured (the login answers 400 for
* that too). A 429 past the flood limit. Never a 500 for a bad token.
*
* The body is form-encoded, which the global `urlencodedParser` reads for this
* path as for every other. It is checked against the shared contract with
* `safeParse` in the handler rather than by the Zod pipe, so that a missing
* token gets the spec's error body and the no-store header, like every other
* refusal here.
*/
@Public('the identity provider calls it server to server; the signed logout token is the credential')
@Controller('api/auth/oidc')
export class OidcBackchannelController {
constructor(
private readonly backchannel: OidcBackchannelService,
private readonly rl: RateLimitService,
) {}
@Post('backchannel-logout')
@HttpCode(200)
@ResponseContract(oidcBackchannelLogoutResponseSchema)
async logout(@Req() req: Request, @Res({ passthrough: true }) res: Response): Promise<OidcBackchannelLogoutResponse> {
res.set('Cache-Control', 'no-store');
res.set('Pragma', 'no-cache');
if (
!(await this.rl.check(
'oidc_backchannel',
req.ip || 'unknown',
BACKCHANNEL_LOGOUT_RATE_LIMIT,
RATE_WINDOW_MS,
Date.now(),
))
) {
throw new DomainError(429, 'too_many_requests', {
details: { error_description: 'Too many requests. Please try again later.' },
});
}
const body = oidcBackchannelLogoutRequestSchema.safeParse(req.body);
if (!body.success) {
throw new DomainError(400, 'invalid_request', {
code: 'missing_logout_token',
details: { error_description: 'The logout_token parameter is missing or malformed.' },
});
}
await this.backchannel.logout(body.data.logout_token, getClientIp(req) ?? null);
return {};
}
}
@@ -0,0 +1,249 @@
import { readEnv } from '../../app-config';
import { Users } from '../../db/entities/Users.entity';
import type { UsersRepository } from '../../db/repositories/Users.repository';
import { logInfo, logWarn } from '../audit/audit-log.logger';
import { AuditService } from '../audit/audit.service';
import { DomainError } from '../common/domain-error';
import { SessionsService } from '../sessions/sessions.service';
import { OidcLogoutReplayStore } from './oidc-logout-replay.store';
import { expectedOidcIssuer, OidcService, type OidcConfig, type OidcDiscoveryDoc } from './oidc.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
/** The `events` member a logout token must carry (section 2.4). */
export const BACKCHANNEL_LOGOUT_EVENT = 'http://schemas.openid.net/event/backchannel-logout';
/**
* How old a logout token's `iat` may be. A provider sends the token the moment
* the user signs out there, so a few seconds is normal; five minutes leaves
* room for a provider that retries a delivery, and keeps the window in which a
* captured token could be replayed, and the replay store has to remember it,
* short.
*/
export const LOGOUT_TOKEN_MAX_AGE_SEC = 300;
/**
* The difference between the provider's clock and this one that is forgiven:
* an `iat` up to this far in the future, and `exp` and `nbf` by this much.
*/
export const LOGOUT_TOKEN_CLOCK_SKEW_SEC = 60;
/**
* The header `typ` values a logout token may carry. Section 2.4 asks for
* `logout+jwt`; many providers send the generic `JWT` or nothing at all, which
* is accepted for compatibility (the `events` and `nonce` checks are what keep
* an id_token out). Any other explicit type, an access token's `at+jwt` for
* one, names a token of another kind and is refused.
*/
const ACCEPTED_TYP = new Set(['logout+jwt', 'application/logout+jwt', 'jwt']);
/** What a logout token said, once every check of section 2.6 passed. */
interface LogoutTokenClaims {
iss: string;
jti: string;
sub?: string;
sid?: string;
/** Epoch milliseconds after which the token would be refused anyway; the replay entry lives until then. */
acceptedUntil: number;
}
/** The outcome of the checks: the claims, or the reason the token was refused (logged, never sent). */
type LogoutTokenCheck = { valid: true; claims: LogoutTokenClaims } | { valid: false; reason: string };
const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
const nonEmptyString = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
/**
* OpenID Connect Back-Channel Logout 1.0: the identity provider tells TREK
* that a user signed out there, and TREK ends the sessions that sign-in made.
*
* The token is checked as section 2.6 asks, through the same verifier the
* login uses for the id_token (`OidcService.verifyProviderJwt`: the provider's
* discovery document and JWKS, an asymmetric algorithm the header names, the
* client id in `aud`, the issuer the login accepts, custom discovery URL
* included), then for what makes it a logout token: a recent `iat`, a `jti`
* not seen before, the back-channel logout event, a `sub` or a `sid`, and no
* `nonce`.
*
* What ends: with a `sid`, the sessions the login stored that `sid` on (of the
* account the `sub` names, when the token names one too); with only a `sub`,
* every session of that account, as a password change does. An account or
* session that does not exist is not an error: the provider gets the same 200
* either way, so the route never tells which subjects have an account here.
*
* Sessions are not announced over the websocket when they end, on any path
* (`SessionsService.revokeAll` callers included): the next request of a
* signed-out browser is refused by the session check, and so is this one's.
*
* Unlike the login, this works while SSO login is switched off: sessions made
* before the switch still came from the provider, and it may still end them.
*/
@Injectable()
export class OidcBackchannelService {
constructor(
private readonly oidc: OidcService,
private readonly sessions: SessionsService,
private readonly audit: AuditService,
private readonly replays: OidcLogoutReplayStore,
@InjectRepository(Users) private readonly usersRepo: UsersRepository,
) {}
/**
* Validate the token and end the sessions it names. Throws a 400
* `invalid_request` DomainError for every token that fails a check (and when
* OIDC is not set up), so the route never answers 500 for a bad token.
*/
async logout(logoutToken: string, ip: string | null): Promise<void> {
const config = await this.oidc.getOidcConfig();
if (!config) throw refusal('not_configured', 'OpenID Connect is not configured.');
const check = await this.validateLogoutToken(logoutToken, config);
// `in` rather than `!check.valid`: the server compiles without
// strictNullChecks, where the boolean discriminant does not narrow.
if ('reason' in check) {
logWarn(`[OIDC] Back-channel logout token refused: ${check.reason}`);
throw refusal(check.reason);
}
const { claims } = check;
// Recorded only once every other check passed, so a token that fails one
// cannot use up the jti of a real one.
const key = `${claims.iss}\n${claims.jti}`;
if (!(await this.replays.claim(key, claims.acceptedUntil, Date.now()))) {
logWarn('[OIDC] Back-channel logout token refused: replayed_jti');
throw refusal('replayed_jti');
}
try {
await this.endSessions(claims, config, ip);
} catch (err) {
// The sessions did not end, so the provider's retry of this token must
// be acted on rather than refused as a replay.
await this.replays.release(key);
throw err;
}
}
/**
* Every check of section 2.6 on one token, in the order the spec lists them.
* Public for the tests, which name a reason for each refusal.
*/
async validateLogoutToken(token: string, config: OidcConfig): Promise<LogoutTokenCheck> {
if (config.issuer && !config.issuer.startsWith('https://') && readEnv().app.isProduction) {
return { valid: false, reason: 'issuer_not_https' };
}
let doc: OidcDiscoveryDoc;
try {
doc = await this.oidc.discover(config.issuer, config.discoveryUrl);
} catch (err) {
return { valid: false, reason: `discovery_failed: ${err instanceof Error ? err.message : String(err)}` };
}
const issuer = expectedOidcIssuer(doc, config);
const verified = await this.oidc.verifyProviderJwt(
token,
doc,
config.clientId,
issuer,
LOGOUT_TOKEN_CLOCK_SKEW_SEC,
);
if ('error' in verified) return { valid: false, reason: verified.error };
const { claims, header } = verified;
if (header.typ !== undefined && (typeof header.typ !== 'string' || !ACCEPTED_TYP.has(header.typ.toLowerCase()))) {
return { valid: false, reason: 'wrong_typ' };
}
const nowSec = Date.now() / 1000;
const iat = claims.iat;
if (typeof iat !== 'number' || !Number.isFinite(iat)) return { valid: false, reason: 'missing_iat' };
if (iat > nowSec + LOGOUT_TOKEN_CLOCK_SKEW_SEC) return { valid: false, reason: 'iat_in_future' };
if (nowSec - iat > LOGOUT_TOKEN_MAX_AGE_SEC + LOGOUT_TOKEN_CLOCK_SKEW_SEC) {
return { valid: false, reason: 'stale_iat' };
}
const jti = claims.jti;
if (!nonEmptyString(jti)) return { valid: false, reason: 'missing_jti' };
const events = claims.events;
if (!isRecord(events) || !isRecord(events[BACKCHANNEL_LOGOUT_EVENT])) {
return { valid: false, reason: 'missing_logout_event' };
}
if ('nonce' in claims) return { valid: false, reason: 'nonce_present' };
if (claims.sub !== undefined && !nonEmptyString(claims.sub)) return { valid: false, reason: 'bad_sub' };
if (claims.sid !== undefined && !nonEmptyString(claims.sid)) return { valid: false, reason: 'bad_sid' };
const sub = nonEmptyString(claims.sub) ? claims.sub : undefined;
const sid = nonEmptyString(claims.sid) ? claims.sid : undefined;
if (sub === undefined && sid === undefined) return { valid: false, reason: 'no_sub_or_sid' };
const exp = typeof claims.exp === 'number' ? claims.exp : Number.POSITIVE_INFINITY;
const acceptedUntilSec = Math.min(exp, iat + LOGOUT_TOKEN_MAX_AGE_SEC) + LOGOUT_TOKEN_CLOCK_SKEW_SEC;
return {
valid: true,
claims: {
iss: issuer,
jti,
...(sub !== undefined ? { sub } : {}),
...(sid !== undefined ? { sid } : {}),
acceptedUntil: Math.ceil(acceptedUntilSec * 1000),
},
};
}
/**
* End what the token names. A `sub` is looked up the way the login links an
* account, by subject and the configured issuer; a `sid` matches the
* sessions the login stored it on.
*/
private async endSessions(claims: LogoutTokenClaims, config: OidcConfig, ip: string | null): Promise<void> {
const revokedByUser = new Map<number, number>();
let scope: 'session' | 'all';
if (claims.sub !== undefined) {
const user = await this.usersRepo.findByOidcIdentity(claims.sub, config.issuer);
if (!user) {
logInfo('[OIDC] Back-channel logout for a subject without an account here; nothing to end.');
return;
}
if (claims.sid !== undefined) {
scope = 'session';
const owners = await this.sessions.revokeByOidcSid(claims.sid, config.issuer, user.id);
revokedByUser.set(user.id, owners.length);
} else {
scope = 'all';
revokedByUser.set(user.id, await this.sessions.revokeAll(user.id));
}
} else if (claims.sid !== undefined) {
scope = 'session';
for (const owner of await this.sessions.revokeByOidcSid(claims.sid, config.issuer)) {
revokedByUser.set(owner, (revokedByUser.get(owner) ?? 0) + 1);
}
} else {
// validateLogoutToken never lets a token through without either.
return;
}
// writeAudit stands on its own and never throws, so the rows are written side by side.
await Promise.all(
[...revokedByUser].map(([userId, revoked]) =>
this.audit.writeAudit({ userId, action: 'oidc.backchannel_logout', ip, details: { scope, revoked } }),
),
);
logInfo(`[OIDC] Back-channel logout ended ${sum(revokedByUser)} session(s) (${scope}).`);
}
}
function sum(counts: Map<number, number>): number {
let total = 0;
for (const n of counts.values()) total += n;
return total;
}
/**
* The 400 of section 2.8. The reason goes into the code and the log, never
* into the body: the caller may be anyone, and the provider only needs to
* know that the token was refused.
*/
function refusal(reason: string, description = 'The logout token is missing or invalid.'): DomainError {
return new DomainError(400, 'invalid_request', {
code: reason,
details: { error_description: description },
});
}
@@ -0,0 +1,75 @@
/**
* The logout tokens already acted on, by issuer and `jti`, so a token seen
* once is refused when it comes again (OpenID Connect Back-Channel Logout 1.0,
* section 2.6, step 6).
*
* An entry only has to live as long as its token would still be accepted: the
* validation refuses a token whose `iat` is older than the accepted window (or
* whose `exp` has passed), so a replay after that is refused without the
* entry. The caller passes that moment as `expiresAt`.
*
* An injectable port like OidcFlowStore: in memory today, replaceable in
* OidcModule by a store shared between processes. Every method returns a
* promise for that reason.
*/
export abstract class OidcLogoutReplayStore {
/**
* Record `key` until `expiresAt` (epoch milliseconds). True when it was not
* held yet, false when it is a replay. Check and record are one step.
*/
abstract claim(key: string, expiresAt: number, now: number): Promise<boolean>;
/**
* Forget `key` again, for a token whose logout failed after its claim, so
* the provider's retry of the same token is acted on.
*/
abstract release(key: string): Promise<void>;
}
/**
* The most entries held at once. Only the provider can sign a token that
* passes validation, so the store fills only as fast as real logouts arrive;
* the cap keeps memory bounded whatever happens. At the cap the expired
* entries go first, then the oldest one.
*/
export const OIDC_LOGOUT_REPLAY_MAX_ENTRIES = 10_000;
/** The current behaviour: one bounded map in this process's memory. */
export class InMemoryOidcLogoutReplayStore extends OidcLogoutReplayStore {
private readonly seen = new Map<string, number>();
constructor(private readonly maxEntries = OIDC_LOGOUT_REPLAY_MAX_ENTRIES) {
super();
}
claim(key: string, expiresAt: number, now: number): Promise<boolean> {
const held = this.seen.get(key);
if (held !== undefined && held > now) return Promise.resolve(false);
this.seen.delete(key);
if (this.seen.size >= this.maxEntries) this.makeRoom(now);
this.seen.set(key, expiresAt);
return Promise.resolve(true);
}
release(key: string): Promise<void> {
this.seen.delete(key);
return Promise.resolve();
}
/** How many entries are held, for the tests of the cap. */
get size(): number {
return this.seen.size;
}
private makeRoom(now: number): void {
for (const [key, expiresAt] of this.seen) {
if (expiresAt <= now) this.seen.delete(key);
}
// Map iteration follows insertion order, so the first key is the oldest.
while (this.seen.size >= this.maxEntries) {
const oldest = this.seen.keys().next();
if (oldest.done) break;
this.seen.delete(oldest.value);
}
}
}
+12 -6
View File
@@ -8,9 +8,9 @@ import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { Public } from '../auth-core/public.decorator';
import { cookieOptions } from '../common/cookie';
import { ManagedForbidden } from '../common/managed';
import { sessionClientFrom } from '../sessions/sessions.service';
import { sessionClientFrom, type SessionClient } from '../sessions/sessions.service';
import { AdminOidcUpdateDto } from './oidc.dto';
import { OidcService, OIDC_STATE_TTL_MS, OIDC_AUTH_CODE_TTL_MS } from './oidc.service';
import { expectedOidcIssuer, OidcService, OIDC_STATE_TTL_MS, OIDC_AUTH_CODE_TTL_MS } from './oidc.service';
import { Body, Controller, Get, HttpException, Put, Query, Req, Res, UseGuards } from '@nestjs/common';
import { oidcLoginQuerySchema } from '@trek/shared';
@@ -150,9 +150,8 @@ export class OidcController {
tokenData.id_token,
doc,
config.clientId,
// Same trim as oidc.service.ts, and the same reason for the lookbehind — this one
// runs over an issuer read out of a fetched discovery document.
(doc.issuer ?? '').replace(/(?<!\/)\/+$/, '') || config.issuer,
// The issuer the back-channel logout accepts too.
expectedOidcIssuer(doc, config),
);
if (idVerify.ok !== true) {
const reason = 'error' in idVerify ? idVerify.error : 'unknown';
@@ -216,7 +215,14 @@ export class OidcController {
// Pass the flag through untouched: `undefined` must reach the token as
// "absent", not `false`, or the sliding renewal would later downgrade the
// default persistent cookie to a browser-session one (remember-me, #1927).
const jwtToken = await this.oidc.generateToken(result.user, pending.remember, sessionClientFrom(req));
// The provider's session id goes on the TREK session, so a back-channel
// logout naming it ends this session and no other (oidc-backchannel.service.ts).
const sid = idVerify.claims.sid;
const client: SessionClient =
typeof sid === 'string' && sid.length > 0
? { ...sessionClientFrom(req), oidcSid: sid }
: sessionClientFrom(req);
const jwtToken = await this.oidc.generateToken(result.user, pending.remember, client);
const { code: authCode, binding } = await this.oidc.createAuthCode(jwtToken, pending.remember);
// Bind the code to THIS browser, the way the state cookie binds the callback.
// The code rides home in a URL, so it is readable from history, from a
+17 -4
View File
@@ -3,8 +3,13 @@ import { InviteTokens } from '../../db/entities/InviteTokens.entity';
import { Users } from '../../db/entities/Users.entity';
import { AuditModule } from '../audit/audit.module';
import { AuthModule } from '../auth/auth.module';
import { RateLimitModule } from '../common/rate-limit.module';
import { SessionsModule } from '../sessions/sessions.module';
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
import { OidcBackchannelController } from './oidc-backchannel.controller';
import { OidcBackchannelService } from './oidc-backchannel.service';
import { InMemoryOidcFlowStore, OidcFlowStore } from './oidc-flow.store';
import { InMemoryOidcLogoutReplayStore, OidcLogoutReplayStore } from './oidc-logout-replay.store';
import { AdminOidcController, OidcController } from './oidc.controller';
import { OidcService } from './oidc.service';
import { MikroOrmModule } from '@mikro-orm/nestjs';
@@ -15,12 +20,20 @@ import { Module } from '@nestjs/common';
AuthModule,
TripMembershipModule,
AuditModule,
RateLimitModule,
SessionsModule,
MikroOrmModule.forFeature([Users, InviteTokens, AppSettings]),
],
controllers: [OidcController, AdminOidcController],
// The login states and codes stay in this process's memory; a store shared
// between processes would be provided here instead.
providers: [OidcService, { provide: OidcFlowStore, useClass: InMemoryOidcFlowStore }],
controllers: [OidcController, OidcBackchannelController, AdminOidcController],
// The login states and codes, and the logout tokens already acted on, stay in
// this process's memory; stores shared between processes would be provided
// here instead.
providers: [
OidcService,
OidcBackchannelService,
{ provide: OidcFlowStore, useClass: InMemoryOidcFlowStore },
{ provide: OidcLogoutReplayStore, useFactory: () => new InMemoryOidcLogoutReplayStore() },
],
// The AI assistant checks a ChatGPT sign-in's ID token with the same verifier.
exports: [OidcService],
})
+43 -4
View File
@@ -163,6 +163,18 @@ function base64UrlDecode(input: string): Buffer {
return Buffer.from(padded, 'base64');
}
/**
* The issuer a provider-signed token must name: the discovery document's
* (trailing slashes trimmed), which with a custom discovery URL may differ from
* the configured one, else the configured issuer. The login callback and the
* back-channel logout both read it from here, so both accept the same issuer.
* The lookbehind pins the trim to the start of the slash run, as in
* getOidcConfig: this runs over an issuer read out of a fetched document.
*/
export function expectedOidcIssuer(doc: OidcDiscoveryDoc, config: Pick<OidcConfig, 'issuer'>): string {
return (doc.issuer ?? '').replace(/(?<!\/)\/+$/, '') || config.issuer;
}
// Sanitize the OIDC `picture` claim before we store it as the avatar. Only https
// URLs are usable: the app's CSP allows https image sources but not http, and we
// render the value directly. Non-strings, non-https and oversized values (e.g. a
@@ -573,16 +585,42 @@ export class OidcService implements OnModuleDestroy {
clientId: string,
expectedIssuer: string,
): Promise<{ ok: true; claims: Record<string, unknown> } | { ok: false; error: string }> {
const verified = await this.verifyProviderJwt(idToken, doc, clientId, expectedIssuer);
return verified.ok ? { ok: true, claims: verified.claims } : verified;
}
/**
* The verification every JWT the provider signs goes through: the id_token
* at login and the logout token of a back-channel logout. The signature is
* checked against the provider's JWKS with the algorithm the header names,
* which must be one of the asymmetric ones (never `none`, never an HMAC the
* client secret could forge), then the audience, `exp` and `nbf`, then the
* issuer. Answers the header too, so a caller can check its `typ`.
*
* `clockToleranceSec` widens the `exp`/`nbf` checks for a token that travels
* between two hosts' clocks; the login leaves it at zero, as it always was.
*/
async verifyProviderJwt(
token: string,
doc: OidcDiscoveryDoc,
clientId: string,
expectedIssuer: string,
clockToleranceSec = 0,
): Promise<
| { ok: true; claims: Record<string, unknown>; header: { kid?: string; alg?: string; typ?: unknown } }
| { ok: false; error: string }
> {
if (!doc.jwks_uri) return { ok: false, error: 'no_jwks_uri' };
const parts = idToken.split('.');
const parts = token.split('.');
if (parts.length !== 3) return { ok: false, error: 'malformed_token' };
let header: { kid?: string; alg?: string };
let header: { kid?: string; alg?: string; typ?: unknown };
try {
header = JSON.parse(base64UrlDecode(parts[0]!).toString('utf8'));
} catch {
return { ok: false, error: 'bad_header' };
}
if (!isRecord(header)) return { ok: false, error: 'bad_header' };
const alg = header.alg;
if (!alg || !/^(RS256|RS384|RS512|ES256|ES384|ES512|PS256|PS384|PS512)$/.test(alg)) {
@@ -615,9 +653,10 @@ export class OidcService implements OnModuleDestroy {
let claims: Record<string, unknown>;
try {
const verified = jwt.verify(idToken, publicKey, {
const verified = jwt.verify(token, publicKey, {
algorithms: [alg as jwt.Algorithm],
audience: clientId,
...(clockToleranceSec > 0 ? { clockTolerance: clockToleranceSec } : {}),
});
claims = typeof verified === 'string' ? {} : (verified as Record<string, unknown>);
} catch (err) {
@@ -632,7 +671,7 @@ export class OidcService implements OnModuleDestroy {
return { ok: false, error: `signature_or_claim_mismatch: jwt issuer invalid. expected: ${expectedIssuer}` };
}
return { ok: true, claims };
return { ok: true, claims, header };
}
// -------------------------------------------------------------------------
+37 -1
View File
@@ -14,11 +14,20 @@ import jwt from 'jsonwebtoken';
/** The longest User-Agent kept, the same cap a Web Push device's gets. */
export const USER_AGENT_MAX_LENGTH = 256;
/** What the issuing request tells about the device a session belongs to. */
/** What the issuing request tells about the device a session belongs to, and where it signed in. */
export interface SessionClient {
userAgent?: string | null;
/**
* The `sid` claim of the verified id_token an SSO sign-in was made with: the
* identity provider's session, which a back-channel logout names to end it.
* Absent for every other way in.
*/
oidcSid?: string | null;
}
/** The longest provider session id kept. Real ones are a UUID or a short opaque string. */
export const OIDC_SID_MAX_LENGTH = 255;
/** The claims a session token is renewed from (decoded by the caller after a guard verified it). */
export interface RenewableSessionClaims {
id: number;
@@ -96,6 +105,7 @@ export class SessionsService {
created_at: dbNow(new Date(iat * 1000)),
expires_at: dbNow(new Date(exp * 1000)),
user_agent: clipUserAgent(client.userAgent),
oidc_sid: usableSid(client.oidcSid),
});
return token;
}
@@ -161,6 +171,17 @@ export class SessionsService {
return this.sessions.findActive(id, userId, now);
}
/**
* The active session a new one is minted from (the native app hand-off),
* with the identity provider's `sid` it was signed in under, null for a
* sign-in without one. Null when that session is revoked, expired, gone or
* another user's.
*/
async findActiveOrigin(id: string, userId: number): Promise<{ oidcSid: string | null } | null> {
const row = await this.sessions.findActiveOidcSid(id, userId, dbNow());
return row ? { oidcSid: row.oidc_sid } : null;
}
/**
* Refresh when a session was last used; the same check calls it at most
* every few minutes.
@@ -213,6 +234,16 @@ export class SessionsService {
return revoked;
}
/**
* A back-channel logout that names the identity provider's session: end the
* active sessions signed in with that `sid` at `issuer`, of the account
* `userId` only when the logout token also named its subject. Answers the
* owner of every session it ended, one entry per session.
*/
async revokeByOidcSid(sid: string, issuer: string, userId?: number): Promise<number[]> {
return this.sessions.revokeByOidcSid(sid, issuer, dbNow(), userId);
}
/**
* Remove the expired rows. A revoked row is kept until it expires too, so
* a session derived from a token from before tracking cannot come back
@@ -247,6 +278,11 @@ function expiryOf(token: string): number | undefined {
return typeof exp === 'number' ? exp : undefined;
}
/** A provider session id worth keeping: a non-empty string within the cap, else nothing. */
function usableSid(sid: string | null | undefined): string | null {
return typeof sid === 'string' && sid.length > 0 && sid.length <= OIDC_SID_MAX_LENGTH ? sid : null;
}
function clipUserAgent(agent: string | null | undefined): string | null {
return agent ? agent.slice(0, USER_AGENT_MAX_LENGTH) : null;
}
@@ -0,0 +1,339 @@
/**
* OpenID Connect Back-Channel Logout end to end: a user signs in through a real
* provider on loopback (discovery, authorize, token with a signed id_token,
* JWKS and userinfo, the way tests/integration/oidc-local-provider.test.ts runs
* it), and that provider then posts signed logout tokens, form-encoded, to
* POST /api/auth/oidc/backchannel-logout of the booted app.
*
* Proves the sid of the id_token is kept on the session the login made and on
* an app session handed off from it, that a token naming that sid ends those
* sessions only, that a token naming only the
* subject ends every session of the account, that an unknown subject answers
* 200, and that a bad or missing token answers the 400 of section 2.8, every
* answer with Cache-Control: no-store.
*/
import { buildApp } from '../../src/bootstrap';
import { BACKCHANNEL_LOGOUT_EVENT } from '../../src/nest/oidc/oidc-backchannel.service';
import { makeUser } from '../helpers/factories/users';
import { resetDatabase } from '../helpers/reset-database';
import { sessionRowsOf } from '../helpers/sessions';
import { resetRateLimits } from '../helpers/test-db';
import { MikroORM } from '@mikro-orm/core';
import type { INestApplication } from '@nestjs/common';
import type { Application } from 'express';
import jwt from 'jsonwebtoken';
import crypto from 'node:crypto';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import request from 'supertest';
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const CLIENT_ID = 'trek-backchannel';
const CLIENT_SECRET = 'backchannel-secret';
const EMAIL = 'sso-user@home.test';
const SUBJECT = 'bcl-sub-1';
const ROUTE = '/api/auth/oidc/backchannel-logout';
/** Read one cookie's value out of a response's Set-Cookie header, as a browser would. */
function readCookie(res: request.Response, name: string): string | undefined {
const raw = res.headers['set-cookie'];
const all: string[] = Array.isArray(raw) ? raw : raw ? [raw as unknown as string] : [];
const value = all
.filter((c) => c.startsWith(`${name}=`))
.pop()
?.split(';')[0]
?.slice(name.length + 1);
return value ? decodeURIComponent(value) : undefined;
}
// ── The provider ────────────────────────────────────────────────────────────
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048 });
const stranger = crypto.generateKeyPairSync('rsa', { modulusLength: 2048 });
const jwk = { ...publicKey.export({ format: 'jwk' }), kid: 'k1', alg: 'RS256', use: 'sig' };
/** Each authorization code, with the provider session (sid) its id_token will carry. */
const codes = new Map<string, string | null>();
/** The sid the next sign-in gets; null for a provider that sends none. */
let nextSid: string | null = null;
let provider: http.Server;
let issuer = '';
function signIdToken(sid: string | null): string {
const now = Math.floor(Date.now() / 1000);
return jwt.sign(
{
iss: issuer,
sub: SUBJECT,
aud: CLIENT_ID,
iat: now,
exp: now + 300,
email: EMAIL,
email_verified: true,
...(sid ? { sid } : {}),
},
privateKey,
{ algorithm: 'RS256', keyid: 'k1' },
);
}
function answerJson(res: http.ServerResponse, status: number, body: unknown) {
res.writeHead(status, { 'content-type': 'application/json' });
res.end(JSON.stringify(body));
}
function handle(req: http.IncomingMessage, res: http.ServerResponse) {
const url = new URL(req.url ?? '/', issuer);
if (url.pathname === '/.well-known/openid-configuration') {
return answerJson(res, 200, {
issuer,
authorization_endpoint: `${issuer}/authorize`,
token_endpoint: `${issuer}/token`,
userinfo_endpoint: `${issuer}/userinfo`,
jwks_uri: `${issuer}/jwks`,
backchannel_logout_supported: true,
backchannel_logout_session_supported: true,
});
}
if (url.pathname === '/authorize') {
const code = crypto.randomBytes(12).toString('hex');
codes.set(code, nextSid);
const back = new URL(url.searchParams.get('redirect_uri') ?? '');
back.searchParams.set('code', code);
back.searchParams.set('state', url.searchParams.get('state') ?? '');
res.writeHead(302, { location: back.toString() });
return res.end();
}
if (url.pathname === '/token' && req.method === 'POST') {
let raw = '';
req.on('data', (chunk) => (raw += chunk));
req.on('end', () => {
const form = new URLSearchParams(raw);
const code = form.get('code') ?? '';
if (!codes.has(code) || form.get('client_secret') !== CLIENT_SECRET) {
return answerJson(res, 400, { error: 'invalid_grant' });
}
const sid = codes.get(code) ?? null;
codes.delete(code);
answerJson(res, 200, { access_token: 'bcl-access', token_type: 'Bearer', id_token: signIdToken(sid) });
});
return;
}
if (url.pathname === '/userinfo') {
return answerJson(res, 200, { sub: SUBJECT, email: EMAIL, email_verified: true, name: 'SSO User' });
}
if (url.pathname === '/jwks') return answerJson(res, 200, { keys: [jwk] });
answerJson(res, 404, { error: 'not_found' });
}
/** A logout token the provider signs; `claims` overrides the defaults, `undefined` drops one. */
function logoutToken(claims: Record<string, unknown>, key: crypto.KeyObject = privateKey): string {
const payload: Record<string, unknown> = {
iss: issuer,
aud: CLIENT_ID,
iat: Math.floor(Date.now() / 1000),
jti: crypto.randomUUID(),
events: { [BACKCHANNEL_LOGOUT_EVENT]: {} },
...claims,
};
for (const [name, value] of Object.entries(payload)) if (value === undefined) delete payload[name];
return jwt.sign(payload, key, { algorithm: 'RS256', header: { alg: 'RS256', kid: 'k1', typ: 'logout+jwt' } });
}
// ── The app ─────────────────────────────────────────────────────────────────
let nestApp: INestApplication;
let app: Application;
let orm: MikroORM;
beforeAll(async () => {
provider = http.createServer(handle);
await new Promise<void>((resolve) => provider.listen(0, '127.0.0.1', resolve));
issuer = `http://127.0.0.1:${(provider.address() as AddressInfo).port}`;
nestApp = await buildApp();
app = nestApp.getHttpAdapter().getInstance();
orm = nestApp.get(MikroORM);
});
beforeEach(async () => {
await resetDatabase(orm);
await resetRateLimits(nestApp);
codes.clear();
nextSid = null;
process.env.OIDC_ISSUER = issuer;
process.env.OIDC_CLIENT_ID = CLIENT_ID;
process.env.OIDC_CLIENT_SECRET = CLIENT_SECRET;
process.env.APP_URL = 'http://localhost:3001';
});
afterEach(() => {
delete process.env.OIDC_ISSUER;
delete process.env.OIDC_CLIENT_ID;
delete process.env.OIDC_CLIENT_SECRET;
delete process.env.APP_URL;
vi.restoreAllMocks();
});
afterAll(async () => {
await nestApp.close();
await new Promise((resolve) => provider.close(resolve));
});
/** One SSO sign-in through the provider, its id_token carrying `sid`; answers the trek_session cookie. */
async function signIn(sid: string | null): Promise<string> {
nextSid = sid;
const login = await request(app).get('/api/auth/oidc/login');
expect(login.status).toBe(302);
const location = login.headers.location;
expect(location).toBeTruthy();
const authorize = new URL(String(location));
const state = readCookie(login, 'trek_oidc_state') ?? '';
const back = await fetch(`${issuer}${authorize.pathname}${authorize.search}`, { redirect: 'manual' });
const callbackUrl = new URL(back.headers.get('location') ?? '');
const cb = await request(app)
.get(`${callbackUrl.pathname}${callbackUrl.search}`)
.set('Cookie', `trek_oidc_state=${state}`);
const landing = new URL(String(cb.headers.location), 'http://localhost');
expect(landing.searchParams.get('oidc_error')).toBeNull();
const exchange = await request(app)
.get(`/api/auth/oidc/exchange?code=${landing.searchParams.get('oidc_code')}`)
.set('Cookie', `trek_oidc_exchange=${readCookie(cb, 'trek_oidc_exchange')}`);
expect(exchange.status).toBe(200);
return `trek_session=${readCookie(exchange, 'trek_session') ?? ''}`;
}
/** The native app hand-off from a signed-in browser session; answers the app's trek_session cookie. */
async function handOffToApp(browserCookie: string): Promise<string> {
const verifier = crypto.randomBytes(32).toString('base64url');
const challenge = crypto.createHash('sha256').update(verifier).digest('hex');
const minted = await request(app).post('/api/auth/native/handoff').set('Cookie', browserCookie).send({ challenge });
expect(minted.status).toBe(200);
const redeemed = await request(app)
.post('/api/auth/native/exchange')
.send({ code: String(minted.body.code), verifier });
expect(redeemed.status).toBe(200);
return `trek_session=${readCookie(redeemed, 'trek_session') ?? ''}`;
}
const me = (cookie: string) => request(app).get('/api/auth/me').set('Cookie', cookie);
const post = (form: Record<string, string>) => request(app).post(ROUTE).type('form').send(form);
describe('POST /api/auth/oidc/backchannel-logout', () => {
it('BCL-E2E-001: a token with sub and sid ends only the session that sign-in made', async () => {
const { user } = await makeUser(orm, { email: EMAIL });
const first = await signIn('op-session-1');
const second = await signIn('op-session-2');
const rows = await sessionRowsOf(orm, user.id);
expect(rows).toHaveLength(2);
const res = await post({ logout_token: logoutToken({ sub: SUBJECT, sid: 'op-session-1' }) });
expect(res.status).toBe(200);
expect(res.headers['cache-control']).toBe('no-store');
expect(res.body).toEqual({});
expect((await me(first)).status).toBe(401);
expect((await me(second)).status).toBe(200);
});
it('BCL-E2E-002: a token with only sid ends that session too', async () => {
await makeUser(orm, { email: EMAIL });
const first = await signIn('op-session-1');
const second = await signIn('op-session-2');
const res = await post({ logout_token: logoutToken({ sid: 'op-session-2' }) });
expect(res.status).toBe(200);
expect((await me(first)).status).toBe(200);
expect((await me(second)).status).toBe(401);
});
it('BCL-E2E-003: a token with only sub ends every session of the account, with or without a sid', async () => {
const { user } = await makeUser(orm, { email: EMAIL });
const withSid = await signIn('op-session-1');
const withoutSid = await signIn(null);
const res = await post({ logout_token: logoutToken({ sub: SUBJECT }) });
expect(res.status).toBe(200);
expect((await me(withSid)).status).toBe(401);
expect((await me(withoutSid)).status).toBe(401);
expect((await sessionRowsOf(orm, user.id)).every((row) => row.revoked_at !== null)).toBe(true);
});
it('BCL-E2E-009: a token with sub and sid ends the app session handed off from that sign-in too', async () => {
const { user } = await makeUser(orm, { email: EMAIL });
const browser = await signIn('op-session-1');
const other = await signIn('op-session-2');
const appSession = await handOffToApp(browser);
expect((await me(appSession)).status).toBe(200);
expect(await sessionRowsOf(orm, user.id)).toHaveLength(3);
const res = await post({ logout_token: logoutToken({ sub: SUBJECT, sid: 'op-session-1' }) });
expect(res.status).toBe(200);
expect((await me(browser)).status).toBe(401);
expect((await me(appSession)).status).toBe(401);
expect((await me(other)).status).toBe(200);
});
it('BCL-E2E-004: an unknown subject answers 200 and ends nothing', async () => {
await makeUser(orm, { email: EMAIL });
const session = await signIn('op-session-1');
const res = await post({ logout_token: logoutToken({ sub: 'someone-else', sid: 'op-session-1' }) });
expect(res.status).toBe(200);
expect(res.headers['cache-control']).toBe('no-store');
expect(res.body).toEqual({});
expect((await me(session)).status).toBe(200);
});
it('BCL-E2E-005: a token signed by another key answers 400 invalid_request and ends nothing', async () => {
await makeUser(orm, { email: EMAIL });
const session = await signIn('op-session-1');
const res = await post({ logout_token: logoutToken({ sub: SUBJECT }, stranger.privateKey) });
expect(res.status).toBe(400);
expect(res.headers['cache-control']).toBe('no-store');
expect(res.body).toEqual({
error: 'invalid_request',
error_description: 'The logout token is missing or invalid.',
});
expect((await me(session)).status).toBe(200);
});
it('BCL-E2E-006: a replayed token answers 400 the second time', async () => {
await makeUser(orm, { email: EMAIL });
await signIn('op-session-1');
const token = logoutToken({ sub: SUBJECT });
expect((await post({ logout_token: token })).status).toBe(200);
const again = await post({ logout_token: token });
expect(again.status).toBe(400);
expect(again.body).toEqual(expect.objectContaining({ error: 'invalid_request' }));
});
it('BCL-E2E-007: a body without logout_token, or a JSON one, answers 400 with no-store', async () => {
const missing = await post({ token: 'x' });
expect(missing.status).toBe(400);
expect(missing.headers['cache-control']).toBe('no-store');
expect(missing.body).toEqual({
error: 'invalid_request',
error_description: 'The logout_token parameter is missing or malformed.',
});
expect((await request(app).post(ROUTE).send({})).status).toBe(400);
});
it('BCL-E2E-008: without OIDC configured the route still answers, with 400', async () => {
delete process.env.OIDC_ISSUER;
delete process.env.OIDC_CLIENT_ID;
delete process.env.OIDC_CLIENT_SECRET;
const res = await post({ logout_token: logoutToken({ sub: SUBJECT }) });
expect(res.status).toBe(400);
expect(res.headers['cache-control']).toBe('no-store');
expect(res.body).toEqual({ error: 'invalid_request', error_description: 'OpenID Connect is not configured.' });
});
});
@@ -117,6 +117,7 @@ const UNNUMBERED = [
'Migration20200101046480_an_address_changed_after_an_admin_made_the_account',
'Migration20200101046490_a_trip_can_switch_its_own_addons',
'Migration20200101046500_an_address_moved_before_an_admin_saved_the_account',
'Migration20200101046510_a_session_knows_its_provider_session',
];
// The last step the positional runner ever had; planLegacyBaseline refuses a
// schema_version past it.
@@ -41,7 +41,7 @@ function revoke(ids: string[], at: string) {
async function add(
id: string,
userId: number,
overrides: { created_at?: string; expires_at?: string; user_agent?: string | null } = {},
overrides: { created_at?: string; expires_at?: string; user_agent?: string | null; oidc_sid?: string | null } = {},
) {
await sessions.insertSession({
id,
@@ -49,6 +49,7 @@ async function add(
created_at: overrides.created_at ?? EARLIER,
expires_at: overrides.expires_at ?? LATER,
user_agent: overrides.user_agent ?? null,
...(overrides.oidc_sid !== undefined ? { oidc_sid: overrides.oidc_sid } : {}),
});
}
@@ -64,6 +65,7 @@ describe('UserSessionsRepository', () => {
expires_at: LATER,
revoked_at: null,
user_agent: 'Firefox',
oidc_sid: null,
});
});
@@ -189,6 +191,7 @@ describe('UserSessionsRepository', () => {
last_seen_at: EARLIER,
expires_at: LATER,
user_agent: 'A',
oidc_sid: null,
},
{
id: 'b1',
@@ -198,6 +201,7 @@ describe('UserSessionsRepository', () => {
last_seen_at: EARLIER,
expires_at: LATER,
user_agent: null,
oidc_sid: null,
},
]);
expect(await sessions.listActiveToCarry(LATER)).toEqual([]);
@@ -226,6 +230,7 @@ describe('UserSessionsRepository', () => {
expires_at: LATER,
revoked_at: null,
user_agent: 'Kept',
oidc_sid: null,
});
// The swapped-in file's own row wins, ended or not.
expect(await row('present')).toEqual(expect.objectContaining({ revoked_at: EARLIER }));
@@ -272,6 +277,7 @@ describe('UserSessionsRepository', () => {
expires_at: LATER,
revoked_at: NOW,
user_agent: 'First',
oidc_sid: null,
});
});
it('SESSREPO-014: lastSeenByUser gives each account its newest last_seen_at, revoked rows included', async () => {
@@ -288,4 +294,62 @@ describe('UserSessionsRepository', () => {
expect(seen.get(other.id)).toBe(EARLIER);
expect(seen.has(idle.id)).toBe(false);
});
it('SESSREPO-015: insertSession keeps the provider session id of an SSO sign-in', async () => {
const { user } = createUser(testDb);
await add('sso', user.id, { oidc_sid: 'op-session-1' });
await add('password', user.id);
expect(await row('sso')).toEqual(expect.objectContaining({ oidc_sid: 'op-session-1' }));
expect(await row('password')).toEqual(expect.objectContaining({ oidc_sid: null }));
});
it('SESSREPO-016: revokeByOidcSid ends the active sessions carrying that sid at that issuer only', async () => {
const ISSUER = 'https://idp.example.test';
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const { user: elsewhere } = createUser(testDb);
await updateRows(t, Users, { id: { $in: [user.id, other.id] } }, { oidc_issuer: ISSUER });
await updateRows(t, Users, { id: elsewhere.id }, { oidc_issuer: 'https://old-idp.example.test' });
await add('mine', user.id, { oidc_sid: 'sid-a' });
await add('mine-too', user.id, { oidc_sid: 'sid-a' });
await add('other-sid', user.id, { oidc_sid: 'sid-b' });
await add('no-sid', user.id);
await add('theirs', other.id, { oidc_sid: 'sid-a' });
await add('old-provider', elsewhere.id, { oidc_sid: 'sid-a' });
await add('ended', user.id, { oidc_sid: 'sid-a' });
await revoke(['ended'], EARLIER);
t.clear();
// Scoped to one account: only its sessions with that sid end.
expect(await sessions.revokeByOidcSid('sid-a', ISSUER, NOW, user.id)).toEqual([user.id, user.id]);
expect(await row('mine')).toEqual(expect.objectContaining({ revoked_at: NOW }));
expect(await row('mine-too')).toEqual(expect.objectContaining({ revoked_at: NOW }));
expect(await row('other-sid')).toEqual(expect.objectContaining({ revoked_at: null }));
expect(await row('no-sid')).toEqual(expect.objectContaining({ revoked_at: null }));
expect(await row('theirs')).toEqual(expect.objectContaining({ revoked_at: null }));
// An ended row keeps the time it ended.
expect(await row('ended')).toEqual(expect.objectContaining({ revoked_at: EARLIER }));
// Without an account the sid is matched across the issuer's accounts, never another issuer's.
expect(await sessions.revokeByOidcSid('sid-a', ISSUER, NOW)).toEqual([other.id]);
expect(await row('old-provider')).toEqual(expect.objectContaining({ revoked_at: null }));
expect(await sessions.revokeByOidcSid('sid-a', ISSUER, NOW)).toEqual([]);
});
it('SESSREPO-017: findActiveOidcSid answers the sid of an active session of that user only', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
await add('sso', user.id, { oidc_sid: 'op-session-1' });
await add('password', user.id);
await add('expired', user.id, { oidc_sid: 'op-session-1', expires_at: NOW });
await add('revoked', user.id, { oidc_sid: 'op-session-1' });
await revoke(['revoked'], EARLIER);
expect(await sessions.findActiveOidcSid('sso', user.id, NOW)).toEqual({ oidc_sid: 'op-session-1' });
expect(await sessions.findActiveOidcSid('password', user.id, NOW)).toEqual({ oidc_sid: null });
expect(await sessions.findActiveOidcSid('sso', other.id, NOW)).toBeNull();
expect(await sessions.findActiveOidcSid('expired', user.id, NOW)).toBeNull();
expect(await sessions.findActiveOidcSid('revoked', user.id, NOW)).toBeNull();
expect(await sessions.findActiveOidcSid('missing', user.id, NOW)).toBeNull();
});
});
@@ -0,0 +1,48 @@
/**
* `Migration20200101046510_a_session_knows_its_provider_session`: the nullable
* `user_sessions.oidc_sid` column and its index. Migrate to the step before
* it with a session already there, apply just this one, and check that the
* existing session comes through untouched with no sid.
*/
import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step';
import { describe, expect, it } from 'vitest';
const TARGET = 'Migration20200101046510_a_session_knows_its_provider_session';
describe('user_sessions.oidc_sid migration', () => {
it('USERSESSSID-001: adds a nullable text column with its index and leaves existing sessions as they were', async () => {
const orm = await createMigrationOrm();
try {
const names = await pendingNames(orm);
const idx = names.indexOf(TARGET);
expect(idx).toBeGreaterThan(0);
const previous = names[idx - 1];
if (!previous) throw new Error('no step before the target');
await migrateTo(orm, previous);
await rawExec(
orm,
"INSERT INTO users (id, username, email, password_hash) VALUES (1, 'owner', 'owner@test', 'x')",
);
await rawExec(
orm,
"INSERT INTO user_sessions (id, user_id, expires_at, user_agent) VALUES ('s1', 1, '2030-01-01 00:00:00', 'Firefox')",
);
await migrateTo(orm, TARGET);
const columns = await rawQuery<{ name: string; type: string; notnull: number }>(
orm,
"SELECT name, type, \"notnull\" FROM pragma_table_info('user_sessions') WHERE name = 'oidc_sid'",
);
expect(columns).toEqual([{ name: 'oidc_sid', type: 'TEXT', notnull: 0 }]);
const indexes = await rawQuery<{ name: string }>(orm, "SELECT name FROM pragma_index_list('user_sessions')");
expect(indexes.map((i) => i.name)).toContain('idx_user_sessions_oidc_sid');
expect(
await rawQuery(orm, "SELECT id, user_id, user_agent, revoked_at, oidc_sid FROM user_sessions WHERE id = 's1'"),
).toEqual([{ id: 's1', user_id: 1, user_agent: 'Firefox', revoked_at: null, oidc_sid: null }]);
} finally {
await orm.close(true);
}
});
});
@@ -0,0 +1,134 @@
/**
* 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) });
});
});
@@ -0,0 +1,415 @@
/**
* OidcBackchannelService: the checks of OpenID Connect Back-Channel Logout 1.0
* section 2.6 on a logout token, one refusal reason per case, and the sessions
* a valid token ends, over the container and a migrated in-memory SQLite.
*
* The provider is real cryptography on a key pair made here: its discovery
* document and JWKS are answered by the SSRF guard's admin-configured fetch,
* which each case reaches through the real OidcService (discovery, JWKS,
* signature, audience, issuer). Only the OIDC configuration is replaced.
*/
import { AuditLog } from '../../../src/db/entities/AuditLog.entity';
import { UserSessions } from '../../../src/db/entities/UserSessions.entity';
import { Users } from '../../../src/db/entities/Users.entity';
import { AppConfigModule } from '../../../src/nest/app-config/app-config.module';
import { DomainError } from '../../../src/nest/common/domain-error';
import {
BACKCHANNEL_LOGOUT_EVENT,
LOGOUT_TOKEN_CLOCK_SKEW_SEC,
LOGOUT_TOKEN_MAX_AGE_SEC,
OidcBackchannelService,
} from '../../../src/nest/oidc/oidc-backchannel.service';
import { OidcModule } from '../../../src/nest/oidc/oidc.module';
import { OidcService, type OidcConfig } from '../../../src/nest/oidc/oidc.service';
import { OIDC_SID_MAX_LENGTH, SessionsService } from '../../../src/nest/sessions/sessions.service';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { findRow, findRows, updateRows } from '../../helpers/factories/rows';
import { makeUser } from '../../helpers/factories/users';
import { resetTestDb } from '../../helpers/test-db';
import { createTestModule, type TestModule } from '../../helpers/test-module';
import { MikroORM } from '@mikro-orm/core';
import { generateKeyPairSync, randomUUID, type KeyObject } from 'crypto';
import jwt from 'jsonwebtoken';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const { safeFetchAdminConfigured } = vi.hoisted(() => ({ safeFetchAdminConfigured: vi.fn() }));
vi.mock('../../../src/utils/ssrfGuard', async (importOriginal) => ({
...(await importOriginal<typeof import('../../../src/utils/ssrfGuard')>()),
safeFetchAdminConfigured,
}));
vi.mock('../../../src/nest/audit/audit-log.logger', async (importOriginal) => ({
...(await importOriginal<typeof import('../../../src/nest/audit/audit-log.logger')>()),
logWarn: vi.fn(),
logInfo: vi.fn(),
}));
const ISSUER = 'https://idp.example.test';
const CLIENT_ID = 'trek-client';
const JWKS_URI = `${ISSUER}/jwks`;
const CONFIG: OidcConfig = {
issuer: ISSUER,
clientId: CLIENT_ID,
clientSecret: 'secret',
displayName: 'SSO',
discoveryUrl: null,
};
const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
const other = generateKeyPairSync('rsa', { modulusLength: 2048 });
const jwk = { ...publicKey.export({ format: 'jwk' }), kid: 'k1', alg: 'RS256', use: 'sig' };
/** The provider's documents: discovery at the issuer, the JWKS beside it. */
function answer(url: string): Response {
const json = (body: unknown) =>
new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } });
if (url.endsWith('/.well-known/openid-configuration') || url === CUSTOM_DISCOVERY) {
return json({
issuer: url === CUSTOM_DISCOVERY ? CUSTOM_ISSUER : ISSUER,
authorization_endpoint: `${ISSUER}/authorize`,
token_endpoint: `${ISSUER}/token`,
userinfo_endpoint: `${ISSUER}/userinfo`,
jwks_uri: JWKS_URI,
});
}
if (url === JWKS_URI) return json({ keys: [jwk] });
return new Response('not found', { status: 404 });
}
const CUSTOM_DISCOVERY = 'https://idp.example.test/realms/trek/.well-known/openid-configuration';
const CUSTOM_ISSUER = 'https://idp.example.test/realms/trek';
const nowSec = () => Math.floor(Date.now() / 1000);
/**
* A logout token. `claims` overrides the valid defaults; an override of
* `undefined` leaves the claim out.
*/
function logoutToken(
claims: Record<string, unknown> = {},
opts: { key?: KeyObject; header?: Record<string, unknown> } = {},
): string {
const payload: Record<string, unknown> = {
iss: ISSUER,
aud: CLIENT_ID,
iat: nowSec(),
jti: randomUUID(),
events: { [BACKCHANNEL_LOGOUT_EVENT]: {} },
sub: 'sub-1',
...claims,
};
for (const [key, value] of Object.entries(payload)) if (value === undefined) delete payload[key];
return jwt.sign(payload, opts.key ?? privateKey, {
algorithm: 'RS256',
// jsonwebtoken keeps a given iat and adds one when there is none; only a
// token meant to lack it is signed without.
noTimestamp: payload.iat === undefined,
header: { alg: 'RS256', kid: 'k1', typ: 'logout+jwt', ...opts.header } as jwt.JwtHeader,
});
}
const b64 = (value: unknown) => Buffer.from(JSON.stringify(value)).toString('base64url');
const db = createSnapshotTestDb();
let t: TestModule;
const orm = () => t.get(MikroORM);
const service = () => t.get(OidcBackchannelService);
beforeAll(async () => {
t = await createTestModule({ db, imports: [AppConfigModule, OidcModule] });
});
afterAll(async () => {
await t.close();
db.close();
});
beforeEach(() => {
resetTestDb(db);
vi.clearAllMocks();
safeFetchAdminConfigured.mockImplementation(async (url: string) => answer(url));
vi.spyOn(t.get(OidcService), 'getOidcConfig').mockResolvedValue(CONFIG);
});
/** An account linked to the provider under `sub`. */
async function linkedUser(sub: string, issuer = ISSUER) {
const { user } = await makeUser(orm());
await updateRows(orm(), Users, { id: user.id }, { oidc_sub: sub, oidc_issuer: issuer });
return user;
}
/** A tracked session for the user, with the provider's `sid` when given; answers its id. */
async function session(userId: number, oidcSid?: string): Promise<string> {
const token = await t.get(SessionsService).issue({ id: userId, pv: 0 }, undefined, oidcSid ? { oidcSid } : {});
return (jwt.decode(token) as { jti: string }).jti;
}
async function revokedAt(id: string): Promise<string | null | undefined> {
return (await findRow(orm(), UserSessions, { id }))?.revoked_at;
}
/** The reason validateLogoutToken gives for a token. */
async function reasonFor(token: string, config: OidcConfig = CONFIG): Promise<string> {
const check = await service().validateLogoutToken(token, config);
return check.valid ? 'valid' : check.reason;
}
describe('OidcBackchannelService.validateLogoutToken: section 2.6, one refusal per check', () => {
it('BCL-SVC-001: a well-formed token passes and answers its claims', async () => {
const token = logoutToken({ sid: 'op-1', jti: 'j-1' });
const check = await service().validateLogoutToken(token, CONFIG);
expect(check).toEqual({
valid: true,
claims: expect.objectContaining({ iss: ISSUER, jti: 'j-1', sub: 'sub-1', sid: 'op-1' }),
});
});
it('BCL-SVC-002: a signature by another key is refused', async () => {
expect(await reasonFor(logoutToken({}, { key: other.privateKey }))).toMatch(/invalid signature/);
});
it('BCL-SVC-003: alg none is refused before any key is looked at', async () => {
const unsigned = `${b64({ alg: 'none', typ: 'logout+jwt' })}.${b64({
iss: ISSUER,
aud: CLIENT_ID,
iat: nowSec(),
jti: 'x',
sub: 'sub-1',
events: { [BACKCHANNEL_LOGOUT_EVENT]: {} },
})}.`;
expect(await reasonFor(unsigned)).toBe('unsupported_alg');
});
it('BCL-SVC-004: an HMAC token (a forgery with the client secret) is refused', async () => {
const hmac = jwt.sign({ iss: ISSUER, aud: CLIENT_ID, sub: 'sub-1' }, 'secret', { algorithm: 'HS256' });
expect(await reasonFor(hmac)).toBe('unsupported_alg');
});
it('BCL-SVC-005: a wrong issuer is refused', async () => {
expect(await reasonFor(logoutToken({ iss: 'https://evil.example.test' }))).toMatch(/issuer invalid/);
});
it('BCL-SVC-006: a wrong audience is refused', async () => {
expect(await reasonFor(logoutToken({ aud: 'another-client' }))).toMatch(/audience invalid/);
});
it('BCL-SVC-007: an audience list holding the client id passes', async () => {
expect(await reasonFor(logoutToken({ aud: ['another-client', CLIENT_ID] }))).toBe('valid');
});
it('BCL-SVC-008: a missing events claim is refused', async () => {
expect(await reasonFor(logoutToken({ events: undefined }))).toBe('missing_logout_event');
});
it('BCL-SVC-009: events without the back-channel logout member, or with a non-object member, are refused', async () => {
expect(await reasonFor(logoutToken({ events: { 'http://example.test/other': {} } }))).toBe('missing_logout_event');
expect(await reasonFor(logoutToken({ events: { [BACKCHANNEL_LOGOUT_EVENT]: 'yes' } }))).toBe(
'missing_logout_event',
);
expect(await reasonFor(logoutToken({ events: [BACKCHANNEL_LOGOUT_EVENT] }))).toBe('missing_logout_event');
});
it('BCL-SVC-010: a nonce is refused (an id_token, not a logout token)', async () => {
expect(await reasonFor(logoutToken({ nonce: 'n-1' }))).toBe('nonce_present');
});
it('BCL-SVC-011: neither sub nor sid is refused, and so is an empty or non-string one', async () => {
expect(await reasonFor(logoutToken({ sub: undefined }))).toBe('no_sub_or_sid');
expect(await reasonFor(logoutToken({ sub: '' }))).toBe('bad_sub');
expect(await reasonFor(logoutToken({ sub: undefined, sid: 42 }))).toBe('bad_sid');
});
it('BCL-SVC-012: a sid alone passes', async () => {
expect(await reasonFor(logoutToken({ sub: undefined, sid: 'op-1' }))).toBe('valid');
});
it('BCL-SVC-013: an iat older than the window is refused, one inside it passes', async () => {
const window = LOGOUT_TOKEN_MAX_AGE_SEC + LOGOUT_TOKEN_CLOCK_SKEW_SEC;
expect(await reasonFor(logoutToken({ iat: nowSec() - window - 5 }))).toBe('stale_iat');
expect(await reasonFor(logoutToken({ iat: nowSec() - LOGOUT_TOKEN_MAX_AGE_SEC + 5 }))).toBe('valid');
});
it('BCL-SVC-014: an iat past the clock skew in the future is refused', async () => {
expect(await reasonFor(logoutToken({ iat: nowSec() + LOGOUT_TOKEN_CLOCK_SKEW_SEC + 30 }))).toBe('iat_in_future');
});
it('BCL-SVC-015: a missing iat is refused', async () => {
expect(await reasonFor(logoutToken({ iat: undefined }))).toBe('missing_iat');
});
it('BCL-SVC-016: an expired exp is refused; a token without exp passes', async () => {
expect(await reasonFor(logoutToken({ exp: nowSec() - LOGOUT_TOKEN_CLOCK_SKEW_SEC - 5 }))).toMatch(/jwt expired/);
expect(await reasonFor(logoutToken({ exp: undefined }))).toBe('valid');
});
it('BCL-SVC-017: a missing jti is refused', async () => {
expect(await reasonFor(logoutToken({ jti: undefined }))).toBe('missing_jti');
});
it('BCL-SVC-018: typ logout+jwt, JWT or none pass; another explicit type is refused', async () => {
expect(await reasonFor(logoutToken({}, { header: { typ: 'JWT' } }))).toBe('valid');
expect(await reasonFor(logoutToken({}, { header: { typ: 'application/logout+jwt' } }))).toBe('valid');
expect(await reasonFor(logoutToken({}, { header: { typ: undefined } }))).toBe('valid');
expect(await reasonFor(logoutToken({}, { header: { typ: 'at+jwt' } }))).toBe('wrong_typ');
});
it('BCL-SVC-019: a malformed token is refused', async () => {
expect(await reasonFor('not-a-jwt')).toBe('malformed_token');
expect(await reasonFor('a.b.c.d.e')).toBe('malformed_token');
});
it('BCL-SVC-020: a provider whose discovery cannot be fetched refuses the token instead of failing', async () => {
safeFetchAdminConfigured.mockImplementation(async () => new Response('down', { status: 503 }));
const config = { ...CONFIG, issuer: 'https://down.example.test' };
expect(await reasonFor(logoutToken({ iss: config.issuer }), config)).toMatch(/^discovery_failed/);
});
it('BCL-SVC-021: with a custom discovery URL the issuer of the discovery document is the one accepted', async () => {
const config = { ...CONFIG, discoveryUrl: CUSTOM_DISCOVERY };
expect(await reasonFor(logoutToken({ iss: CUSTOM_ISSUER }), config)).toBe('valid');
expect(await reasonFor(logoutToken({ iss: ISSUER }), config)).toMatch(/issuer invalid/);
});
});
describe('OidcBackchannelService.logout', () => {
/** What the route answers for a refused token, and the reason recorded in the error code. */
async function refusal(token: string): Promise<{ status: number; body: unknown; code: string }> {
const err = await service()
.logout(token, '203.0.113.5')
.then(
() => null,
(e: unknown) => e,
);
expect(err).toBeInstanceOf(DomainError);
const domain = err as DomainError;
return { status: domain.getStatus(), body: domain.toBody(), code: domain.code };
}
it('BCL-SVC-030: a token with sub and sid ends only the sessions carrying that sid for that account', async () => {
const user = await linkedUser('sub-1');
const stranger = await linkedUser('sub-2');
const ended = await session(user.id, 'op-1');
const sibling = await session(user.id, 'op-2');
const password = await session(user.id);
const theirs = await session(stranger.id, 'op-1');
await service().logout(logoutToken({ sub: 'sub-1', sid: 'op-1' }), '203.0.113.5');
expect(await revokedAt(ended)).not.toBeNull();
expect(await revokedAt(sibling)).toBeNull();
expect(await revokedAt(password)).toBeNull();
expect(await revokedAt(theirs)).toBeNull();
const audit = await findRows(orm(), AuditLog, { action: 'oidc.backchannel_logout' });
expect(audit).toHaveLength(1);
expect(audit[0]).toEqual(expect.objectContaining({ user_id: user.id, ip: '203.0.113.5' }));
expect(JSON.parse(String(audit[0]?.details))).toEqual({ scope: 'session', revoked: 1 });
});
it('BCL-SVC-031: a token with only sub ends every session of the account', async () => {
const user = await linkedUser('sub-1');
const stranger = await linkedUser('sub-2');
const a = await session(user.id, 'op-1');
const b = await session(user.id);
const theirs = await session(stranger.id);
await service().logout(logoutToken({ sub: 'sub-1' }), null);
expect(await revokedAt(a)).not.toBeNull();
expect(await revokedAt(b)).not.toBeNull();
expect(await revokedAt(theirs)).toBeNull();
});
it('BCL-SVC-032: a token with only sid ends that provider session wherever it is, never one of another issuer', async () => {
const user = await linkedUser('sub-1');
const moved = await linkedUser('sub-9', 'https://old-idp.example.test');
const ended = await session(user.id, 'op-1');
const kept = await session(user.id, 'op-2');
const elsewhere = await session(moved.id, 'op-1');
await service().logout(logoutToken({ sub: undefined, sid: 'op-1' }), null);
expect(await revokedAt(ended)).not.toBeNull();
expect(await revokedAt(kept)).toBeNull();
expect(await revokedAt(elsewhere)).toBeNull();
});
it('BCL-SVC-033: a subject without an account here succeeds and ends nothing', async () => {
const user = await linkedUser('sub-1');
const live = await session(user.id, 'op-1');
await expect(service().logout(logoutToken({ sub: 'nobody', sid: 'op-1' }), null)).resolves.toBeUndefined();
expect(await revokedAt(live)).toBeNull();
expect(await findRows(orm(), AuditLog, { action: 'oidc.backchannel_logout' })).toHaveLength(0);
});
it('BCL-SVC-034: a sid no session carries succeeds and ends nothing', async () => {
const user = await linkedUser('sub-1');
const live = await session(user.id, 'op-1');
await expect(service().logout(logoutToken({ sub: undefined, sid: 'unknown' }), null)).resolves.toBeUndefined();
expect(await revokedAt(live)).toBeNull();
});
it('BCL-SVC-035: the same jti is refused the second time, as a replay', async () => {
await linkedUser('sub-1');
const token = logoutToken({ jti: 'once' });
await service().logout(token, null);
expect(await refusal(token)).toEqual({
status: 400,
body: { error: 'invalid_request', error_description: 'The logout token is missing or invalid.' },
code: 'replayed_jti',
});
});
it('BCL-SVC-036: a refused token never uses up the jti of a real one', async () => {
await linkedUser('sub-1');
expect((await refusal(logoutToken({ jti: 'shared', nonce: 'n' }))).code).toBe('nonce_present');
await expect(service().logout(logoutToken({ jti: 'shared' }), null)).resolves.toBeUndefined();
});
it('BCL-SVC-040: a logout that fails while ending the sessions frees the jti, so the retry is acted on', async () => {
const user = await linkedUser('sub-1');
const live = await session(user.id);
const token = logoutToken({ jti: 'retried' });
const revokeAll = vi
.spyOn(t.get(SessionsService), 'revokeAll')
.mockRejectedValueOnce(new Error('database is locked'));
try {
await expect(service().logout(token, null)).rejects.toThrow('database is locked');
expect(await revokedAt(live)).toBeNull();
await expect(service().logout(token, null)).resolves.toBeUndefined();
expect(await revokedAt(live)).not.toBeNull();
expect((await refusal(token)).code).toBe('replayed_jti');
} finally {
revokeAll.mockRestore();
}
});
it('BCL-SVC-037: every refusal is the 400 invalid_request of section 2.8, the reason only in the code', async () => {
const result = await refusal(logoutToken({}, { key: other.privateKey }));
expect(result.status).toBe(400);
expect(result.body).toEqual({
error: 'invalid_request',
error_description: 'The logout token is missing or invalid.',
});
expect(result.code).toMatch(/invalid signature/);
});
it('BCL-SVC-038: without an OIDC configuration the token is refused with 400', async () => {
vi.spyOn(t.get(OidcService), 'getOidcConfig').mockResolvedValue(null);
expect(await refusal(logoutToken())).toEqual({
status: 400,
body: { error: 'invalid_request', error_description: 'OpenID Connect is not configured.' },
code: 'not_configured',
});
expect(safeFetchAdminConfigured).not.toHaveBeenCalled();
});
it('BCL-SVC-039: the login stores the sid on the session, and drops one past the length cap', async () => {
const user = await linkedUser('sub-1');
const kept = await session(user.id, 'op-1');
const dropped = await session(user.id, 'x'.repeat(OIDC_SID_MAX_LENGTH + 1));
expect((await findRow(orm(), UserSessions, { id: kept }))?.oidc_sid).toBe('op-1');
expect((await findRow(orm(), UserSessions, { id: dropped }))?.oidc_sid).toBeNull();
});
});
@@ -0,0 +1,64 @@
/**
* The in-memory store of logout tokens already acted on: a key is refused
* while its entry lives, accepted again once it expired or was released, and the map never
* holds more than its cap.
*/
import {
InMemoryOidcLogoutReplayStore,
OIDC_LOGOUT_REPLAY_MAX_ENTRIES,
} from '../../../src/nest/oidc/oidc-logout-replay.store';
import { describe, expect, it } from 'vitest';
describe('InMemoryOidcLogoutReplayStore', () => {
it('BCL-REPLAY-001: the first claim wins, a second one while the entry lives is a replay', async () => {
const store = new InMemoryOidcLogoutReplayStore();
expect(await store.claim('iss\nj1', 2000, 1000)).toBe(true);
expect(await store.claim('iss\nj1', 2000, 1500)).toBe(false);
expect(await store.claim('iss\nj2', 2000, 1500)).toBe(true);
});
it('BCL-REPLAY-002: an expired entry no longer refuses its key', async () => {
const store = new InMemoryOidcLogoutReplayStore();
expect(await store.claim('k', 2000, 1000)).toBe(true);
expect(await store.claim('k', 3000, 2000)).toBe(true);
expect(await store.claim('k', 3000, 2500)).toBe(false);
});
it('BCL-REPLAY-003: at the cap the expired entries go first', async () => {
const store = new InMemoryOidcLogoutReplayStore(3);
await store.claim('old', 1100, 1000);
await store.claim('live-a', 9000, 1000);
await store.claim('live-b', 9000, 1000);
expect(await store.claim('new', 9000, 2000)).toBe(true);
expect(store.size).toBe(3);
// The live ones are still held, the expired one made the room.
expect(await store.claim('live-a', 9000, 2000)).toBe(false);
expect(await store.claim('live-b', 9000, 2000)).toBe(false);
});
it('BCL-REPLAY-004: with nothing expired the oldest entry goes, so memory stays bounded', async () => {
const store = new InMemoryOidcLogoutReplayStore(2);
await store.claim('first', 9000, 1000);
await store.claim('second', 9000, 1000);
await store.claim('third', 9000, 1000);
expect(store.size).toBe(2);
expect(await store.claim('second', 9000, 1000)).toBe(false);
expect(await store.claim('third', 9000, 1000)).toBe(false);
});
it('BCL-REPLAY-005: the default cap is the documented one', () => {
expect(OIDC_LOGOUT_REPLAY_MAX_ENTRIES).toBe(10_000);
});
it('BCL-REPLAY-006: a released key is accepted again, and the other keys stay held', async () => {
const store = new InMemoryOidcLogoutReplayStore();
expect(await store.claim('a', 9000, 1000)).toBe(true);
expect(await store.claim('b', 9000, 1000)).toBe(true);
await store.release('a');
expect(store.size).toBe(1);
expect(await store.claim('a', 9000, 1500)).toBe(true);
expect(await store.claim('b', 9000, 1500)).toBe(false);
await expect(store.release('never-held')).resolves.toBeUndefined();
});
});
@@ -614,6 +614,27 @@ describe('OidcController /callback', () => {
expect(createAuthCode).toHaveBeenCalledWith('jwt', remember);
}
});
it.each([
{ sid: 'op-session-1', client: { userAgent: null, oidcSid: 'op-session-1' } },
{ sid: '', client: { userAgent: null } },
{ sid: 42, client: { userAgent: null } },
])(
"keeps the id_token's sid on the session it issues, for back-channel logout; an empty or non-string sid is left out (sid $sid)",
async ({ sid, client }) => {
const generateToken = vi.fn().mockReturnValue('jwt');
await ctl(
svc({
exchangeCodeForToken: vi.fn().mockResolvedValue({ _ok: true, access_token: 'at', id_token: 'it' }),
verifyIdToken: vi.fn().mockResolvedValue({ ok: true, claims: { sub: 'u1', sid } }),
getUserInfo: vi.fn().mockResolvedValue({ email: 'a@b.c', sub: 'u1' }),
findOrCreateUser: vi.fn().mockReturnValue({ user: { id: 1 } }),
generateToken,
}),
).callback('c', 's', undefined, reqCb('s'), makeRes());
expect(generateToken).toHaveBeenCalledWith({ id: 1 }, undefined, client);
},
);
});
describe('OidcController /exchange', () => {
@@ -92,6 +92,7 @@ describe('SessionsService.issue', () => {
expires_at: textOf(claims.exp),
revoked_at: null,
user_agent: 'Firefox/130',
oidc_sid: null,
});
});
@@ -347,6 +348,19 @@ describe('SessionsService list and revoke', () => {
});
describe('SessionsService as the session check', () => {
it('SESS-017: findActiveOrigin answers the provider sid a session was signed in with, null once it ended', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const sso = claimsOf(await svc.issue({ id: user.id, pv: 0 }, undefined, { oidcSid: 'op-session-1' }));
const password = claimsOf(await svc.issue({ id: user.id, pv: 0 }));
expect(await svc.findActiveOrigin(sso.jti, user.id)).toEqual({ oidcSid: 'op-session-1' });
expect(await svc.findActiveOrigin(password.jti, user.id)).toEqual({ oidcSid: null });
expect(await svc.findActiveOrigin(sso.jti, other.id)).toBeNull();
await svc.revoke(user.id, sso.jti);
expect(await svc.findActiveOrigin(sso.jti, user.id)).toBeNull();
});
it('SESS-016: answers findActive and touchLastSeen for verifyJwtAndLoadUser', async () => {
const { user } = createUser(testDb);
const live = claimsOf(await svc.issue({ id: user.id, pv: 0 }));
+37 -1
View File
@@ -1,4 +1,11 @@
import { oidcCallbackQuerySchema, oidcExchangeQuerySchema, oidcLoginQuerySchema } from './oidc.schema';
import {
OIDC_LOGOUT_TOKEN_MAX_LENGTH,
oidcBackchannelLogoutErrorSchema,
oidcBackchannelLogoutRequestSchema,
oidcCallbackQuerySchema,
oidcExchangeQuerySchema,
oidcLoginQuerySchema,
} from './oidc.schema';
import { describe, it, expect } from 'vitest';
@@ -31,3 +38,32 @@ describe('oidcExchangeQuerySchema', () => {
expect(oidcExchangeQuerySchema.safeParse({}).success).toBe(false);
});
});
describe('oidcBackchannelLogoutRequestSchema', () => {
it('requires a non-empty logout_token string', () => {
expect(oidcBackchannelLogoutRequestSchema.safeParse({ logout_token: 'a.b.c' }).success).toBe(true);
expect(oidcBackchannelLogoutRequestSchema.safeParse({}).success).toBe(false);
expect(oidcBackchannelLogoutRequestSchema.safeParse({ logout_token: '' }).success).toBe(false);
});
it('refuses a token that is not one string (a repeated form field parses to an array)', () => {
expect(oidcBackchannelLogoutRequestSchema.safeParse({ logout_token: ['a', 'b'] }).success).toBe(false);
expect(oidcBackchannelLogoutRequestSchema.safeParse({ logout_token: 5 }).success).toBe(false);
});
it('refuses a token past the length cap', () => {
const long = 'a'.repeat(OIDC_LOGOUT_TOKEN_MAX_LENGTH + 1);
expect(oidcBackchannelLogoutRequestSchema.safeParse({ logout_token: long }).success).toBe(false);
});
});
describe('oidcBackchannelLogoutErrorSchema', () => {
it('describes the spec 2.8 error body', () => {
expect(
oidcBackchannelLogoutErrorSchema.safeParse({ error: 'invalid_request', error_description: 'x' }).success,
).toBe(true);
expect(oidcBackchannelLogoutErrorSchema.safeParse({ error: 'server_error', error_description: 'x' }).success).toBe(
false,
);
});
});
+33
View File
@@ -28,3 +28,36 @@ export const oidcExchangeQuerySchema = z.object({
code: z.string(),
});
export type OidcExchangeQuery = z.infer<typeof oidcExchangeQuerySchema>;
/**
* The longest logout token accepted. A signed logout token holds a handful of
* short claims and is well under 2 KB; the cap only keeps a stranger's body
* from reaching the JWT parser at the size of the global body limit.
*/
export const OIDC_LOGOUT_TOKEN_MAX_LENGTH = 16_384;
/**
* POST /api/auth/oidc/backchannel-logout, OpenID Connect Back-Channel Logout 1.0
* section 2.5: the identity provider posts an `application/x-www-form-urlencoded`
* body with one parameter, the signed `logout_token`. Everything else in the body
* is ignored, as the spec leaves room for nothing else.
*/
export const oidcBackchannelLogoutRequestSchema = z.object({
logout_token: z.string().min(1).max(OIDC_LOGOUT_TOKEN_MAX_LENGTH),
});
export type OidcBackchannelLogoutRequest = z.infer<typeof oidcBackchannelLogoutRequestSchema>;
/**
* The 200 answer (section 2.8). The spec asks for no body; the route answers an
* empty JSON object, also when no account or session matched the token, so the
* provider cannot tell which subjects have a TREK account.
*/
export const oidcBackchannelLogoutResponseSchema = z.object({});
export type OidcBackchannelLogoutResponse = z.infer<typeof oidcBackchannelLogoutResponseSchema>;
/** The 400 answer (section 2.8) for a missing or invalid logout token. */
export const oidcBackchannelLogoutErrorSchema = z.object({
error: z.literal('invalid_request'),
error_description: z.string(),
});
export type OidcBackchannelLogoutError = z.infer<typeof oidcBackchannelLogoutErrorSchema>;
+1
View File
@@ -57,6 +57,7 @@ Logging out writes no row, and neither do the sessions a password change, a rese
| Action key | Description |
|---|---|
| `oidc.role_change` | An SSO login changed a user's role through the OIDC claim mapping (`from`, `to` and the claim **name** in details, never the claim's value) |
| `oidc.backchannel_logout` | The identity provider signed a user out through [back-channel logout](OIDC-SSO#back-channel-logout) (`scope` is `session` when one provider session ended, `all` when every session of the account did; `revoked` = how many ended) |
### Trips
+31
View File
@@ -136,6 +136,37 @@ When password login and password registration are both off, through `OIDC_ONLY`
> **Note:** The admin panel prevents you from disabling all login methods simultaneously. At least one method (password or SSO) must remain active. Similarly, you cannot remove the OIDC configuration from the admin panel while password login is disabled.
## Back-channel logout
When a user signs out at the identity provider, or an admin ends their session there, the provider can tell TREK to end the matching TREK sessions too. TREK supports [OpenID Connect Back-Channel Logout 1.0](https://openid.net/specs/openid-connect-backchannel-1_0.html). Nothing needs to be switched on in TREK: enter this URL as the client's back-channel logout URL in the provider and it takes effect.
```
<APP_URL>/api/auth/oidc/backchannel-logout
```
For example: `https://trek.example.com/api/auth/oidc/backchannel-logout`
Where the field lives:
| Provider | Setting |
|---|---|
| Authentik | **Applications → Providers**, edit the OAuth2/OpenID provider of TREK: enter the URL as **Logout URI** and set **Logout Method** to back-channel |
| Keycloak | **Clients**, open the TREK client, **Settings → Logout settings**: enter the URL as **Backchannel logout URL** and keep **Backchannel logout session required** on, so the token names the session |
| Pocket ID | **OIDC Clients**, edit the TREK client: enter the URL in the back-channel logout field where your version has one. A version without such a field sends no logout tokens |
The provider must be able to reach TREK at that address, server to server. Field names differ between provider versions; look for "back-channel" or "backchannel" logout in the client settings.
What ends:
- A logout token naming the provider's session (`sid`) ends the TREK sessions that were signed in through that provider session, the mobile app sessions handed off from such a browser sign-in included, and no other. TREK keeps the `sid` of the id_token on the session the SSO sign-in creates, and an app signed in from that browser session gets the same `sid`. Sessions signed in before this was available, or with a provider that sends no `sid`, carry none, and only a logout of the whole account reaches them.
- A logout token naming only the subject (`sub`) ends every TREK session of that account, password and passkey sign-ins included, as a password change does.
With Keycloak and **Backchannel logout session required** on, signing a user out from the Keycloak admin console ends all of their Keycloak sessions but sends TREK a single logout token naming one of them, so TREK ends only the sessions of that one. To have such a sign-out end every TREK session of the user, turn the setting off: Keycloak then names only the user, and every logout there, a single browser's sign-out included, ends all of the user's TREK sessions.
TREK checks every logout token as the specification requires: the signature against the provider's published keys (the same keys and issuer as the login, the custom discovery URL included), the client id in the audience, an issue time no older than five minutes (one minute of clock difference is allowed either way), the back-channel logout event, no `nonce`, and a `jti` not seen before. A valid token answers `200`, also when it names no account or session in TREK; an invalid or missing token answers `400` with `{"error":"invalid_request"}`, and the server log names the reason (`[OIDC] Back-channel logout token refused: <reason>`). More than 600 logout requests a minute from one address answer `429` with `{"error":"too_many_requests"}`; providers retry them. An encrypted logout token is not supported. Each sign-out is recorded in the [Audit-Log](Audit-Log) as `oidc.backchannel_logout`.
Signing out of TREK itself does not sign you out at the identity provider.
---
**See also:** [Login-and-Registration](Login-and-Registration), [Environment-Variables](Environment-Variables)