auth

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

session.test.js (12117B)


      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 { closeRealms } from '../src/lib/realm.js';
      6 import {
      7   SESSION_COOKIE,
      8   SHORT_SESSION_TTL,
      9   authenticateRequest,
     10   createHostSession,
     11   destroySession,
     12   getSessionByToken,
     13   listSessionAccounts,
     14   selectSessionAccount,
     15 } from '../src/lib/session.js';
     16 import { createUser } from '../src/lib/users.js';
     17 import {
     18   canonicalContext,
     19   clientContext,
     20   mockRequest,
     21   mockResponse,
     22   realmContext,
     23   setup,
     24 } from './helpers/session-harness.js';
     25 
     26 test('sessions store only the group token hash and authenticate the user', async () => {
     27   const { dir, realm, realmDb, systemDb, userId } = await setup();
     28   try {
     29     const context = realmContext(realm);
     30     const { token, group, session } = await createHostSession(systemDb, {
     31       context,
     32       userId,
     33       ttl: SHORT_SESSION_TTL,
     34       userAgent: 'test',
     35       ip: '127.0.0.1',
     36     });
     37     const id = crypto.createHash('sha256').update(token).digest('hex');
     38 
     39     assert.equal(group.id, id);
     40     assert.notEqual(session.public_id, token);
     41 
     42     const found = await getSessionByToken(systemDb, token);
     43     assert.equal(found.session.id, session.id);
     44 
     45     const req = mockRequest(`${SESSION_COOKIE}=${token}`);
     46     const res = mockResponse();
     47     const auth = await authenticateRequest({
     48       systemDb,
     49       realmDb,
     50       req,
     51       res,
     52       context,
     53     });
     54     assert.equal(auth.user.id, userId);
     55     assert.equal(auth.membership.status, 'active');
     56   } finally {
     57     await closeRealms();
     58     await fs.rm(dir, { recursive: true, force: true });
     59   }
     60 });
     61 
     62 test('host scopes are stored from the request context', async () => {
     63   const { dir, realm, systemDb, userId } = await setup();
     64   try {
     65     const global = await createHostSession(systemDb, {
     66       context: canonicalContext(),
     67       userId,
     68       ttl: SHORT_SESSION_TTL,
     69     });
     70     assert.equal(global.session.scope_type, 'global');
     71     assert.equal(global.session.scope_host, 'identity.test');
     72     assert.equal(global.session.realm_id, null);
     73 
     74     const client = await createHostSession(systemDb, {
     75       context: clientContext(realm),
     76       userId,
     77       ttl: SHORT_SESSION_TTL,
     78     });
     79     assert.equal(client.session.scope_type, 'client');
     80     assert.equal(client.session.scope_host, 'app.acme.localhost');
     81     assert.equal(client.session.realm_id, realm.id);
     82     assert.equal(client.session.client_id, 'internal-app');
     83   } finally {
     84     await closeRealms();
     85     await fs.rm(dir, { recursive: true, force: true });
     86   }
     87 });
     88 
     89 test('sliding sessions extend expiry and reissue the cookie', async () => {
     90   const { dir, realm, realmDb, systemDb, userId } = await setup();
     91   try {
     92     const context = realmContext(realm);
     93     const { token, session } = await createHostSession(
     94       systemDb,
     95       { context, userId, ttl: SHORT_SESSION_TTL },
     96       1000
     97     );
     98     const req = mockRequest(`${SESSION_COOKIE}=${token}`);
     99     const res = mockResponse();
    100 
    101     await authenticateRequest({
    102       systemDb,
    103       realmDb,
    104       req,
    105       res,
    106       context,
    107       now: 1000 + 61_000,
    108     });
    109 
    110     const updated = await systemDb.get(
    111       'SELECT expires_at, last_seen_at FROM sessions WHERE id = {id}',
    112       { id: session.id }
    113     );
    114     assert.equal(updated.expires_at, 1000 + 61_000 + SHORT_SESSION_TTL * 1000);
    115     assert.ok(res.getHeader('set-cookie'));
    116   } finally {
    117     await closeRealms();
    118     await fs.rm(dir, { recursive: true, force: true });
    119   }
    120 });
    121 
    122 test('expired sessions are rejected and their group is removed', async () => {
    123   const { dir, realm, realmDb, systemDb, userId } = await setup();
    124   try {
    125     const context = realmContext(realm);
    126     const { token, group } = await createHostSession(
    127       systemDb,
    128       { context, userId, ttl: 1 },
    129       1000
    130     );
    131 
    132     assert.equal(await getSessionByToken(systemDb, token, 3000), null);
    133     await authenticateRequest({
    134       systemDb,
    135       realmDb,
    136       req: mockRequest(`${SESSION_COOKIE}=${token}`),
    137       res: mockResponse(),
    138       context,
    139       now: 3000,
    140     });
    141     const row = await systemDb.get('SELECT id FROM session_groups WHERE id = {id}', {
    142       id: group.id,
    143     });
    144     assert.equal(row, undefined);
    145   } finally {
    146     await closeRealms();
    147     await fs.rm(dir, { recursive: true, force: true });
    148   }
    149 });
    150 
    151 test('disabled users lose access and their session group is removed', async () => {
    152   const { dir, realm, realmDb, systemDb, userId } = await setup();
    153   try {
    154     const context = realmContext(realm);
    155     const { token, group } = await createHostSession(systemDb, {
    156       context,
    157       userId,
    158       ttl: SHORT_SESSION_TTL,
    159     });
    160 
    161     await systemDb.run('UPDATE users SET status = {status} WHERE id = {id}', {
    162       status: 'disabled',
    163       id: userId,
    164     });
    165     assert.equal(
    166       await authenticateRequest({
    167         systemDb,
    168         realmDb,
    169         req: mockRequest(`${SESSION_COOKIE}=${token}`),
    170         res: mockResponse(),
    171         context,
    172       }),
    173       null
    174     );
    175 
    176     const row = await systemDb.get('SELECT id FROM session_groups WHERE id = {id}', {
    177       id: group.id,
    178     });
    179     assert.equal(row, undefined);
    180   } finally {
    181     await closeRealms();
    182     await fs.rm(dir, { recursive: true, force: true });
    183   }
    184 });
    185 
    186 test('disabling the active account keeps other accounts in the group', async () => {
    187   const { dir, realm, systemDb, userId } = await setup();
    188   try {
    189     const context = realmContext(realm);
    190     const first = await createHostSession(systemDb, {
    191       context,
    192       userId,
    193       ttl: SHORT_SESSION_TTL,
    194     });
    195     const otherId = await createUser(systemDb, { username: 'bob', displayName: 'Bob' });
    196     const second = await createHostSession(systemDb, {
    197       context,
    198       token: first.token,
    199       userId: otherId,
    200       ttl: SHORT_SESSION_TTL,
    201     });
    202 
    203     await systemDb.run('UPDATE users SET status = {status} WHERE id = {id}', {
    204       status: 'disabled',
    205       id: otherId,
    206     });
    207 
    208     const res = mockResponse();
    209     assert.equal(
    210       await authenticateRequest({
    211         systemDb,
    212         realmDb: null,
    213         req: mockRequest(`${SESSION_COOKIE}=${first.token}`),
    214         res,
    215         context,
    216       }),
    217       null
    218     );
    219 
    220     const found = await getSessionByToken(systemDb, first.token);
    221     assert.equal(found.session.user_id, userId);
    222 
    223     const accounts = await listSessionAccounts(systemDb, second.group);
    224     assert.equal(accounts.length, 1);
    225     assert.equal(accounts[0].user.id, userId);
    226   } finally {
    227     await closeRealms();
    228     await fs.rm(dir, { recursive: true, force: true });
    229   }
    230 });
    231 
    232 test('a session is rejected on a different host scope', async () => {
    233   const { dir, realm, realmDb, systemDb, userId } = await setup();
    234   try {
    235     const context = realmContext(realm);
    236     const { token, group } = await createHostSession(systemDb, {
    237       context,
    238       userId,
    239       ttl: SHORT_SESSION_TTL,
    240     });
    241 
    242     assert.equal(
    243       await authenticateRequest({
    244         systemDb,
    245         realmDb,
    246         req: mockRequest(`${SESSION_COOKIE}=${token}`),
    247         res: mockResponse(),
    248         context: clientContext(realm),
    249       }),
    250       null
    251     );
    252 
    253     const row = await systemDb.get('SELECT id FROM session_groups WHERE id = {id}', {
    254       id: group.id,
    255     });
    256     assert.equal(row.id, group.id);
    257   } finally {
    258     await closeRealms();
    259     await fs.rm(dir, { recursive: true, force: true });
    260   }
    261 });
    262 
    263 test('the same user reuses a session and a different user adds an account', async () => {
    264   const { dir, realm, systemDb, userId } = await setup();
    265   try {
    266     const context = realmContext(realm);
    267     const first = await createHostSession(systemDb, {
    268       context,
    269       userId,
    270       ttl: SHORT_SESSION_TTL,
    271     });
    272     const second = await createHostSession(systemDb, {
    273       context,
    274       token: first.token,
    275       userId,
    276       ttl: SHORT_SESSION_TTL,
    277     });
    278     assert.equal(second.group.id, first.group.id);
    279     assert.equal(second.token, first.token);
    280     assert.equal(second.session.id, first.session.id);
    281 
    282     const otherId = await createUser(systemDb, { username: 'bob', displayName: 'Bob' });
    283     const third = await createHostSession(systemDb, {
    284       context,
    285       token: first.token,
    286       userId: otherId,
    287       ttl: SHORT_SESSION_TTL,
    288     });
    289     assert.equal(third.group.id, first.group.id);
    290     assert.equal(third.token, first.token);
    291     assert.equal(third.session.user_id, otherId);
    292 
    293     const old = await systemDb.get('SELECT id FROM sessions WHERE id = {id}', {
    294       id: first.session.id,
    295     });
    296     assert.equal(old.id, first.session.id);
    297 
    298     const accounts = await listSessionAccounts(systemDb, third.group);
    299     assert.deepEqual(
    300       accounts.map((account) => account.user.username),
    301       ['alice', 'bob']
    302     );
    303     assert.equal(accounts.find((account) => account.user.id === otherId).active, true);
    304   } finally {
    305     await closeRealms();
    306     await fs.rm(dir, { recursive: true, force: true });
    307   }
    308 });
    309 
    310 test('selecting an account updates the active session', async () => {
    311   const { dir, realm, systemDb, userId } = await setup();
    312   try {
    313     const context = realmContext(realm);
    314     const first = await createHostSession(systemDb, {
    315       context,
    316       userId,
    317       ttl: SHORT_SESSION_TTL,
    318     });
    319     const otherId = await createUser(systemDb, { username: 'bob', displayName: 'Bob' });
    320     const second = await createHostSession(systemDb, {
    321       context,
    322       token: first.token,
    323       userId: otherId,
    324       ttl: SHORT_SESSION_TTL,
    325     });
    326 
    327     const selected = await selectSessionAccount(systemDb, {
    328       token: first.token,
    329       context,
    330       publicId: first.session.public_id,
    331     });
    332     assert.equal(selected.user.id, userId);
    333     assert.equal(selected.session.id, first.session.id);
    334 
    335     const found = await getSessionByToken(systemDb, first.token);
    336     assert.equal(found.session.id, first.session.id);
    337 
    338     const rejectedHost = await selectSessionAccount(systemDb, {
    339       token: first.token,
    340       context: clientContext(realm),
    341       publicId: second.session.public_id,
    342     });
    343     assert.equal(rejectedHost, null);
    344 
    345     const rejectedAccount = await selectSessionAccount(systemDb, {
    346       token: first.token,
    347       context,
    348       publicId: 'missing',
    349     });
    350     assert.equal(rejectedAccount, null);
    351   } finally {
    352     await closeRealms();
    353     await fs.rm(dir, { recursive: true, force: true });
    354   }
    355 });
    356 
    357 test('logout deletes the active session and group', async () => {
    358   const { dir, realm, systemDb, userId } = await setup();
    359   try {
    360     const { token, group } = await createHostSession(systemDb, {
    361       context: realmContext(realm),
    362       userId,
    363       ttl: SHORT_SESSION_TTL,
    364     });
    365 
    366     const result = await destroySession(systemDb, token);
    367     assert.equal(result.groupDeleted, true);
    368     assert.equal(await getSessionByToken(systemDb, token), null);
    369 
    370     const row = await systemDb.get('SELECT id FROM session_groups WHERE id = {id}', {
    371       id: group.id,
    372     });
    373     assert.equal(row, undefined);
    374   } finally {
    375     await closeRealms();
    376     await fs.rm(dir, { recursive: true, force: true });
    377   }
    378 });
    379 
    380 test('logout keeps the group when another account remains', async () => {
    381   const { dir, realm, systemDb, userId } = await setup();
    382   try {
    383     const context = realmContext(realm);
    384     const first = await createHostSession(systemDb, {
    385       context,
    386       userId,
    387       ttl: SHORT_SESSION_TTL,
    388     });
    389     const otherId = await createUser(systemDb, { username: 'bob', displayName: 'Bob' });
    390     const second = await createHostSession(systemDb, {
    391       context,
    392       token: first.token,
    393       userId: otherId,
    394       ttl: SHORT_SESSION_TTL,
    395     });
    396 
    397     const result = await destroySession(systemDb, first.token);
    398     assert.equal(result.groupDeleted, false);
    399 
    400     const found = await getSessionByToken(systemDb, first.token);
    401     assert.equal(found.session.id, first.session.id);
    402 
    403     const accounts = await listSessionAccounts(systemDb, second.group);
    404     assert.equal(accounts.length, 1);
    405     assert.equal(accounts[0].user.id, userId);
    406   } finally {
    407     await closeRealms();
    408     await fs.rm(dir, { recursive: true, force: true });
    409   }
    410 });