gitoria

components

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit3d43c1873d43c187ident-access: server-side check of an ident access key (Bearer or Basic password), asks ident on every call, README, gate tests/ident-access.mjs (ident#27 app side)mre3d43c187/tests/ident-access.mjs

10.6 KB

  1. // tests/ident-access.mjs — THE GATE of components/ident-access/: an app checks an ident access key (ident#27, app side).
  2. // It starts a LOCAL ident (IDENT_APP, default ../ident-checkout) with its own storage, registers an app, gives identities keys through
  3. // ident's own API, then starts tests/ident-access/project.hl (the component wired as its README says) and asks it over HTTP.
  4. // Red before the component exists (the gate app cannot compile), green after. Ports: IA_IDENT_PORT (8788), IA_APP_PORT (8789).
  5. // Run: IDENT_APP=/path/to/ident node tests/ident-access.mjs (exit 0 = all passed; every PID it starts is killed at the end)
  6. import { spawn } from 'node:child_process';
  7. import { readFileSync, writeFileSync, rmSync, mkdirSync } from 'node:fs';
  8. import { dirname, join } from 'node:path';
  9. import { fileURLToPath } from 'node:url';
  10. const HERE = join(dirname(fileURLToPath(import.meta.url)), '..');
  11. const IDENT = process.env.IDENT_APP;
  12. if (!IDENT) { console.log('set IDENT_APP to an ident checkout (with bin/hybriel)'); process.exit(2); }
  13. const G = process.env.IA_GATE_DIR || join(HERE, '.scratch/ident-access-gate');
  14. const PI = Number(process.env.IA_IDENT_PORT || 8788), PA = Number(process.env.IA_APP_PORT || 8789);
  15. const ID = 'http://127.0.0.1:' + PI, APP = 'http://127.0.0.1:' + PA;
  16. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  17. let passed = 0, failed = 0;
  18. const check = (name, ok, detail = '') => { if (ok) { passed++; console.log(' ok ' + name); } else { failed++; console.log(' FAIL ' + name + (detail ? ' — ' + detail : '')); } };
  19. const J = JSON.stringify;
  20. rmSync(G, { recursive: true, force: true }); mkdirSync(G, { recursive: true });
  21. const procs = [];
  22. let logs = '';
  23. function start(name, cwd, bin, args, env) {
  24. const p = spawn(bin, args, { cwd, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ...env } });
  25. p.stdout.on('data', d => { logs += `[${name}] ` + d; }); p.stderr.on('data', d => { logs += `[${name}] ` + d; });
  26. procs.push(p); writeFileSync(join(G, name + '.pid'), String(p.pid));
  27. return p;
  28. }
  29. const stopAll = () => { for (const p of procs) { try { p.kill(); } catch {} } };
  30. process.on('exit', stopAll);
  31. async function up(url, p, what) {
  32. for (const end = Date.now() + 150000; Date.now() < end;) {
  33. if (p.exitCode !== null) throw new Error(what + ' exited with ' + p.exitCode + '\n' + logs.slice(-2500));
  34. try { await fetch(url, { redirect: 'manual' }); return; } catch {} await sleep(300);
  35. }
  36. throw new Error(what + ' did not come up\n' + logs.slice(-2500));
  37. }
  38. // ---- the local ident --------------------------------------------------------------------
  39. const identProc = start('ident', IDENT, join(IDENT, 'bin/hybriel'), ['project.hl'], { SMTP_HOST: '', SMTP_USER: '', SMTP_PASSWORD: '', IDENT_PORT: String(PI), IDENT_STORAGE: join(G, 'ident'), IDENT_SESSIONS: join(G, 'sess') + '/', IDENT_MAIL_SINK: join(G, 'mail.txt'), IDENT_IP_LIMIT: '1000', IDENT_IP_DAY_LIMIT: '1000', IDENT_WATCH: '0' });
  40. await up(ID + '/', identProc, 'ident');
  41. let emitI = 0;
  42. async function emit(event, payload, cookie) {
  43. const r = await fetch(ID + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) }, body: J({ t: 'emit', i: ++emitI, event, payload }) });
  44. const t = await r.text(); let j = null; try { j = JSON.parse(t); } catch {}
  45. return { cookie: (r.headers.get('set-cookie') || '').split(';')[0], value: j && j.value, raw: t };
  46. }
  47. const email = '[email protected]';
  48. await fetch(ID + '/api/code', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ email }) });
  49. const lines = readFileSync(join(G, 'mail.txt'), 'utf8').trim().split('\n').filter(l => l.startsWith(email + ' '));
  50. const login = await emit('verifyCode', [email, lines[lines.length - 1].split(' ')[1], 'UTC']);
  51. if (!login.cookie) throw new Error('ident login failed: ' + login.raw);
  52. const mkApp = async (name) => {
  53. let r;
  54. for (let i = 0; i < 6; i++) { r = await emit('appCreate', [{ name, origins: ['http://127.0.0.1:1'] }], login.cookie); if (r.value && r.value.app) break; await sleep(1000); }
  55. if (!r.value || !r.value.app) throw new Error('appCreate failed: ' + r.raw);
  56. return { id: r.value.app.id, key: r.value.app.apiKey, secret: r.value.secret };
  57. };
  58. const give = async (name, apps, level) => {
  59. const r = await emit('accGiveAccess', [{ newName: name, apps, level, label: name }], login.cookie);
  60. if (!r.value || !r.value.key) throw new Error('give failed: ' + r.raw);
  61. return r.value;
  62. };
  63. const tickets = await mkApp('tickets'), other = await mkApp('otherapp');
  64. const writer = await give('Hermes', [tickets.id], 'write');
  65. const reader = await give('Reader', [tickets.id], 'read');
  66. const stranger = await give('Stranger', [other.id], 'write');
  67. const victim = await give('Victim', [tickets.id], 'write');
  68. // ---- the gate app: the component wired as its README says ---------------------------------
  69. const appEnv = { GATE_APP_PORT: String(PA), IDENT_URL: ID, IDENT_APP_KEY: tickets.key, IDENT_APP_SECRET: tickets.secret };
  70. const appProc = start('gateapp', join(HERE, 'tests/ident-access'), join(HERE, 'bin/hybriel'), ['project.hl'], appEnv);
  71. await up(APP + '/whoami', appProc, 'gate app');
  72. const ask = async (path, headers = {}, method = 'GET') => {
  73. const r = await fetch(APP + path, { method, headers, body: method === 'POST' ? '{}' : undefined });
  74. const t = await r.text(); let j = null; try { j = JSON.parse(t); } catch {}
  75. return { status: r.status, j, t, www: r.headers.get('www-authenticate') };
  76. };
  77. const bearer = (k) => ({ authorization: 'Bearer ' + k });
  78. const basic = (u, p) => ({ authorization: 'Basic ' + Buffer.from(u + ':' + p).toString('base64') });
  79. console.log('# ident-access');
  80. let r = await ask('/whoami', bearer(writer.key));
  81. check('a valid write key: 200, identity, name, access write', r.status === 200 && r.j && /^[2-9a-hj-km-np-z]{5}$/.test(r.j.identity) && r.j.name === 'Hermes' && r.j.access === 'write', r.status + ' ' + r.t);
  82. const hermesId = r.j && r.j.identity;
  83. r = await ask('/write', bearer(writer.key), 'POST');
  84. check('a write key may write', r.status === 200 && r.j && r.j.wrote === true, r.status + ' ' + r.t);
  85. r = await ask('/whoami', basic('git', writer.key));
  86. check('HTTP Basic with the key as the password (git) works, any user name', r.status === 200 && r.j && r.j.identity === hermesId, r.status + ' ' + r.t);
  87. r = await ask('/whoami', bearer(reader.key));
  88. check('a read key: whoami 200 with access read', r.status === 200 && r.j && r.j.access === 'read' && r.j.name === 'Reader', r.status + ' ' + r.t);
  89. r = await ask('/write', bearer(reader.key), 'POST');
  90. check('a read key may not write: 403, nothing written', r.status === 403 && !(r.j && r.j.wrote), r.status + ' ' + r.t);
  91. r = await ask('/whoami', bearer(stranger.key));
  92. check('a key given for another app only: 401', r.status === 401 && !(r.j && r.j.identity), r.status + ' ' + r.t);
  93. check('a refused answer never carries the key back', !r.t.includes(stranger.key));
  94. // revoked: valid, revoke, the very next call refused (no cache that outlives it)
  95. r = await ask('/whoami', bearer(victim.key));
  96. check('before the revoke the victim key is valid', r.status === 200, r.status + ' ' + r.t);
  97. const rv = await emit('accRevokeCell', [victim.identity, tickets.id], login.cookie);
  98. r = await ask('/whoami', bearer(victim.key));
  99. check('revoked: refused at the very next call', r.status === 401, r.status + ' ' + r.t + ' ' + rv.raw);
  100. // wrong shapes and missing headers
  101. for (const [name, h] of [
  102. ['no header at all', {}],
  103. ['an empty Authorization header', { authorization: '' }],
  104. ['a Bearer without a token', { authorization: 'Bearer ' }],
  105. ['a token of another kind (tkt_…)', bearer('tkt_abc123')],
  106. ['idt_ with too few digits', bearer('idt_' + 'a'.repeat(47))],
  107. ['idt_ with too many digits', bearer('idt_' + 'a'.repeat(49))],
  108. ['idt_ with upper-case hex', bearer('idt_' + 'A'.repeat(48))],
  109. ['idt_ with non-hex letters', bearer('idt_' + 'z'.repeat(48))],
  110. ['a scheme that is neither Bearer nor Basic', { authorization: 'Digest ' + writer.key }],
  111. ['the key bare, without a scheme', { authorization: writer.key }],
  112. ['Basic that is not base64', { authorization: 'Basic %%%%' }],
  113. ['Basic with no colon', { authorization: 'Basic ' + Buffer.from(writer.key).toString('base64') }],
  114. ['Basic with bytes that are not UTF-8', { authorization: 'Basic ' + Buffer.from([0x67, 0x3a, 0xff, 0xfe, 0xc3, 0x28]).toString('base64') }],
  115. ['an unknown but well-formed key', bearer('idt_' + '0'.repeat(48))],
  116. ]) {
  117. r = await ask('/whoami', h);
  118. check(name + ': refused with 401, not allowed, not a crash', r.status === 401 && !(r.j && r.j.identity), r.status + ' ' + r.t);
  119. }
  120. r = await ask('/whoami', {});
  121. check('a missing header: the answer asks for credentials (WWW-Authenticate: Basic, so git prompts)', /^Basic /i.test(r.www || ''), String(r.www));
  122. r = await ask('/write', {}, 'POST');
  123. check('a missing header on a write: 401', r.status === 401 && !(r.j && r.j.wrote), r.status + ' ' + r.t);
  124. // the app's settings wrong (secret): ident says 401 to the APP — the user must be refused, not allowed (503: our fault, not theirs)
  125. const badApp = start('badapp', join(HERE, 'tests/ident-access'), join(HERE, 'bin/hybriel'), ['project.hl'], { ...appEnv, GATE_APP_PORT: String(PA + 1), IDENT_APP_SECRET: 'sk_wrong' });
  126. await up('http://127.0.0.1:' + (PA + 1) + '/whoami', badApp, 'gate app with a wrong secret');
  127. const rb = await fetch('http://127.0.0.1:' + (PA + 1) + '/whoami', { headers: bearer(writer.key) });
  128. check('wrong app secret in the settings: the valid key is refused (503), not allowed', rb.status === 503, String(rb.status));
  129. const rbt = await rb.text();
  130. check('…and the answer does not leak the secret', !rbt.includes('sk_'));
  131. // ident down
  132. identProc.kill();
  133. for (const end = Date.now() + 10000; identProc.exitCode === null && Date.now() < end;) await sleep(100);
  134. // hl:fetch has no catch for a refused connection (the Hybriel gap in the README): the framework answers 500, which is a refusal too.
  135. // What matters: never 200, no identity, and nothing secret in the text.
  136. const refused = (x) => x.status >= 500 && x.status < 600 && !(x.j && (x.j.identity || x.j.wrote)) && !x.t.includes(appEnv.IDENT_APP_SECRET) && !x.t.includes(writer.key);
  137. r = await ask('/whoami', bearer(writer.key));
  138. check('ident down: a valid key is refused (5xx), never allowed', refused(r), r.status + ' ' + r.t);
  139. r = await ask('/write', bearer(writer.key), 'POST');
  140. check('ident down: a write is refused too', refused(r), r.status + ' ' + r.t);
  141. r = await ask('/whoami', bearer(writer.key));
  142. check('ident down: still refused on the second call (nothing was remembered)', refused(r), r.status + ' ' + r.t);
  143. r = await ask('/whoami', {});
  144. check('ident down: a missing header is still a plain 401', r.status === 401, r.status + ' ' + r.t);
  145. console.log(`\n${passed} passed, ${failed} failed`);
  146. stopAll();
  147. process.exit(failed ? 1 : 0);

Branches

Latest commits

  • 3d43c187ident-access: server-side check of an ident access key (Bearer or Basic password), asks ident on every call, README, gate tests/ident-access.mjs (ident#27 app side)mre
  • 59704ce1Merge branch 'n5b-pipes'mre
  • 23b9164aMdEditor: a clipboard whose text is only the names or file:// paths of its files (a file manager copy) is about the files, as before; any other text wins (tickets#49); gate casesmre
  • b0f1ec28MdEditor: a clipboard with text always pastes the text, also when a picture is on it too (a spreadsheet or office app), files on or off; a picture alone still goes to the files; real Ctrl+V gate tests/md-paste-files.mjs (tickets#49)mre
  • ad4e929bMdEditor: pipe rows without a delimiter row are a table (first row = header, short rows padded, written back without an invented | --- | line) (notes#5)mre
  • 4bd11128MdEditor: the Table button's empty table is written as a real pipe table (empty cells), so it survives the source switch, a save and a reload (notes#7)mre
  • 7437e32bMdEditor draws its surface at once when claimed from server HTML: 1 ms mount animation, the first editor mounts all editors of the pagemre
  • 5de0264cRe-vendor onto Hybriel master acaceaf3 (set-day27b): binary, lib and plugins; exit 1 on a startup fault; .gitignore binmre
  • 79c77e7dMerge sb3-standby: components deploys through its standbymre
  • c5442043components: no jobs switch needed in the standbymre
  • 8d2fb24ccomponents: a standby container (port 45016, profile standby); deploy hands over through standby-swap.sh without a gapmre
  • c2834dd3Merge mr-fixes: media player state after a queue pick, Range handling, cover-less audio, accessibility labelsmre
  • 354fe3c6Media player: audio without a cover starts and shows its time (the mount tick sits on the seek bar, which every item has); the speed button names the current speed, the seek slider says its time in words; a gate page for the first render on cover-less audio and a fourth demo queue item without a covermre
  • ee4aee1eMedia player: a new queue item shows its own speed, mute, play state and time and starts when asked, also for two videos in a row; the media route reads suffix ranges and ignores range lists and garbage instead of answering 500; stronger gate checks (the 10 percent drag, the played bar, the queue tap)mre
  • 9a4f9b31Merge mp-player: media served from the committed filesmre
  • ab96e686Media route: serve the demo's media from the committed files in components/media-player (storage/ is not in git, the deploy gate found no files)mre
  • b2980734Merge mp-player: the media player (components/media-player), its demo and the media iconsmre
  • 1c41293eMediaPlayer: back / forward 10 s as replay / forward 10 icons (circular arrow with a 10), the play button keeps its surface background on audio and video, the media route's range end is a letmre
  • 9e1ab228MP: report, LOG line, STATUS entrymre
  • dd003e5dMediaPlayer: audio and video in one phone-first player (components/media-player), its demo /media-player with a queue, the media icons in components/icons, the demo's media files served with ranges (lib/media.hl), 35 gate checksmre