user-sessions-global.test.js (13697B)
1 import test from 'node:test'; 2 import assert from 'node:assert/strict'; 3 import crypto from 'node:crypto'; 4 import fs from 'node:fs/promises'; 5 import os from 'node:os'; 6 import path from 'node:path'; 7 import { app } from '../src/app.js'; 8 import { HttpError } from '../src/lib/http/http-error.js'; 9 import { HttpOk } from '../src/lib/http/http-ok.js'; 10 import { HttpResponse } from '../src/lib/http/http-response.js'; 11 import { signToken } from '../src/lib/oidc/keys.js'; 12 import { systemIssuer } from '../src/lib/oidc/context.js'; 13 import { 14 closeRealms, 15 createRealm, 16 getSystemDatabase, 17 initRealms, 18 openRealmDatabase, 19 } from '../src/lib/realm.js'; 20 import { createHostSession } from '../src/lib/session.js'; 21 import { createUser, ensureMembership } from '../src/lib/users.js'; 22 import listRoute from '../src/controller/admin/user-sessions-global/list.js'; 23 import terminateAllRoute from '../src/controller/admin/user-sessions-global/terminate-all.js'; 24 import terminateRoute from '../src/controller/admin/user-sessions-global/terminate.js'; 25 26 const PUBLIC_HOST = 'identity.test'; 27 const PUBLIC_URL = `http://${PUBLIC_HOST}`; 28 29 Object.assign(app, { HttpError, HttpOk, HttpResponse }); 30 app.config = { server: { public_url: PUBLIC_URL } }; 31 32 async function withAdminApi(fn) { 33 const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'auth-user-sessions-global-')); 34 try { 35 await initRealms({ 36 database: { 37 dialect: 'sqlite', 38 path: path.join(dir, 'system.sqlite'), 39 realms: path.join(dir, 'realms'), 40 }, 41 }); 42 await fn(getSystemDatabase()); 43 } finally { 44 await closeRealms(); 45 await fs.rm(dir, { recursive: true, force: true }); 46 } 47 } 48 49 async function invokeRoute(route, { url, bearer, params }) { 50 const req = { 51 method: route.method, 52 url, 53 params, 54 headers: { host: PUBLIC_HOST, authorization: `Bearer ${bearer}` }, 55 }; 56 try { 57 const response = await route.handler(req); 58 return { status: response.status, headers: response.headers, json: response.body }; 59 } catch (error) { 60 if (error instanceof HttpError) { 61 return { status: error.status, json: error.toResponse().body }; 62 } 63 throw error; 64 } 65 } 66 67 async function issueAdminBearer(systemDb, userId) { 68 const { session } = await createHostSession(systemDb, { 69 context: { mode: 'canonical', host: PUBLIC_HOST }, 70 userId, 71 ttl: 3600, 72 }); 73 return signToken( 74 systemDb, 75 { sub: userId, client_id: 'admin', scope: 'openid', roles: [], sid: session.id }, 76 { 77 issuer: systemIssuer(PUBLIC_URL), 78 audience: 'admin', 79 expiresIn: 3600, 80 table: 'system_signing_keys', 81 } 82 ); 83 } 84 85 async function makeActor(systemDb, { username, isSystemAdmin = false }) { 86 const id = await createUser(systemDb, { username, isSystemAdmin }); 87 return { id, bearer: await issueAdminBearer(systemDb, id) }; 88 } 89 90 async function makeRealmAdmin(systemDb, realm, username) { 91 const actor = await makeActor(systemDb, { username }); 92 const realmDb = await openRealmDatabase(realm); 93 await ensureMembership(realmDb, actor.id, 'active'); 94 await realmDb.run( 95 `INSERT INTO membership_roles (user_id, role_id) 96 SELECT {userId}, id FROM roles WHERE slug = 'realm-admin'`, 97 { userId: actor.id } 98 ); 99 return actor; 100 } 101 102 // carol has no home realm, the gap realm-scoped routes cannot cover. 103 async function seedFixtures(systemDb) { 104 const acme = await createRealm({ slug: 'acme', displayName: 'Acme' }); 105 const globex = await createRealm({ slug: 'globex', displayName: 'Globex' }); 106 const carol = await createUser(systemDb, { username: 'carol' }); 107 const bob = await createUser(systemDb, { username: 'bob', homeRealmId: acme.id }); 108 109 const base = Date.now(); 110 const firefox = await createHostSession( 111 systemDb, 112 { 113 context: { mode: 'canonical', host: PUBLIC_HOST }, 114 userId: carol, 115 ttl: 3600, 116 userAgent: 'Firefox/1.0', 117 ip: '10.1.0.1', 118 }, 119 base + 1000 120 ); 121 const safari = await createHostSession( 122 systemDb, 123 { 124 context: { mode: 'realm', host: 'globex.localhost', realm: globex }, 125 userId: carol, 126 ttl: 3600, 127 userAgent: 'Safari/1.0', 128 ip: '10.1.0.2', 129 }, 130 base + 2000 131 ); 132 const chrome = await createHostSession( 133 systemDb, 134 { 135 context: { 136 mode: 'client', 137 host: 'app.acme.localhost', 138 realm: acme, 139 clientId: 'internal-app', 140 }, 141 userId: carol, 142 ttl: 3600, 143 userAgent: 'Chrome/1.0', 144 ip: '10.1.0.3', 145 }, 146 base + 3000 147 ); 148 const expired = await createHostSession( 149 systemDb, 150 { 151 context: { mode: 'realm', host: 'acme.localhost', realm: acme }, 152 userId: carol, 153 ttl: 3600, 154 userAgent: 'Edge/1.0', 155 }, 156 base - 7_200_000 157 ); 158 const bobSession = await createHostSession(systemDb, { 159 context: { mode: 'realm', host: 'acme.localhost', realm: acme }, 160 userId: bob, 161 ttl: 3600, 162 userAgent: 'Wget/1.0', 163 }); 164 165 return { acme, globex, carol, bob, expired, bobSession, sessions: { firefox, safari, chrome } }; 166 } 167 168 function listPath(userId, query = '') { 169 const base = `/api/v1/admin/users/${userId}/sessions`; 170 return query ? `${base}?${query}` : base; 171 } 172 173 function listRequest(actor, userId, query) { 174 return invokeRoute(listRoute, { 175 url: listPath(userId, query), 176 bearer: actor.bearer, 177 params: { userId }, 178 }); 179 } 180 181 function terminateAllRequest(actor, userId) { 182 return invokeRoute(terminateAllRoute, { 183 url: listPath(userId), 184 bearer: actor.bearer, 185 params: { userId }, 186 }); 187 } 188 189 function terminateRequest(actor, userId, publicId) { 190 return invokeRoute(terminateRoute, { 191 url: `${listPath(userId)}/${publicId}`, 192 bearer: actor.bearer, 193 params: { userId, publicId }, 194 }); 195 } 196 197 async function sessionExists(systemDb, id) { 198 return Boolean( 199 await systemDb.get('SELECT id FROM sessions WHERE id = {id}', { id }) 200 ); 201 } 202 203 test('global list returns live sessions on every host newest first', async () => { 204 await withAdminApi(async (systemDb) => { 205 const { carol, sessions } = await seedFixtures(systemDb); 206 const actor = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true }); 207 208 const response = await listRequest(actor, carol); 209 assert.equal(response.status, 200); 210 assert.equal(response.headers['cache-control'], 'no-store'); 211 assert.deepEqual(response.json.page, { limit: 25, offset: 0, total: 3 }); 212 assert.deepEqual( 213 response.json.sessions.map((session) => session.user_agent), 214 ['Chrome/1.0', 'Safari/1.0', 'Firefox/1.0'] 215 ); 216 217 const first = response.json.sessions[0]; 218 assert.equal(first.public_id, sessions.chrome.session.public_id); 219 assert.deepEqual(first.scope, { 220 type: 'client', 221 host: 'app.acme.localhost', 222 client_id: 'internal-app', 223 }); 224 assert.equal(first.user.id, carol); 225 assert.equal(first.user.username, 'carol'); 226 assert.equal(first.ip, '10.1.0.3'); 227 assert.equal(first.revoked_at, null); 228 assert.equal(first.revoked_by, null); 229 assert.equal(first.can_terminate, true); 230 }); 231 }); 232 233 test('global list pages results with limit and offset while total stays unpaginated', async () => { 234 await withAdminApi(async (systemDb) => { 235 const { carol, sessions } = await seedFixtures(systemDb); 236 const actor = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true }); 237 238 const second = await listRequest(actor, carol, 'limit=1&offset=1'); 239 assert.equal(second.status, 200); 240 assert.deepEqual(second.json.page, { limit: 1, offset: 1, total: 3 }); 241 assert.deepEqual( 242 second.json.sessions.map((session) => session.public_id), 243 [sessions.safari.session.public_id] 244 ); 245 246 const past = await listRequest(actor, carol, 'limit=1&offset=3'); 247 assert.deepEqual(past.json.sessions, []); 248 assert.deepEqual(past.json.page, { limit: 1, offset: 3, total: 3 }); 249 }); 250 }); 251 252 test('global list filters sessions across the whitelisted columns', async () => { 253 await withAdminApi(async (systemDb) => { 254 const { carol, sessions } = await seedFixtures(systemDb); 255 const actor = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true }); 256 257 const byAgent = await listRequest(actor, carol, 'q=chrome'); 258 assert.deepEqual(byAgent.json.page, { limit: 25, offset: 0, total: 1 }); 259 assert.equal(byAgent.json.sessions[0].public_id, sessions.chrome.session.public_id); 260 261 const byHost = await listRequest(actor, carol, 'q=globex.localhost'); 262 assert.equal(byHost.json.sessions[0].public_id, sessions.safari.session.public_id); 263 264 const byIp = await listRequest(actor, carol, 'q=10.1.0.1'); 265 assert.equal(byIp.json.sessions[0].public_id, sessions.firefox.session.public_id); 266 267 const byClient = await listRequest(actor, carol, 'q=internal-app'); 268 assert.equal(byClient.json.page.total, 1); 269 270 const byType = await listRequest(actor, carol, 'q=global'); 271 assert.equal(byType.json.page.total, 1); 272 273 const miss = await listRequest(actor, carol, 'q=zzzz'); 274 assert.deepEqual(miss.json.sessions, []); 275 assert.equal(miss.json.page.total, 0); 276 }); 277 }); 278 279 test('global routes reject a realm admin without system privileges', async () => { 280 await withAdminApi(async (systemDb) => { 281 const { acme, carol, sessions } = await seedFixtures(systemDb); 282 const actor = await makeRealmAdmin(systemDb, acme, 'acme-admin'); 283 284 const forbiddenList = await listRequest(actor, carol); 285 assert.equal(forbiddenList.status, 403); 286 assert.equal(forbiddenList.json.error.code, 'forbidden'); 287 288 const forbiddenAll = await terminateAllRequest(actor, carol); 289 assert.equal(forbiddenAll.status, 403); 290 assert.equal(forbiddenAll.json.error.code, 'forbidden'); 291 292 const forbiddenOne = await terminateRequest( 293 actor, 294 carol, 295 sessions.firefox.session.public_id 296 ); 297 assert.equal(forbiddenOne.status, 403); 298 assert.equal(forbiddenOne.json.error.code, 'forbidden'); 299 300 assert.ok(await sessionExists(systemDb, sessions.firefox.session.id)); 301 }); 302 }); 303 304 test('global routes return 404 for an unknown user id', async () => { 305 await withAdminApi(async (systemDb) => { 306 const actor = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true }); 307 const unknownUser = crypto.randomUUID(); 308 309 const missingList = await listRequest(actor, unknownUser); 310 assert.equal(missingList.status, 404); 311 assert.equal(missingList.json.error.code, 'user_not_found'); 312 313 const missingAll = await terminateAllRequest(actor, unknownUser); 314 assert.equal(missingAll.status, 404); 315 assert.equal(missingAll.json.error.code, 'user_not_found'); 316 }); 317 }); 318 319 test('global terminate-all destroys sessions on every host including expired rows', async () => { 320 await withAdminApi(async (systemDb) => { 321 const { carol, expired, bobSession, sessions } = await seedFixtures(systemDb); 322 const actor = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true }); 323 324 const response = await terminateAllRequest(actor, carol); 325 assert.equal(response.status, 200); 326 assert.deepEqual(response.json, { ok: true, destroyed: 4 }); 327 assert.equal(response.headers['cache-control'], 'no-store'); 328 329 assert.equal( 330 (await systemDb.get('SELECT COUNT(*) AS count FROM sessions WHERE user_id = {userId}', { 331 userId: carol, 332 })).count, 333 0 334 ); 335 for (const { group } of [sessions.firefox, sessions.safari, sessions.chrome, expired]) { 336 assert.equal( 337 await systemDb.get('SELECT id FROM session_groups WHERE id = {id}', { id: group.id }), 338 undefined 339 ); 340 } 341 assert.ok(await sessionExists(systemDb, bobSession.session.id)); 342 343 const again = await terminateAllRequest(actor, carol); 344 assert.deepEqual(again.json, { ok: true, destroyed: 0 }); 345 }); 346 }); 347 348 test('global terminate removes one session by public id and drops its group', async () => { 349 await withAdminApi(async (systemDb) => { 350 const { carol, expired, sessions } = await seedFixtures(systemDb); 351 const actor = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true }); 352 353 const firefoxId = sessions.firefox.session.public_id; 354 const response = await terminateRequest(actor, carol, firefoxId); 355 assert.equal(response.status, 200); 356 assert.deepEqual(response.json, { ok: true }); 357 assert.equal(response.headers['cache-control'], 'no-store'); 358 359 assert.ok(!(await sessionExists(systemDb, sessions.firefox.session.id))); 360 assert.equal( 361 await systemDb.get('SELECT id FROM session_groups WHERE id = {id}', { 362 id: sessions.firefox.group.id, 363 }), 364 undefined 365 ); 366 assert.ok(await sessionExists(systemDb, sessions.chrome.session.id)); 367 368 // Stale expired rows stay terminable by public id. 369 const stale = await terminateRequest(actor, carol, expired.session.public_id); 370 assert.equal(stale.status, 200); 371 assert.ok(!(await sessionExists(systemDb, expired.session.id))); 372 373 const again = await terminateRequest(actor, carol, firefoxId); 374 assert.equal(again.status, 404); 375 assert.equal(again.json.error.code, 'session_not_found'); 376 }); 377 }); 378 379 test('global terminate returns 404 for a public id owned by another user', async () => { 380 await withAdminApi(async (systemDb) => { 381 const { carol, bobSession } = await seedFixtures(systemDb); 382 const actor = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true }); 383 384 const response = await terminateRequest( 385 actor, 386 carol, 387 bobSession.session.public_id 388 ); 389 assert.equal(response.status, 404); 390 assert.equal(response.json.error.code, 'session_not_found'); 391 assert.ok(await sessionExists(systemDb, bobSession.session.id)); 392 }); 393 });