auth

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

user-sessions.test.js (15604B)


      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/list.js';
     23 import terminateAllRoute from '../src/controller/admin/user-sessions/terminate-all.js';
     24 
     25 const PUBLIC_HOST = 'identity.test';
     26 const PUBLIC_URL = `http://${PUBLIC_HOST}`;
     27 
     28 Object.assign(app, { HttpError, HttpOk, HttpResponse });
     29 app.config = { server: { public_url: PUBLIC_URL } };
     30 
     31 async function withAdminApi(fn) {
     32   const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'auth-user-sessions-'));
     33   try {
     34     await initRealms({
     35       database: {
     36         dialect: 'sqlite',
     37         path: path.join(dir, 'system.sqlite'),
     38         realms: path.join(dir, 'realms'),
     39       },
     40     });
     41     await fn(getSystemDatabase());
     42   } finally {
     43     await closeRealms();
     44     await fs.rm(dir, { recursive: true, force: true });
     45   }
     46 }
     47 
     48 async function invokeRoute(route, { url, bearer, params }) {
     49   const req = {
     50     method: route.method,
     51     url,
     52     params,
     53     headers: { host: PUBLIC_HOST, authorization: `Bearer ${bearer}` },
     54   };
     55   try {
     56     const response = await route.handler(req);
     57     return { status: response.status, headers: response.headers, json: response.body };
     58   } catch (error) {
     59     if (error instanceof HttpError) {
     60       return { status: error.status, json: error.toResponse().body };
     61     }
     62     throw error;
     63   }
     64 }
     65 
     66 async function issueAdminBearer(systemDb, userId) {
     67   const { session } = await createHostSession(systemDb, {
     68     context: { mode: 'canonical', host: PUBLIC_HOST },
     69     userId,
     70     ttl: 3600,
     71   });
     72   return signToken(
     73     systemDb,
     74     { sub: userId, client_id: 'admin', scope: 'openid', roles: [], sid: session.id },
     75     {
     76       issuer: systemIssuer(PUBLIC_URL),
     77       audience: 'admin',
     78       expiresIn: 3600,
     79       table: 'system_signing_keys',
     80     }
     81   );
     82 }
     83 
     84 async function makeActor(systemDb, { username, isSystemAdmin = false }) {
     85   const id = await createUser(systemDb, { username, isSystemAdmin });
     86   return { id, bearer: await issueAdminBearer(systemDb, id) };
     87 }
     88 
     89 async function makeRealmAdmin(systemDb, realm, username) {
     90   const actor = await makeActor(systemDb, { username });
     91   const realmDb = await openRealmDatabase(realm);
     92   await ensureMembership(realmDb, actor.id, 'active');
     93   await realmDb.run(
     94     `INSERT INTO membership_roles (user_id, role_id)
     95      SELECT {userId}, id FROM roles WHERE slug = 'realm-admin'`,
     96     { userId: actor.id }
     97   );
     98   return actor;
     99 }
    100 
    101 async function seedListFixtures(systemDb) {
    102   const acme = await createRealm({ slug: 'acme', displayName: 'Acme' });
    103   const globex = await createRealm({ slug: 'globex', displayName: 'Globex' });
    104   const alice = await createUser(systemDb, {
    105     username: 'alice',
    106     displayName: 'Alice',
    107     homeRealmId: acme.id,
    108   });
    109   const bob = await createUser(systemDb, { username: 'bob', homeRealmId: globex.id });
    110 
    111   const base = Date.now();
    112   const firefox = await createHostSession(
    113     systemDb,
    114     {
    115       context: { mode: 'canonical', host: PUBLIC_HOST },
    116       userId: alice,
    117       ttl: 3600,
    118       userAgent: 'Firefox/1.0',
    119       ip: '10.0.0.1',
    120     },
    121     base + 1000
    122   );
    123   const safari = await createHostSession(
    124     systemDb,
    125     {
    126       context: { mode: 'realm', host: 'globex.localhost', realm: globex },
    127       userId: alice,
    128       ttl: 3600,
    129       userAgent: 'Safari/1.0',
    130       ip: '10.0.0.2',
    131     },
    132     base + 2000
    133   );
    134   const chrome = await createHostSession(
    135     systemDb,
    136     {
    137       context: { mode: 'client', host: 'app.acme.localhost', realm: acme, clientId: 'internal-app' },
    138       userId: alice,
    139       ttl: 3600,
    140       userAgent: 'Chrome/1.0',
    141       ip: '10.0.0.3',
    142     },
    143     base + 3000
    144   );
    145   await createHostSession(
    146     systemDb,
    147     {
    148       context: { mode: 'realm', host: 'acme.localhost', realm: acme },
    149       userId: alice,
    150       ttl: 3600,
    151       userAgent: 'Edge/1.0',
    152     },
    153     base - 7_200_000
    154   );
    155   await createHostSession(systemDb, {
    156     context: { mode: 'realm', host: 'acme.localhost', realm: acme },
    157     userId: bob,
    158     ttl: 3600,
    159     userAgent: 'Wget/1.0',
    160   });
    161 
    162   return { acme, globex, alice, sessions: { firefox, safari, chrome } };
    163 }
    164 
    165 function listPath(realmSlug, userId, query = '') {
    166   const base = `/api/v1/admin/realms/${realmSlug}/users/${userId}/sessions`;
    167   return query ? `${base}?${query}` : base;
    168 }
    169 
    170 function listRequest(actor, realmSlug, userId, query) {
    171   return invokeRoute(listRoute, {
    172     url: listPath(realmSlug, userId, query),
    173     bearer: actor.bearer,
    174     params: { realm: realmSlug, userId },
    175   });
    176 }
    177 
    178 test('list returns live sessions on every host newest first', async () => {
    179   await withAdminApi(async (systemDb) => {
    180     const { acme, alice, sessions } = await seedListFixtures(systemDb);
    181     const actor = await makeRealmAdmin(systemDb, acme, 'acme-admin');
    182 
    183     const response = await listRequest(actor, 'acme', alice);
    184     assert.equal(response.status, 200);
    185     assert.equal(response.headers['cache-control'], 'no-store');
    186     assert.deepEqual(response.json.page, { limit: 25, offset: 0, total: 3 });
    187     assert.deepEqual(
    188       response.json.sessions.map((session) => session.user_agent),
    189       ['Chrome/1.0', 'Safari/1.0', 'Firefox/1.0']
    190     );
    191 
    192     const first = response.json.sessions[0];
    193     assert.equal(first.public_id, sessions.chrome.session.public_id);
    194     assert.deepEqual(first.scope, {
    195       type: 'client',
    196       host: 'app.acme.localhost',
    197       client_id: 'internal-app',
    198     });
    199     assert.equal(first.user.id, alice);
    200     assert.equal(first.user.username, 'alice');
    201     assert.equal(first.ip, '10.0.0.3');
    202     assert.equal(first.revoked_at, null);
    203     assert.equal(first.can_terminate, true);
    204   });
    205 });
    206 
    207 test('list pages results with limit and offset while total stays unpaginated', async () => {
    208   await withAdminApi(async (systemDb) => {
    209     const { acme, alice, sessions } = await seedListFixtures(systemDb);
    210     const actor = await makeRealmAdmin(systemDb, acme, 'acme-admin');
    211 
    212     const second = await listRequest(actor, 'acme', alice, 'limit=1&offset=1');
    213     assert.equal(second.status, 200);
    214     assert.deepEqual(second.json.page, { limit: 1, offset: 1, total: 3 });
    215     assert.deepEqual(
    216       second.json.sessions.map((session) => session.public_id),
    217       [sessions.safari.session.public_id]
    218     );
    219 
    220     const past = await listRequest(actor, 'acme', alice, 'limit=1&offset=3');
    221     assert.deepEqual(past.json.sessions, []);
    222     assert.deepEqual(past.json.page, { limit: 1, offset: 3, total: 3 });
    223   });
    224 });
    225 
    226 test('list filters sessions case-insensitively across the whitelisted columns', async () => {
    227   await withAdminApi(async (systemDb) => {
    228     const { acme, alice, sessions } = await seedListFixtures(systemDb);
    229     const actor = await makeRealmAdmin(systemDb, acme, 'acme-admin');
    230 
    231     const byAgent = await listRequest(actor, 'acme', alice, 'q=chrome');
    232     assert.deepEqual(byAgent.json.page, { limit: 25, offset: 0, total: 1 });
    233     assert.deepEqual(
    234       byAgent.json.sessions.map((session) => session.public_id),
    235       [sessions.chrome.session.public_id]
    236     );
    237 
    238     const byHost = await listRequest(actor, 'acme', alice, 'q=globex.localhost');
    239     assert.equal(byHost.json.page.total, 1);
    240     assert.equal(byHost.json.sessions[0].public_id, sessions.safari.session.public_id);
    241 
    242     const byIp = await listRequest(actor, 'acme', alice, 'q=10.0.0.1');
    243     assert.equal(byIp.json.sessions[0].public_id, sessions.firefox.session.public_id);
    244 
    245     const byClient = await listRequest(actor, 'acme', alice, 'q=internal-app');
    246     assert.equal(byClient.json.page.total, 1);
    247 
    248     const byType = await listRequest(actor, 'acme', alice, 'q=global');
    249     assert.equal(byType.json.page.total, 1);
    250     assert.equal(byType.json.sessions[0].public_id, sessions.firefox.session.public_id);
    251 
    252     const miss = await listRequest(actor, 'acme', alice, 'q=zzzz');
    253     assert.deepEqual(miss.json.sessions, []);
    254     assert.equal(miss.json.page.total, 0);
    255   });
    256 });
    257 
    258 test('list rejects invalid pagination and search parameters', async () => {
    259   await withAdminApi(async (systemDb) => {
    260     const { acme, alice } = await seedListFixtures(systemDb);
    261     const actor = await makeRealmAdmin(systemDb, acme, 'acme-admin');
    262 
    263     const invalidQueries = [
    264       'limit=0',
    265       'limit=-5',
    266       'limit=1.5',
    267       'limit=abc',
    268       'offset=-1',
    269       'offset=abc',
    270       `q=${'x'.repeat(129)}`,
    271     ];
    272     for (const query of invalidQueries) {
    273       const response = await listRequest(actor, 'acme', alice, query);
    274       assert.equal(response.status, 400, `expected 400 for ${query}`);
    275       assert.equal(response.json.error.code, 'invalid_request');
    276     }
    277   });
    278 });
    279 
    280 test('list returns 404 for an unknown user id', async () => {
    281   await withAdminApi(async (systemDb) => {
    282     const acme = await createRealm({ slug: 'acme', displayName: 'Acme' });
    283     const actor = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true });
    284 
    285     const response = await listRequest(actor, 'acme', crypto.randomUUID());
    286     assert.equal(response.status, 404);
    287     assert.equal(response.json.error.code, 'user_not_found');
    288   });
    289 });
    290 
    291 test('list returns 403 for a realm admin outside the user home realm', async () => {
    292   await withAdminApi(async (systemDb) => {
    293     const { globex, alice } = await seedListFixtures(systemDb);
    294     const actor = await makeRealmAdmin(systemDb, globex, 'globex-admin');
    295 
    296     const response = await listRequest(actor, 'globex', alice);
    297     assert.equal(response.status, 403);
    298     assert.equal(response.json.error.code, 'forbidden');
    299   });
    300 });
    301 
    302 test('a system admin can list user sessions from any realm', async () => {
    303   await withAdminApi(async (systemDb) => {
    304     const { alice } = await seedListFixtures(systemDb);
    305     const actor = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true });
    306 
    307     const response = await listRequest(actor, 'globex', alice);
    308     assert.equal(response.status, 200);
    309     assert.equal(response.json.page.total, 3);
    310     assert.equal(response.json.sessions[0].can_terminate, true);
    311   });
    312 });
    313 
    314 test('terminate-all destroys sessions on every host including expired rows', async () => {
    315   await withAdminApi(async (systemDb) => {
    316     const acme = await createRealm({ slug: 'acme', displayName: 'Acme' });
    317     const alice = await createUser(systemDb, { username: 'alice', homeRealmId: acme.id });
    318     const bob = await createUser(systemDb, { username: 'bob' });
    319     const actor = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true });
    320     const canonical = { mode: 'canonical', host: PUBLIC_HOST };
    321 
    322     const shared = await createHostSession(systemDb, { context: canonical, userId: alice, ttl: 3600 });
    323     const bobShared = await createHostSession(systemDb, {
    324       context: canonical,
    325       token: shared.token,
    326       userId: bob,
    327       ttl: 3600,
    328     });
    329     await createHostSession(systemDb, {
    330       context: canonical,
    331       token: shared.token,
    332       userId: alice,
    333       ttl: 3600,
    334     });
    335     const realmSession = await createHostSession(systemDb, {
    336       context: { mode: 'realm', host: 'acme.localhost', realm: acme },
    337       userId: alice,
    338       ttl: 3600,
    339     });
    340     const expired = await createHostSession(
    341       systemDb,
    342       {
    343         context: { mode: 'client', host: 'app.acme.localhost', realm: acme, clientId: 'internal-app' },
    344         userId: alice,
    345         ttl: 3600,
    346       },
    347       Date.now() - 7_200_000
    348     );
    349 
    350     const response = await invokeRoute(terminateAllRoute, {
    351       url: listPath('acme', alice),
    352       bearer: actor.bearer,
    353       params: { realm: 'acme', userId: alice },
    354     });
    355     assert.equal(response.status, 200);
    356     assert.deepEqual(response.json, { ok: true, destroyed: 3 });
    357     assert.equal(response.headers['cache-control'], 'no-store');
    358 
    359     assert.equal(
    360       (await systemDb.get('SELECT COUNT(*) AS count FROM sessions WHERE user_id = {userId}', {
    361         userId: alice,
    362       })).count,
    363       0
    364     );
    365     assert.ok(await systemDb.get('SELECT id FROM sessions WHERE id = {id}', {
    366       id: bobShared.session.id,
    367     }));
    368     assert.equal(
    369       await systemDb.get('SELECT id FROM session_groups WHERE id = {id}', {
    370         id: realmSession.group.id,
    371       }),
    372       undefined
    373     );
    374     assert.equal(
    375       await systemDb.get('SELECT id FROM session_groups WHERE id = {id}', {
    376         id: expired.group.id,
    377       }),
    378       undefined
    379     );
    380 
    381     const repaired = await systemDb.get(
    382       'SELECT active_session_id FROM session_groups WHERE id = {id}',
    383       { id: shared.group.id }
    384     );
    385     assert.equal(repaired.active_session_id, bobShared.session.id);
    386   });
    387 });
    388 
    389 test('re-terminating a user with no sessions destroys nothing', async () => {
    390   await withAdminApi(async (systemDb) => {
    391     const acme = await createRealm({ slug: 'acme', displayName: 'Acme' });
    392     const alice = await createUser(systemDb, { username: 'alice', homeRealmId: acme.id });
    393     const actor = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true });
    394 
    395     await createHostSession(systemDb, {
    396       context: { mode: 'canonical', host: PUBLIC_HOST },
    397       userId: alice,
    398       ttl: 3600,
    399     });
    400 
    401     const first = await invokeRoute(terminateAllRoute, {
    402       url: listPath('acme', alice),
    403       bearer: actor.bearer,
    404       params: { realm: 'acme', userId: alice },
    405     });
    406     assert.deepEqual(first.json, { ok: true, destroyed: 1 });
    407 
    408     const second = await invokeRoute(terminateAllRoute, {
    409       url: listPath('acme', alice),
    410       bearer: actor.bearer,
    411       params: { realm: 'acme', userId: alice },
    412     });
    413     assert.deepEqual(second.json, { ok: true, destroyed: 0 });
    414   });
    415 });
    416 
    417 test('terminate-all enforces user level authorization', async () => {
    418   await withAdminApi(async (systemDb) => {
    419     const { acme, globex, alice } = await seedListFixtures(systemDb);
    420     const outside = await makeRealmAdmin(systemDb, globex, 'globex-admin');
    421     const sysadmin = await makeActor(systemDb, { username: 'sysadmin', isSystemAdmin: true });
    422 
    423     const forbidden = await invokeRoute(terminateAllRoute, {
    424       url: listPath('globex', alice),
    425       bearer: outside.bearer,
    426       params: { realm: 'globex', userId: alice },
    427     });
    428     assert.equal(forbidden.status, 403);
    429     assert.equal(forbidden.json.error.code, 'forbidden');
    430 
    431     const unknownUser = crypto.randomUUID();
    432     const missing = await invokeRoute(terminateAllRoute, {
    433       url: listPath('acme', unknownUser),
    434       bearer: sysadmin.bearer,
    435       params: { realm: 'acme', userId: unknownUser },
    436     });
    437     assert.equal(missing.status, 404);
    438     assert.equal(missing.json.error.code, 'user_not_found');
    439 
    440     const homeAdmin = await makeRealmAdmin(systemDb, acme, 'acme-admin');
    441     const allowed = await invokeRoute(terminateAllRoute, {
    442       url: listPath('acme', alice),
    443       bearer: homeAdmin.bearer,
    444       params: { realm: 'acme', userId: alice },
    445     });
    446     assert.equal(allowed.status, 200);
    447     assert.deepEqual(allowed.json, { ok: true, destroyed: 4 });
    448   });
    449 });