gitoria

gitoria

All repositories: gitoria

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

27.0 KB

  1. import { requiredPort } from './gate-ports.mjs';
  2. // tests/events.mjs — GATE OF THE SIGNED EVENTS (gitoria#43): a tiny local receiver, a real local gitoria + its own ident, the REAL git binary over HTTPS-style push.
  3. // pull_request opened / synchronize (forced) / merged (the Merge button) / closed, ping (at connect and "Send ping"), the signature verified by the receiver
  4. // (and proved against RFC 4231 case 2 and `openssl dgst -hmac`), retries with the same delivery id, redirects not followed, no delivery to another repo's app,
  5. // a push that does not wait for a hanging receiver, a second process on the same storage that sends nothing twice, the retention.
  6. // node tests/events.mjs (ports: GITORIA_EVENTS_PORT 8720 = gitoria, +1 receiver, +3 second gitoria, +4 ident)
  7. import { spawn, spawnSync } from 'node:child_process';
  8. import { request, createServer } from 'node:http';
  9. import { createHmac } from 'node:crypto';
  10. import { mkdirSync, rmSync, writeFileSync, existsSync, readdirSync } 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 HERE = dirname(fileURLToPath(import.meta.url));
  15. const APP = resolve(HERE, '..');
  16. const PORT = requiredPort('GITORIA_EVENTS_PORT'), RPORT = PORT + 1, PORT2 = process.env.GITORIA_EVENTS_PORT2 ? requiredPort('GITORIA_EVENTS_PORT2') : PORT + 3, IDENT_PORT = process.env.GITORIA_EVENTS_IDENT_PORT ? requiredPort('GITORIA_EVENTS_IDENT_PORT') : PORT + 4;
  17. 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')));
  18. const STORE = join(APP, '.scratch/events-store');
  19. const DB = join(STORE, 'mpackdb'), GIT = join(STORE, 'git'), WORK = join(STORE, 'work');
  20. const BIN = join(APP, 'bin/hybriel');
  21. const J = JSON.stringify, sleep = (ms) => new Promise(r => setTimeout(r, ms));
  22. let passes = 0, failures = 0;
  23. const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + String(detail).slice(0, 500)}`); if (ok) passes++; else failures++; };
  24. const waitFor = async (fn, ms = 20000) => { const t0 = Date.now(); for (;;) { const v = await fn(); if (v) return v; if (Date.now() - t0 > ms) return null; await sleep(100); } };
  25. // ---- the receiver: records every request; mode = ok | drop (connection cut) | 500 | hang | redirect
  26. const got = []; // { path, headers, body }
  27. let mode = 'ok', dropFirst = 0, redirectHits = 0;
  28. const receiver = createServer((req, res) => {
  29. const c = []; req.on('data', d => c.push(d));
  30. req.on('end', () => {
  31. const body = Buffer.concat(c);
  32. if (req.url.startsWith('/elsewhere')) { redirectHits++; res.end('moved here'); return; }
  33. got.push({ path: req.url, headers: req.headers, body, at: Date.now() });
  34. if (mode === 'hang') return;
  35. if (mode === 'drop' || dropFirst > 0) { if (dropFirst > 0) dropFirst--; req.socket.destroy(); return; }
  36. if (mode === '500') { res.statusCode = 500; res.end('no'); return; }
  37. if (mode === 'redirect') { res.statusCode = 302; res.setHeader('location', `http://127.0.0.1:${RPORT}/elsewhere`); res.end(); return; }
  38. res.statusCode = 204; res.end();
  39. });
  40. });
  41. await new Promise(r => receiver.listen(RPORT, '127.0.0.1', r));
  42. function raw(port, method, path, { host = `localhost:${port}`, headers = {}, body = null, cookie = null } = {}) {
  43. return new Promise((res, rej) => {
  44. const h = { host, ...headers }; if (cookie) h.cookie = cookie;
  45. if (body !== null) h['content-length'] = Buffer.byteLength(body);
  46. const r = request({ host: '127.0.0.1', 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') })); });
  47. r.on('error', rej); if (body !== null) r.write(body); r.end();
  48. });
  49. }
  50. 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]' };
  51. 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() }; };
  52. const must = (cwd, args) => { const r = git(cwd, args); if (!r.ok) throw new Error('git ' + args.join(' ') + ': ' + r.err); return r.out; };
  53. const procs = [];
  54. function spawnServer(port, extra = {}) {
  55. let log = '';
  56. const p = spawn(BIN, ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, GITORIA_PORT: String(port), GITORIA_WATCH: '0', GITORIA_PUBLIC_URL: `http://localhost:${PORT}`, GITORIA_SSH_SECRET: 'sshsecret-events-gate', GITORIA_TICKETS_URL: 'http://127.0.0.1:1',
  57. GITORIA_APP_HOSTS: `http://127.0.0.1:${RPORT}`, GITORIA_EVENTS_TICK: '0.3', GITORIA_EVENTS_RETRY_MS: '1500,1500,1500', ...extra } });
  58. p.stdout.on('data', d => log += d); p.stderr.on('data', d => log += d); procs.push(p);
  59. return { p, log: () => log };
  60. }
  61. async function up(port, srv) { for (let i = 0; i < 960; i++) { try { if ((await raw(port, 'GET', '/api/repos')).status === 200) return; } catch {} await sleep(250); } throw new Error('gitoria did not come up\n' + srv.log()); }
  62. const cleanup = () => { for (const p of procs) try { p.kill('SIGTERM'); } catch {} try { receiver.close(); } catch {} };
  63. process.on('exit', cleanup);
  64. let ident, s1 = null;
  65. try {
  66. rmSync(STORE, { recursive: true, force: true }); mkdirSync(DB, { recursive: true }); mkdirSync(GIT, { recursive: true }); mkdirSync(WORK, { recursive: true });
  67. const probeEnv = { ...process.env, GITORIA_STORAGE: DB, GITORIA_GIT: GIT };
  68. const probe = (...a) => { const r = spawnSync(BIN, ['tests/events-probe.hl', ...a], { cwd: APP, env: probeEnv, encoding: 'utf8' }); return r.stdout + r.stderr; };
  69. // ---- 0. the signature: RFC 4231 test case 2, openssl, a uuid
  70. const sig = (secret, text) => (/SIG (\S+)/.exec(probe('sign', secret, text)) || [])[1];
  71. check('HMAC-SHA256 RFC 4231 case 2 (key "Jefe") through hl:crypto hkdfExtract', sig('Jefe', 'what do ya want for nothing?') === 'sha256=5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843', sig('Jefe', 'what do ya want for nothing?'));
  72. const sk = 'a1b2c3d4'.repeat(8), txt = '{"title":"Ünï ✓","n":1}';
  73. const ossl = spawnSync('openssl', ['dgst', '-sha256', '-hmac', sk], { input: txt, encoding: 'utf8' }).stdout.trim().split(' ').pop();
  74. check('cross-check with `openssl dgst -sha256 -hmac` (64-hex secret as ASCII key, UTF-8 body)', sig(sk, txt) === 'sha256=' + ossl, sig(sk, txt) + ' vs ' + ossl);
  75. const u = (/UUID (\S+)/.exec(probe('uuid')) || [])[1] || '';
  76. check('a delivery id is a uuid v4', /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(u), u);
  77. // ---- the servers
  78. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  79. const alice = await ident.signIn('[email protected]'), bob = await ident.signIn('[email protected]');
  80. const BASE = `http://localhost:${PORT}`;
  81. const app = await ident.registerApp(alice, 'gitoria (events gate)', [BASE]);
  82. const ENV = { GITORIA_STORAGE: DB, 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 };
  83. s1 = spawnServer(PORT, ENV); await up(PORT, s1);
  84. const get = (path, o = {}) => raw(PORT, 'GET', path, o);
  85. const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;
  86. const login = async (who) => { const ck = cookieOf(await get('/')); const code = await ident.selectorCode(who, app, BASE); const cb = await get('/login/callback?ident_code=' + code + '&next=%2F', { cookie: ck }); return { cookie: cookieOf(cb) || ck }; };
  87. let n = 0;
  88. const face = async (who, event, payload) => { const r = await raw(PORT, '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 { status: r.status, value: j && j.value }; };
  89. const A = await login(alice), B = await login(bob);
  90. await face(A, 'gitoriaSaveName', ['Alice Ünï']); await face(B, 'gitoriaSaveName', ['Bob']);
  91. const token = (await face(A, 'gitoriaMakeToken', ['gate'])).value.token;
  92. check('alice makes repos ev-test and ev-other', !!(await face(A, 'gitoriaCreate', ['ev-test', 'x'])).value.repo && !!(await face(A, 'gitoriaCreate', ['ev-other', 'x'])).value.repo);
  93. // ---- 1. ping at connect (way B), only to the app of that repo
  94. const addA = (await face(A, 'gitoriaAppAdd', ['ev-test', 'Reviewer', `http://127.0.0.1:${RPORT}/a`])).value;
  95. const addB = (await face(A, 'gitoriaAppAdd', ['ev-other', 'Other', `http://127.0.0.1:${RPORT}/b`])).value;
  96. check('the manual add shows a 64-hex secret once', addA && /^[0-9a-f]{64}$/.test(addA.secret || '') && addB && /^[0-9a-f]{64}$/.test(addB.secret || ''), J(addA));
  97. const secretOf = { '/a': addA.secret, '/b': addB.secret };
  98. await waitFor(() => got.some(g => g.path === '/a') && got.some(g => g.path === '/b'));
  99. const at = (p, since = 0) => got.slice(since).filter(g => g.path === p);
  100. const bodyOf = (g) => JSON.parse(g.body.toString('utf8'));
  101. const sigOk = (g) => g.headers['x-push-signature-256'] === 'sha256=' + createHmac('sha256', secretOf[g.path]).update(g.body).digest('hex');
  102. const pingA = at('/a')[0], pingB = at('/b')[0];
  103. check('ping reached both apps, each its own repo only', !!pingA && !!pingB && at('/a').length === 1 && at('/b').length === 1);
  104. const pj = pingA ? bodyOf(pingA) : {};
  105. check('ping headers: type, agent, event, delivery = body.delivery, signature verified by the receiver', pingA && pingA.headers['content-type'] === 'application/json' && pingA.headers['user-agent'] === 'gitoria' && pingA.headers['x-push-event'] === 'ping' && pingA.headers['x-push-delivery'] === pj.delivery && sigOk(pingA) && sigOk(pingB), J(pingA && pingA.headers));
  106. check('ping body: common body (repo, app, sender), action null', pj.event === 'ping' && pj.action === null && /^\d{4}-\d\d-\d\dT.*Z$/.test(pj.time) && pj.repo && pj.repo.full === 'ev-test' && pj.repo.private === false && pj.repo.api === `http://ev-test.localhost:${PORT}/api` && pj.repo.clone === `http://ev-test.localhost:${PORT}/ev-test.git` && /^[0-9a-z]{12}$/.test(pj.repo.id) && pj.app.name === 'Reviewer' && pj.sender && pj.sender.name === 'Alice Ünï', J(pj));
  107. check('ping body of the other repo names the other repo and app', bodyOf(pingB).repo.full === 'ev-other' && bodyOf(pingB).app.name === 'Other');
  108. const rowsA = (await get('/settings', { host: `ev-test.localhost:${PORT}`, cookie: A.cookie })).body;
  109. check('Settings → Apps shows the last delivery status and a Send ping button; no secret in the page', /ping delivered \(204\)/.test(rowsA) && /Send ping/.test(rowsA) && !rowsA.includes(addA.secret), rowsA.slice(rowsA.indexOf('applist'), rowsA.indexOf('applist') + 400));
  110. // ---- 2. pushes
  111. const URL = (slug) => `http://app:${token}@${slug}.localhost:${PORT}/${slug}.git`;
  112. const RES = (slug) => ['-c', `http.curloptResolve=${slug}.localhost:${PORT}:127.0.0.1`];
  113. const push = (cwd, slug, refs, extra = []) => { const t0 = Date.now(); const r = git(cwd, [...RES(slug), 'push', ...extra, URL(slug), ...refs]); return { ...r, ms: Date.now() - t0 }; };
  114. const W = join(WORK, 'w'); mkdirSync(W);
  115. must(W, ['init', '-q', '-b', 'main']); writeFileSync(join(W, 'a.txt'), 'a\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', 'base']);
  116. let r = push(W, 'ev-test', ['main']); const base = r.ms;
  117. check('first push works and raises no pull event', r.ok && at('/a').length === 1, r.err);
  118. must(W, ['checkout', '-q', '-b', 'f1']); writeFileSync(join(W, 'f1.txt'), '1\n'); must(W, ['add', '.']);
  119. must(W, ['commit', '-q', '-m', '|||PR Füge ✓ hinzu', '-m', 'Body text. Fixes proj#7']);
  120. const f1a = must(W, ['rev-parse', 'HEAD']);
  121. let k = got.length; r = push(W, 'ev-test', ['f1']);
  122. check('push with a |||PR commit works', r.ok, r.err);
  123. await waitFor(() => at('/a', k).length >= 1);
  124. let e = at('/a', k); let j = e[0] ? bodyOf(e[0]) : {};
  125. check('opened: one delivery, signature ok, event headers', e.length === 1 && e[0].headers['x-push-event'] === 'pull_request' && sigOk(e[0]) && j.delivery === e[0].headers['x-push-delivery'] && j.action === 'opened', J(j));
  126. check('opened: pull object (number, title with umlaut, body, head, refs, tickets, state)', j.pull && j.pull.number === 1 && j.pull.title === 'Füge ✓ hinzu' && /Body text/.test(j.pull.body) && j.pull.head === f1a && j.pull.ref === 'refs/pull/1/head' && j.pull.baseRef === 'refs/heads/main' && j.pull.state === 'open' && j.pull.source === 'f1' && j.pull.target === 'main' && J(j.pull.tickets) === '["proj#7"]' && j.pull.draft === false, J(j.pull));
  127. check('opened: sender is the pusher, repo and app named', j.sender && j.sender.name === 'Alice Ünï' && j.repo.full === 'ev-test' && j.app.name === 'Reviewer');
  128. check('opened: nothing for the other repo\'s app', at('/b').length === 1);
  129. const fetched = git(WORK, ['ls-remote', join(GIT, 'ev-test.git'), 'refs/pull/1/head']);
  130. check('refs/pull/1/head already points at pull.head when the event is delivered', fetched.out.startsWith(f1a), fetched.out);
  131. check('the push took about as long as one without a PR (the sender is a timer)', r.ms < base + 4000, `${r.ms} ms vs ${base} ms`);
  132. // synchronize + forced
  133. writeFileSync(join(W, 'f1b.txt'), 'b\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', 'more']);
  134. const f1b = must(W, ['rev-parse', 'HEAD']);
  135. k = got.length; push(W, 'ev-test', ['f1']); await waitFor(() => at('/a', k).length >= 1);
  136. j = at('/a', k)[0] ? bodyOf(at('/a', k)[0]) : {};
  137. check('synchronize (not forced): before, after, forced false', j.action === 'synchronize' && j.before === f1a && j.after === f1b && j.forced === false && j.pull.head === f1b, J(j));
  138. must(W, ['commit', '-q', '--amend', '-m', 'more amended']);
  139. const f1c = must(W, ['rev-parse', 'HEAD']);
  140. k = got.length; r = push(W, 'ev-test', ['f1'], ['--force']); await waitFor(() => at('/a', k).length >= 1);
  141. j = at('/a', k)[0] ? bodyOf(at('/a', k)[0]) : {};
  142. check('synchronize (force push): forced true, before = the old head, after = the new one', r.ok && j.action === 'synchronize' && j.forced === true && j.before === f1b && j.after === f1c && sigOk(at('/a', k)[0]), J(j));
  143. // merged by the Merge button (the face of the page, as the owner)
  144. must(W, ['checkout', '-q', 'main']); must(W, ['checkout', '-q', '-b', 'f2']); writeFileSync(join(W, 'f2.txt'), '2\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', '|||PR second']);
  145. const f2sha = must(W, ['rev-parse', 'HEAD']);
  146. k = got.length; push(W, 'ev-test', ['f2']); await waitFor(() => at('/a', k).length >= 1);
  147. check('second PR opened as number 2', at('/a', k)[0] && bodyOf(at('/a', k)[0]).pull.number === 2);
  148. k = got.length;
  149. const mr = await face(A, 'gitoriaMergePull', ['ev-test', f2sha]);
  150. check('the Merge button merges', mr.value && !mr.value.error, J(mr.value).slice(0, 200));
  151. await waitFor(() => at('/a', k).length >= 1);
  152. j = at('/a', k)[0] ? bodyOf(at('/a', k)[0]) : {};
  153. const mainTip = git(join(GIT, 'ev-test.git'), ['rev-parse', 'refs/heads/main']).out;
  154. check('merged by the Merge button: state merged, mergeCommit = the new tip of main, sender Alice', j.action === 'merged' && j.pull.state === 'merged' && j.pull.number === 2 && j.mergeCommit === mainTip && j.sender && j.sender.name === 'Alice Ünï' && sigOk(at('/a', k)[0]), J(j).slice(0, 400));
  155. // closed by deleting the branch
  156. must(W, ['checkout', '-q', 'main']); must(W, ['checkout', '-q', '-b', 'f3']); writeFileSync(join(W, 'f3.txt'), '3\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', '|||PR third']);
  157. k = got.length; push(W, 'ev-test', ['f3']); await waitFor(() => at('/a', k).length >= 1);
  158. k = got.length; push(W, 'ev-test', [':f3']); await waitFor(() => at('/a', k).length >= 1);
  159. j = at('/a', k)[0] ? bodyOf(at('/a', k)[0]) : {};
  160. check('closed by deleting the branch: pull.state closed', j.action === 'closed' && j.pull.number === 3 && j.pull.state === 'closed', J(j).slice(0, 300));
  161. // ---- 3. Send ping
  162. k = got.length;
  163. const pr = await face(A, 'gitoriaAppPing', ['ev-test', addA.rows[0].id]);
  164. await waitFor(() => at('/a', k).length >= 1);
  165. check('"Send ping" delivers a ping to that app', pr.value && pr.value.name === 'Reviewer' && at('/a', k).length === 1 && at('/a', k)[0].headers['x-push-event'] === 'ping' && sigOk(at('/a', k)[0]), J(pr.value));
  166. check('"Send ping" by another person is refused', !!(await face(B, 'gitoriaAppPing', ['ev-test', addA.rows[0].id])).value.error && !!(await face(null, 'gitoriaAppPing', ['ev-test', addA.rows[0].id])).value.error);
  167. // ---- 4. the receiver does not answer: retries with the SAME delivery id
  168. dropFirst = 2; k = got.length;
  169. must(W, ['checkout', '-q', 'main']); must(W, ['checkout', '-q', '-b', 'f4']); writeFileSync(join(W, 'f4.txt'), '4\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', '|||PR fourth']);
  170. push(W, 'ev-test', ['f4']);
  171. await waitFor(() => at('/a', k).length >= 3, 30000);
  172. e = at('/a', k);
  173. check('receiver cut the connection twice: the third try arrives, all with one X-Push-Delivery and the same body', e.length === 3 && new Set(e.map(x => x.headers['x-push-delivery'])).size === 1 && new Set(e.map(x => x.body.toString('hex'))).size === 1 && e.every(sigOk), `${e.length}`);
  174. check('the retries wait (about the test steps of 1.5 s), not a busy loop', e.length === 3 && e[1].at - e[0].at >= 1300 && e[2].at - e[1].at >= 1300, J(e.map(x => x.at - e[0].at)));
  175. await sleep(1200);
  176. check('delivered once it is 2xx: no further tries', at('/a', k).length === 3);
  177. const dl = await get('/settings', { host: `ev-test.localhost:${PORT}`, cookie: A.cookie });
  178. check('the app status says delivered', /pull_request delivered \(204\)/.test(dl.body));
  179. // 500 until failed (3 retry steps → 4 tries, then failed), and a redirect is not followed
  180. mode = '500'; k = got.length;
  181. must(W, ['checkout', '-q', 'main']); must(W, ['checkout', '-q', '-b', 'f5']); writeFileSync(join(W, 'f5.txt'), '5\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', '|||PR fifth']);
  182. push(W, 'ev-test', ['f5']);
  183. await waitFor(() => at('/a', k).length >= 4, 30000); await sleep(2500);
  184. check('answers 500: tried 4 times (first + 3 retry steps), then given up', at('/a', k).length === 4, String(at('/a', k).length));
  185. const st500 = await get('/settings', { host: `ev-test.localhost:${PORT}`, cookie: A.cookie });
  186. check('the app status says failed (500)', /pull_request failed \(500\)/.test(st500.body));
  187. mode = 'redirect'; k = got.length;
  188. must(W, ['checkout', '-q', 'main']); must(W, ['checkout', '-q', '-b', 'f6']); writeFileSync(join(W, 'f6.txt'), '6\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', '|||PR sixth']);
  189. push(W, 'ev-test', ['f6']);
  190. await waitFor(() => at('/a', k).length >= 4, 30000); await sleep(1500);
  191. check('a 302 is a failure and is NOT followed (the other path never gets a hit)', at('/a', k).length === 4 && redirectHits === 0, `${at('/a', k).length} ${redirectHits}`);
  192. // ---- 5. a receiver that hangs does not slow a push
  193. mode = 'hang'; k = got.length;
  194. must(W, ['checkout', '-q', 'main']); must(W, ['checkout', '-q', '-b', 'f7']); writeFileSync(join(W, 'f7.txt'), '7\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', '|||PR seventh']);
  195. r = push(W, 'ev-test', ['f7']);
  196. await waitFor(() => at('/a', k).length >= 1);
  197. check('hanging receiver: the PR push answers at once (the request is hanging at the receiver meanwhile)', r.ok && r.ms < base + 4000 && at('/a', k).length >= 1, `${r.ms} ms vs ${base}`);
  198. writeFileSync(join(W, 'f7b.txt'), 'b\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', 'again']);
  199. r = push(W, 'ev-test', ['f7']);
  200. check('and so does the next push, and a page view, while a delivery hangs', r.ok && r.ms < base + 4000 && (await get('/api/repos')).status === 200, `${r.ms} ms`);
  201. mode = 'ok';
  202. await waitFor(() => at('/a', k).length >= 3, 30000);
  203. await sleep(1500);
  204. // ---- 6. a second process on the same storage: every delivery is sent once
  205. const s2 = spawnServer(PORT2, { ...ENV, GITORIA_PUBLIC_URL: `http://localhost:${PORT}` }); await up(PORT2, s2);
  206. k = got.length;
  207. for (let i = 0; i < 6; i++) { writeFileSync(join(W, `m${i}.txt`), 'm\n'); must(W, ['checkout', '-q', 'main']); must(W, ['checkout', '-q', '-b', 'g' + i]); writeFileSync(join(W, `g${i}.txt`), 'g\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', '|||PR many ' + i]); push(W, 'ev-test', ['g' + i]); }
  208. await waitFor(() => at('/a', k).length >= 6, 30000); await sleep(3000);
  209. e = at('/a', k).filter(x => bodyOf(x).pull && bodyOf(x).pull.number >= 8); const ids = e.map(x => x.headers['x-push-delivery']);
  210. check('two gitoria processes on one storage: 6 events, 6 deliveries, none twice', e.length === 6 && new Set(ids).size === 6, `${e.length} ${new Set(ids).size} ${J(at('/a', k).map(x => [bodyOf(x).pull && bodyOf(x).pull.number, bodyOf(x).action, x.headers['x-push-delivery'].slice(0, 6)]))}`);
  211. const claims = existsSync(join(DB, 'claims')) ? readdirSync(join(DB, 'claims')).length : 0;
  212. check('the claim folders exist (one per attempt)', claims >= 6, String(claims));
  213. // ---- 7. the delivery log and redelivery for the app (GET {api}/deliveries, POST …/redeliver), with the app's own token
  214. const API = (slug, path, o = {}) => raw(PORT, o.method || 'GET', '/api' + path, { host: `${slug}.localhost:${PORT}`, ...o });
  215. const keyA = addA.key, keyB = addB.key;
  216. const tokenOf = async (slug, key) => JSON.parse((await API(slug, '/apps/token', { method: 'POST', headers: { authorization: 'Bearer ' + key } })).body).token;
  217. const tA = await tokenOf('ev-test', keyA), tB = await tokenOf('ev-other', keyB);
  218. const bearer = (t) => ({ headers: { authorization: 'Bearer ' + t } });
  219. const l1 = await API('ev-test', '/deliveries?limit=5', bearer(tA));
  220. const p1 = JSON.parse(l1.body);
  221. check('GET /deliveries: 200, 5 rows of the app, newest first, contract fields', l1.status === 200 && p1.deliveries.length === 5 && !!p1.next && p1.deliveries.every(d => d.id && d.event && 'action' in d && /^\d{4}-/.test(d.time) && ['pending', 'delivered', 'failed'].includes(d.status) && typeof d.tries === 'number' && typeof d.lastCode === 'number') && p1.deliveries[0].time >= p1.deliveries[4].time, l1.body.slice(0, 300));
  222. const all = []; let cur = null, pages = 0;
  223. do { const r = JSON.parse((await API('ev-test', '/deliveries?limit=4' + (cur ? '&cursor=' + encodeURIComponent(cur) : ''), bearer(tA))).body); all.push(...r.deliveries); cur = r.next; pages++; } while (cur && pages < 30);
  224. check('paging with next → cursor walks every delivery once', new Set(all.map(d => d.id)).size === all.length && all.length >= 16 && pages > 3, `${all.length} in ${pages}`);
  225. const seenIds = new Set(got.filter(g => g.path === '/a').map(g => g.headers['x-push-delivery']));
  226. check('every delivery the receiver saw is in the log, with status and tries', [...seenIds].every(id => all.some(d => d.id === id)) && all.some(d => d.status === 'failed' && d.lastCode === 500 && d.tries === 4) && all.some(d => d.status === 'delivered' && d.tries === 3 && d.event === 'pull_request'), J(all.slice(0, 3)));
  227. const otherLog = JSON.parse((await API('ev-other', '/deliveries', bearer(tB))).body).deliveries;
  228. check('the other app sees only its own deliveries (its ping), none of the first app', otherLog.length === 1 && otherLog[0].event === 'ping' && !otherLog.some(d => seenIds.has(d.id)));
  229. check('a log without a token is 401, with the other repo\'s token 404', (await API('ev-test', '/deliveries')).status === 401 && (await API('ev-test', '/deliveries', bearer(tB))).status === 404);
  230. const failedRow = all.find(d => d.status === 'failed');
  231. const rd0 = await API('ev-other', `/deliveries/${failedRow.id}/redeliver`, { method: 'POST', ...bearer(tB) });
  232. check("another app's delivery id: redeliver is 404, nothing is sent", rd0.status === 404 && JSON.parse(rd0.body).error.code === 'not_found');
  233. check('redeliver without a token 401; GET on redeliver is refused', (await API('ev-test', `/deliveries/${failedRow.id}/redeliver`, { method: 'POST' })).status === 401 && (await API('ev-test', `/deliveries/${failedRow.id}/redeliver`, bearer(tA))).status === 405);
  234. mode = 'ok'; k = got.length;
  235. const rd = await API('ev-test', `/deliveries/${failedRow.id}/redeliver`, { method: 'POST', ...bearer(tA) });
  236. await waitFor(() => at('/a', k).length >= 1);
  237. check('redeliver: 202, the receiver gets the SAME delivery id and the same signed bytes again', rd.status === 202 && at('/a', k).length === 1 && at('/a', k)[0].headers['x-push-delivery'] === failedRow.id && sigOk(at('/a', k)[0]) && at('/a', k)[0].body.toString('hex') === got.find(g => g.headers['x-push-delivery'] === failedRow.id).body.toString('hex'), String(rd.status));
  238. await sleep(800);
  239. const after = JSON.parse((await API('ev-test', '/deliveries?limit=100', bearer(tA))).body).deliveries.find(d => d.id === failedRow.id);
  240. check('and the log shows it delivered now', after && after.status === 'delivered', J(after));
  241. // ---- the sender never writes the apps row: rotate the secret, let deliveries happen, the secret stays the new one
  242. const rot = (await face(A, 'gitoriaAppRotate', ['ev-test', addA.rows[0].id])).value;
  243. check('rotate gives a new secret', rot && /^[0-9a-f]{64}$/.test(rot.secret || '') && rot.secret !== addA.secret);
  244. secretOf['/a'] = rot.secret; k = got.length;
  245. await face(A, 'gitoriaAppPing', ['ev-test', addA.rows[0].id]);
  246. await waitFor(() => at('/a', k).length >= 1); await sleep(800);
  247. check('after the delivery the receiver verifies with the NEW secret (the sender did not bring the old one back)', at('/a', k).length === 1 && sigOk(at('/a', k)[0]) && at('/a', k)[0].headers['x-push-signature-256'] !== 'sha256=' + createHmac('sha256', addA.secret).update(at('/a', k)[0].body).digest('hex'));
  248. k = got.length; await face(A, 'gitoriaAppPing', ['ev-test', addA.rows[0].id]); await waitFor(() => at('/a', k).length >= 1); await sleep(800);
  249. check('a second delivery after the rotation is still signed with the new secret', at('/a', k).length === 1 && sigOk(at('/a', k)[0]));
  250. const pageR = (await get('/settings', { host: `ev-test.localhost:${PORT}`, cookie: A.cookie })).body;
  251. check('Settings → Apps still shows the last status (from the deliveries), and no secret', /ping delivered \(204\)/.test(pageR) && !pageR.includes(rot.secret));
  252. // ---- 8. retention (after the servers stop)
  253. for (const p of procs) p.kill('SIGTERM'); await sleep(1500);
  254. const out = probe('retention', addA.rows[0].id);
  255. check('retention: rows older than 7 days are deleted', /OLDGONE true/.test(out), out.slice(-300));
  256. const kept = Number((/KEPT (\d+)/.exec(out) || [])[1]);
  257. check('retention: at most 200 rows per app stay, the newest ones', kept === 200 && /NEWESTKEPT true/.test(out) && /OLDESTDROPPED true/.test(out), out.slice(-300));
  258. } catch (err) {
  259. check('gate ran to the end', false, String(err && err.stack || err));
  260. } finally {
  261. cleanup(); if (ident && ident.stop) try { await ident.stop(); } catch {}
  262. }
  263. if (failures && s1) console.log('--- server log (tail) ---\n' + s1.log().split('\n').slice(-40).join('\n'));
  264. console.log(`\n${passes} passed, ${failures} failed`);
  265. 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