gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit5a996ea85a996ea8gitoria#42: short-lived app tokens, read-only git fetch with them (merge w42-app-token)mre5a996ea8/tests/pull-ssh.mjs

7.7 KB

  1. // tests/pull-ssh.mjs — PULL REQUESTS OVER SSH (gitoria#40 addendum): the REAL sshd container (docker/sshd, built here) around a push.
  2. // gitoria-shell calls /__git/pushed before and after receive-pack: a |||PR commit pushed over ssh gets its number and refs/pull/N/head, the log
  3. // shows `opened` with the pusher's user id; a wrong secret is refused; a push to refs/pull/* over ssh is refused.
  4. // node tests/pull-ssh.mjs (GITORIA_PULLSSH_PORT default 8725, GITORIA_PULLSSH_SSH_PORT default 8726)
  5. import { spawn, spawnSync } from 'node:child_process';
  6. import { request as httpRequest } from 'node:http';
  7. import { rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
  8. import { dirname, join, resolve } from 'node:path';
  9. import { fileURLToPath } from 'node:url';
  10. const APP = resolve(dirname(fileURLToPath(import.meta.url)), '..');
  11. const PORT = Number(process.env.GITORIA_PULLSSH_PORT || 8725), SSHPORT = Number(process.env.GITORIA_PULLSSH_SSH_PORT || 8726);
  12. const STORE = join(APP, '.scratch', 'pullssh-store'), DB = join(STORE, 'db'), GIT = join(STORE, 'git'), WORK = join(STORE, 'work'), KEY = join(STORE, 'key');
  13. const LOG = join(DB, 'pull-changes.log'), SECRET = 'w40-' + Math.random().toString(16).slice(2) + 'ssh', CONTAINER = 'gitoria-sshd-w40gate';
  14. const BIN = join(APP, 'bin/hybriel');
  15. const env = { ...process.env, GITORIA_STORAGE: DB, GITORIA_GIT: GIT, GITORIA_PORT: String(PORT), GITORIA_WATCH: '0', GITORIA_PUBLIC_URL: `http://gitoria.test:${PORT}`, GITORIA_TICKETS_URL: 'http://127.0.0.1:1', GITORIA_SSH_SECRET: SECRET, GITORIA_SSH_PORT: String(SSHPORT) };
  16. let failures = 0, passes = 0;
  17. function check(label, ok, detail = '') { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + String(detail).slice(0, 500)}`); if (ok) passes++; else failures++; }
  18. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  19. const raw = (path, headers) => new Promise((res, rej) => { const r = httpRequest({ host: '127.0.0.1', port: PORT, path, headers: { host: 'gitoria.test', ...headers } }, (x) => { let b = ''; x.on('data', d => b += d); x.on('end', () => res({ status: x.statusCode, body: b })); }); r.on('error', rej); r.end(); });
  20. const gitEnv = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_AUTHOR_NAME: 'Dev', GIT_AUTHOR_EMAIL: '[email protected]', GIT_COMMITTER_NAME: 'Dev', GIT_COMMITTER_EMAIL: '[email protected]',
  21. GIT_SSH_COMMAND: `ssh -i ${KEY} -p ${SSHPORT} -o IdentitiesOnly=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o BatchMode=yes -o LogLevel=ERROR` };
  22. const git = (cwd, args) => { const r = spawnSync('git', args, { cwd, encoding: 'utf8', env: gitEnv }); return { ok: r.status === 0, out: (r.stdout || '').trim(), err: (r.stderr || '').trim() }; };
  23. const must = (cwd, args) => { const r = git(cwd, args); if (!r.ok) throw new Error('git ' + args.join(' ') + ': ' + r.err); return r.out; };
  24. const bareRef = (ref) => git(join(GIT, 'pr-ssh.git'), ['rev-parse', '--verify', '-q', ref]).out;
  25. const changes = () => existsSync(LOG) ? readFileSync(LOG, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l)) : [];
  26. let server = null;
  27. const cleanup = () => { try { server && server.kill('SIGTERM'); } catch {} spawnSync('docker', ['rm', '-f', CONTAINER]); };
  28. process.on('exit', cleanup);
  29. try {
  30. rmSync(STORE, { recursive: true, force: true }); mkdirSync(DB, { recursive: true }); mkdirSync(GIT, { recursive: true }); mkdirSync(WORK, { recursive: true });
  31. spawnSync('ssh-keygen', ['-q', '-t', 'ed25519', '-N', '', '-C', 'w40@gate', '-f', KEY]);
  32. const pub = readFileSync(KEY + '.pub', 'utf8').trim();
  33. const seed = spawnSync(BIN, ['tests/pulls-seed.hl', 'pr-ssh', pub], { cwd: APP, env, encoding: 'utf8' });
  34. const USER = (/USER (\S+)/.exec(seed.stdout) || [])[1];
  35. check('seed: user, repo, ssh key', !!USER, seed.stdout + seed.stderr);
  36. server = spawn(BIN, ['project.hl'], { cwd: APP, env, stdio: ['ignore', 'pipe', 'pipe'] });
  37. let slog = ''; server.stdout.on('data', d => slog += d); server.stderr.on('data', d => slog += d);
  38. for (let i = 0; i < 960; i++) { try { if ((await raw('/api/repos')).status === 200) break; } catch {} await sleep(250); if (i === 959) throw new Error('server did not come up\n' + slog); }
  39. spawnSync('docker', ['rm', '-f', CONTAINER]);
  40. const built = spawnSync('docker', ['build', '-q', '-t', 'gitoria-sshd-w40gate', join(APP, 'docker/sshd')], { encoding: 'utf8' });
  41. check('sshd image builds', built.status === 0, built.stderr);
  42. const run = spawnSync('docker', ['run', '-d', '--rm', '--name', CONTAINER, '--network', 'host', '-e', 'GITORIA_SSH_SECRET=' + SECRET, '-e', 'GITORIA_SSH_PORT=' + SSHPORT, '-e', 'GITORIA_URL=http://127.0.0.1:' + PORT, '-v', GIT + ':/repos', 'gitoria-sshd-w40gate'], { encoding: 'utf8' });
  43. check('sshd container starts', run.status === 0, run.stderr);
  44. for (let i = 0; i < 60; i++) { const r = spawnSync('sh', ['-c', `ssh-keyscan -p ${SSHPORT} 127.0.0.1 2>/dev/null | grep -c ssh-`], { encoding: 'utf8' }); if (Number(r.stdout) > 0) break; await sleep(250); }
  45. check('/__git/pushed with a wrong secret is refused (403)', (await raw(`/__git/pushed?user=${USER}&slug=pr-ssh&phase=after`, { 'x-gitoria-secret': 'nope' })).status === 403);
  46. check('/__git/pushed without a secret is refused (403)', (await raw(`/__git/pushed?user=${USER}&slug=pr-ssh&phase=after`)).status === 403);
  47. check('/__git/pushed from another user is refused (403)', (await raw(`/__git/pushed?user=nobody&slug=pr-ssh&phase=after`, { 'x-gitoria-secret': SECRET })).status === 403);
  48. const W = join(WORK, 'w'); mkdirSync(W); must(W, ['init', '-q', '-b', 'main']);
  49. const U = `ssh://[email protected]:${SSHPORT}/pr-ssh.git`;
  50. writeFileSync(join(W, 'a.txt'), 'a\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', 'base']);
  51. let r = git(W, ['push', U, 'main']);
  52. check('ssh push of main works', r.ok, r.err);
  53. check('no PR → no change', changes().length === 0);
  54. must(W, ['checkout', '-q', '-b', 'f1']); writeFileSync(join(W, 'f1.txt'), '1\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', '|||PR over ssh']);
  55. const a = must(W, ['rev-parse', 'HEAD']);
  56. r = git(W, ['push', U, 'f1']);
  57. check('ssh push of a |||PR branch works (git status kept)', r.ok, r.err);
  58. const ch = changes();
  59. check('log: opened #1 with the pusher\'s user id', ch.length === 1 && ch[0].action === 'opened' && ch[0].number === 1 && ch[0].after === a && ch[0].sender && ch[0].sender.id === USER, JSON.stringify(ch));
  60. check('refs/pull/1/head = the head', bareRef('refs/pull/1/head') === a);
  61. must(W, ['commit', '-q', '--allow-empty', '-m', 'more']);
  62. const b = must(W, ['rev-parse', 'HEAD']);
  63. git(W, ['push', U, 'f1']);
  64. const c2 = changes();
  65. check('second ssh push → synchronize, not forced', c2.length === 2 && c2[1].action === 'synchronize' && c2[1].before === a && c2[1].after === b && c2[1].forced === false && c2[1].sender.id === USER, JSON.stringify(c2));
  66. for (const spec of ['main:refs/pull/1/head', 'main:refs/pull/7/head', ':refs/pull/1/head', `main:refs/pull/1/heads/${'b'.repeat(40)}`]) {
  67. r = git(W, ['push', U, spec]);
  68. check(`ssh push of ${spec.slice(0, 32)} is refused`, !r.ok && /hidden ref|rejected|deny/i.test(r.err), r.err);
  69. }
  70. check('refs/pull/1/head unchanged', bareRef('refs/pull/1/head') === b && bareRef('refs/pull/7/head') === '');
  71. check('refused pushes made no change', changes().length === 2);
  72. // old heads survive gc
  73. must(W, ['reset', '-q', '--hard', 'HEAD~1']); must(W, ['commit', '-q', '--allow-empty', '-m', 'rewritten']);
  74. git(W, ['push', '--force', U, 'f1']);
  75. const gc = git(join(GIT, 'pr-ssh.git'), ['gc', '-q', '--prune=now']);
  76. check('gc ran', gc.ok, gc.err);
  77. check('old head (replaced by a force-push) still resolves after gc --prune=now', git(join(GIT, 'pr-ssh.git'), ['cat-file', '-e', b + '^{commit}']).ok);
  78. } catch (e) {
  79. check('gate ran to the end', false, String(e && e.stack || e));
  80. } finally { cleanup(); }
  81. console.log(`\n${passes} passed, ${failures} failed`);
  82. process.exit(failures ? 1 : 0);

Branches

Latest commits

  • 5a996ea8gitoria#42: short-lived app tokens, read-only git fetch with them (merge w42-app-token)mre
  • b5d696fegitoria#42: app tokens (gat_, one hour), appOfRequest, app token as the git read passwordmre
  • 1997e77dgitoria#40: stable PR numbers, refs/pull/N/head, ssh pushes reach the app (merge w40-pr-number)mre
  • 9364fb16gitoria#40: ssh pushes call /__git/pushed before and after (ensurePulls, notifyPush, syncPulls); gate over the sshd imagemre
  • fdb9ed28gitoria#41: repo owners can connect an app (merge w41-apps-connect)mre
  • 2ef23df0gitoria#40: the browser gate reads the title without the #Nmre
  • 9af07ecegitoria#41: connect an app to a repo (apps table, connect flow, manual add, allow-list, settings)mre
  • b9137ff0gitoria#40: pull requests are stored with a number, refs/pull/N/head, syncPulls and pullObject; /pulls shows #Nmre
  • 06d622daown image tag gitoria-runtime:debian12 for gitoria and standby (shared tag lost git)mre
  • 20caa33agitoria#37: media queries in the language's @media block (minWidth = '60rem') in list, codebrowser and repomre
  • c4175e6dgitoria: a startup error prints its message before exit 1 (hybriel#247)mre
  • c50d17efKeep function-route not-found style in shared stylesheetmre
  • e42d78d3Preserve ticket state CSS and document function-route style gapmre
  • c6b7154eWIP gitoria#26: move styles into nested component blocksmre
  • 77a2c31cgitoria#31: plain declarations instead of needless let in lib/ and tools/ (103 let removed, 137 kept because reassigned); no other changemre
  • 4b98ab62gitoria: an ident access key (idt_) works as the git password; read key clones only, bad key 401, ident down 503 (ident#27); gate tests/ident-access-gitoria.mjs in deploy.shmre
  • 1185f686gitoria#36: a failed return from tickets shows a note on the settings page and leaves one log line per outcome; no code is exchangedmre
  • 5d2c385agitoria: the sign-in callback keeps the session it finds and signs it in (same cookie, nothing signed out; ident#28); security gate 71+5 failing → 76 passed; deploy.sh runs tests/private.mjs toomre
  • 241ef3f9deploy.sh: rebuild the sshd image before up -d (GO34c)mre
  • 821cdbb1gitoria#34b: styles, create-repo tool, docs, push/ssh gates sign in through the selector, shots scriptmre