gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmainfe209ffeMerge branch 'w56-owner-members' into mainGitoriamain/tests/pull-ssh.mjs

9.5 KB

  1. import { requiredPort } from './gate-ports.mjs';
  2. // tests/pull-ssh.mjs — PULL REQUESTS OVER SSH (gitoria#40 addendum): the REAL sshd container (docker/sshd, built here) around a push.
  3. // 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
  4. // shows `opened` with the pusher's user id; a wrong secret is refused; a push to refs/pull/* over ssh is refused.
  5. // node tests/pull-ssh.mjs (GITORIA_PULLSSH_PORT required, GITORIA_PULLSSH_SSH_PORT required)
  6. import { spawn, spawnSync } from 'node:child_process';
  7. import { request as httpRequest } from 'node:http';
  8. import { rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
  9. import { dirname, join, resolve } from 'node:path';
  10. import { fileURLToPath } from 'node:url';
  11. const APP = resolve(dirname(fileURLToPath(import.meta.url)), '..');
  12. const PORT = requiredPort('GITORIA_PULLSSH_PORT'), SSHPORT = requiredPort('GITORIA_PULLSSH_SSH_PORT');
  13. const STORE = join(APP, '.scratch', 'pullssh-store'), DB = join(STORE, 'db'), GIT = join(STORE, 'git'), WORK = join(STORE, 'work'), KEY = join(STORE, 'key');
  14. const LOG = join(DB, 'pull-changes.log'), SECRET = 'w40-' + Math.random().toString(16).slice(2) + 'ssh', CONTAINER = 'gitoria-sshd-w40gate';
  15. const BIN = join(APP, 'bin/hybriel');
  16. 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) };
  17. let failures = 0, passes = 0;
  18. function check(label, ok, detail = '') { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + String(detail).slice(0, 500)}`); if (ok) passes++; else failures++; }
  19. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  20. 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(); });
  21. 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]',
  22. GIT_SSH_COMMAND: `ssh -i ${KEY} -p ${SSHPORT} -o IdentitiesOnly=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o BatchMode=yes -o LogLevel=ERROR` };
  23. 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() }; };
  24. const must = (cwd, args) => { const r = git(cwd, args); if (!r.ok) throw new Error('git ' + args.join(' ') + ': ' + r.err); return r.out; };
  25. const bareRef = (ref) => git(join(GIT, 'pr-ssh.git'), ['rev-parse', '--verify', '-q', ref]).out;
  26. const changes = () => existsSync(LOG) ? readFileSync(LOG, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l)) : [];
  27. let server = null;
  28. const cleanup = () => { try { server && server.kill('SIGTERM'); } catch {} spawnSync('docker', ['rm', '-f', CONTAINER]); };
  29. process.on('exit', cleanup);
  30. try {
  31. rmSync(STORE, { recursive: true, force: true }); mkdirSync(DB, { recursive: true }); mkdirSync(GIT, { recursive: true }); mkdirSync(WORK, { recursive: true });
  32. spawnSync('ssh-keygen', ['-q', '-t', 'ed25519', '-N', '', '-C', 'w40@gate', '-f', KEY]);
  33. const pub = readFileSync(KEY + '.pub', 'utf8').trim();
  34. const seed = spawnSync(BIN, ['tests/pulls-seed.hl', 'pr-ssh', pub], { cwd: APP, env, encoding: 'utf8' });
  35. const USER = (/USER (\S+)/.exec(seed.stdout) || [])[1];
  36. check('seed: user, repo, ssh key', !!USER, seed.stdout + seed.stderr);
  37. server = spawn(BIN, ['project.hl'], { cwd: APP, env, stdio: ['ignore', 'pipe', 'pipe'] });
  38. let slog = ''; server.stdout.on('data', d => slog += d); server.stderr.on('data', d => slog += d);
  39. 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); }
  40. spawnSync('docker', ['rm', '-f', CONTAINER]);
  41. const built = spawnSync('docker', ['build', '-q', '-t', 'gitoria-sshd-w40gate', join(APP, 'docker/sshd')], { encoding: 'utf8' });
  42. check('sshd image builds', built.status === 0, built.stderr);
  43. 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' });
  44. check('sshd container starts', run.status === 0, run.stderr);
  45. 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); }
  46. 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);
  47. check('/__git/pushed without a secret is refused (403)', (await raw(`/__git/pushed?user=${USER}&slug=pr-ssh&phase=after`)).status === 403);
  48. 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);
  49. const W = join(WORK, 'w'); mkdirSync(W); must(W, ['init', '-q', '-b', 'main']);
  50. const U = `ssh://[email protected]:${SSHPORT}/pr-ssh.git`;
  51. writeFileSync(join(W, 'a.txt'), 'a\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', 'base']);
  52. let r = git(W, ['push', U, 'main']);
  53. check('ssh push of main works', r.ok, r.err);
  54. check('no PR → no change', changes().length === 0);
  55. await raw('/pulls', { host: 'pr-ssh.gitoria.test' });
  56. must(W, ['checkout', '-q', '-b', 'f1']); writeFileSync(join(W, 'f1.txt'), '1\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', '|||PR over ssh']);
  57. const a = must(W, ['rev-parse', 'HEAD']);
  58. r = git(W, ['push', U, 'f1']);
  59. check('ssh push of a |||PR branch works (git status kept)', r.ok, r.err);
  60. const nextPage = await raw('/pulls', { host: 'pr-ssh.gitoria.test' });
  61. check('SSH push appears on the next /pulls view', nextPage.status === 200 && nextPage.body.includes('over ssh'));
  62. const ch = changes();
  63. 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));
  64. check('refs/pull/1/head = the head', bareRef('refs/pull/1/head') === a);
  65. must(W, ['commit', '-q', '--allow-empty', '-m', 'more']);
  66. const b = must(W, ['rev-parse', 'HEAD']);
  67. git(W, ['push', U, 'f1']);
  68. const c2 = changes();
  69. 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));
  70. 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)}`]) {
  71. r = git(W, ['push', U, spec]);
  72. check(`ssh push of ${spec.slice(0, 32)} is refused`, !r.ok && /hidden ref|rejected|deny/i.test(r.err), r.err);
  73. }
  74. check('refs/pull/1/head unchanged', bareRef('refs/pull/1/head') === b && bareRef('refs/pull/7/head') === '');
  75. check('refused pushes made no change', changes().length === 2);
  76. // old heads survive gc
  77. must(W, ['reset', '-q', '--hard', 'HEAD~1']); must(W, ['commit', '-q', '--allow-empty', '-m', 'rewritten']);
  78. git(W, ['push', '--force', U, 'f1']);
  79. const gc = git(join(GIT, 'pr-ssh.git'), ['gc', '-q', '--prune=now']);
  80. check('gc ran', gc.ok, gc.err);
  81. 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);
  82. // W54: the shared move function's forward also serves the real SSH transport.
  83. const oldServer = server; server = null; oldServer.kill('SIGTERM'); await new Promise(resolve => oldServer.once('exit', resolve));
  84. const moved = spawnSync(BIN, ['tools/move-repo.hl', 'pr-ssh', 'pr-ssh-renamed', 'public'], { cwd: APP, env, encoding: 'utf8' });
  85. check('shared move tool renames SSH fixture', moved.status === 0, moved.stderr);
  86. server = spawn(BIN, ['project.hl'], { cwd: APP, env, stdio: ['ignore', 'pipe', 'pipe'] });
  87. server.stdout.on('data', d => slog += d); server.stderr.on('data', d => slog += d);
  88. 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('renamed server did not come up'); }
  89. const clone = join(WORK, 'old-url-clone');
  90. r = git(WORK, ['clone', '-q', U, clone]);
  91. check('old SSH URL clones after rename', r.ok && existsSync(join(clone, 'a.txt')), r.err);
  92. must(W, ['commit', '-q', '--allow-empty', '-m', 'push through old SSH name']);
  93. const renamedHead = must(W, ['rev-parse', 'HEAD']);
  94. r = git(W, ['push', U, 'HEAD:renamed-ssh']);
  95. check('old SSH URL pushes into new folder', r.ok && git(join(GIT, 'pr-ssh-renamed.git'), ['rev-parse', 'renamed-ssh']).out === renamedHead, r.err);
  96. r = git(clone, ['fetch', '-q', 'origin']);
  97. check('old SSH URL fetches after renamed push', r.ok && git(clone, ['rev-parse', 'origin/renamed-ssh']).out === renamedHead, r.err);
  98. } catch (e) {
  99. check('gate ran to the end', false, String(e && e.stack || e));
  100. } finally { cleanup(); }
  101. console.log(`\n${passes} passed, ${failures} failed`);
  102. 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