auth

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

http-harness.js (20765B)


      1 import assert from 'node:assert/strict';
      2 import { spawn } from 'node:child_process';
      3 import crypto from 'node:crypto';
      4 import fs from 'node:fs/promises';
      5 import http from 'node:http';
      6 import net from 'node:net';
      7 import os from 'node:os';
      8 import path from 'node:path';
      9 import { DatabaseSync } from 'node:sqlite';
     10 import { fileURLToPath } from 'node:url';
     11 
     12 const serverDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
     13 
     14 function freePort() {
     15   return new Promise((resolve, reject) => {
     16     const server = net.createServer();
     17     server.once('error', reject);
     18     server.listen(0, '127.0.0.1', () => {
     19       const { port } = server.address();
     20       server.close(() => resolve(port));
     21     });
     22   });
     23 }
     24 
     25 function runNode(script, env) {
     26   return new Promise((resolve, reject) => {
     27     const child = spawn(process.execPath, [script], {
     28       cwd: serverDir,
     29       env: { ...process.env, ...env },
     30       stdio: ['ignore', 'pipe', 'pipe'],
     31     });
     32     let stdout = '';
     33     let stderr = '';
     34     child.stdout.on('data', (chunk) => {
     35       stdout += chunk;
     36     });
     37     child.stderr.on('data', (chunk) => {
     38       stderr += chunk;
     39     });
     40     child.once('error', reject);
     41     child.once('exit', (code) => {
     42       if (code === 0) resolve({ stdout, stderr });
     43       else reject(new Error(`${script} exited ${code}\n${stdout}\n${stderr}`));
     44     });
     45   });
     46 }
     47 
     48 function startServer(env) {
     49   return new Promise((resolve, reject) => {
     50     const child = spawn(process.execPath, ['src/index.js'], {
     51       cwd: serverDir,
     52       env: { ...process.env, ...env },
     53       stdio: ['ignore', 'pipe', 'pipe'],
     54     });
     55     let stdout = '';
     56     let stderr = '';
     57     child.stdout.on('data', (chunk) => {
     58       stdout += chunk;
     59     });
     60     child.stderr.on('data', (chunk) => {
     61       stderr += chunk;
     62     });
     63     child.once('error', reject);
     64     child.once('exit', (code) => {
     65       if (code !== 0 && !stdout.includes('Listening on')) {
     66         reject(new Error(`server exited ${code}\n${stdout}\n${stderr}`));
     67       }
     68     });
     69     const deadline = Date.now() + 15_000;
     70     const timer = setInterval(() => {
     71       if (stdout.includes('Listening on')) {
     72         clearInterval(timer);
     73         resolve(child);
     74         return;
     75       }
     76       if (Date.now() > deadline) {
     77         clearInterval(timer);
     78         child.kill('SIGTERM');
     79         reject(new Error(`server did not start\n${stdout}\n${stderr}`));
     80       }
     81     }, 50);
     82   });
     83 }
     84 
     85 function request(
     86   port,
     87   { method = 'GET', path: requestPath = '/', host, body, form, cookie, bearer, headers: extraHeaders = {} } = {}
     88 ) {
     89   return new Promise((resolve, reject) => {
     90     let payload = null;
     91     const headers = { host, ...extraHeaders };
     92     if (body !== undefined) {
     93       payload = JSON.stringify(body);
     94       headers['content-type'] = 'application/json';
     95       headers['content-length'] = Buffer.byteLength(payload);
     96     } else if (form !== undefined) {
     97       payload = new URLSearchParams(form).toString();
     98       headers['content-type'] = 'application/x-www-form-urlencoded';
     99       headers['content-length'] = Buffer.byteLength(payload);
    100     }
    101     if (cookie) headers.cookie = cookie;
    102     if (bearer) headers.authorization = `Bearer ${bearer}`;
    103 
    104     const req = http.request(
    105       { host: '127.0.0.1', port, method, path: requestPath, headers },
    106       (res) => {
    107         const chunks = [];
    108         res.on('data', (chunk) => chunks.push(chunk));
    109         res.on('end', () => {
    110           const text = Buffer.concat(chunks).toString('utf8');
    111           let json = null;
    112           try {
    113             json = JSON.parse(text);
    114           } catch {
    115             json = null;
    116           }
    117           resolve({ status: res.statusCode, headers: res.headers, text, json });
    118         });
    119       }
    120     );
    121     req.once('error', reject);
    122     if (payload !== null) req.write(payload);
    123     req.end();
    124   });
    125 }
    126 
    127 function responseCookies(response) {
    128   const values = response.headers['set-cookie'];
    129   return Array.isArray(values) ? values.map((value) => value.split(';')[0]) : [];
    130 }
    131 
    132 function mergeCookies(existing, response) {
    133   const jar = new Map();
    134   for (const pair of existing ? existing.split('; ') : []) {
    135     const index = pair.indexOf('=');
    136     if (index !== -1) jar.set(pair.slice(0, index), pair.slice(index + 1));
    137   }
    138   for (const pair of responseCookies(response)) {
    139     const index = pair.indexOf('=');
    140     if (index !== -1) jar.set(pair.slice(0, index), pair.slice(index + 1));
    141   }
    142   return [...jar.entries()].map(([name, value]) => `${name}=${value}`).join('; ');
    143 }
    144 
    145 function maxAge(response) {
    146   const values = response.headers['set-cookie'];
    147   if (!values || values.length === 0) return null;
    148   const match = /Max-Age=(\d+)/.exec(values[0]);
    149   return match ? Number(match[1]) : null;
    150 }
    151 
    152 function pkce() {
    153   const verifier = crypto.randomBytes(32).toString('base64url');
    154   const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
    155   return { verifier, challenge };
    156 }
    157 
    158 function locationQuery(response) {
    159   return new URL(response.headers.location, 'http://localhost');
    160 }
    161 
    162 function cookieValue(cookie, name) {
    163   const pair = cookie
    164     .split('; ')
    165     .find((value) => value.startsWith(`${name}=`));
    166   return pair ? pair.slice(name.length + 1) : null;
    167 }
    168 
    169 function withSystemDatabase(env, fn) {
    170   const database = new DatabaseSync(env.AUTH_DATABASE_PATH);
    171   try {
    172     return fn(database);
    173   } finally {
    174     database.close();
    175   }
    176 }
    177 
    178 function activeSessionId(env, cookie) {
    179   const token = cookieValue(cookie, 'auth_session');
    180   const groupId = crypto.createHash('sha256').update(token).digest('hex');
    181   return withSystemDatabase(env, (database) => {
    182     const row = database
    183       .prepare('SELECT active_session_id FROM session_groups WHERE id = ?')
    184       .get(groupId);
    185     return row.active_session_id;
    186   });
    187 }
    188 
    189 function activeSessionPublicId(env, cookie) {
    190   const token = cookieValue(cookie, 'auth_session');
    191   const groupId = crypto.createHash('sha256').update(token).digest('hex');
    192   return withSystemDatabase(env, (database) => {
    193     const row = database
    194       .prepare(
    195         `SELECT s.public_id
    196            FROM sessions s
    197            JOIN session_groups g ON g.active_session_id = s.id
    198           WHERE g.id = ?`
    199       )
    200       .get(groupId);
    201     return row.public_id;
    202   });
    203 }
    204 
    205 function sessionGroupId(env, cookie) {
    206   const token = cookieValue(cookie, 'auth_session');
    207   return crypto.createHash('sha256').update(token).digest('hex');
    208 }
    209 
    210 function sessionGroupCount(env, groupId) {
    211   return withSystemDatabase(env, (database) =>
    212     database.prepare('SELECT COUNT(*) AS count FROM session_groups WHERE id = ?').get(groupId).count
    213   );
    214 }
    215 
    216 function clearConsent(env, { username, realm, clientId }) {
    217   withSystemDatabase(env, (database) => {
    218     database
    219       .prepare(
    220         `DELETE FROM client_consents
    221           WHERE user_id = (SELECT id FROM users WHERE username = ?)
    222             AND client_id = ?
    223             AND realm_id = (SELECT id FROM realms WHERE slug = ?)`
    224       )
    225       .run(username, clientId, realm);
    226   });
    227 }
    228 
    229 function setAdminConsent(
    230   env,
    231   { username, realm, clientId, scopes = 'openid', grantedVia = 'user', revokedAt = null }
    232 ) {
    233   const now = Date.now();
    234   const targetUserId = userId(env, username);
    235   const targetRealmId = realmId(env, realm);
    236   withSystemDatabase(env, (database) => {
    237     database
    238       .prepare(
    239         `INSERT OR REPLACE INTO client_consents
    240           (user_id, realm_id, client_id, scopes, granted_via, created_at, updated_at, revoked_at)
    241          VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
    242       )
    243       .run(
    244         targetUserId,
    245         targetRealmId,
    246         clientId,
    247         scopes,
    248         grantedVia,
    249         now,
    250         revokedAt || now,
    251         revokedAt
    252       );
    253   });
    254   return revokedAt || now;
    255 }
    256 
    257 function setConsentMode(env, { realm, clientId, mode }) {
    258   withRealmDatabase(env, realm, (database) => {
    259     database
    260       .prepare('UPDATE oidc_clients SET consent_mode = ? WHERE client_id = ?')
    261       .run(mode, clientId);
    262   });
    263 }
    264 
    265 function userId(env, username) {
    266   return withSystemDatabase(env, (database) =>
    267     database.prepare('SELECT id FROM users WHERE username = ?').get(username).id
    268   );
    269 }
    270 
    271 function realmId(env, slug) {
    272   return withSystemDatabase(env, (database) =>
    273     database.prepare('SELECT id FROM realms WHERE slug = ?').get(slug).id
    274   );
    275 }
    276 
    277 function clearBans(env, { username, realm, clientId = null }) {
    278   const id = userId(env, username);
    279   withRealmDatabase(env, realm, (database) => {
    280     if (clientId) {
    281       database
    282         .prepare('DELETE FROM app_bans WHERE user_id = ? AND client_id = ?')
    283         .run(id, clientId);
    284     } else {
    285       database.prepare('DELETE FROM app_bans WHERE user_id = ?').run(id);
    286     }
    287   });
    288 }
    289 
    290 function insertRefreshToken(
    291   env,
    292   { sessionId, userId: tokenUserId, realmId: tokenRealmId, clientId, scopes = 'openid' }
    293 ) {
    294   const id = crypto.randomUUID();
    295   const now = Date.now();
    296   withSystemDatabase(env, (database) => {
    297     database
    298       .prepare(
    299         `INSERT INTO refresh_tokens
    300           (id, family_id, session_id, user_id, realm_id, client_id, scopes,
    301            created_at, expires_at, consumed_at, replaced_by, revoked_at)
    302          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL)`
    303       )
    304       .run(
    305         id,
    306         crypto.randomUUID(),
    307         sessionId,
    308         tokenUserId,
    309         tokenRealmId,
    310         clientId,
    311         scopes,
    312         now,
    313         now + 60_000
    314       );
    315   });
    316   return id;
    317 }
    318 
    319 function withRealmDatabase(env, slug, fn) {
    320   const system = new DatabaseSync(env.AUTH_DATABASE_PATH);
    321   try {
    322     const realm = system
    323       .prepare('SELECT db_file FROM realms WHERE slug = ?')
    324       .get(slug);
    325     const database = new DatabaseSync(path.join(env.AUTH_REALMS_PATH, realm.db_file));
    326     try {
    327       return fn(database);
    328     } finally {
    329       database.close();
    330     }
    331   } finally {
    332     system.close();
    333   }
    334 }
    335 
    336 function insertTestUser(
    337   env,
    338   { username, email = null, displayName = username, status = 'active', isSystemAdmin = false }
    339 ) {
    340   const id = crypto.randomUUID();
    341   const now = Date.now();
    342   withSystemDatabase(env, (database) => {
    343     database
    344       .prepare(
    345         `INSERT INTO users
    346           (id, username, username_normalized, display_name, status, home_realm_id,
    347            is_system_admin, profile, created_at, updated_at)
    348          VALUES (?, ?, ?, ?, ?, NULL, ?, '{}', ?, ?)`
    349       )
    350       .run(
    351         id,
    352         username,
    353         username.toLowerCase(),
    354         displayName,
    355         status,
    356         isSystemAdmin ? 1 : 0,
    357         now,
    358         now
    359       );
    360     if (email) {
    361       database
    362         .prepare(
    363           `INSERT INTO user_emails
    364             (id, user_id, email, email_normalized, verified, is_primary, created_at, verified_at)
    365            VALUES (?, ?, ?, ?, 1, 1, ?, ?)`
    366         )
    367         .run(crypto.randomUUID(), id, email, email.toLowerCase(), now, now);
    368     }
    369   });
    370   return id;
    371 }
    372 
    373 function setTestUserPasswordFrom(env, { username, sourceUsername }) {
    374   const source = withSystemDatabase(env, (database) =>
    375     database
    376       .prepare(
    377         `SELECT c.secret_hash
    378            FROM credentials c
    379            JOIN users u ON u.id = c.user_id
    380           WHERE u.username = ? AND c.type = 'password'`
    381       )
    382       .get(sourceUsername)
    383   );
    384   const targetId = userId(env, username);
    385   const now = Date.now();
    386   withSystemDatabase(env, (database) => {
    387     database
    388       .prepare(
    389         `INSERT INTO credentials (id, user_id, type, secret_hash, created_at, updated_at)
    390          VALUES (?, ?, 'password', ?, ?, ?)`
    391       )
    392       .run(crypto.randomUUID(), targetId, source.secret_hash, now, now);
    393   });
    394 }
    395 
    396 function clearRealmMembership(env, realmSlug, membershipUserId) {
    397   withRealmDatabase(env, realmSlug, (database) => {
    398     database.prepare('DELETE FROM membership_roles WHERE user_id = ?').run(membershipUserId);
    399     database.prepare('DELETE FROM realm_memberships WHERE user_id = ?').run(membershipUserId);
    400   });
    401 }
    402 
    403 function clearUserRealmSessions(env, membershipUserId) {
    404   withSystemDatabase(env, (database) => {
    405     const sessions = database.prepare('SELECT id FROM sessions WHERE user_id = ?').all(membershipUserId);
    406     for (const session of sessions) {
    407       database.prepare('DELETE FROM session_realms WHERE session_id = ?').run(session.id);
    408       database.prepare('DELETE FROM refresh_tokens WHERE session_id = ?').run(session.id);
    409     }
    410     database.prepare('DELETE FROM sessions WHERE user_id = ?').run(membershipUserId);
    411     database
    412       .prepare(
    413         `DELETE FROM session_groups
    414           WHERE id NOT IN (SELECT group_id FROM sessions)`
    415       )
    416       .run();
    417   });
    418 }
    419 
    420 function setTestMembershipStatus(env, realmSlug, membershipUserId, status) {
    421   const now = Date.now();
    422   withRealmDatabase(env, realmSlug, (database) => {
    423     const existing = database
    424       .prepare('SELECT user_id FROM realm_memberships WHERE user_id = ?')
    425       .get(membershipUserId);
    426     if (existing) {
    427       database
    428         .prepare('UPDATE realm_memberships SET status = ?, updated_at = ? WHERE user_id = ?')
    429         .run(status, now, membershipUserId);
    430       return;
    431     }
    432     database
    433       .prepare('INSERT INTO realm_memberships (user_id, status, created_at, updated_at) VALUES (?, ?, ?, ?)')
    434       .run(membershipUserId, status, now, now);
    435   });
    436 }
    437 
    438 export {
    439   activeSessionId,
    440   activeSessionPublicId,
    441   clearBans,
    442   clearConsent,
    443   clearRealmMembership,
    444   clearUserRealmSessions,
    445   cookieValue,
    446   freePort,
    447   insertRefreshToken,
    448   insertTestUser,
    449   locationQuery,
    450   maxAge,
    451   mergeCookies,
    452   pkce,
    453   realmId,
    454   request,
    455   responseCookies,
    456   runNode,
    457   sessionGroupCount,
    458   sessionGroupId,
    459   setAdminConsent,
    460   setConsentMode,
    461   setTestMembershipStatus,
    462   setTestUserPasswordFrom,
    463   startServer,
    464   userId,
    465   withRealmDatabase,
    466   withSystemDatabase,
    467 };
    468 
    469 // retry reseeds into a fresh dir: seed-demo stores the port in client redirect uris
    470 export async function createHttpHarness({ attempts = 3 } = {}) {
    471   async function openHarness(dir, port) {
    472     const publicUrl = `http://identity.test:${port}`;
    473     const env = {
    474       AUTH_DATABASE_PATH: path.join(dir, 'system.sqlite'),
    475       AUTH_REALMS_PATH: path.join(dir, 'realms'),
    476       AUTH_PORT: String(port),
    477       AUTH_PUBLIC_URL: publicUrl,
    478       AUTH_ADMIN_APP_URL: `http://admin.test:${port}`,
    479       AUTH_ACCOUNT_APP_URL: `http://account.test:${port}`,
    480       AUTH_SECRETS_KEY: 'ab'.repeat(32),
    481     };
    482 
    483     const origin = (host) => `http://${host}:${port}`;
    484     await runNode('scripts/seed-demo.js', env);
    485     const server = await startServer(env);
    486 
    487     const identity = (options = {}) =>
    488       request(port, { host: `identity.test:${port}`, ...options });
    489     const acme = (options = {}) => request(port, { host: `acme.localhost:${port}`, ...options });
    490     const globex = (options = {}) => request(port, { host: `globex.localhost:${port}`, ...options });
    491     const app = (options = {}) => request(port, { host: `app.acme.localhost:${port}`, ...options });
    492 
    493     async function completeAuthorization(requester, { path, cookie, clientId }) {
    494       let response = await requester({ path, cookie });
    495       let jar = cookie || '';
    496 
    497       for (let attempt = 0; attempt < 2; attempt += 1) {
    498         if (response.status !== 302) break;
    499         const location = locationQuery(response);
    500         if (!location.pathname.endsWith('/consent')) break;
    501 
    502         jar = mergeCookies(jar, response);
    503         const consent = await requester({
    504           path: `/api/v1/consent?client_id=${encodeURIComponent(clientId)}`,
    505           cookie: jar,
    506         });
    507         assert.equal(consent.status, 200);
    508         assert.deepEqual(consent.json.client.id, clientId);
    509 
    510         const allow = await requester({
    511           method: 'POST',
    512           path: '/api/v1/consent',
    513           body: { client_id: clientId, decision: 'allow' },
    514           cookie: jar,
    515         });
    516         assert.equal(allow.status, 200);
    517         response = await requester({ path: path.split('?')[0], cookie: jar });
    518       }
    519 
    520       return { response, cookie: jar };
    521     }
    522 
    523     async function accessToken(
    524       requester,
    525       { clientId, identifier, redirectUri, scope = 'openid profile' }
    526     ) {
    527       const { verifier, challenge } = pkce();
    528       const authorizePath =
    529         `/oidc/${clientId}/authorize?response_type=code&client_id=${clientId}` +
    530         `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${encodeURIComponent(scope)}` +
    531         `&state=admin-api&code_challenge=${challenge}&code_challenge_method=S256`;
    532 
    533       const first = await requester({ path: authorizePath });
    534       assert.equal(first.status, 302);
    535       let jar = mergeCookies('', first);
    536       const login = await requester({
    537         method: 'POST',
    538         path: '/api/v1/login/password',
    539         body: { client_id: clientId, identifier, password: 'demo' },
    540         cookie: jar,
    541       });
    542       assert.equal(login.status, 200);
    543       jar = mergeCookies(jar, login);
    544 
    545       const completed = await completeAuthorization(requester, {
    546         path: authorizePath.split('?')[0],
    547         cookie: jar,
    548         clientId,
    549       });
    550       assert.equal(completed.response.status, 302);
    551       const code = locationQuery(completed.response).searchParams.get('code');
    552       assert.ok(code);
    553 
    554       const tokenResponse = await requester({
    555         method: 'POST',
    556         path: `/oidc/${clientId}/token`,
    557         form: {
    558           grant_type: 'authorization_code',
    559           code,
    560           redirect_uri: redirectUri,
    561           client_id: clientId,
    562           code_verifier: verifier,
    563         },
    564       });
    565       assert.equal(tokenResponse.status, 200);
    566       return {
    567         access_token: tokenResponse.json.access_token,
    568         refresh_token: tokenResponse.json.refresh_token,
    569         cookie: completed.cookie,
    570       };
    571     }
    572 
    573     async function adminToken(identifier = 'admin@system.test') {
    574       return accessToken(identity, {
    575         clientId: 'admin',
    576         identifier,
    577         redirectUri: `${origin('identity.test')}/app/admin/callback`,
    578       });
    579     }
    580 
    581     const adminRequest = (admin, options) =>
    582       identity({ bearer: admin.access_token, ...options });
    583 
    584     async function createAdminClient(admin, realm, body) {
    585       return adminRequest(admin, {
    586         method: 'POST',
    587         path: `/api/v1/admin/realms/${realm}/clients`,
    588         body,
    589       });
    590     }
    591 
    592     async function updateAdminClient(admin, realm, clientId, body) {
    593       return adminRequest(admin, {
    594         method: 'PATCH',
    595         path: `/api/v1/admin/realms/${realm}/clients/${encodeURIComponent(clientId)}`,
    596         body,
    597       });
    598     }
    599 
    600     async function deleteAdminClient(admin, realm, clientId) {
    601       return adminRequest(admin, {
    602         method: 'DELETE',
    603         path: `/api/v1/admin/realms/${realm}/clients/${encodeURIComponent(clientId)}`,
    604       });
    605     }
    606 
    607     async function authorizeCodeForClient(
    608       requester,
    609       { clientId, identifier, redirectUri, scope = 'openid profile', state }
    610     ) {
    611       const { verifier, challenge } = pkce();
    612       const authorizePath =
    613         `/oidc/${clientId}/authorize?response_type=code&client_id=${clientId}` +
    614         `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${encodeURIComponent(scope)}` +
    615         `&state=${state}&code_challenge=${challenge}&code_challenge_method=S256`;
    616       const first = await requester({ path: authorizePath });
    617       let jar = mergeCookies('', first);
    618       const login = await requester({
    619         method: 'POST',
    620         path: '/api/v1/login/password',
    621         body: { client_id: clientId, identifier, password: 'demo' },
    622         cookie: jar,
    623       });
    624       jar = mergeCookies(jar, login);
    625       const completed = await completeAuthorization(requester, {
    626         path: authorizePath.split('?')[0],
    627         cookie: jar,
    628         clientId,
    629       });
    630       const code = locationQuery(completed.response).searchParams.get('code');
    631       assert.ok(code);
    632       return { verifier, code };
    633     }
    634 
    635     async function close() {
    636       server.kill('SIGTERM');
    637       await new Promise((resolve) => server.once('exit', resolve));
    638       await fs.rm(dir, { recursive: true, force: true });
    639     }
    640 
    641     return {
    642       dir,
    643       port,
    644       publicUrl,
    645       env,
    646       origin,
    647       server,
    648       identity,
    649       acme,
    650       globex,
    651       app,
    652       completeAuthorization,
    653       accessToken,
    654       adminToken,
    655       adminRequest,
    656       createAdminClient,
    657       updateAdminClient,
    658       deleteAdminClient,
    659       authorizeCodeForClient,
    660       close,
    661     };
    662   }
    663 
    664   let lastError = null;
    665   for (let attempt = 1; attempt <= attempts; attempt += 1) {
    666     const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'auth-http-'));
    667     const port = await freePort();
    668     try {
    669       return await openHarness(dir, port);
    670     } catch (error) {
    671       lastError = error;
    672       await fs.rm(dir, { recursive: true, force: true });
    673       if (attempt === attempts) break;
    674     }
    675   }
    676   throw lastError;
    677 }