tickets
All repositories: gitoria
11.5 KB
// tests/ident-access-tickets.mjs — GATE: tickets' API accepts an ident access key (`Authorization: Bearer idt_…`, ident#27, app side).// A LOCAL ident (tests/identkit.mjs, a copy of TICKETS_GATE_IDENT_DIR, default ../ident.worldapi.org) with an app 'tickets' and identities that// were given keys through ident's own API; a LOCAL tickets (store seeded by tests/events-seed.hl: alice with a tkt_ token, a// project key for beta) started with that ident's key and secret. Checked: a write key makes a project, a ticket and a comment AS the// identity (author = the identity's name, same user on the second call); a read key reads (GET 200) and every write is 403; revoked,// unknown, wrong-shape and other-app keys are 401; ident down is 503 and nothing is written; tkt_ token and project key work as before.// node tests/ident-access-tickets.mjs (TICKETS_IDA_PORT 8769, TICKETS_IDA_IDENT_PORT 8768; every PID it starts is killed at the end)import { spawn, spawnSync } from 'node:child_process';import { rmSync, mkdirSync, existsSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import { startIdent } from './identkit.mjs';const APP = resolve(dirname(fileURLToPath(import.meta.url)), '..');const BIN = join(APP, 'bin/hybriel');const PORT = Number(process.env.TICKETS_IDA_PORT || 8769), IPORT = Number(process.env.TICKETS_IDA_IDENT_PORT || 8768);const BASE = `http://127.0.0.1:${PORT}`;const IDENT_DIR = process.env.TICKETS_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/WorldAPI/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));const WORK = process.env.TICKETS_IDA_DIR || join(APP, '.scratch/ident-access-gate');const COLD_MS = Number(process.env.TICKETS_COLD_MS || 120000);const J = JSON.stringify;const sleep = (ms) => new Promise(r => setTimeout(r, ms));let passes = 0, failures = 0;const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + String(detail).slice(0, 400)}`); if (ok) passes++; else failures++; };rmSync(WORK, { recursive: true, force: true });mkdirSync(join(WORK, 'mpackdb'), { recursive: true }); mkdirSync(join(WORK, 'sessions'), { recursive: true });let ident = null, server = null, log = '';const stopAll = async () => { try { server && server.kill(); } catch {} try { ident && await ident.stop(); } catch {} };process.on('exit', () => { try { server && server.kill(); } catch {} try { ident && ident.proc.kill(); } catch {} });try {const seedOut = spawnSync(BIN, ['tests/events-seed.hl'], { cwd: APP, env: { ...process.env, TICKETS_STORAGE: join(WORK, 'mpackdb') }, encoding: 'utf8', timeout: COLD_MS });const seedLine = ((seedOut.stdout || '') + (seedOut.stderr || '')).split('\n').find(l => l.startsWith('SEED '));if (!seedLine) throw new Error('the seed failed:\n' + seedOut.stdout + seedOut.stderr);const K = JSON.parse(seedLine.slice(5));ident = await startIdent({ identDir: IDENT_DIR, workDir: join(WORK, 'ident'), port: IPORT });const alice = await ident.signIn('[email protected]');const mkApp = async (name) => { const a = await ident.registerApp(alice, name, ['http://127.0.0.1:1']); a.id = a.raw.app.id; return a; };const tk = await mkApp('tickets'), other = await mkApp('otherapp');const give = async (name, apps, level) => {const r = await ident.emit('accGiveAccess', [{ newName: name, apps, level, label: name }], alice.cookie);if (!r.value || !r.value.key) throw new Error('give failed: ' + r.raw);return r.value;};const writer = await give('Hermes', [tk.id], 'write');const reader = await give('Reader', [tk.id], 'read');const stranger = await give('Stranger', [other.id], 'write');const victim = await give('Victim', [tk.id], 'write');server = spawn(BIN, ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, TICKETS_PORT: String(PORT),TICKETS_STORAGE: join(WORK, 'mpackdb'), TICKETS_SESSIONS: join(WORK, 'sessions'), TICKETS_WATCH: '0', TICKETS_PUBLIC_URL: BASE,IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base, IDENT_API_KEY: tk.key, IDENT_API_SECRET: tk.secret, TICKETS_CREATOR_IDENTITY: '' } });server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);for (const end = Date.now() + COLD_MS; Date.now() < end;) { try { await fetch(BASE + '/api/projects'); break; } catch { await sleep(300); } }const call = async (method, path, token, body) => {const h = {}; if (token) h.authorization = 'Bearer ' + token;if (body !== undefined) h['content-type'] = 'application/json';const r = await fetch(BASE + path, { method, headers: h, body: body === undefined ? undefined : J(body) });const t = await r.text(); let j = null; try { j = JSON.parse(t); } catch {}return { status: r.status, j, t };};console.log('# an idt_ write key');let r = await call('POST', '/api/projects', writer.key, { title: 'Hermes work', slug: 'hermes' });check('a write key makes a project (201)', r.status === 201, r.status + ' ' + r.t);r = await call('POST', '/api/projects/hermes/tickets', writer.key, { subject: 'made by a key', summary: 'no tkt_ token was made by hand' });check('a write key creates a ticket (201)', r.status === 201 && r.j && r.j.ticket, r.status + ' ' + r.t);const tid = r.j && r.j.ticket && r.j.ticket.id;r = await call('POST', '/api/tickets/' + tid + '/comments', writer.key, { text: 'a comment by the same key' });check('a write key comments (200/201)', r.status === 200 || r.status === 201, r.status + ' ' + r.t);r = await call('GET', '/api/tickets/' + tid, null);const authors = r.j && r.j.events ? r.j.events.map(e => e.author) : [];check('the ticket and its comment name the identity (Hermes) as author', authors.length >= 2 && authors.every(a => a === 'Hermes'), J(authors) + ' ' + r.t.slice(0, 200));r = await call('GET', '/api/projects/hermes', null);check('the project has one member, the identity, as admin (no second user made by the second call)', r.j && r.j.members && r.j.members.length === 1, r.t.slice(0, 300));r = await call('POST', '/api/projects/hermes/tickets', writer.key, { subject: 'second', summary: 'again' });check('a second call with the key works', r.status === 201, r.status + ' ' + r.t);r = await call('GET', '/api/projects/hermes', null);check('…and is still one member', r.j && r.j.members && r.j.members.length === 1, r.t.slice(0, 300));r = await call('GET', '/api/inbox', writer.key);check('a read endpoint with the write key (inbox) answers 200', r.status === 200, r.status + ' ' + r.t);console.log('# an idt_ read key');r = await call('GET', '/api/inbox', reader.key);check('a read key: GET (inbox) 200', r.status === 200, r.status + ' ' + r.t);const ac = new AbortController();const es = await fetch(BASE + '/api/events?project=hermes', { headers: { authorization: 'Bearer ' + reader.key }, signal: ac.signal });check('a read key opens the event stream (200)', es.status === 200, '' + es.status);ac.abort();const before = await call('GET', '/api/projects/hermes/tickets', null);const n0 = before.j.tickets.length;for (const [name, m, p, b] of [['create a ticket', 'POST', '/api/projects/hermes/tickets', { subject: 'nope' }],['create a project', 'POST', '/api/projects', { title: 'nope project' }],['comment', 'POST', '/api/tickets/' + tid + '/comments', { text: 'nope' }],['change the state', 'POST', '/api/tickets/' + tid + '/state', { state: 'done' }],]) {r = await call(m, p, reader.key, b);check('a read key may not ' + name + ': 403', r.status === 403, r.status + ' ' + r.t);}const after = await call('GET', '/api/projects/hermes/tickets', null);check('nothing was written by the read key', after.j.tickets.length === n0);r = await call('GET', '/api/projects', null);check('no project made by the read key', r.j && !r.j.projects.includes('nope-project'), r.t.slice(0, 200));console.log('# refused keys');r = await call('POST', '/api/projects/hermes/tickets', stranger.key, { subject: 'foreign' });check('a key for another app: 401', r.status === 401, r.status + ' ' + r.t);r = await call('POST', '/api/projects/hermes/tickets', 'idt_' + '0'.repeat(48), { subject: 'unknown' });check('an unknown well-formed key: 401', r.status === 401, r.status + ' ' + r.t);r = await call('POST', '/api/projects/hermes/tickets', 'idt_abc', { subject: 'short' });check('a malformed idt_ key: 401', r.status === 401, r.status + ' ' + r.t);r = await call('POST', '/api/projects/hermes/tickets', victim.key, { subject: 'victim 1' });check('before the revoke the victim key writes (hermes is not its project: 403/404 is a decision of the roles, not 401)', r.status !== 401 && r.status !== 503, r.status + ' ' + r.t);await ident.emit('accRevokeCell', [victim.identity, tk.id], alice.cookie);r = await call('POST', '/api/projects/hermes/tickets', victim.key, { subject: 'victim 2' });check('revoked: 401 at the very next call', r.status === 401, r.status + ' ' + r.t);check('no refusal carries the key back', !r.t.includes(victim.key));const nx = await call('GET', '/api/projects/hermes/tickets', null);console.log('# the old ways');r = await call('POST', '/api/projects/alpha/tickets', K.aliceToken, { subject: 'by a tkt_ token' });check('a tkt_ token still creates a ticket as alice', r.status === 201, r.status + ' ' + r.t);r = await call('POST', '/api/tickets/' + K.alphaTicket + '/comments', K.aliceToken, { text: 'by token' });check('a tkt_ token still comments', r.status === 200 || r.status === 201, r.status + ' ' + r.t);r = await fetch(BASE + '/api/projects/beta/tickets', { method: 'POST', headers: { authorization: 'Bearer ' + K.betaKey, 'x-tickets-identity': 'evbob0001', 'content-type': 'application/json' }, body: J({ subject: 'by a project key' }) });check('a project key still creates a ticket (named person)', r.status === 201, r.status + ' ' + await r.text());r = await call('POST', '/api/projects/alpha/tickets', 'tkt_' + '0'.repeat(48), { subject: 'x' });check('an unknown tkt_ token is still 401', r.status === 401, r.status + ' ' + r.t);r = await call('POST', '/api/projects/alpha/tickets', null, { subject: 'x' });check('no header is still 401', r.status === 401, r.status + ' ' + r.t);console.log('# ident down');await ident.stop();const count = (await call('GET', '/api/projects/hermes/tickets', null)).j.tickets.length;r = await call('POST', '/api/projects/hermes/tickets', writer.key, { subject: 'while ident is down' });check('ident down: a valid write key is refused with 503', r.status === 503 && !r.t.includes(writer.key) && !r.t.includes(tk.secret), r.status + ' ' + r.t);r = await call('GET', '/api/inbox', reader.key);check('ident down: a read key is refused with 503 too', r.status === 503, r.status + ' ' + r.t);const count2 = (await call('GET', '/api/projects/hermes/tickets', null)).j.tickets.length;check('ident down: nothing was written', count2 === count, count + ' ' + count2);r = await call('POST', '/api/projects/alpha/tickets', K.aliceToken, { subject: 'tkt_ with ident down' });check('ident down: a tkt_ token still works', r.status === 201, r.status + ' ' + r.t);r = await call('POST', '/api/projects/alpha/tickets', null, { subject: 'x' });check('ident down: no header is a plain 401', r.status === 401, r.status + ' ' + r.t);} catch (e) {failures++; console.log('FAIL gate error: ' + (e.stack || e) + '\n' + log.slice(-1500));} finally {await stopAll();}console.log(`\n${passes} passed, ${failures} failed`);process.exit(failures ? 1 : 0);
Branches
Latest commits
- 5d144817Merge branch 'records-t40' into mainTickets
- 44ee6f06|||PR records: #43 #45 livemre
- b8fdeee9Merge branch 'p39-routes' into mainTickets
- a0187a0a|||PR Remove redundant route-order loopmre
- 369e4b9cMerge branch 'k40-lists' into mainTickets
- 9af8e780|||PR Use keyed list mutations for live ticket updatesmre
- 610d8e8aMerge branch 'records-t39' into mainTickets
- 32bcdf24|||PR records: GO P39 K40mre
- 4123c6d1Merge branch 'records-t38' into mainTickets
- cd3641a1|||PR records: day72 deploy live, tickets closedmre
- 7d44d852Merge branch 'records-t37' into mainTickets
- 926f7061|||PR records: merges, D36 deploymre
- bf58534eMerge branch 'l33-final' into mainTickets
- 759a9ac3|||PR thin login (tickets#46, #45): merge main, route entry cleanupmre
- 239436d8Merge remote-tracking branch 'origin/main' into l33-finalmre
- 5822cb3aMerge branch 'o34-clean' into mainTickets
- 0870653c|||PR offline note from __hlOnline, no polling (tickets#41)mre
- 14cf96b4Merge branch 'records-t36' into mainTickets
- 07749fa1|||PR records: day72 + #40 mergedmre
- ecd7e226|||PR Consolidate login and move handler logic into topic libraries (partial)mre