gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmainfe209ffeMerge branch 'w56-owner-members' into mainGitoriamain/tests/ident-access-gitoria.mjs

12.2 KB

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

Branches

Latest commits

  • fe209ffeMerge branch 'w56-owner-members' into mainGitoria
  • fa0754c8|||PR repository owner transfer and members API (#55)mre
  • 8862e537Merge branch 'w55-rename-org' into mainGitoria
  • 014d2b7fOne immutable readers snapshot per move for the left-organization event (#53)mre
  • 1859d506Decide who hears a repo left its organization by its readers before the move (#53)mre
  • 499f25f2Review fixes for the Settings organization move (#53)mre
  • ed3b922b|||PR move a repository into an organization in Settings (#53)mre
  • 74ec2af8Merge branch 'w54-repo-rename-pr' into mainGitoria
  • 9f7ce8d8Preserve rename compatibility and live page titlesmre
  • c3d95b6e|||PR separate names and addresses, rename repositories in Settings (#53)mre
  • ce08920dMerge branch 'w52c-header-phone' into mainGitoria
  • 0bab9e46|||PR header: ident status wraps on phones instead of clippingmre
  • e7af3eceMerge branch 'w52b-approval-followup' into mainGitoria
  • c01e66c6|||PR approvals follow-up: live Merge after status writes, helpers (#52)mre
  • 841da497Merge branch 'w53-pulls-speed-pr' into mainGitoria
  • 80307ae2|||PR pulls page cache: live PR numbers, complete scans onlymre
  • 69141f65|||PR pulls page: cache the git part per repo by branch tipsmre
  • 155861f6Merge branch 'w52-person-approval' into mainGitoria
  • b5435de8|||PR person approvals: second Kunibert round (#52)mre
  • 3a8b2fb8|||PR person approvals: Kunibert review fixes (#52)mre