gitoria
All repositories: gitoria
27.0 KB
import { requiredPort } from './gate-ports.mjs';// 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.// pull_request opened / synchronize (forced) / merged (the Merge button) / closed, ping (at connect and "Send ping"), the signature verified by the receiver// (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,// a push that does not wait for a hanging receiver, a second process on the same storage that sends nothing twice, the retention.// node tests/events.mjs (ports: GITORIA_EVENTS_PORT 8720 = gitoria, +1 receiver, +3 second gitoria, +4 ident)import { spawn, spawnSync } from 'node:child_process';import { request, createServer } from 'node:http';import { createHmac } from 'node:crypto';import { mkdirSync, rmSync, writeFileSync, existsSync, readdirSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import { startIdent } from './identkit.mjs';const HERE = dirname(fileURLToPath(import.meta.url));const APP = resolve(HERE, '..');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;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/events-store');const DB = join(STORE, 'mpackdb'), GIT = join(STORE, 'git'), WORK = join(STORE, 'work');const BIN = join(APP, 'bin/hybriel');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, 500)}`); if (ok) passes++; else failures++; };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); } };// ---- the receiver: records every request; mode = ok | drop (connection cut) | 500 | hang | redirectconst got = []; // { path, headers, body }let mode = 'ok', dropFirst = 0, redirectHits = 0;const receiver = createServer((req, res) => {const c = []; req.on('data', d => c.push(d));req.on('end', () => {const body = Buffer.concat(c);if (req.url.startsWith('/elsewhere')) { redirectHits++; res.end('moved here'); return; }got.push({ path: req.url, headers: req.headers, body, at: Date.now() });if (mode === 'hang') return;if (mode === 'drop' || dropFirst > 0) { if (dropFirst > 0) dropFirst--; req.socket.destroy(); return; }if (mode === '500') { res.statusCode = 500; res.end('no'); return; }if (mode === 'redirect') { res.statusCode = 302; res.setHeader('location', `http://127.0.0.1:${RPORT}/elsewhere`); res.end(); return; }res.statusCode = 204; res.end();});});await new Promise(r => receiver.listen(RPORT, '127.0.0.1', r));function raw(port, 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, 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') })); });r.on('error', rej); if (body !== null) r.write(body); r.end();});}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]' };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() }; };const must = (cwd, args) => { const r = git(cwd, args); if (!r.ok) throw new Error('git ' + args.join(' ') + ': ' + r.err); return r.out; };const procs = [];function spawnServer(port, extra = {}) {let log = '';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',GITORIA_APP_HOSTS: `http://127.0.0.1:${RPORT}`, GITORIA_EVENTS_TICK: '0.3', GITORIA_EVENTS_RETRY_MS: '1500,1500,1500', ...extra } });p.stdout.on('data', d => log += d); p.stderr.on('data', d => log += d); procs.push(p);return { p, log: () => log };}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()); }const cleanup = () => { for (const p of procs) try { p.kill('SIGTERM'); } catch {} try { receiver.close(); } catch {} };process.on('exit', cleanup);let ident, s1 = null;try {rmSync(STORE, { recursive: true, force: true }); mkdirSync(DB, { recursive: true }); mkdirSync(GIT, { recursive: true }); mkdirSync(WORK, { recursive: true });const probeEnv = { ...process.env, GITORIA_STORAGE: DB, GITORIA_GIT: GIT };const probe = (...a) => { const r = spawnSync(BIN, ['tests/events-probe.hl', ...a], { cwd: APP, env: probeEnv, encoding: 'utf8' }); return r.stdout + r.stderr; };// ---- 0. the signature: RFC 4231 test case 2, openssl, a uuidconst sig = (secret, text) => (/SIG (\S+)/.exec(probe('sign', secret, text)) || [])[1];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?'));const sk = 'a1b2c3d4'.repeat(8), txt = '{"title":"Ünï ✓","n":1}';const ossl = spawnSync('openssl', ['dgst', '-sha256', '-hmac', sk], { input: txt, encoding: 'utf8' }).stdout.trim().split(' ').pop();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);const u = (/UUID (\S+)/.exec(probe('uuid')) || [])[1] || '';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);// ---- the serversident = 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]');const BASE = `http://localhost:${PORT}`;const app = await ident.registerApp(alice, 'gitoria (events gate)', [BASE]);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 };s1 = spawnServer(PORT, ENV); await up(PORT, s1);const get = (path, o = {}) => raw(PORT, 'GET', path, o);const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;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 }; };let n = 0;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 }; };const A = await login(alice), B = await login(bob);await face(A, 'gitoriaSaveName', ['Alice Ünï']); await face(B, 'gitoriaSaveName', ['Bob']);const token = (await face(A, 'gitoriaMakeToken', ['gate'])).value.token;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);// ---- 1. ping at connect (way B), only to the app of that repoconst addA = (await face(A, 'gitoriaAppAdd', ['ev-test', 'Reviewer', `http://127.0.0.1:${RPORT}/a`])).value;const addB = (await face(A, 'gitoriaAppAdd', ['ev-other', 'Other', `http://127.0.0.1:${RPORT}/b`])).value;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));const secretOf = { '/a': addA.secret, '/b': addB.secret };await waitFor(() => got.some(g => g.path === '/a') && got.some(g => g.path === '/b'));const at = (p, since = 0) => got.slice(since).filter(g => g.path === p);const bodyOf = (g) => JSON.parse(g.body.toString('utf8'));const sigOk = (g) => g.headers['x-push-signature-256'] === 'sha256=' + createHmac('sha256', secretOf[g.path]).update(g.body).digest('hex');const pingA = at('/a')[0], pingB = at('/b')[0];check('ping reached both apps, each its own repo only', !!pingA && !!pingB && at('/a').length === 1 && at('/b').length === 1);const pj = pingA ? bodyOf(pingA) : {};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));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));check('ping body of the other repo names the other repo and app', bodyOf(pingB).repo.full === 'ev-other' && bodyOf(pingB).app.name === 'Other');const rowsA = (await get('/settings', { host: `ev-test.localhost:${PORT}`, cookie: A.cookie })).body;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));// ---- 2. pushesconst URL = (slug) => `http://app:${token}@${slug}.localhost:${PORT}/${slug}.git`;const RES = (slug) => ['-c', `http.curloptResolve=${slug}.localhost:${PORT}:127.0.0.1`];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 }; };const W = join(WORK, 'w'); mkdirSync(W);must(W, ['init', '-q', '-b', 'main']); writeFileSync(join(W, 'a.txt'), 'a\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', 'base']);let r = push(W, 'ev-test', ['main']); const base = r.ms;check('first push works and raises no pull event', r.ok && at('/a').length === 1, r.err);must(W, ['checkout', '-q', '-b', 'f1']); writeFileSync(join(W, 'f1.txt'), '1\n'); must(W, ['add', '.']);must(W, ['commit', '-q', '-m', '|||PR Füge ✓ hinzu', '-m', 'Body text. Fixes proj#7']);const f1a = must(W, ['rev-parse', 'HEAD']);let k = got.length; r = push(W, 'ev-test', ['f1']);check('push with a |||PR commit works', r.ok, r.err);await waitFor(() => at('/a', k).length >= 1);let e = at('/a', k); let j = e[0] ? bodyOf(e[0]) : {};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));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));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');check('opened: nothing for the other repo\'s app', at('/b').length === 1);const fetched = git(WORK, ['ls-remote', join(GIT, 'ev-test.git'), 'refs/pull/1/head']);check('refs/pull/1/head already points at pull.head when the event is delivered', fetched.out.startsWith(f1a), fetched.out);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`);// synchronize + forcedwriteFileSync(join(W, 'f1b.txt'), 'b\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', 'more']);const f1b = must(W, ['rev-parse', 'HEAD']);k = got.length; push(W, 'ev-test', ['f1']); await waitFor(() => at('/a', k).length >= 1);j = at('/a', k)[0] ? bodyOf(at('/a', k)[0]) : {};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));must(W, ['commit', '-q', '--amend', '-m', 'more amended']);const f1c = must(W, ['rev-parse', 'HEAD']);k = got.length; r = push(W, 'ev-test', ['f1'], ['--force']); await waitFor(() => at('/a', k).length >= 1);j = at('/a', k)[0] ? bodyOf(at('/a', k)[0]) : {};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));// merged by the Merge button (the face of the page, as the owner)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']);const f2sha = must(W, ['rev-parse', 'HEAD']);k = got.length; push(W, 'ev-test', ['f2']); await waitFor(() => at('/a', k).length >= 1);check('second PR opened as number 2', at('/a', k)[0] && bodyOf(at('/a', k)[0]).pull.number === 2);k = got.length;const mr = await face(A, 'gitoriaMergePull', ['ev-test', f2sha]);check('the Merge button merges', mr.value && !mr.value.error, J(mr.value).slice(0, 200));await waitFor(() => at('/a', k).length >= 1);j = at('/a', k)[0] ? bodyOf(at('/a', k)[0]) : {};const mainTip = git(join(GIT, 'ev-test.git'), ['rev-parse', 'refs/heads/main']).out;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));// closed by deleting the branchmust(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']);k = got.length; push(W, 'ev-test', ['f3']); await waitFor(() => at('/a', k).length >= 1);k = got.length; push(W, 'ev-test', [':f3']); await waitFor(() => at('/a', k).length >= 1);j = at('/a', k)[0] ? bodyOf(at('/a', k)[0]) : {};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));// ---- 3. Send pingk = got.length;const pr = await face(A, 'gitoriaAppPing', ['ev-test', addA.rows[0].id]);await waitFor(() => at('/a', k).length >= 1);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));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);// ---- 4. the receiver does not answer: retries with the SAME delivery iddropFirst = 2; k = got.length;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']);push(W, 'ev-test', ['f4']);await waitFor(() => at('/a', k).length >= 3, 30000);e = at('/a', k);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}`);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)));await sleep(1200);check('delivered once it is 2xx: no further tries', at('/a', k).length === 3);const dl = await get('/settings', { host: `ev-test.localhost:${PORT}`, cookie: A.cookie });check('the app status says delivered', /pull_request delivered \(204\)/.test(dl.body));// 500 until failed (3 retry steps → 4 tries, then failed), and a redirect is not followedmode = '500'; k = got.length;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']);push(W, 'ev-test', ['f5']);await waitFor(() => at('/a', k).length >= 4, 30000); await sleep(2500);check('answers 500: tried 4 times (first + 3 retry steps), then given up', at('/a', k).length === 4, String(at('/a', k).length));const st500 = await get('/settings', { host: `ev-test.localhost:${PORT}`, cookie: A.cookie });check('the app status says failed (500)', /pull_request failed \(500\)/.test(st500.body));mode = 'redirect'; k = got.length;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']);push(W, 'ev-test', ['f6']);await waitFor(() => at('/a', k).length >= 4, 30000); await sleep(1500);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}`);// ---- 5. a receiver that hangs does not slow a pushmode = 'hang'; k = got.length;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']);r = push(W, 'ev-test', ['f7']);await waitFor(() => at('/a', k).length >= 1);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}`);writeFileSync(join(W, 'f7b.txt'), 'b\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', 'again']);r = push(W, 'ev-test', ['f7']);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`);mode = 'ok';await waitFor(() => at('/a', k).length >= 3, 30000);await sleep(1500);// ---- 6. a second process on the same storage: every delivery is sent onceconst s2 = spawnServer(PORT2, { ...ENV, GITORIA_PUBLIC_URL: `http://localhost:${PORT}` }); await up(PORT2, s2);k = got.length;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]); }await waitFor(() => at('/a', k).length >= 6, 30000); await sleep(3000);e = at('/a', k).filter(x => bodyOf(x).pull && bodyOf(x).pull.number >= 8); const ids = e.map(x => x.headers['x-push-delivery']);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)]))}`);const claims = existsSync(join(DB, 'claims')) ? readdirSync(join(DB, 'claims')).length : 0;check('the claim folders exist (one per attempt)', claims >= 6, String(claims));// ---- 7. the delivery log and redelivery for the app (GET {api}/deliveries, POST …/redeliver), with the app's own tokenconst API = (slug, path, o = {}) => raw(PORT, o.method || 'GET', '/api' + path, { host: `${slug}.localhost:${PORT}`, ...o });const keyA = addA.key, keyB = addB.key;const tokenOf = async (slug, key) => JSON.parse((await API(slug, '/apps/token', { method: 'POST', headers: { authorization: 'Bearer ' + key } })).body).token;const tA = await tokenOf('ev-test', keyA), tB = await tokenOf('ev-other', keyB);const bearer = (t) => ({ headers: { authorization: 'Bearer ' + t } });const l1 = await API('ev-test', '/deliveries?limit=5', bearer(tA));const p1 = JSON.parse(l1.body);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));const all = []; let cur = null, pages = 0;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);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}`);const seenIds = new Set(got.filter(g => g.path === '/a').map(g => g.headers['x-push-delivery']));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)));const otherLog = JSON.parse((await API('ev-other', '/deliveries', bearer(tB))).body).deliveries;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)));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);const failedRow = all.find(d => d.status === 'failed');const rd0 = await API('ev-other', `/deliveries/${failedRow.id}/redeliver`, { method: 'POST', ...bearer(tB) });check("another app's delivery id: redeliver is 404, nothing is sent", rd0.status === 404 && JSON.parse(rd0.body).error.code === 'not_found');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);mode = 'ok'; k = got.length;const rd = await API('ev-test', `/deliveries/${failedRow.id}/redeliver`, { method: 'POST', ...bearer(tA) });await waitFor(() => at('/a', k).length >= 1);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));await sleep(800);const after = JSON.parse((await API('ev-test', '/deliveries?limit=100', bearer(tA))).body).deliveries.find(d => d.id === failedRow.id);check('and the log shows it delivered now', after && after.status === 'delivered', J(after));// ---- the sender never writes the apps row: rotate the secret, let deliveries happen, the secret stays the new oneconst rot = (await face(A, 'gitoriaAppRotate', ['ev-test', addA.rows[0].id])).value;check('rotate gives a new secret', rot && /^[0-9a-f]{64}$/.test(rot.secret || '') && rot.secret !== addA.secret);secretOf['/a'] = rot.secret; k = got.length;await face(A, 'gitoriaAppPing', ['ev-test', addA.rows[0].id]);await waitFor(() => at('/a', k).length >= 1); await sleep(800);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'));k = got.length; await face(A, 'gitoriaAppPing', ['ev-test', addA.rows[0].id]); await waitFor(() => at('/a', k).length >= 1); await sleep(800);check('a second delivery after the rotation is still signed with the new secret', at('/a', k).length === 1 && sigOk(at('/a', k)[0]));const pageR = (await get('/settings', { host: `ev-test.localhost:${PORT}`, cookie: A.cookie })).body;check('Settings → Apps still shows the last status (from the deliveries), and no secret', /ping delivered \(204\)/.test(pageR) && !pageR.includes(rot.secret));// ---- 8. retention (after the servers stop)for (const p of procs) p.kill('SIGTERM'); await sleep(1500);const out = probe('retention', addA.rows[0].id);check('retention: rows older than 7 days are deleted', /OLDGONE true/.test(out), out.slice(-300));const kept = Number((/KEPT (\d+)/.exec(out) || [])[1]);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));} catch (err) {check('gate ran to the end', false, String(err && err.stack || err));} finally {cleanup(); if (ident && ident.stop) try { await ident.stop(); } catch {}}if (failures && s1) console.log('--- server log (tail) ---\n' + s1.log().split('\n').slice(-40).join('\n'));console.log(`\n${passes} passed, ${failures} failed`);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