gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain5d144817Merge branch 'records-t40' into mainTicketsmain/tests/ident-access-tickets.mjs

11.5 KB

  1. // tests/ident-access-tickets.mjs — GATE: tickets' API accepts an ident access key (`Authorization: Bearer idt_…`, ident#27, app side).
  2. // A LOCAL ident (tests/identkit.mjs, a copy of TICKETS_GATE_IDENT_DIR, default ../ident.worldapi.org) with an app 'tickets' and identities that
  3. // were given keys through ident's own API; a LOCAL tickets (store seeded by tests/events-seed.hl: alice with a tkt_ token, a
  4. // 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
  5. // identity (author = the identity's name, same user on the second call); a read key reads (GET 200) and every write is 403; revoked,
  6. // 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.
  7. // node tests/ident-access-tickets.mjs (TICKETS_IDA_PORT 8769, TICKETS_IDA_IDENT_PORT 8768; every PID it starts is killed at the end)
  8. import { spawn, spawnSync } from 'node:child_process';
  9. import { rmSync, mkdirSync, existsSync } from 'node:fs';
  10. import { dirname, join, resolve } from 'node:path';
  11. import { fileURLToPath } from 'node:url';
  12. import { startIdent } from './identkit.mjs';
  13. const APP = resolve(dirname(fileURLToPath(import.meta.url)), '..');
  14. const BIN = join(APP, 'bin/hybriel');
  15. const PORT = Number(process.env.TICKETS_IDA_PORT || 8769), IPORT = Number(process.env.TICKETS_IDA_IDENT_PORT || 8768);
  16. const BASE = `http://127.0.0.1:${PORT}`;
  17. 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')));
  18. const WORK = process.env.TICKETS_IDA_DIR || join(APP, '.scratch/ident-access-gate');
  19. const COLD_MS = Number(process.env.TICKETS_COLD_MS || 120000);
  20. const J = JSON.stringify;
  21. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  22. let passes = 0, failures = 0;
  23. const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + String(detail).slice(0, 400)}`); if (ok) passes++; else failures++; };
  24. rmSync(WORK, { recursive: true, force: true });
  25. mkdirSync(join(WORK, 'mpackdb'), { recursive: true }); mkdirSync(join(WORK, 'sessions'), { recursive: true });
  26. let ident = null, server = null, log = '';
  27. const stopAll = async () => { try { server && server.kill(); } catch {} try { ident && await ident.stop(); } catch {} };
  28. process.on('exit', () => { try { server && server.kill(); } catch {} try { ident && ident.proc.kill(); } catch {} });
  29. try {
  30. const seedOut = spawnSync(BIN, ['tests/events-seed.hl'], { cwd: APP, env: { ...process.env, TICKETS_STORAGE: join(WORK, 'mpackdb') }, encoding: 'utf8', timeout: COLD_MS });
  31. const seedLine = ((seedOut.stdout || '') + (seedOut.stderr || '')).split('\n').find(l => l.startsWith('SEED '));
  32. if (!seedLine) throw new Error('the seed failed:\n' + seedOut.stdout + seedOut.stderr);
  33. const K = JSON.parse(seedLine.slice(5));
  34. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(WORK, 'ident'), port: IPORT });
  35. const alice = await ident.signIn('[email protected]');
  36. 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; };
  37. const tk = await mkApp('tickets'), other = await mkApp('otherapp');
  38. const give = async (name, apps, level) => {
  39. const r = await ident.emit('accGiveAccess', [{ newName: name, apps, level, label: name }], alice.cookie);
  40. if (!r.value || !r.value.key) throw new Error('give failed: ' + r.raw);
  41. return r.value;
  42. };
  43. const writer = await give('Hermes', [tk.id], 'write');
  44. const reader = await give('Reader', [tk.id], 'read');
  45. const stranger = await give('Stranger', [other.id], 'write');
  46. const victim = await give('Victim', [tk.id], 'write');
  47. server = spawn(BIN, ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, TICKETS_PORT: String(PORT),
  48. TICKETS_STORAGE: join(WORK, 'mpackdb'), TICKETS_SESSIONS: join(WORK, 'sessions'), TICKETS_WATCH: '0', TICKETS_PUBLIC_URL: BASE,
  49. IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base, IDENT_API_KEY: tk.key, IDENT_API_SECRET: tk.secret, TICKETS_CREATOR_IDENTITY: '' } });
  50. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  51. for (const end = Date.now() + COLD_MS; Date.now() < end;) { try { await fetch(BASE + '/api/projects'); break; } catch { await sleep(300); } }
  52. const call = async (method, path, token, body) => {
  53. const h = {}; if (token) h.authorization = 'Bearer ' + token;
  54. if (body !== undefined) h['content-type'] = 'application/json';
  55. const r = await fetch(BASE + path, { method, headers: h, body: body === undefined ? undefined : J(body) });
  56. const t = await r.text(); let j = null; try { j = JSON.parse(t); } catch {}
  57. return { status: r.status, j, t };
  58. };
  59. console.log('# an idt_ write key');
  60. let r = await call('POST', '/api/projects', writer.key, { title: 'Hermes work', slug: 'hermes' });
  61. check('a write key makes a project (201)', r.status === 201, r.status + ' ' + r.t);
  62. r = await call('POST', '/api/projects/hermes/tickets', writer.key, { subject: 'made by a key', summary: 'no tkt_ token was made by hand' });
  63. check('a write key creates a ticket (201)', r.status === 201 && r.j && r.j.ticket, r.status + ' ' + r.t);
  64. const tid = r.j && r.j.ticket && r.j.ticket.id;
  65. r = await call('POST', '/api/tickets/' + tid + '/comments', writer.key, { text: 'a comment by the same key' });
  66. check('a write key comments (200/201)', r.status === 200 || r.status === 201, r.status + ' ' + r.t);
  67. r = await call('GET', '/api/tickets/' + tid, null);
  68. const authors = r.j && r.j.events ? r.j.events.map(e => e.author) : [];
  69. 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));
  70. r = await call('GET', '/api/projects/hermes', null);
  71. 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));
  72. r = await call('POST', '/api/projects/hermes/tickets', writer.key, { subject: 'second', summary: 'again' });
  73. check('a second call with the key works', r.status === 201, r.status + ' ' + r.t);
  74. r = await call('GET', '/api/projects/hermes', null);
  75. check('…and is still one member', r.j && r.j.members && r.j.members.length === 1, r.t.slice(0, 300));
  76. r = await call('GET', '/api/inbox', writer.key);
  77. check('a read endpoint with the write key (inbox) answers 200', r.status === 200, r.status + ' ' + r.t);
  78. console.log('# an idt_ read key');
  79. r = await call('GET', '/api/inbox', reader.key);
  80. check('a read key: GET (inbox) 200', r.status === 200, r.status + ' ' + r.t);
  81. const ac = new AbortController();
  82. const es = await fetch(BASE + '/api/events?project=hermes', { headers: { authorization: 'Bearer ' + reader.key }, signal: ac.signal });
  83. check('a read key opens the event stream (200)', es.status === 200, '' + es.status);
  84. ac.abort();
  85. const before = await call('GET', '/api/projects/hermes/tickets', null);
  86. const n0 = before.j.tickets.length;
  87. for (const [name, m, p, b] of [
  88. ['create a ticket', 'POST', '/api/projects/hermes/tickets', { subject: 'nope' }],
  89. ['create a project', 'POST', '/api/projects', { title: 'nope project' }],
  90. ['comment', 'POST', '/api/tickets/' + tid + '/comments', { text: 'nope' }],
  91. ['change the state', 'POST', '/api/tickets/' + tid + '/state', { state: 'done' }],
  92. ]) {
  93. r = await call(m, p, reader.key, b);
  94. check('a read key may not ' + name + ': 403', r.status === 403, r.status + ' ' + r.t);
  95. }
  96. const after = await call('GET', '/api/projects/hermes/tickets', null);
  97. check('nothing was written by the read key', after.j.tickets.length === n0);
  98. r = await call('GET', '/api/projects', null);
  99. check('no project made by the read key', r.j && !r.j.projects.includes('nope-project'), r.t.slice(0, 200));
  100. console.log('# refused keys');
  101. r = await call('POST', '/api/projects/hermes/tickets', stranger.key, { subject: 'foreign' });
  102. check('a key for another app: 401', r.status === 401, r.status + ' ' + r.t);
  103. r = await call('POST', '/api/projects/hermes/tickets', 'idt_' + '0'.repeat(48), { subject: 'unknown' });
  104. check('an unknown well-formed key: 401', r.status === 401, r.status + ' ' + r.t);
  105. r = await call('POST', '/api/projects/hermes/tickets', 'idt_abc', { subject: 'short' });
  106. check('a malformed idt_ key: 401', r.status === 401, r.status + ' ' + r.t);
  107. r = await call('POST', '/api/projects/hermes/tickets', victim.key, { subject: 'victim 1' });
  108. 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);
  109. await ident.emit('accRevokeCell', [victim.identity, tk.id], alice.cookie);
  110. r = await call('POST', '/api/projects/hermes/tickets', victim.key, { subject: 'victim 2' });
  111. check('revoked: 401 at the very next call', r.status === 401, r.status + ' ' + r.t);
  112. check('no refusal carries the key back', !r.t.includes(victim.key));
  113. const nx = await call('GET', '/api/projects/hermes/tickets', null);
  114. console.log('# the old ways');
  115. r = await call('POST', '/api/projects/alpha/tickets', K.aliceToken, { subject: 'by a tkt_ token' });
  116. check('a tkt_ token still creates a ticket as alice', r.status === 201, r.status + ' ' + r.t);
  117. r = await call('POST', '/api/tickets/' + K.alphaTicket + '/comments', K.aliceToken, { text: 'by token' });
  118. check('a tkt_ token still comments', r.status === 200 || r.status === 201, r.status + ' ' + r.t);
  119. 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' }) });
  120. check('a project key still creates a ticket (named person)', r.status === 201, r.status + ' ' + await r.text());
  121. r = await call('POST', '/api/projects/alpha/tickets', 'tkt_' + '0'.repeat(48), { subject: 'x' });
  122. check('an unknown tkt_ token is still 401', r.status === 401, r.status + ' ' + r.t);
  123. r = await call('POST', '/api/projects/alpha/tickets', null, { subject: 'x' });
  124. check('no header is still 401', r.status === 401, r.status + ' ' + r.t);
  125. console.log('# ident down');
  126. await ident.stop();
  127. const count = (await call('GET', '/api/projects/hermes/tickets', null)).j.tickets.length;
  128. r = await call('POST', '/api/projects/hermes/tickets', writer.key, { subject: 'while ident is down' });
  129. 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);
  130. r = await call('GET', '/api/inbox', reader.key);
  131. check('ident down: a read key is refused with 503 too', r.status === 503, r.status + ' ' + r.t);
  132. const count2 = (await call('GET', '/api/projects/hermes/tickets', null)).j.tickets.length;
  133. check('ident down: nothing was written', count2 === count, count + ' ' + count2);
  134. r = await call('POST', '/api/projects/alpha/tickets', K.aliceToken, { subject: 'tkt_ with ident down' });
  135. check('ident down: a tkt_ token still works', r.status === 201, r.status + ' ' + r.t);
  136. r = await call('POST', '/api/projects/alpha/tickets', null, { subject: 'x' });
  137. check('ident down: no header is a plain 401', r.status === 401, r.status + ' ' + r.t);
  138. } catch (e) {
  139. failures++; console.log('FAIL gate error: ' + (e.stack || e) + '\n' + log.slice(-1500));
  140. } finally {
  141. await stopAll();
  142. }
  143. console.log(`\n${passes} passed, ${failures} failed`);
  144. 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