gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Branchf2-api-bugs26117255|||PR apps API: review comments on files with spaces in their namemref2-api-bugs/tests/ident-access-gitoria.mjs

12.2 KB

  1. // tests/ident-access-gitoria.mjs — GATE: gitoria takes an ident access key (idt_…, ident#27, app side) as the git password.
  2. // A LOCAL ident (tests/identkit.mjs) with the app 'gitoria' and identities given keys through ident's own API; a LOCAL gitoria started with that
  3. // app's key and secret; the real `git` binary clones and pushes over http. Checked: a write key of a member pushes (and the commit is in the repo),
  4. // a read key clones and its push is 403, a private repo with a key that has no access is 404, a revoked / unknown / foreign key is 401 (with the Basic
  5. // realm), ident down is 503 and nothing is pushed, a gtr_ token still clones and pushes.
  6. // node tests/ident-access-gitoria.mjs (GITORIA_IDA_PORT 8760, GITORIA_IDA_IDENT_PORT 8761)
  7. import { spawn, execFileSync } from 'node:child_process';
  8. import { request } from 'node:http';
  9. import { mkdirSync, rmSync, writeFileSync, 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 PORT = Number(process.env.GITORIA_IDA_PORT || 8760), IDENT_PORT = Number(process.env.GITORIA_IDA_IDENT_PORT || 8761);
  15. const IDENT_DIR = process.env.GITORIA_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/WorldAPI/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));
  16. const STORE = join(APP, '.scratch/ida-store');
  17. const J = JSON.stringify, sleep = (ms) => new Promise(r => setTimeout(r, ms));
  18. let passes = 0, failures = 0;
  19. const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + String(detail).slice(0, 400)}`); if (ok) passes++; else failures++; };
  20. function raw(method, path, { host = `localhost:${PORT}`, headers = {}, body = null, cookie = null } = {}) {
  21. return new Promise((res, rej) => {
  22. const h = { host, ...headers }; if (cookie) h.cookie = cookie;
  23. if (body !== null) h['content-length'] = Buffer.byteLength(body);
  24. const r = request({ host: '127.0.0.1', port: PORT, method, path, headers: h }, (m) => { const c = []; m.on('data', d => c.push(d)); m.on('end', () => res({ status: m.statusCode, headers: m.headers, body: Buffer.concat(c).toString('latin1') })); });
  25. r.on('error', rej); if (body !== null) r.write(body); r.end();
  26. });
  27. }
  28. const get = (path, o = {}) => raw('GET', path, o);
  29. let server = null, log = '', ident = null;
  30. function startServer(env) {
  31. const p = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],
  32. env: { ...process.env, GITORIA_PORT: String(PORT), GITORIA_WATCH: '0', GITORIA_PUBLIC_URL: `http://localhost:${PORT}`, GITORIA_SSH_SECRET: 'sshsecret-for-the-ida-gate', GITORIA_TICKETS_URL: 'http://127.0.0.1:1', ...env } });
  33. p.stdout.on('data', d => log += d); p.stderr.on('data', d => log += d);
  34. server = p;
  35. }
  36. async function up() { for (let i = 0; i < 960; i++) { try { if ((await get('/api/repos')).status === 200) return; } catch {} await sleep(250); } throw new Error('gitoria did not come up\n' + log); }
  37. process.on('exit', () => { try { server && server.kill(); } catch {} try { ident && ident.proc.kill(); } catch {} });
  38. try {
  39. rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });
  40. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  41. const alice = await ident.signIn('[email protected]');
  42. const BASE = `http://localhost:${PORT}`;
  43. const app = await ident.registerApp(alice, 'gitoria (ida gate)', [BASE]); app.id = app.raw.app.id;
  44. const other = await ident.registerApp(alice, 'otherapp', ['http://127.0.0.1:1']); other.id = other.raw.app.id;
  45. const give = async (name, apps, level) => {
  46. const r = await ident.emit('accGiveAccess', [{ newName: name, apps, level, label: name }], alice.cookie);
  47. if (!r.value || !r.value.key) throw new Error('give failed: ' + r.raw);
  48. return r.value;
  49. };
  50. const writer = await give('Hermes', [app.id], 'write'), reader = await give('Reader', [app.id], 'read');
  51. const stranger = await give('Stranger', [other.id], 'write'), victim = await give('Victim', [app.id], 'write'), nobody = await give('Nobody', [app.id], 'write');
  52. startServer({ GITORIA_STORAGE: join(STORE, 'mpackdb'), GITORIA_SESSIONS: join(STORE, 'sessions') + '/', GITORIA_GIT: join(STORE, 'git'), IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base, IDENT_API_KEY: app.key, IDENT_API_SECRET: app.secret });
  53. await up();
  54. const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;
  55. const A = await (async () => { const ck = cookieOf(await get('/')); const code = await ident.selectorCode(alice, app, BASE); const cb = await get('/login/callback?ident_code=' + code + '&next=%2F', { cookie: ck }); return { cookie: cookieOf(cb) || ck }; })();
  56. let n = 0;
  57. const face = async (who, event, payload) => {
  58. const r = await raw('POST', '/__hl/emit', { headers: { 'content-type': 'application/json' }, cookie: who.cookie, body: J({ t: 'emit', i: ++n, event, payload }) });
  59. let j = null; try { j = JSON.parse(r.body); } catch {}
  60. return { status: r.status, value: j && j.value, error: j && j.error };
  61. };
  62. await face(A, 'gitoriaSaveName', ['Alice']);
  63. const tA = (await face(A, 'gitoriaMakeToken', ['a'])).value.token;
  64. const W = join(STORE, 'work'); mkdirSync(W, { recursive: true });
  65. const genv = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_GLOBAL: '/dev/null', GIT_AUTHOR_NAME: 'a', GIT_AUTHOR_EMAIL: 'a@a', GIT_COMMITTER_NAME: 'a', GIT_COMMITTER_EMAIL: 'a@a' };
  66. const g = (...a) => execFileSync('git', a, { cwd: W, encoding: 'utf8', env: genv, stdio: ['ignore', 'pipe', 'pipe'] });
  67. g('init', '-q', '-b', 'main'); writeFileSync(join(W, 'README.md'), '# Ida\n'); g('add', '-A'); g('commit', '-q', '-m', 'init');
  68. const urlOf = (t, host, path) => `http://u:${t}@${host}.localhost:${PORT}/${path}`;
  69. const pushTo = (t, host, path, ref = 'main') => { try { g('push', '-q', urlOf(t, host, path), ref); return true; } catch { return false; } };
  70. const lsRemote = (t, host, path) => { try { return g('ls-remote', urlOf(t, host, path)); } catch { return null; } };
  71. const cloneTo = (t, host, path, dir) => { try { execFileSync('git', ['clone', '-q', urlOf(t, host, path), join(STORE, dir)], { env: genv, stdio: 'pipe' }); return existsSync(join(STORE, dir, 'README.md')); } catch { return false; } };
  72. const basic = (k) => ({ authorization: 'Basic ' + Buffer.from('x:' + k).toString('base64') });
  73. const refs = (k, host, slug, svc = 'git-upload-pack') => get(`/${slug}.git/info/refs?service=${svc}`, { host: `${host}.localhost:${PORT}`, headers: k ? basic(k) : {} });
  74. const headOf = (host, slug) => { try { return execFileSync('git', ['ls-remote', urlOf(tA, host, slug + '.git'), 'main'], { env: genv, encoding: 'utf8' }).split('\t')[0]; } catch { return null; } };
  75. // Hermes uses his key once (a public clone) so his gitoria user exists, named Hermes; then Alice adds him by name to her private repo
  76. console.log('# a write key');
  77. await face(A, 'gitoriaCreate', ['pubrepo', 'public']);
  78. await face(A, 'gitoriaCreateRepo', ['secretrepo', 'private', '', true]);
  79. check('setup: Alice pushes both repos with her gtr_ token', pushTo(tA, 'pubrepo', 'pubrepo.git') && pushTo(tA, 'secretrepo', 'secretrepo.git'));
  80. check('a write key clones a public repo', cloneTo(writer.key, 'pubrepo', 'pubrepo.git', 'c1'));
  81. let r = await refs(writer.key, 'secretrepo', 'secretrepo');
  82. check('a write key that is not a member: private repo is 404, as for a name that does not exist', r.status === 404, r.status);
  83. const add = await face(A, 'gitoriaChangeMember', ['secretrepo', 'Hermes', true]);
  84. check('Alice adds Hermes (the key\'s identity, named by ident) as a member', !!(add.value && add.value.members && add.value.members.some(m => m.name === 'Hermes')), J(add.value));
  85. check('the member key clones the private repo', cloneTo(writer.key, 'secretrepo', 'secretrepo.git', 'c2'));
  86. writeFileSync(join(W, 'viakey.txt'), 'pushed with an idt_ key\n'); g('add', '-A'); g('commit', '-q', '-m', 'pushed with an idt_ key');
  87. const sha = g('rev-parse', 'HEAD').trim();
  88. check('the member write key pushes', pushTo(writer.key, 'secretrepo', 'secretrepo.git'));
  89. check('…and the commit is the repo\'s head', headOf('secretrepo', 'secretrepo') === sha);
  90. check('the key made no second gitoria user (the member list still names one Hermes)', (await face(A, 'gitoriaChangeMember', ['secretrepo', 'Hermes', true])).value.members.filter(m => m.name === 'Hermes').length === 1);
  91. r = await refs(writer.key, 'pubrepo', 'pubrepo', 'git-receive-pack');
  92. check('a write key that is not a member may not push to Alice\'s public repo: 403', r.status === 403, r.status);
  93. console.log('# a read key');
  94. check('a read key clones a public repo', cloneTo(reader.key, 'pubrepo', 'pubrepo.git', 'c3'));
  95. r = await refs(reader.key, 'pubrepo', 'pubrepo', 'git-receive-pack');
  96. check('a read key: the push advertisement is 403', r.status === 403, r.status);
  97. writeFileSync(join(W, 'nope.txt'), 'x\n'); g('add', '-A'); g('commit', '-q', '-m', 'by a read key');
  98. const before = headOf('pubrepo', 'pubrepo');
  99. check('a read key: git push fails', !pushTo(reader.key, 'pubrepo', 'pubrepo.git'));
  100. check('…and nothing was pushed', headOf('pubrepo', 'pubrepo') === before);
  101. r = await refs(reader.key, 'secretrepo', 'secretrepo');
  102. check('a read key that is no member: private repo is 404', r.status === 404, r.status);
  103. r = await refs(nobody.key, 'secretrepo', 'secretrepo', 'git-receive-pack');
  104. check('a write key with no access to the private repo: 404 for the push too', r.status === 404, r.status);
  105. console.log('# refused keys');
  106. r = await refs(stranger.key, 'pubrepo', 'pubrepo');
  107. check('a key for another app: 401 with the Basic realm', r.status === 401 && /Basic/.test(r.headers['www-authenticate'] || ''), r.status);
  108. r = await refs('idt_' + '0'.repeat(48), 'pubrepo', 'pubrepo');
  109. check('an unknown well-formed key: 401', r.status === 401, r.status);
  110. r = await refs('idt_abc', 'pubrepo', 'pubrepo');
  111. check('a malformed idt_ key: 401', r.status === 401, r.status);
  112. check('git clone of a private repo with an unknown key fails (git sends the key only after the 401)', !cloneTo('idt_' + '0'.repeat(48), 'secretrepo', 'secretrepo.git', 'c4'));
  113. check('before the revoke the victim key clones', cloneTo(victim.key, 'pubrepo', 'pubrepo.git', 'c5'));
  114. await ident.emit('accRevokeCell', [victim.identity, app.id], alice.cookie);
  115. r = await refs(victim.key, 'pubrepo', 'pubrepo');
  116. check('revoked: 401 at the very next call', r.status === 401 && !r.body.includes(victim.key), r.status);
  117. console.log('# the old way');
  118. check('a gtr_ token still clones a private repo', cloneTo(tA, 'secretrepo', 'secretrepo.git', 'c6'));
  119. check('a gtr_ token still pushes (the owner)', pushTo(tA, 'secretrepo', 'secretrepo.git'));
  120. r = await refs(null, 'secretrepo', 'secretrepo');
  121. check('no credentials, private repo: the same 401 as before', r.status === 401, r.status);
  122. r = await refs('gtr_' + '0'.repeat(40), 'secretrepo', 'secretrepo');
  123. check('an unknown gtr_ token: 404 as before', r.status === 404, r.status);
  124. console.log('# ident down');
  125. await ident.stop();
  126. const head0 = headOf('secretrepo', 'secretrepo');
  127. r = await refs(writer.key, 'pubrepo', 'pubrepo');
  128. check('ident down: a valid key is refused with 503 (not 401, not served)', r.status === 503 && !r.body.includes(writer.key) && !r.body.includes(app.secret), r.status);
  129. writeFileSync(join(W, 'down.txt'), 'x\n'); g('add', '-A'); g('commit', '-q', '-m', 'while ident is down');
  130. check('ident down: git push with a key fails', !pushTo(writer.key, 'secretrepo', 'secretrepo.git'));
  131. check('ident down: nothing was pushed', headOf('secretrepo', 'secretrepo') === head0);
  132. check('ident down: a gtr_ token still pushes', pushTo(tA, 'secretrepo', 'secretrepo.git'));
  133. check('ident down: anonymous clone of a public repo still works', !!execFileSync('git', ['ls-remote', `http://pubrepo.localhost:${PORT}/pubrepo.git`], { env: genv, encoding: 'utf8' }));
  134. } catch (e) {
  135. failures++; console.log('FAIL gate error: ' + (e.stack || e) + '\n' + log.slice(-1500));
  136. } finally {
  137. try { server && server.kill(); } catch {} try { ident && await ident.stop(); } catch {}
  138. }
  139. console.log(`\n${passes} passed, ${failures} failed`);
  140. process.exit(failures ? 1 : 0);

Branches

Latest commits

  • 26117255|||PR apps API: review comments on files with spaces in their namemre
  • b8796cecMerge branch 'f1-broken-json' into mainGitoria
  • 2f2959c5|||PR apps API: broken JSON body gives 400 invalid_json, not 500mre
  • f7c6ca07Merge branch 'ident-chooser-selector' into mainGitoria
  • 691abb8e|||PR tests: find ident identity choice without the removed .choose classmre
  • 16a3530fMerge branch 'heap-revert' into mainGitoria
  • 220a80e0|||PR Remove temporary /__heap route and heap helper; logmre
  • 13f0c342Merge branch 'hl25-records' into mainGitoria
  • a002ecb7|||PR records: HL25 report, heap helper, logmre
  • 2492a55cTemporary keyed /__heap route for the live memory snapshotmre
  • fefaedd2log: tracker PR-only, HL25 startedmre
  • 21aa57calog: parkmre
  • e9f950a8reports: G25c soakmre
  • a7783686log: deploy 9f41ffcmre
  • 9f41ffc1log: W30b mergedmre
  • bef635c1Merge branch 'w30b'mre
  • 15b996a5Org list: keyed rows by @id, newest first, concat instead of hand loopmre
  • c4f6d9e3reports: G25c growth huntmre
  • b88e39f1log: privacy cleanup donemre
  • bfd7826ddocs: neutral example organisation namemre