gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit477d7bdc477d7bdcMerge branch 'p50'mre477d7bdc/tests/protect-main.mjs

14.0 KB

  1. // tests/protect-main.mjs — "REFUSE DIRECT PUSHES TO THE MAIN BRANCH" (gitoria#50): the owner's repo setting, enforced by the server's pre-receive hook
  2. // (docker/sshd/hooks/pre-receive) over HTTPS and over the REAL sshd container. Off (default): a direct push to main works. On: an update or a delete of main is
  3. // refused with the message naming the PR way; other branches, tags and the creation of main in an empty repo stay allowed; the |||PR branch is pushed and merged
  4. // (API and Merge-button face) as before. Only the owner may flip the setting. Real HTTP, real git, ident + docker like pull-ssh.mjs / member-merge.mjs.
  5. // node tests/protect-main.mjs (GITORIA_PM_PORT default 8731 = gitoria, +2 sshd, +4 ident)
  6. import { spawn, spawnSync, execFileSync } from 'node:child_process';
  7. import { request } from 'node:http';
  8. import { mkdirSync, rmSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
  9. import { dirname, join, resolve } from 'node:path';
  10. import { fileURLToPath } from 'node:url';
  11. import { startIdent } from './identkit.mjs';
  12. const APP = resolve(dirname(fileURLToPath(import.meta.url)), '..');
  13. const PORT = Number(process.env.GITORIA_PM_PORT || 8731), SSHPORT = PORT + 2, IDENT_PORT = PORT + 4;
  14. 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')));
  15. const STORE = join(APP, '.scratch/protect-main-store'), CONTAINER = 'gitoria-sshd-pmgate', SECRET = 'pm-' + Math.random().toString(16).slice(2);
  16. const J = JSON.stringify, sleep = (ms) => new Promise(r => setTimeout(r, ms));
  17. let passes = 0, failures = 0;
  18. const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + String(detail).slice(0, 600)}`); if (ok) passes++; else failures++; };
  19. function raw(method, path, { host = `localhost:${PORT}`, headers = {}, body = null, cookie = null } = {}) {
  20. return new Promise((res, rej) => {
  21. const h = { host, ...headers }; if (cookie) h.cookie = cookie;
  22. if (body !== null) h['content-length'] = Buffer.byteLength(body);
  23. 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, body: Buffer.concat(c).toString('utf8'), headers: m.headers })); });
  24. r.on('error', rej); if (body !== null) r.write(body); r.end();
  25. });
  26. }
  27. let server = null, log = '', ident = 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(STORE, { recursive: true });
  32. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  33. const alice = await ident.signIn('[email protected]'), bob = await ident.signIn('[email protected]'), carol = await ident.signIn('[email protected]');
  34. const BASE = `http://localhost:${PORT}`, GIT = join(STORE, 'git');
  35. const app = await ident.registerApp(alice, 'gitoria (protect-main gate)', [BASE]);
  36. server = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],
  37. env: { ...process.env, GITORIA_PORT: String(PORT), GITORIA_WATCH: '0', GITORIA_PUBLIC_URL: BASE, GITORIA_SSH_SECRET: SECRET, GITORIA_SSH_PORT: String(SSHPORT), GITORIA_TICKETS_URL: 'http://127.0.0.1:1',
  38. GITORIA_STORAGE: join(STORE, 'mpackdb'), GITORIA_SESSIONS: join(STORE, 'sessions') + '/', GITORIA_GIT: GIT, IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base, IDENT_API_KEY: app.key, IDENT_API_SECRET: app.secret } });
  39. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  40. for (let i = 0; i < 960; i++) { try { if ((await raw('GET', '/api/repos')).status === 200) break; } catch {} await sleep(250); if (i === 959) throw new Error('gitoria did not come up\n' + log); }
  41. const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;
  42. const login = async (who) => { const ck = cookieOf(await raw('GET', '/')); const cb = await raw('GET', '/login/callback?ident_code=' + await ident.selectorCode(who, app, BASE) + '&next=%2F', { cookie: ck }); return { cookie: cookieOf(cb) || ck }; };
  43. let n = 0;
  44. const face = async (who, event, payload) => { const r = await raw('POST', '/__hl/emit', { headers: { 'content-type': 'application/json' }, cookie: who && who.cookie, body: J({ t: 'emit', i: ++n, event, payload }) }); let j = null; try { j = JSON.parse(r.body); } catch {} return j && j.value; };
  45. const A = await login(alice), B = await login(bob), C = await login(carol);
  46. await face(A, 'gitoriaSaveName', ['Alice']); await face(B, 'gitoriaSaveName', ['Bob']); await face(C, 'gitoriaSaveName', ['Carol']);
  47. const tA = (await face(A, 'gitoriaMakeToken', ['a'])).token;
  48. spawnSync('ssh-keygen', ['-q', '-t', 'ed25519', '-N', '', '-C', 'pm@gate', '-f', join(STORE, 'key')]);
  49. const added = await face(A, 'gitoriaAddKey', ['gate', readFileSync(join(STORE, 'key.pub'), 'utf8').trim()]);
  50. check('alice adds her ssh key', added && !added.error, J(added));
  51. spawnSync('docker', ['rm', '-f', CONTAINER]);
  52. const built = spawnSync('docker', ['build', '-q', '-t', 'gitoria-sshd-pmgate', join(APP, 'docker/sshd')], { encoding: 'utf8' });
  53. check('sshd image builds', built.status === 0, built.stderr);
  54. 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-pmgate'], { encoding: 'utf8' });
  55. check('sshd container starts', run.status === 0, run.stderr);
  56. 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); }
  57. const W = join(STORE, 'work'); mkdirSync(W, { recursive: true });
  58. 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',
  59. GIT_SSH_COMMAND: `ssh -i ${join(STORE, 'key')} -p ${SSHPORT} -o IdentitiesOnly=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o BatchMode=yes -o LogLevel=ERROR` };
  60. const git = (cwd, args) => { const r = spawnSync('git', args, { cwd, encoding: 'utf8', env: genv }); return { ok: r.status === 0, out: (r.stdout || '').trim(), err: (r.stderr || '').trim() }; };
  61. const g = (...a) => { const r = git(W, a); if (!r.ok) throw new Error('git ' + a.join(' ') + ': ' + r.err); return r.out; };
  62. const bare = (slug, ...a) => git(join(GIT, slug + '.git'), a).out;
  63. const HTTPS = (slug) => `http://a:${tA}@${slug}.localhost:${PORT}/${slug}.git`, SSH = (slug) => `ssh://[email protected]:${SSHPORT}/${slug}.git`;
  64. const commit = (msg) => { writeFileSync(join(W, 'f.txt'), msg + Math.random() + '\n'); g('add', '-A'); g('commit', '-q', '-m', msg); return g('rev-parse', 'HEAD'); };
  65. const MSG = /direct pushes to 'main' are refused.*\|\|\|PR.*\/pulls/;
  66. g('init', '-q', '-b', 'main'); commit('init');
  67. check('alice creates "pm"', !!(await face(A, 'gitoriaCreate', ['pm', 'm'])).repo);
  68. await face(A, 'gitoriaChangeMember', ['pm', 'Bob', true]);
  69. const settingsPage = async (who) => (await raw('GET', '/settings', { host: `pm.localhost:${PORT}`, cookie: who.cookie })).body;
  70. check('settings page: the owner sees the switch, a stranger does not', /id="toggleprotect"/.test(await settingsPage(A)) && !/id="toggleprotect"/.test(await settingsPage(C)));
  71. check('settings page: default OFF text', /Anybody who may push can push to the main branch/.test(await settingsPage(A)));
  72. // ---- OFF (the default): direct pushes work, HTTPS and ssh, as before
  73. check('OFF: https push of main works', git(W, ['push', '-q', HTTPS('pm'), 'main']).ok);
  74. const c2 = commit('second');
  75. check('OFF: https push (update) of main works', git(W, ['push', '-q', HTTPS('pm'), 'main']).ok && bare('pm', 'rev-parse', 'main') === c2);
  76. const c3 = commit('third');
  77. check('OFF: ssh push (update) of main works', git(W, ['push', '-q', SSH('pm'), 'main']).ok && bare('pm', 'rev-parse', 'main') === c3);
  78. check('OFF: no marker file in the repo', !existsSync(join(GIT, 'pm.git/gitoria-protect')));
  79. // ---- only the owner flips it
  80. for (const [who, name] of [[B, 'a member'], [C, 'a stranger'], [null, 'nobody signed in']]) {
  81. const r = await face(who, 'gitoriaSetProtect', ['pm', true]);
  82. check(`${name} cannot switch it on (refused: ${r && r.error})`, !!(r && r.error) && !existsSync(join(GIT, 'pm.git/gitoria-protect')), J(r));
  83. }
  84. const on = await face(A, 'gitoriaSetProtect', ['pm', true]);
  85. check('the owner switches it on', on && on.protect === true, J(on));
  86. check('settings page: ON text and the button to allow', /Direct pushes to the main branch are refused/.test(await settingsPage(A)) && /Allow direct pushes/.test(await settingsPage(A)));
  87. const offB = await face(B, 'gitoriaSetProtect', ['pm', false]);
  88. check('a member cannot switch it off either', !!(offB && offB.error) && existsSync(join(GIT, 'pm.git/gitoria-protect')), J(offB));
  89. // ---- ON: refused with the message, HTTPS and ssh; the branch does not move
  90. const c4 = commit('direct');
  91. for (const [way, url] of [['https', HTTPS('pm')], ['ssh', SSH('pm')]]) {
  92. let r = git(W, ['push', url, 'main']);
  93. check(`ON: ${way} push (update) of main is refused with the PR message`, !r.ok && MSG.test(r.err), r.err);
  94. r = git(W, ['push', '--force', url, 'main']);
  95. check(`ON: ${way} force push of main is refused`, !r.ok && MSG.test(r.err), r.err);
  96. r = git(W, ['push', url, ':main']);
  97. check(`ON: ${way} delete of main is refused`, !r.ok && MSG.test(r.err), r.err);
  98. }
  99. check('main did not move', bare('pm', 'rev-parse', 'main') === c3);
  100. // ---- ON: branches and tags stay allowed; the |||PR way works through push + merge
  101. g('checkout', '-q', '-b', 'feat'); writeFileSync(join(W, 'feat.txt'), 'x\n'); g('add', '-A'); g('commit', '-q', '-m', '|||PR add feat'); const sf = g('rev-parse', 'HEAD');
  102. check('ON: https push of a branch works', git(W, ['push', '-q', HTTPS('pm'), 'feat']).ok);
  103. g('tag', 'v1', sf);
  104. check('ON: https push of a tag works', git(W, ['push', '-q', HTTPS('pm'), 'v1']).ok && bare('pm', 'rev-parse', 'v1^{commit}') === sf);
  105. g('checkout', '-q', '-b', 'feat2', 'main'); writeFileSync(join(W, 'feat2.txt'), 'y\n'); g('add', '-A'); g('commit', '-q', '-m', '|||PR second via ssh'); const sf2 = g('rev-parse', 'HEAD');
  106. check('ON: ssh push of a branch works', git(W, ['push', '-q', SSH('pm'), 'feat2']).ok && bare('pm', 'rev-parse', 'feat2') === sf2);
  107. g('tag', 'v2', sf2);
  108. check('ON: ssh push of a tag works', git(W, ['push', '-q', SSH('pm'), 'v2']).ok);
  109. const HOST = `pm.localhost:${PORT}`;
  110. const pulls = JSON.parse((await raw('GET', '/api/pulls?state=all', { host: HOST, headers: { authorization: 'Bearer ' + tA } })).body).pulls || [];
  111. const p1 = pulls.find(x => x.head === sf), p2 = pulls.find(x => x.head === sf2);
  112. check('both |||PR branches became pull requests', !!p1 && !!p2, J(pulls));
  113. const m1 = await raw('POST', `/api/pulls/${p1.number}/merge`, { host: HOST, headers: { authorization: 'Bearer ' + tA, 'content-type': 'application/json' }, body: '{}' });
  114. check('ON: merge through the API works (not a push)', m1.status === 200 && bare('pm', 'merge-base', '--is-ancestor', sf, 'main') === '' && git(join(GIT, 'pm.git'), ['merge-base', '--is-ancestor', sf, 'main']).ok, m1.status + m1.body);
  115. const m2 = await face(A, 'gitoriaMergePull', ['pm', sf2]);
  116. check('ON: merge through the Merge button\'s face works', git(join(GIT, 'pm.git'), ['merge-base', '--is-ancestor', sf2, 'main']).ok, J(m2));
  117. check('main moved only by the merges', bare('pm', 'rev-parse', 'main') !== c3);
  118. // ---- the creation of main in an empty repo stays allowed
  119. check('alice creates "pm2" (empty)', !!(await face(A, 'gitoriaCreate', ['pm2', 'm'])).repo);
  120. check('pm2: switched on while empty', (await face(A, 'gitoriaSetProtect', ['pm2', true])).protect === true);
  121. g('checkout', '-q', 'main');
  122. check('ON, empty repo: creating main over https works', git(W, ['push', '-q', HTTPS('pm2'), 'main']).ok && bare('pm2', 'rev-parse', 'main') !== '');
  123. g('checkout', '-q', '-b', 'later'); commit('later');
  124. check('pm2 now refuses a second push to main', !git(W, ['push', HTTPS('pm2'), 'later:main']).ok);
  125. // ---- the setting follows the main branch setting (the PR target): protecting `trunk`, not `main`
  126. const mk = await face(A, 'gitoriaSetBranch', ['pm', 'feat2', 'code', '']);
  127. check('alice makes feat2 the main branch of pm (the PR target)', !!mk && !mk.error, J(mk));
  128. check('the marker (switched on) now names feat2', (await face(A, 'gitoriaSetProtect', ['pm', true])).protect === true && readFileSync(join(GIT, 'pm.git/gitoria-protect'), 'utf8').trim() === 'feat2', existsSync(join(GIT, 'pm.git/gitoria-protect')) ? JSON.stringify(readFileSync(join(GIT, 'pm.git/gitoria-protect'), 'utf8')) : 'no file');
  129. g('checkout', '-q', 'feat2'); commit('onto feat2');
  130. const rr = git(W, ['push', HTTPS('pm'), 'feat2']);
  131. check('ON: the PR target branch (feat2) is the protected one, main is not', !rr.ok && /direct pushes to 'feat2' are refused/.test(rr.err), rr.err);
  132. g('checkout', '-q', 'main'); commit('main is free now');
  133. check('ON: main (no longer the target) accepts a push', git(W, ['push', '--force', '-q', HTTPS('pm'), 'main']).ok);
  134. // ---- OFF again: direct push works again
  135. const off = await face(A, 'gitoriaSetProtect', ['pm', false]);
  136. check('the owner switches it off', off && off.protect === false && !existsSync(join(GIT, 'pm.git/gitoria-protect')), J(off));
  137. g('checkout', '-q', 'feat2'); const c5 = commit('direct again');
  138. check('OFF again: https push to the main branch works', git(W, ['push', '-q', HTTPS('pm'), 'feat2']).ok && bare('pm', 'rev-parse', 'feat2') === c5);
  139. } catch (e) {
  140. check('gate ran to the end', false, String(e && e.stack || e) + '\n' + log.slice(-1500));
  141. } finally { cleanup(); try { ident && ident.stop && ident.stop(); } catch {} }
  142. console.log(`\n${passes} passed, ${failures} failed`);
  143. process.exit(failures ? 1 : 0);

Branches

Latest commits

  • 477d7bdcMerge branch 'p50'mre
  • 00efc06fP50 reportmre
  • e3f85afblog: commit mention slipmre
  • 4d1a4cf4log: #25 numbersmre
  • 1af0a60ddocs: H25 run() correctionmre
  • eefa2dbcRepo setting: refuse direct pushes to the main branch (pre-receive over HTTPS and ssh)mre
  • 8c8ba2f1log: PR flow announcedmre
  • fa00cd35log: Kunibert pings provenmre
  • 3a68cfaclog: components decisionmre
  • 87de8e31log: Kunibert connected to 9 app reposmre
  • c22aff69log: PR-only rollout startedmre
  • 25309981log: STOP and paused workers 2026-11-08mre
  • 5286803alog: worker briefs and reports of 2026-11-08mre
  • 85c86605log: 2026-11-08 Arachne on list shapemre
  • cb634512log: 2026-11-08 keyed lists livemre
  • 07c98d4aLists: keyed rows with @id, remove(id) and one whole-list assignment instead of hand-rebuilt loopsmre
  • 0db0d81elog: 2026-11-08 day52 live, W30 startedmre
  • b05f6d92tests/status: the gate's 3 s app token expired during the restart; it lives 60 s like status-keyedmre
  • 1e8f4f0avendor: Hybriel set-day52 (fault-path leak fix #335, keyed rows #331)mre
  • f5f0fb7blog: 2026-11-08 day50/#29 live, H25 correction, V52 startedmre