auth

Main authentication module for my projects
git clone git://git.finwo.net/app/auth
Log | Files | Refs

commit aaacbaf97eb9e16a8a8399be1bc54e9e4b42f4ee
parent 321c8d23e0e84250d2c9523278c4fb437785c9d9
Author: finwo <finwo@pm.me>
Date:   Wed,  2 Dec 2026 00:01:07 +0100

server: global user session endpoints for system admins

Diffstat:
Aserver/src/controller/admin/user-sessions-global/list.js | 24++++++++++++++++++++++++
Aserver/src/controller/admin/user-sessions-global/terminate-all.js | 28++++++++++++++++++++++++++++
Aserver/src/controller/admin/user-sessions-global/terminate.js | 32++++++++++++++++++++++++++++++++
Mserver/src/controller/admin/user-sessions/list.js | 69++++++++++-----------------------------------------------------------
Aserver/src/lib/admin-user-sessions.js | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/test/user-sessions-global.test.js | 393+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 565 insertions(+), 59 deletions(-)

diff --git a/server/src/controller/admin/user-sessions-global/list.js b/server/src/controller/admin/user-sessions-global/list.js @@ -0,0 +1,24 @@ +import { app } from '../../../app.js'; +import { listUserSessions } from '../../../lib/admin-user-sessions.js'; +import { authenticateAdminSession } from '../../../lib/admin-auth.js'; +import { parsePagination } from '../../../lib/pagination.js'; + +export default { + method: 'get', + path: '/api/v1/admin/users/:userId/sessions', + name: 'admin.userSessionsGlobal.list', + async handler(req) { + const auth = await authenticateAdminSession(req); + const url = new URL(req.url, 'http://localhost'); + const pagination = parsePagination(Object.fromEntries(url.searchParams)); + + const result = await listUserSessions(auth.systemDb, { + userId: req.params.userId, + actor: auth.user, + realmId: null, + pagination, + }); + + return new app.HttpOk(result, { 'cache-control': 'no-store' }); + }, +}; diff --git a/server/src/controller/admin/user-sessions-global/terminate-all.js b/server/src/controller/admin/user-sessions-global/terminate-all.js @@ -0,0 +1,28 @@ +import { app } from '../../../app.js'; +import { authenticateAdminSession } 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/users/:userId/sessions', + name: 'admin.userSessionsGlobal.terminateAll', + async handler(req) { + const auth = await authenticateAdminSession(req); + if (!isSystemAdmin(auth.user)) { + throw new HttpError(403, 'forbidden', 'System administrator access is required'); + } + const user = await findUserById(auth.systemDb, req.params.userId); + if (!user) { + throw new HttpError(404, 'user_not_found', 'User not found'); + } + + 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/controller/admin/user-sessions-global/terminate.js b/server/src/controller/admin/user-sessions-global/terminate.js @@ -0,0 +1,32 @@ +import { app } from '../../../app.js'; +import { authenticateAdminSession } from '../../../lib/admin-auth.js'; +import { HttpError } from '../../../lib/http/http-error.js'; +import { isSystemAdmin } from '../../../lib/policy.js'; +import { destroySessionById } from '../../../lib/session.js'; + +export default { + method: 'delete', + path: '/api/v1/admin/users/:userId/sessions/:publicId', + name: 'admin.userSessionsGlobal.terminate', + async handler(req) { + const auth = await authenticateAdminSession(req); + if (!isSystemAdmin(auth.user)) { + throw new HttpError(403, 'forbidden', 'System administrator access is required'); + } + + // Expired rows stay terminable so stale group and refresh state can be + // cleared; ownership on user_id keeps cross-user guesses at 404. + const row = await auth.systemDb.get( + `SELECT id FROM sessions + WHERE id = (SELECT id FROM sessions WHERE public_id = {publicId}) + AND user_id = {userId}`, + { publicId: req.params.publicId, userId: req.params.userId } + ); + if (!row) { + throw new HttpError(404, 'session_not_found', 'Session not found'); + } + + await destroySessionById(auth.systemDb, row.id); + return new app.HttpOk({ ok: true }, { 'cache-control': 'no-store' }); + }, +}; diff --git a/server/src/controller/admin/user-sessions/list.js b/server/src/controller/admin/user-sessions/list.js @@ -1,12 +1,7 @@ import { app } from '../../../app.js'; +import { listUserSessions } from '../../../lib/admin-user-sessions.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']; +import { parsePagination } from '../../../lib/pagination.js'; export default { method: 'get', @@ -16,60 +11,16 @@ export default { 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 pagination = parsePagination(Object.fromEntries(url.searchParams)); - 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 result = await listUserSessions(auth.systemDb, { + userId: req.params.userId, + actor: auth.user, + realmId: auth.realm.id, + pagination, + }); - 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' } - ); + return new app.HttpOk(result, { 'cache-control': 'no-store' }); }, }; diff --git a/server/src/lib/admin-user-sessions.js b/server/src/lib/admin-user-sessions.js @@ -0,0 +1,78 @@ +import { ADMIN_SESSION_FIELDS, serialize } from './admin-sessions.js'; +import { HttpError } from './http/http-error.js'; +import { pagedResult, searchClause } from './pagination.js'; +import { isSystemAdmin } from './policy.js'; +import { findUserById } from './users.js'; + +const SEARCH_COLUMNS = ['s.user_agent', 's.ip', 's.scope_host', 's.client_id', 's.scope_type']; + +// A null realmId drops the session_realms join. The single-row NULL stub keeps +// the ADMIN_SESSION_FIELDS projection and serialize() shape without a realm +// context; can_terminate then falls out of the system-admin check below. +function realmBinding(realmId) { + if (realmId === null) { + return 'CROSS JOIN (SELECT NULL AS revoked_at, NULL AS revoked_by) sr'; + } + return `LEFT JOIN session_realms sr + ON sr.session_id = s.id AND sr.realm_id = {realmId}`; +} + +export async function listUserSessions( + systemDb, + { userId, actor, realmId, pagination } +) { + const user = await findUserById(systemDb, userId); + if (!user) { + throw new HttpError(404, 'user_not_found', 'User not found'); + } + if (!isSystemAdmin(actor)) { + if (realmId === null) { + throw new HttpError(403, 'forbidden', 'System administrator access is required'); + } + if (user.home_realm_id !== realmId) { + throw new HttpError( + 403, + 'forbidden', + 'Only home-realm and system admins can list sessions for this user' + ); + } + } + + const params = { + userId: user.id, + now: Date.now(), + limit: pagination.limit, + offset: pagination.offset, + }; + if (realmId !== null) params.realmId = realmId; + + let filter = 's.user_id = {userId} AND s.expires_at > {now}'; + if (pagination.q) { + const search = searchClause(pagination.q, SEARCH_COLUMNS); + filter += ` AND ${search.clause}`; + Object.assign(params, search.params); + } + + const rows = await systemDb.all( + `SELECT ${ADMIN_SESSION_FIELDS} + FROM sessions s + JOIN users u ON u.id = s.user_id + ${realmBinding(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 systemDb.get( + `SELECT COUNT(*) AS total + FROM sessions s + WHERE ${filter}`, + params + ); + + return pagedResult('sessions', rows.map((row) => serialize(row, actor, realmId)), { + limit: pagination.limit, + offset: pagination.offset, + total: count.total, + }); +} diff --git a/server/test/user-sessions-global.test.js b/server/test/user-sessions-global.test.js @@ -0,0 +1,393 @@ +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-global/list.js'; +import terminateAllRoute from '../src/controller/admin/user-sessions-global/terminate-all.js'; +import terminateRoute from '../src/controller/admin/user-sessions-global/terminate.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-global-')); + 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; +} + +// carol has no home realm, the gap realm-scoped routes cannot cover. +async function seedFixtures(systemDb) { + const acme = await createRealm({ slug: 'acme', displayName: 'Acme' }); + const globex = await createRealm({ slug: 'globex', displayName: 'Globex' }); + const carol = await createUser(systemDb, { username: 'carol' }); + const bob = await createUser(systemDb, { username: 'bob', homeRealmId: acme.id }); + + const base = Date.now(); + const firefox = await createHostSession( + systemDb, + { + context: { mode: 'canonical', host: PUBLIC_HOST }, + userId: carol, + ttl: 3600, + userAgent: 'Firefox/1.0', + ip: '10.1.0.1', + }, + base + 1000 + ); + const safari = await createHostSession( + systemDb, + { + context: { mode: 'realm', host: 'globex.localhost', realm: globex }, + userId: carol, + ttl: 3600, + userAgent: 'Safari/1.0', + ip: '10.1.0.2', + }, + base + 2000 + ); + const chrome = await createHostSession( + systemDb, + { + context: { + mode: 'client', + host: 'app.acme.localhost', + realm: acme, + clientId: 'internal-app', + }, + userId: carol, + ttl: 3600, + userAgent: 'Chrome/1.0', + ip: '10.1.0.3', + }, + base + 3000 + ); + const expired = await createHostSession( + systemDb, + { + context: { mode: 'realm', host: 'acme.localhost', realm: acme }, + userId: carol, + ttl: 3600, + userAgent: 'Edge/1.0', + }, + base - 7_200_000 + ); + const bobSession = await createHostSession(systemDb, { + context: { mode: 'realm', host: 'acme.localhost', realm: acme }, + userId: bob, + ttl: 3600, + userAgent: 'Wget/1.0', + }); + + return { acme, globex, carol, bob, expired, bobSession, sessions: { firefox, safari, chrome } }; +} + +function listPath(userId, query = '') { + const base = `/api/v1/admin/users/${userId}/sessions`; + return query ? `${base}?${query}` : base; +} + +function listRequest(actor, userId, query) { + return invokeRoute(listRoute, { + url: listPath(userId, query), + bearer: actor.bearer, + params: { userId }, + }); +} + +function terminateAllRequest(actor, userId) { + return invokeRoute(terminateAllRoute, { + url: listPath(userId), + bearer: actor.bearer, + params: { userId }, + }); +} + +function terminateRequest(actor, userId, publicId) { + return invokeRoute(terminateRoute, { + url: `${listPath(userId)}/${publicId}`, + bearer: actor.bearer, + params: { userId, publicId }, + }); +} + +async function sessionExists(systemDb, id) { + return Boolean( + await systemDb.get('SELECT id FROM sessions WHERE id = {id}', { id }) + ); +} + +test('global list returns live sessions on every host newest first', async () => { + await withAdminApi(async (systemDb) => { + const { carol, sessions } = await seedFixtures(systemDb); + const actor = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true }); + + const response = await listRequest(actor, carol); + 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, carol); + assert.equal(first.user.username, 'carol'); + assert.equal(first.ip, '10.1.0.3'); + assert.equal(first.revoked_at, null); + assert.equal(first.revoked_by, null); + assert.equal(first.can_terminate, true); + }); +}); + +test('global list pages results with limit and offset while total stays unpaginated', async () => { + await withAdminApi(async (systemDb) => { + const { carol, sessions } = await seedFixtures(systemDb); + const actor = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true }); + + const second = await listRequest(actor, carol, '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, carol, 'limit=1&offset=3'); + assert.deepEqual(past.json.sessions, []); + assert.deepEqual(past.json.page, { limit: 1, offset: 3, total: 3 }); + }); +}); + +test('global list filters sessions across the whitelisted columns', async () => { + await withAdminApi(async (systemDb) => { + const { carol, sessions } = await seedFixtures(systemDb); + const actor = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true }); + + const byAgent = await listRequest(actor, carol, 'q=chrome'); + assert.deepEqual(byAgent.json.page, { limit: 25, offset: 0, total: 1 }); + assert.equal(byAgent.json.sessions[0].public_id, sessions.chrome.session.public_id); + + const byHost = await listRequest(actor, carol, 'q=globex.localhost'); + assert.equal(byHost.json.sessions[0].public_id, sessions.safari.session.public_id); + + const byIp = await listRequest(actor, carol, 'q=10.1.0.1'); + assert.equal(byIp.json.sessions[0].public_id, sessions.firefox.session.public_id); + + const byClient = await listRequest(actor, carol, 'q=internal-app'); + assert.equal(byClient.json.page.total, 1); + + const byType = await listRequest(actor, carol, 'q=global'); + assert.equal(byType.json.page.total, 1); + + const miss = await listRequest(actor, carol, 'q=zzzz'); + assert.deepEqual(miss.json.sessions, []); + assert.equal(miss.json.page.total, 0); + }); +}); + +test('global routes reject a realm admin without system privileges', async () => { + await withAdminApi(async (systemDb) => { + const { acme, carol, sessions } = await seedFixtures(systemDb); + const actor = await makeRealmAdmin(systemDb, acme, 'acme-admin'); + + const forbiddenList = await listRequest(actor, carol); + assert.equal(forbiddenList.status, 403); + assert.equal(forbiddenList.json.error.code, 'forbidden'); + + const forbiddenAll = await terminateAllRequest(actor, carol); + assert.equal(forbiddenAll.status, 403); + assert.equal(forbiddenAll.json.error.code, 'forbidden'); + + const forbiddenOne = await terminateRequest( + actor, + carol, + sessions.firefox.session.public_id + ); + assert.equal(forbiddenOne.status, 403); + assert.equal(forbiddenOne.json.error.code, 'forbidden'); + + assert.ok(await sessionExists(systemDb, sessions.firefox.session.id)); + }); +}); + +test('global routes return 404 for an unknown user id', async () => { + await withAdminApi(async (systemDb) => { + const actor = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true }); + const unknownUser = crypto.randomUUID(); + + const missingList = await listRequest(actor, unknownUser); + assert.equal(missingList.status, 404); + assert.equal(missingList.json.error.code, 'user_not_found'); + + const missingAll = await terminateAllRequest(actor, unknownUser); + assert.equal(missingAll.status, 404); + assert.equal(missingAll.json.error.code, 'user_not_found'); + }); +}); + +test('global terminate-all destroys sessions on every host including expired rows', async () => { + await withAdminApi(async (systemDb) => { + const { carol, expired, bobSession, sessions } = await seedFixtures(systemDb); + const actor = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true }); + + const response = await terminateAllRequest(actor, carol); + assert.equal(response.status, 200); + assert.deepEqual(response.json, { ok: true, destroyed: 4 }); + assert.equal(response.headers['cache-control'], 'no-store'); + + assert.equal( + (await systemDb.get('SELECT COUNT(*) AS count FROM sessions WHERE user_id = {userId}', { + userId: carol, + })).count, + 0 + ); + for (const { group } of [sessions.firefox, sessions.safari, sessions.chrome, expired]) { + assert.equal( + await systemDb.get('SELECT id FROM session_groups WHERE id = {id}', { id: group.id }), + undefined + ); + } + assert.ok(await sessionExists(systemDb, bobSession.session.id)); + + const again = await terminateAllRequest(actor, carol); + assert.deepEqual(again.json, { ok: true, destroyed: 0 }); + }); +}); + +test('global terminate removes one session by public id and drops its group', async () => { + await withAdminApi(async (systemDb) => { + const { carol, expired, sessions } = await seedFixtures(systemDb); + const actor = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true }); + + const firefoxId = sessions.firefox.session.public_id; + const response = await terminateRequest(actor, carol, firefoxId); + assert.equal(response.status, 200); + assert.deepEqual(response.json, { ok: true }); + assert.equal(response.headers['cache-control'], 'no-store'); + + assert.ok(!(await sessionExists(systemDb, sessions.firefox.session.id))); + assert.equal( + await systemDb.get('SELECT id FROM session_groups WHERE id = {id}', { + id: sessions.firefox.group.id, + }), + undefined + ); + assert.ok(await sessionExists(systemDb, sessions.chrome.session.id)); + + // Stale expired rows stay terminable by public id. + const stale = await terminateRequest(actor, carol, expired.session.public_id); + assert.equal(stale.status, 200); + assert.ok(!(await sessionExists(systemDb, expired.session.id))); + + const again = await terminateRequest(actor, carol, firefoxId); + assert.equal(again.status, 404); + assert.equal(again.json.error.code, 'session_not_found'); + }); +}); + +test('global terminate returns 404 for a public id owned by another user', async () => { + await withAdminApi(async (systemDb) => { + const { carol, bobSession } = await seedFixtures(systemDb); + const actor = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true }); + + const response = await terminateRequest( + actor, + carol, + bobSession.session.public_id + ); + assert.equal(response.status, 404); + assert.equal(response.json.error.code, 'session_not_found'); + assert.ok(await sessionExists(systemDb, bobSession.session.id)); + }); +});