commit 321c8d23e0e84250d2c9523278c4fb437785c9d9
parent bb4064b38a490906b38cb46acbb9494bb9ff90f4
Author: finwo <finwo@pm.me>
Date: Mon, 30 Nov 2026 21:27:08 +0100
server: user-wide session termination with list pagination
Diffstat:
7 files changed, 737 insertions(+), 2 deletions(-)
diff --git a/server/src/controller/admin/user-sessions/list.js b/server/src/controller/admin/user-sessions/list.js
@@ -0,0 +1,75 @@
+import { app } from '../../../app.js';
+import { authenticateAdminRequest } from '../../../lib/admin-auth.js';
+import { ADMIN_SESSION_FIELDS, serialize } from '../../../lib/admin-sessions.js';
+import { HttpError } from '../../../lib/http/http-error.js';
+import { pagedResult, parsePagination, searchClause } from '../../../lib/pagination.js';
+import { isSystemAdmin } from '../../../lib/policy.js';
+import { findUserById } from '../../../lib/users.js';
+
+const SEARCH_COLUMNS = ['s.user_agent', 's.ip', 's.scope_host', 's.client_id', 's.scope_type'];
+
+export default {
+ method: 'get',
+ path: '/api/v1/admin/realms/:realm/users/:userId/sessions',
+ name: 'admin.userSessions.list',
+ async handler(req) {
+ const auth = await authenticateAdminRequest(req, {
+ realmSlug: req.params.realm,
+ });
+ const user = await findUserById(auth.systemDb, req.params.userId);
+ if (!user) {
+ throw new HttpError(404, 'user_not_found', 'User not found');
+ }
+ if (!isSystemAdmin(auth.user) && user.home_realm_id !== auth.realm.id) {
+ throw new HttpError(
+ 403,
+ 'forbidden',
+ 'Only home-realm and system admins can list sessions for this user'
+ );
+ }
+
+ const url = new URL(req.url, 'http://localhost');
+ const page = parsePagination(Object.fromEntries(url.searchParams));
+ const params = {
+ userId: user.id,
+ realmId: auth.realm.id,
+ now: Date.now(),
+ limit: page.limit,
+ offset: page.offset,
+ };
+ let filter = 's.user_id = {userId} AND s.expires_at > {now}';
+ if (page.q) {
+ const search = searchClause(page.q, SEARCH_COLUMNS);
+ filter += ` AND ${search.clause}`;
+ Object.assign(params, search.params);
+ }
+
+ const rows = await auth.systemDb.all(
+ `SELECT ${ADMIN_SESSION_FIELDS}
+ FROM sessions s
+ JOIN users u ON u.id = s.user_id
+ LEFT JOIN session_realms sr
+ ON sr.session_id = s.id AND sr.realm_id = {realmId}
+ WHERE ${filter}
+ ORDER BY s.last_seen_at DESC, s.created_at DESC, s.id DESC
+ LIMIT {limit} OFFSET {offset}`,
+ params
+ );
+ const count = await auth.systemDb.get(
+ `SELECT COUNT(*) AS total
+ FROM sessions s
+ WHERE ${filter}`,
+ params
+ );
+
+ const sessions = rows.map((row) => serialize(row, auth.user, auth.realm.id));
+ return new app.HttpOk(
+ pagedResult('sessions', sessions, {
+ limit: page.limit,
+ offset: page.offset,
+ total: count.total,
+ }),
+ { 'cache-control': 'no-store' }
+ );
+ },
+};
diff --git a/server/src/controller/admin/user-sessions/terminate-all.js b/server/src/controller/admin/user-sessions/terminate-all.js
@@ -0,0 +1,34 @@
+import { app } from '../../../app.js';
+import { authenticateAdminRequest } from '../../../lib/admin-auth.js';
+import { HttpError } from '../../../lib/http/http-error.js';
+import { isSystemAdmin } from '../../../lib/policy.js';
+import { destroyUserSessions } from '../../../lib/session.js';
+import { findUserById } from '../../../lib/users.js';
+
+export default {
+ method: 'delete',
+ path: '/api/v1/admin/realms/:realm/users/:userId/sessions',
+ name: 'admin.userSessions.terminateAll',
+ async handler(req) {
+ const auth = await authenticateAdminRequest(req, {
+ realmSlug: req.params.realm,
+ });
+ const user = await findUserById(auth.systemDb, req.params.userId);
+ if (!user) {
+ throw new HttpError(404, 'user_not_found', 'User not found');
+ }
+ if (!isSystemAdmin(auth.user) && user.home_realm_id !== auth.realm.id) {
+ throw new HttpError(
+ 403,
+ 'forbidden',
+ 'Only home-realm and system admins can terminate sessions for this user'
+ );
+ }
+
+ const result = await destroyUserSessions(auth.systemDb, { userId: user.id });
+ return new app.HttpOk(
+ { ok: true, destroyed: result.destroyed },
+ { 'cache-control': 'no-store' }
+ );
+ },
+};
diff --git a/server/src/lib/admin-sessions.js b/server/src/lib/admin-sessions.js
@@ -1,13 +1,13 @@
import { isSystemAdmin } from './policy.js';
-const ADMIN_SESSION_FIELDS = `
+export const ADMIN_SESSION_FIELDS = `
s.id, s.public_id, s.group_id, s.user_id, s.scope_type, s.scope_host,
s.client_id, s.created_at, s.last_seen_at, s.expires_at, s.user_agent, s.ip,
u.username, u.display_name, u.home_realm_id, u.status AS user_status,
sr.revoked_at, sr.revoked_by
`;
-function serialize(row, actor, realmId) {
+export function serialize(row, actor, realmId) {
return {
public_id: row.public_id,
user: {
diff --git a/server/src/lib/pagination.js b/server/src/lib/pagination.js
@@ -0,0 +1,69 @@
+import { HttpError } from './http/http-error.js';
+
+const DEFAULT_LIMIT = 25;
+const MAX_LIMIT = 100;
+const MAX_SEARCH_LENGTH = 128;
+const SEARCH_COLUMN = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)?$/;
+
+function invalidRequest(message) {
+ return new HttpError(400, 'invalid_request', message);
+}
+
+export function parsePagination(query = {}) {
+ let limit = DEFAULT_LIMIT;
+ if (query.limit !== undefined) {
+ limit = Number(query.limit);
+ if (!Number.isInteger(limit) || limit < 1) {
+ throw invalidRequest('limit must be a positive integer');
+ }
+ if (limit > MAX_LIMIT) limit = MAX_LIMIT;
+ }
+
+ let offset = 0;
+ if (query.offset !== undefined) {
+ offset = Number(query.offset);
+ if (!Number.isInteger(offset) || offset < 0) {
+ throw invalidRequest('offset must be a non-negative integer');
+ }
+ }
+
+ let q = null;
+ if (query.q !== undefined) {
+ q = String(query.q).trim();
+ if (q.length > MAX_SEARCH_LENGTH) {
+ throw invalidRequest(`q must be at most ${MAX_SEARCH_LENGTH} characters`);
+ }
+ if (!q) q = null;
+ }
+
+ return { limit, offset, q };
+}
+
+export function pagedResult(resourceKey, rows, { limit, offset, total }) {
+ return {
+ [resourceKey]: rows,
+ page: { limit, offset, total },
+ };
+}
+
+export function escapeLikeTerm(term) {
+ return String(term).replace(/[\\%_]/g, (char) => `\\${char}`);
+}
+
+// Column names come from caller-owned whitelists, never request input; the
+// identifier guard keeps that contract enforced at runtime.
+export function searchClause(term, columns, param = 'search') {
+ if (!Array.isArray(columns) || columns.length === 0) {
+ throw new Error('searchClause requires at least one column');
+ }
+ const conditions = columns.map((column) => {
+ if (!SEARCH_COLUMN.test(column)) {
+ throw new Error(`invalid search column: ${column}`);
+ }
+ return `${column} LIKE {${param}} ESCAPE '\\'`;
+ });
+ return {
+ clause: `(${conditions.join(' OR ')})`,
+ params: { [param]: `%${escapeLikeTerm(term)}%` },
+ };
+}
diff --git a/server/src/lib/session.js b/server/src/lib/session.js
@@ -592,6 +592,20 @@ export async function destroyClientHostSessions(
});
}
+export async function destroyUserSessions(systemDb, { userId, now = Date.now() }) {
+ return systemDb.transaction(async (tx) => {
+ // Expired rows are included so stale refresh tokens cascade too.
+ const sessions = await tx.all(
+ 'SELECT id, group_id FROM sessions WHERE user_id = {userId}',
+ { userId }
+ );
+ for (const session of sessions) {
+ await removeSession(tx, session, now);
+ }
+ return { destroyed: sessions.length };
+ });
+}
+
export async function getSessionRealmBinding(systemDb, sessionId, realmId) {
return systemDb.get(
`SELECT session_id, realm_id, created_at, last_seen_at, revoked_at, revoked_by
diff --git a/server/test/pagination.test.js b/server/test/pagination.test.js
@@ -0,0 +1,94 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ escapeLikeTerm,
+ pagedResult,
+ parsePagination,
+ searchClause,
+} from '../src/lib/pagination.js';
+
+function expectHttpError(fn, status, code) {
+ try {
+ fn();
+ } catch (error) {
+ assert.equal(error.status, status);
+ assert.equal(error.code, code);
+ return;
+ }
+ assert.fail('Expected an HTTP error');
+}
+
+test('parsePagination applies defaults and parses integer parameters', () => {
+ assert.deepEqual(parsePagination({}), { limit: 25, offset: 0, q: null });
+ assert.deepEqual(parsePagination({ limit: '10', offset: '30' }), {
+ limit: 10,
+ offset: 30,
+ q: null,
+ });
+ assert.deepEqual(parsePagination({ limit: 3, offset: 7 }), {
+ limit: 3,
+ offset: 7,
+ q: null,
+ });
+});
+
+test('parsePagination clamps limits above the maximum', () => {
+ assert.equal(parsePagination({ limit: '100' }).limit, 100);
+ assert.equal(parsePagination({ limit: '101' }).limit, 100);
+ assert.equal(parsePagination({ limit: '10000' }).limit, 100);
+});
+
+test('parsePagination rejects invalid limits', () => {
+ for (const limit of ['0', '-5', '1.5', '', 'abc', 'NaN', 'Infinity']) {
+ expectHttpError(() => parsePagination({ limit }), 400, 'invalid_request');
+ }
+});
+
+test('parsePagination rejects invalid offsets', () => {
+ for (const offset of ['-1', '1.5', 'abc', 'NaN']) {
+ expectHttpError(() => parsePagination({ offset }), 400, 'invalid_request');
+ }
+});
+
+test('parsePagination trims and bounds the search term', () => {
+ assert.equal(parsePagination({ q: ' hello ' }).q, 'hello');
+ assert.equal(parsePagination({ q: ' ' }).q, null);
+ assert.equal(parsePagination({ q: 'x'.repeat(128) }).q.length, 128);
+ expectHttpError(() => parsePagination({ q: 'x'.repeat(129) }), 400, 'invalid_request');
+});
+
+test('pagedResult builds the rows and page envelope', () => {
+ assert.deepEqual(
+ pagedResult('sessions', [{ id: 'a' }], { limit: 25, offset: 50, total: 41 }),
+ {
+ sessions: [{ id: 'a' }],
+ page: { limit: 25, offset: 50, total: 41 },
+ }
+ );
+});
+
+test('escapeLikeTerm escapes backslash, percent and underscore', () => {
+ assert.equal(escapeLikeTerm('a\\b%c_d'), 'a\\\\b\\%c\\_d');
+ assert.equal(escapeLikeTerm('plain'), 'plain');
+});
+
+test('searchClause OR-matches whitelisted columns with an escaped term', () => {
+ const { clause, params } = searchClause('100%_a\\b', ['s.user_agent', 's.ip']);
+ assert.equal(
+ clause,
+ "(s.user_agent LIKE {search} ESCAPE '\\' OR s.ip LIKE {search} ESCAPE '\\')"
+ );
+ assert.deepEqual(params, { search: '%100\\%\\_a\\\\b%' });
+});
+
+test('searchClause accepts a custom parameter name and single columns', () => {
+ const { clause, params } = searchClause('x', ['s.client_id'], 'filter');
+ assert.equal(clause, "(s.client_id LIKE {filter} ESCAPE '\\')");
+ assert.deepEqual(params, { filter: '%x%' });
+});
+
+test('searchClause rejects identifiers that are not qualified column names', () => {
+ assert.throws(() => searchClause('x', ['s.ip; DROP TABLE users']));
+ assert.throws(() => searchClause('x', ['1 = 1']));
+ assert.throws(() => searchClause('x', []));
+});
diff --git a/server/test/user-sessions.test.js b/server/test/user-sessions.test.js
@@ -0,0 +1,449 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import crypto from 'node:crypto';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { app } from '../src/app.js';
+import { HttpError } from '../src/lib/http/http-error.js';
+import { HttpOk } from '../src/lib/http/http-ok.js';
+import { HttpResponse } from '../src/lib/http/http-response.js';
+import { signToken } from '../src/lib/oidc/keys.js';
+import { systemIssuer } from '../src/lib/oidc/context.js';
+import {
+ closeRealms,
+ createRealm,
+ getSystemDatabase,
+ initRealms,
+ openRealmDatabase,
+} from '../src/lib/realm.js';
+import { createHostSession } from '../src/lib/session.js';
+import { createUser, ensureMembership } from '../src/lib/users.js';
+import listRoute from '../src/controller/admin/user-sessions/list.js';
+import terminateAllRoute from '../src/controller/admin/user-sessions/terminate-all.js';
+
+const PUBLIC_HOST = 'identity.test';
+const PUBLIC_URL = `http://${PUBLIC_HOST}`;
+
+Object.assign(app, { HttpError, HttpOk, HttpResponse });
+app.config = { server: { public_url: PUBLIC_URL } };
+
+async function withAdminApi(fn) {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'auth-user-sessions-'));
+ try {
+ await initRealms({
+ database: {
+ dialect: 'sqlite',
+ path: path.join(dir, 'system.sqlite'),
+ realms: path.join(dir, 'realms'),
+ },
+ });
+ await fn(getSystemDatabase());
+ } finally {
+ await closeRealms();
+ await fs.rm(dir, { recursive: true, force: true });
+ }
+}
+
+async function invokeRoute(route, { url, bearer, params }) {
+ const req = {
+ method: route.method,
+ url,
+ params,
+ headers: { host: PUBLIC_HOST, authorization: `Bearer ${bearer}` },
+ };
+ try {
+ const response = await route.handler(req);
+ return { status: response.status, headers: response.headers, json: response.body };
+ } catch (error) {
+ if (error instanceof HttpError) {
+ return { status: error.status, json: error.toResponse().body };
+ }
+ throw error;
+ }
+}
+
+async function issueAdminBearer(systemDb, userId) {
+ const { session } = await createHostSession(systemDb, {
+ context: { mode: 'canonical', host: PUBLIC_HOST },
+ userId,
+ ttl: 3600,
+ });
+ return signToken(
+ systemDb,
+ { sub: userId, client_id: 'admin', scope: 'openid', roles: [], sid: session.id },
+ {
+ issuer: systemIssuer(PUBLIC_URL),
+ audience: 'admin',
+ expiresIn: 3600,
+ table: 'system_signing_keys',
+ }
+ );
+}
+
+async function makeActor(systemDb, { username, isSystemAdmin = false }) {
+ const id = await createUser(systemDb, { username, isSystemAdmin });
+ return { id, bearer: await issueAdminBearer(systemDb, id) };
+}
+
+async function makeRealmAdmin(systemDb, realm, username) {
+ const actor = await makeActor(systemDb, { username });
+ const realmDb = await openRealmDatabase(realm);
+ await ensureMembership(realmDb, actor.id, 'active');
+ await realmDb.run(
+ `INSERT INTO membership_roles (user_id, role_id)
+ SELECT {userId}, id FROM roles WHERE slug = 'realm-admin'`,
+ { userId: actor.id }
+ );
+ return actor;
+}
+
+async function seedListFixtures(systemDb) {
+ const acme = await createRealm({ slug: 'acme', displayName: 'Acme' });
+ const globex = await createRealm({ slug: 'globex', displayName: 'Globex' });
+ const alice = await createUser(systemDb, {
+ username: 'alice',
+ displayName: 'Alice',
+ homeRealmId: acme.id,
+ });
+ const bob = await createUser(systemDb, { username: 'bob', homeRealmId: globex.id });
+
+ const base = Date.now();
+ const firefox = await createHostSession(
+ systemDb,
+ {
+ context: { mode: 'canonical', host: PUBLIC_HOST },
+ userId: alice,
+ ttl: 3600,
+ userAgent: 'Firefox/1.0',
+ ip: '10.0.0.1',
+ },
+ base + 1000
+ );
+ const safari = await createHostSession(
+ systemDb,
+ {
+ context: { mode: 'realm', host: 'globex.localhost', realm: globex },
+ userId: alice,
+ ttl: 3600,
+ userAgent: 'Safari/1.0',
+ ip: '10.0.0.2',
+ },
+ base + 2000
+ );
+ const chrome = await createHostSession(
+ systemDb,
+ {
+ context: { mode: 'client', host: 'app.acme.localhost', realm: acme, clientId: 'internal-app' },
+ userId: alice,
+ ttl: 3600,
+ userAgent: 'Chrome/1.0',
+ ip: '10.0.0.3',
+ },
+ base + 3000
+ );
+ await createHostSession(
+ systemDb,
+ {
+ context: { mode: 'realm', host: 'acme.localhost', realm: acme },
+ userId: alice,
+ ttl: 3600,
+ userAgent: 'Edge/1.0',
+ },
+ base - 7_200_000
+ );
+ await createHostSession(systemDb, {
+ context: { mode: 'realm', host: 'acme.localhost', realm: acme },
+ userId: bob,
+ ttl: 3600,
+ userAgent: 'Wget/1.0',
+ });
+
+ return { acme, globex, alice, sessions: { firefox, safari, chrome } };
+}
+
+function listPath(realmSlug, userId, query = '') {
+ const base = `/api/v1/admin/realms/${realmSlug}/users/${userId}/sessions`;
+ return query ? `${base}?${query}` : base;
+}
+
+function listRequest(actor, realmSlug, userId, query) {
+ return invokeRoute(listRoute, {
+ url: listPath(realmSlug, userId, query),
+ bearer: actor.bearer,
+ params: { realm: realmSlug, userId },
+ });
+}
+
+test('list returns live sessions on every host newest first', async () => {
+ await withAdminApi(async (systemDb) => {
+ const { acme, alice, sessions } = await seedListFixtures(systemDb);
+ const actor = await makeRealmAdmin(systemDb, acme, 'acme-admin');
+
+ const response = await listRequest(actor, 'acme', alice);
+ assert.equal(response.status, 200);
+ assert.equal(response.headers['cache-control'], 'no-store');
+ assert.deepEqual(response.json.page, { limit: 25, offset: 0, total: 3 });
+ assert.deepEqual(
+ response.json.sessions.map((session) => session.user_agent),
+ ['Chrome/1.0', 'Safari/1.0', 'Firefox/1.0']
+ );
+
+ const first = response.json.sessions[0];
+ assert.equal(first.public_id, sessions.chrome.session.public_id);
+ assert.deepEqual(first.scope, {
+ type: 'client',
+ host: 'app.acme.localhost',
+ client_id: 'internal-app',
+ });
+ assert.equal(first.user.id, alice);
+ assert.equal(first.user.username, 'alice');
+ assert.equal(first.ip, '10.0.0.3');
+ assert.equal(first.revoked_at, null);
+ assert.equal(first.can_terminate, true);
+ });
+});
+
+test('list pages results with limit and offset while total stays unpaginated', async () => {
+ await withAdminApi(async (systemDb) => {
+ const { acme, alice, sessions } = await seedListFixtures(systemDb);
+ const actor = await makeRealmAdmin(systemDb, acme, 'acme-admin');
+
+ const second = await listRequest(actor, 'acme', alice, 'limit=1&offset=1');
+ assert.equal(second.status, 200);
+ assert.deepEqual(second.json.page, { limit: 1, offset: 1, total: 3 });
+ assert.deepEqual(
+ second.json.sessions.map((session) => session.public_id),
+ [sessions.safari.session.public_id]
+ );
+
+ const past = await listRequest(actor, 'acme', alice, 'limit=1&offset=3');
+ assert.deepEqual(past.json.sessions, []);
+ assert.deepEqual(past.json.page, { limit: 1, offset: 3, total: 3 });
+ });
+});
+
+test('list filters sessions case-insensitively across the whitelisted columns', async () => {
+ await withAdminApi(async (systemDb) => {
+ const { acme, alice, sessions } = await seedListFixtures(systemDb);
+ const actor = await makeRealmAdmin(systemDb, acme, 'acme-admin');
+
+ const byAgent = await listRequest(actor, 'acme', alice, 'q=chrome');
+ assert.deepEqual(byAgent.json.page, { limit: 25, offset: 0, total: 1 });
+ assert.deepEqual(
+ byAgent.json.sessions.map((session) => session.public_id),
+ [sessions.chrome.session.public_id]
+ );
+
+ const byHost = await listRequest(actor, 'acme', alice, 'q=globex.localhost');
+ assert.equal(byHost.json.page.total, 1);
+ assert.equal(byHost.json.sessions[0].public_id, sessions.safari.session.public_id);
+
+ const byIp = await listRequest(actor, 'acme', alice, 'q=10.0.0.1');
+ assert.equal(byIp.json.sessions[0].public_id, sessions.firefox.session.public_id);
+
+ const byClient = await listRequest(actor, 'acme', alice, 'q=internal-app');
+ assert.equal(byClient.json.page.total, 1);
+
+ const byType = await listRequest(actor, 'acme', alice, 'q=global');
+ assert.equal(byType.json.page.total, 1);
+ assert.equal(byType.json.sessions[0].public_id, sessions.firefox.session.public_id);
+
+ const miss = await listRequest(actor, 'acme', alice, 'q=zzzz');
+ assert.deepEqual(miss.json.sessions, []);
+ assert.equal(miss.json.page.total, 0);
+ });
+});
+
+test('list rejects invalid pagination and search parameters', async () => {
+ await withAdminApi(async (systemDb) => {
+ const { acme, alice } = await seedListFixtures(systemDb);
+ const actor = await makeRealmAdmin(systemDb, acme, 'acme-admin');
+
+ const invalidQueries = [
+ 'limit=0',
+ 'limit=-5',
+ 'limit=1.5',
+ 'limit=abc',
+ 'offset=-1',
+ 'offset=abc',
+ `q=${'x'.repeat(129)}`,
+ ];
+ for (const query of invalidQueries) {
+ const response = await listRequest(actor, 'acme', alice, query);
+ assert.equal(response.status, 400, `expected 400 for ${query}`);
+ assert.equal(response.json.error.code, 'invalid_request');
+ }
+ });
+});
+
+test('list returns 404 for an unknown user id', async () => {
+ await withAdminApi(async (systemDb) => {
+ const acme = await createRealm({ slug: 'acme', displayName: 'Acme' });
+ const actor = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true });
+
+ const response = await listRequest(actor, 'acme', crypto.randomUUID());
+ assert.equal(response.status, 404);
+ assert.equal(response.json.error.code, 'user_not_found');
+ });
+});
+
+test('list returns 403 for a realm admin outside the user home realm', async () => {
+ await withAdminApi(async (systemDb) => {
+ const { globex, alice } = await seedListFixtures(systemDb);
+ const actor = await makeRealmAdmin(systemDb, globex, 'globex-admin');
+
+ const response = await listRequest(actor, 'globex', alice);
+ assert.equal(response.status, 403);
+ assert.equal(response.json.error.code, 'forbidden');
+ });
+});
+
+test('a system admin can list user sessions from any realm', async () => {
+ await withAdminApi(async (systemDb) => {
+ const { alice } = await seedListFixtures(systemDb);
+ const actor = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true });
+
+ const response = await listRequest(actor, 'globex', alice);
+ assert.equal(response.status, 200);
+ assert.equal(response.json.page.total, 3);
+ assert.equal(response.json.sessions[0].can_terminate, true);
+ });
+});
+
+test('terminate-all destroys sessions on every host including expired rows', async () => {
+ await withAdminApi(async (systemDb) => {
+ const acme = await createRealm({ slug: 'acme', displayName: 'Acme' });
+ const alice = await createUser(systemDb, { username: 'alice', homeRealmId: acme.id });
+ const bob = await createUser(systemDb, { username: 'bob' });
+ const actor = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true });
+ const canonical = { mode: 'canonical', host: PUBLIC_HOST };
+
+ const shared = await createHostSession(systemDb, { context: canonical, userId: alice, ttl: 3600 });
+ const bobShared = await createHostSession(systemDb, {
+ context: canonical,
+ token: shared.token,
+ userId: bob,
+ ttl: 3600,
+ });
+ await createHostSession(systemDb, {
+ context: canonical,
+ token: shared.token,
+ userId: alice,
+ ttl: 3600,
+ });
+ const realmSession = await createHostSession(systemDb, {
+ context: { mode: 'realm', host: 'acme.localhost', realm: acme },
+ userId: alice,
+ ttl: 3600,
+ });
+ const expired = await createHostSession(
+ systemDb,
+ {
+ context: { mode: 'client', host: 'app.acme.localhost', realm: acme, clientId: 'internal-app' },
+ userId: alice,
+ ttl: 3600,
+ },
+ Date.now() - 7_200_000
+ );
+
+ const response = await invokeRoute(terminateAllRoute, {
+ url: listPath('acme', alice),
+ bearer: actor.bearer,
+ params: { realm: 'acme', userId: alice },
+ });
+ assert.equal(response.status, 200);
+ assert.deepEqual(response.json, { ok: true, destroyed: 3 });
+ assert.equal(response.headers['cache-control'], 'no-store');
+
+ assert.equal(
+ (await systemDb.get('SELECT COUNT(*) AS count FROM sessions WHERE user_id = {userId}', {
+ userId: alice,
+ })).count,
+ 0
+ );
+ assert.ok(await systemDb.get('SELECT id FROM sessions WHERE id = {id}', {
+ id: bobShared.session.id,
+ }));
+ assert.equal(
+ await systemDb.get('SELECT id FROM session_groups WHERE id = {id}', {
+ id: realmSession.group.id,
+ }),
+ undefined
+ );
+ assert.equal(
+ await systemDb.get('SELECT id FROM session_groups WHERE id = {id}', {
+ id: expired.group.id,
+ }),
+ undefined
+ );
+
+ const repaired = await systemDb.get(
+ 'SELECT active_session_id FROM session_groups WHERE id = {id}',
+ { id: shared.group.id }
+ );
+ assert.equal(repaired.active_session_id, bobShared.session.id);
+ });
+});
+
+test('re-terminating a user with no sessions destroys nothing', async () => {
+ await withAdminApi(async (systemDb) => {
+ const acme = await createRealm({ slug: 'acme', displayName: 'Acme' });
+ const alice = await createUser(systemDb, { username: 'alice', homeRealmId: acme.id });
+ const actor = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true });
+
+ await createHostSession(systemDb, {
+ context: { mode: 'canonical', host: PUBLIC_HOST },
+ userId: alice,
+ ttl: 3600,
+ });
+
+ const first = await invokeRoute(terminateAllRoute, {
+ url: listPath('acme', alice),
+ bearer: actor.bearer,
+ params: { realm: 'acme', userId: alice },
+ });
+ assert.deepEqual(first.json, { ok: true, destroyed: 1 });
+
+ const second = await invokeRoute(terminateAllRoute, {
+ url: listPath('acme', alice),
+ bearer: actor.bearer,
+ params: { realm: 'acme', userId: alice },
+ });
+ assert.deepEqual(second.json, { ok: true, destroyed: 0 });
+ });
+});
+
+test('terminate-all enforces user level authorization', async () => {
+ await withAdminApi(async (systemDb) => {
+ const { acme, globex, alice } = await seedListFixtures(systemDb);
+ const outside = await makeRealmAdmin(systemDb, globex, 'globex-admin');
+ const sysadmin = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true });
+
+ const forbidden = await invokeRoute(terminateAllRoute, {
+ url: listPath('globex', alice),
+ bearer: outside.bearer,
+ params: { realm: 'globex', userId: alice },
+ });
+ assert.equal(forbidden.status, 403);
+ assert.equal(forbidden.json.error.code, 'forbidden');
+
+ const unknownUser = crypto.randomUUID();
+ const missing = await invokeRoute(terminateAllRoute, {
+ url: listPath('acme', unknownUser),
+ bearer: sysadmin.bearer,
+ params: { realm: 'acme', userId: unknownUser },
+ });
+ assert.equal(missing.status, 404);
+ assert.equal(missing.json.error.code, 'user_not_found');
+
+ const homeAdmin = await makeRealmAdmin(systemDb, acme, 'acme-admin');
+ const allowed = await invokeRoute(terminateAllRoute, {
+ url: listPath('acme', alice),
+ bearer: homeAdmin.bearer,
+ params: { realm: 'acme', userId: alice },
+ });
+ assert.equal(allowed.status, 200);
+ assert.deepEqual(allowed.json, { ok: true, destroyed: 4 });
+ });
+});