gitoria
All repositories: gitoria
14.0 KB
// 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// (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// 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// (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.// node tests/protect-main.mjs (GITORIA_PM_PORT default 8731 = gitoria, +2 sshd, +4 ident)import { spawn, spawnSync, execFileSync } from 'node:child_process';import { request } from 'node:http';import { mkdirSync, rmSync, writeFileSync, readFileSync, existsSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import { startIdent } from './identkit.mjs';const APP = resolve(dirname(fileURLToPath(import.meta.url)), '..');const PORT = Number(process.env.GITORIA_PM_PORT || 8731), SSHPORT = PORT + 2, IDENT_PORT = PORT + 4;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')));const STORE = join(APP, '.scratch/protect-main-store'), CONTAINER = 'gitoria-sshd-pmgate', SECRET = 'pm-' + Math.random().toString(16).slice(2);const J = JSON.stringify, sleep = (ms) => new Promise(r => setTimeout(r, ms));let passes = 0, failures = 0;const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + String(detail).slice(0, 600)}`); if (ok) passes++; else failures++; };function raw(method, path, { host = `localhost:${PORT}`, headers = {}, body = null, cookie = null } = {}) {return new Promise((res, rej) => {const h = { host, ...headers }; if (cookie) h.cookie = cookie;if (body !== null) h['content-length'] = Buffer.byteLength(body);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 })); });r.on('error', rej); if (body !== null) r.write(body); r.end();});}let server = null, log = '', ident = null;const cleanup = () => { try { server && server.kill('SIGTERM'); } catch {} spawnSync('docker', ['rm', '-f', CONTAINER]); };process.on('exit', cleanup);try {rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });const alice = await ident.signIn('[email protected]'), bob = await ident.signIn('[email protected]'), carol = await ident.signIn('[email protected]');const BASE = `http://localhost:${PORT}`, GIT = join(STORE, 'git');const app = await ident.registerApp(alice, 'gitoria (protect-main gate)', [BASE]);server = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],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',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 } });server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);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); }const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;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 }; };let n = 0;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; };const A = await login(alice), B = await login(bob), C = await login(carol);await face(A, 'gitoriaSaveName', ['Alice']); await face(B, 'gitoriaSaveName', ['Bob']); await face(C, 'gitoriaSaveName', ['Carol']);const tA = (await face(A, 'gitoriaMakeToken', ['a'])).token;spawnSync('ssh-keygen', ['-q', '-t', 'ed25519', '-N', '', '-C', 'pm@gate', '-f', join(STORE, 'key')]);const added = await face(A, 'gitoriaAddKey', ['gate', readFileSync(join(STORE, 'key.pub'), 'utf8').trim()]);check('alice adds her ssh key', added && !added.error, J(added));spawnSync('docker', ['rm', '-f', CONTAINER]);const built = spawnSync('docker', ['build', '-q', '-t', 'gitoria-sshd-pmgate', join(APP, 'docker/sshd')], { encoding: 'utf8' });check('sshd image builds', built.status === 0, built.stderr);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' });check('sshd container starts', run.status === 0, run.stderr);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); }const W = join(STORE, 'work'); mkdirSync(W, { recursive: true });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',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` };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() }; };const g = (...a) => { const r = git(W, a); if (!r.ok) throw new Error('git ' + a.join(' ') + ': ' + r.err); return r.out; };const bare = (slug, ...a) => git(join(GIT, slug + '.git'), a).out;const HTTPS = (slug) => `http://a:${tA}@${slug}.localhost:${PORT}/${slug}.git`, SSH = (slug) => `ssh://[email protected]:${SSHPORT}/${slug}.git`;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'); };const MSG = /direct pushes to 'main' are refused.*\|\|\|PR.*\/pulls/;g('init', '-q', '-b', 'main'); commit('init');check('alice creates "pm"', !!(await face(A, 'gitoriaCreate', ['pm', 'm'])).repo);await face(A, 'gitoriaChangeMember', ['pm', 'Bob', true]);const settingsPage = async (who) => (await raw('GET', '/settings', { host: `pm.localhost:${PORT}`, cookie: who.cookie })).body;check('settings page: the owner sees the switch, a stranger does not', /id="toggleprotect"/.test(await settingsPage(A)) && !/id="toggleprotect"/.test(await settingsPage(C)));check('settings page: default OFF text', /Anybody who may push can push to the main branch/.test(await settingsPage(A)));// ---- OFF (the default): direct pushes work, HTTPS and ssh, as beforecheck('OFF: https push of main works', git(W, ['push', '-q', HTTPS('pm'), 'main']).ok);const c2 = commit('second');check('OFF: https push (update) of main works', git(W, ['push', '-q', HTTPS('pm'), 'main']).ok && bare('pm', 'rev-parse', 'main') === c2);const c3 = commit('third');check('OFF: ssh push (update) of main works', git(W, ['push', '-q', SSH('pm'), 'main']).ok && bare('pm', 'rev-parse', 'main') === c3);check('OFF: no marker file in the repo', !existsSync(join(GIT, 'pm.git/gitoria-protect')));// ---- only the owner flips itfor (const [who, name] of [[B, 'a member'], [C, 'a stranger'], [null, 'nobody signed in']]) {const r = await face(who, 'gitoriaSetProtect', ['pm', true]);check(`${name} cannot switch it on (refused: ${r && r.error})`, !!(r && r.error) && !existsSync(join(GIT, 'pm.git/gitoria-protect')), J(r));}const on = await face(A, 'gitoriaSetProtect', ['pm', true]);check('the owner switches it on', on && on.protect === true, J(on));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)));const offB = await face(B, 'gitoriaSetProtect', ['pm', false]);check('a member cannot switch it off either', !!(offB && offB.error) && existsSync(join(GIT, 'pm.git/gitoria-protect')), J(offB));// ---- ON: refused with the message, HTTPS and ssh; the branch does not moveconst c4 = commit('direct');for (const [way, url] of [['https', HTTPS('pm')], ['ssh', SSH('pm')]]) {let r = git(W, ['push', url, 'main']);check(`ON: ${way} push (update) of main is refused with the PR message`, !r.ok && MSG.test(r.err), r.err);r = git(W, ['push', '--force', url, 'main']);check(`ON: ${way} force push of main is refused`, !r.ok && MSG.test(r.err), r.err);r = git(W, ['push', url, ':main']);check(`ON: ${way} delete of main is refused`, !r.ok && MSG.test(r.err), r.err);}check('main did not move', bare('pm', 'rev-parse', 'main') === c3);// ---- ON: branches and tags stay allowed; the |||PR way works through push + mergeg('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');check('ON: https push of a branch works', git(W, ['push', '-q', HTTPS('pm'), 'feat']).ok);g('tag', 'v1', sf);check('ON: https push of a tag works', git(W, ['push', '-q', HTTPS('pm'), 'v1']).ok && bare('pm', 'rev-parse', 'v1^{commit}') === sf);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');check('ON: ssh push of a branch works', git(W, ['push', '-q', SSH('pm'), 'feat2']).ok && bare('pm', 'rev-parse', 'feat2') === sf2);g('tag', 'v2', sf2);check('ON: ssh push of a tag works', git(W, ['push', '-q', SSH('pm'), 'v2']).ok);const HOST = `pm.localhost:${PORT}`;const pulls = JSON.parse((await raw('GET', '/api/pulls?state=all', { host: HOST, headers: { authorization: 'Bearer ' + tA } })).body).pulls || [];const p1 = pulls.find(x => x.head === sf), p2 = pulls.find(x => x.head === sf2);check('both |||PR branches became pull requests', !!p1 && !!p2, J(pulls));const m1 = await raw('POST', `/api/pulls/${p1.number}/merge`, { host: HOST, headers: { authorization: 'Bearer ' + tA, 'content-type': 'application/json' }, body: '{}' });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);const m2 = await face(A, 'gitoriaMergePull', ['pm', sf2]);check('ON: merge through the Merge button\'s face works', git(join(GIT, 'pm.git'), ['merge-base', '--is-ancestor', sf2, 'main']).ok, J(m2));check('main moved only by the merges', bare('pm', 'rev-parse', 'main') !== c3);// ---- the creation of main in an empty repo stays allowedcheck('alice creates "pm2" (empty)', !!(await face(A, 'gitoriaCreate', ['pm2', 'm'])).repo);check('pm2: switched on while empty', (await face(A, 'gitoriaSetProtect', ['pm2', true])).protect === true);g('checkout', '-q', 'main');check('ON, empty repo: creating main over https works', git(W, ['push', '-q', HTTPS('pm2'), 'main']).ok && bare('pm2', 'rev-parse', 'main') !== '');g('checkout', '-q', '-b', 'later'); commit('later');check('pm2 now refuses a second push to main', !git(W, ['push', HTTPS('pm2'), 'later:main']).ok);// ---- the setting follows the main branch setting (the PR target): protecting `trunk`, not `main`const mk = await face(A, 'gitoriaSetBranch', ['pm', 'feat2', 'code', '']);check('alice makes feat2 the main branch of pm (the PR target)', !!mk && !mk.error, J(mk));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');g('checkout', '-q', 'feat2'); commit('onto feat2');const rr = git(W, ['push', HTTPS('pm'), 'feat2']);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);g('checkout', '-q', 'main'); commit('main is free now');check('ON: main (no longer the target) accepts a push', git(W, ['push', '--force', '-q', HTTPS('pm'), 'main']).ok);// ---- OFF again: direct push works againconst off = await face(A, 'gitoriaSetProtect', ['pm', false]);check('the owner switches it off', off && off.protect === false && !existsSync(join(GIT, 'pm.git/gitoria-protect')), J(off));g('checkout', '-q', 'feat2'); const c5 = commit('direct again');check('OFF again: https push to the main branch works', git(W, ['push', '-q', HTTPS('pm'), 'feat2']).ok && bare('pm', 'rev-parse', 'feat2') === c5);} catch (e) {check('gate ran to the end', false, String(e && e.stack || e) + '\n' + log.slice(-1500));} finally { cleanup(); try { ident && ident.stop && ident.stop(); } catch {} }console.log(`\n${passes} passed, ${failures} failed`);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