gitoria
All repositories: gitoria
29.7 KB
import { requiredPort, requiredPortRange } from './gate-ports.mjs';// tests/member-merge.mjs — GATE OF THE MEMBER MERGE (gitoria#48): a member of a repo (the people who may push) merges a pull request with a gtr_ user token// — POST {api}/pulls/N/merge — once the REQUIRED checks are success; the owner too; apps (gat_) and strangers never. Blocked (422) while a required status is// pending / failure, a stale head is 409, the pull_request `merged` event carries sender = the member, the Merge button shows for owner and member only.// Real HTTP, the real `git`, its own storage under .scratch/member-merge-store.// node tests/member-merge.mjs (GITORIA_MM_PORT required = gitoria, +1 event receiver, +4 ident)import { spawn, execFileSync } from 'node:child_process';import { request, createServer } from 'node:http';import { mkdirSync, rmSync, writeFileSync, existsSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import { startIdent } from './identkit.mjs';import { launchBrowser } from './cdp.mjs';const HERE = dirname(fileURLToPath(import.meta.url));const APP = resolve(HERE, '..');const CHROME = requiredPortRange('GITORIA_GATE_CHROME');const PORT = requiredPort('GITORIA_MM_PORT'), RPORT = PORT + 1, IDENT_PORT = process.env.GITORIA_MM_IDENT_PORT ? requiredPort('GITORIA_MM_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/member-merge-store');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 ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; };const got = [];const receiver = createServer((req, res) => { const c = []; req.on('data', d => c.push(d)); req.on('end', () => { got.push({ path: req.url, headers: req.headers, body: Buffer.concat(c).toString('utf8') }); res.statusCode = 204; res.end(); }); });await new Promise(r => receiver.listen(RPORT, '127.0.0.1', r));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, headers: m.headers, body: Buffer.concat(c).toString('utf8') })); });r.on('error', rej); if (body !== null) r.write(body); r.end();});}const get = (path, o = {}) => raw('GET', path, o);const errOf = (r) => { try { return JSON.parse(r.body).error; } catch { return {}; } };let server = null, log = '';async function up() { for (let i = 0; i < 960; i++) { try { if ((await get('/api/repos')).status === 200) return; } catch {} await sleep(250); } throw new Error('gitoria did not come up\n' + log); }const stop = async () => { if (server) { const p = server; server = null; p.kill(); await new Promise(r => p.once('exit', r)); } };let ident;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}`;const app = await ident.registerApp(alice, 'gitoria (member-merge gate)', [BASE]);const GIT = join(STORE, 'git');const env = { 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 = 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: 'sshsecret-mm-gate', GITORIA_TICKETS_URL: 'http://127.0.0.1:1', GITORIA_APP_HOSTS: `http://127.0.0.1:${RPORT}`, GITORIA_EVENTS_TICK: '0.3', ...env } });server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);await up();const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;const login = async (who) => { const ck = cookieOf(await get('/')); const cb = await 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, tB = (await face(B, 'gitoriaMakeToken', ['b'])).token, tC = (await face(C, 'gitoriaMakeToken', ['c'])).token;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' };const g = (...a) => execFileSync('git', a, { cwd: W, encoding: 'utf8', env: genv, stdio: ['ignore', 'pipe', 'pipe'] });const bare = (...a) => execFileSync('git', a, { cwd: join(GIT, 'mm.git'), encoding: 'utf8', env: genv, stdio: ['ignore', 'pipe', 'pipe'] }).trim();const push = (...refs) => { try { g('push', '-q', `http://a:${tA}@mm.localhost:${PORT}/mm.git`, ...refs); return true; } catch { return false; } };const sha = () => g('rev-parse', 'HEAD').trim();const mkPr = (branch, title) => { g('checkout', '-q', 'main'); g('checkout', '-q', '-b', branch); writeFileSync(join(W, branch + '.txt'), branch + '\n'); g('add', '-A'); g('commit', '-q', '-m', '|||PR ' + title); const s = sha(); push(branch); return s; };g('init', '-q', '-b', 'main'); writeFileSync(join(W, 'README.md'), '# t\n'); g('add', '-A'); g('commit', '-q', '-m', 'init');check('alice creates "mm", pushes main', !!(await face(A, 'gitoriaCreate', ['mm', 'm'])).repo && push('main'));const added = await face(A, 'gitoriaChangeMember', ['mm', 'Bob', true]);check('alice adds Bob as a member (Carol is not)', added && added.members && added.members.length === 1, J(added));const kApp = await face(A, 'gitoriaAppAdd', ['mm', 'Kunibert', `http://127.0.0.1:${RPORT}/a`]);const tApp = JSON.parse((await raw('POST', '/api/apps/token', { host: `mm.localhost:${PORT}`, headers: { authorization: 'Bearer ' + kApp.key } })).body).token;const idK = (kApp.rows.find(x => x.name === 'Kunibert') || {}).id;check('an app (Kunibert) is connected to mm and has a token', /^gak_/.test(kApp.key || '') && !!tApp && !!idK);const HOST = `mm.localhost:${PORT}`;const merge = (token, num, body = null) => raw('POST', `/api/pulls/${num}/merge`, { host: HOST, headers: { ...(token ? { authorization: 'Bearer ' + token } : {}), 'content-type': 'application/json' }, body });const put = (sha_, state) => raw('PUT', '/api/statuses/' + sha_, { host: HOST, headers: { authorization: 'Bearer ' + tApp, 'content-type': 'application/json' }, body: J({ context: 'ci', state, title: 't', summary: '', url: null }) });const prNum = async (s) => { const l = JSON.parse((await raw('GET', '/api/pulls?state=all', { host: HOST, headers: { authorization: 'Bearer ' + tApp } })).body).pulls; const p = l.find(x => x.head === s || x.sha === s); return p ? p.number : null; };// ---- 1. nothing required yet: the owner merges (API), a member merges through the button's faceconst s1 = mkPr('f1', 'one'), s2 = mkPr('f2', 'two'), s3 = mkPr('f3', 'three'), s4 = mkPr('f4', 'four');const n1 = await prNum(s1), n2 = await prNum(s2), n3 = await prNum(s3), n4 = await prNum(s4);check('four PRs are numbered', [n1, n2, n3, n4].every(x => x != null) && new Set([n1, n2, n3, n4]).size === 4, J([n1, n2, n3, n4]));// W49: member reads share the app body shape; only apps can write or inspect deliveries.const api = (token, method, path, body = null) => raw(method, path, { host: HOST, headers: { ...(token ? { authorization: 'Bearer ' + token } : {}), 'content-type': 'application/json' }, body: body == null ? null : J(body) });const review = await api(tApp, 'POST', `/api/pulls/${n3}/reviews`, { head: s3, verdict: 'comment', body: 'first review', comments: [{ path: 'f3.txt', line: 1, body: 'inline' }] });check('W49 app still posts a review with an inline thread', review.status === 201, review.body);const threadId = JSON.parse(review.body).threads[0].id;check('W49 app still posts a conversation comment', (await api(tApp, 'POST', `/api/pulls/${n3}/comments`, { body: 'conversation' })).status === 201);await put(s4, 'pending');const paths = ['/api/pulls?state=all', `/api/pulls/${n3}`, `/api/pulls/${n3}/reviews`, `/api/pulls/${n3}/threads`, `/api/pulls/${n3}/comments`, '/api/statuses/' + s4];for (const path of paths) {const a = await api(tApp, 'GET', path), b = await api(tB, 'GET', path), owner = await api(tA, 'GET', path);check('W49 member and owner read same app body: ' + path, a.status === 200 && b.status === 200 && owner.status === 200 && a.body === b.body && a.body === owner.body, [a.status, b.status, owner.status].join());const stranger = await api(tC, 'GET', path), anon = await api(null, 'GET', path), bad = await api('gtr_' + 'a'.repeat(40), 'GET', path);const anonOpen = path === `/api/pulls/${n3}` || path === '/api/statuses/' + s4;check('W49 stranger 404, no token and unknown user token 401 (#51: no header at all reads a public pull and statuses): ' + path, stranger.status === 404 && errOf(stranger).code === 'not_found' && (anonOpen ? anon.status === 200 && anon.body === owner.body : anon.status === 401) && bad.status === 401, [stranger.status, anon.status, bad.status].join());}// ---- gitoria#51: anonymous reads of public repos (no Authorization header at all), only GET pulls/N and GET statuses/<sha>const anonPull = await api(null, 'GET', `/api/pulls/${n3}`), anonSt = await api(null, 'GET', '/api/statuses/' + s4);check('#51 public: anonymous GET pulls/N → 200 with the pull object', anonPull.status === 200 && JSON.parse(anonPull.body).number === n3 && JSON.parse(anonPull.body).head === s3, anonPull.status + anonPull.body.slice(0, 200));check('#51 public: anonymous GET statuses/<sha> → 200 { statuses }', anonSt.status === 200 && Array.isArray(JSON.parse(anonSt.body).statuses) && JSON.parse(anonSt.body).statuses.length === 1, anonSt.status + anonSt.body.slice(0, 200));const anon404 = await api(null, 'GET', '/api/pulls/999'), anonSha = await api(null, 'GET', '/api/statuses/' + 'e'.repeat(40));check('#51 public: unknown PR and unknown sha → 404 not_found', anon404.status === 404 && errOf(anon404).code === 'not_found' && anonSha.status === 404 && errOf(anonSha).code === 'not_found', anon404.status + ' ' + anonSha.status);check('#51 public: the PR list, reviews, threads, comments stay 401 without a token', (await Promise.all(['/api/pulls', `/api/pulls/${n3}/reviews`, `/api/pulls/${n3}/threads`, `/api/pulls/${n3}/comments`].map(x => api(null, 'GET', x)))).every(r => r.status === 401));check('#51 public: an invalid gtr_ is 401, a non-member gtr_ is 404 still', (await api('gtr_' + 'a'.repeat(40), 'GET', `/api/pulls/${n3}`)).status === 401 && (await api(tC, 'GET', `/api/pulls/${n3}`)).status === 404);const missing = await raw('GET', `/api/pulls/${n3}`, { host: `nosuchrepo.localhost:${PORT}` });check('#51 a missing repo → 404 not_found', missing.status === 404 && errOf(missing).code === 'not_found', missing.status + missing.body);const goPriv = await face(A, 'gitoriaSetPrivate', ['mm', true]);check('#51 the owner makes mm private', !!(goPriv && goPriv.value ? goPriv.value.repo && goPriv.value.repo.isPrivate : goPriv && goPriv.repo && goPriv.repo.isPrivate), J(goPriv).slice(0, 200));const pPull = await api(null, 'GET', `/api/pulls/${n3}`), pSt = await api(null, 'GET', '/api/statuses/' + s4), pNo = await api(null, 'GET', '/api/pulls/999');check('#51 private: both anonymous reads → 404 not_found, the same body as a missing repo', pPull.status === 404 && pSt.status === 404 && pNo.status === 404 && pPull.body === missing.body && pSt.body === missing.body && pNo.body === missing.body, [pPull.status, pSt.status, pNo.status].join() + pPull.body);check('#51 private: the members still read with a token', (await api(tB, 'GET', `/api/pulls/${n3}`)).status === 200 && (await api(tA, 'GET', '/api/statuses/' + s4)).status === 200);await face(A, 'gitoriaSetPrivate', ['mm', false]);check('#51 public again: anonymous GET pulls/N → 200', (await api(null, 'GET', `/api/pulls/${n3}`)).status === 200);if (process.env.W49_REAL_CDP) {process.env.HL_CDP_URL = process.env.W49_REAL_CDP;const before = (await (await fetch(process.env.HL_CDP_URL + '/json/list')).json()).filter(t => t.type === 'page');writeFileSync(join(APP, '.scratch/w49/chrome-before.json'), J(before));const browser = await launchBrowser({ debugPortRange: CHROME }); let page;try {page = await browser.newPage();await page.goto(`http://mm.localhost:${PORT}/pulls/${n3}`);for (const [width, height] of [[390, 844], [800, 1280], [1280, 800], [1280, 900]]) {await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width === 390 });for (const path of paths) {const got = await page.evaluate(`(async () => { const r = await fetch(${J(path)}, { headers: { authorization: ${J('Bearer ' + tB)} } }); return { status: r.status, body: await r.text() }; })()`);check(`W49 real Chrome ${width}x${height} member reads ${path}`, got.status === 200, got.status);}await page.send('Page.reload');await page.waitForSelector('#pullpage');const shot = await page.send('Page.captureScreenshot', { format: 'png' });writeFileSync(join(APP, `.scratch/w49/chrome-${width}x${height}.png`), Buffer.from(shot.data, 'base64'));}} finally {try { if (page) await page.close(); } finally { browser.conn.close(); }const after = (await (await fetch(process.env.HL_CDP_URL + '/json/list')).json()).filter(t => t.type === 'page');writeFileSync(join(APP, '.scratch/w49/chrome-after.json'), J(after));check('W49 real Chrome leaves only original page targets', J(after.map(t => t.id).sort()) === J(before.map(t => t.id).sort()));delete process.env.HL_CDP_URL;}}const message = 'this route needs an app token (gat_); user tokens (gtr_) can read pulls, reviews, threads, comments and statuses and merge with POST /pulls/N/merge';for (const [method, path] of [['POST', `/api/pulls/${n3}/reviews`], ['POST', `/api/pulls/${n3}/comments`], ['POST', `/api/pulls/${n3}/threads/${threadId}/replies`], ['POST', `/api/pulls/${n3}/threads/${threadId}/resolve`], ['PUT', '/api/statuses/' + s3], ['GET', '/api/deliveries'], ['POST', '/api/deliveries/unknown/redeliver'], ['POST', '/api/apps/token']]) {const r = await api(tB, method, path, {});check('W49 app-only explains gtr_: ' + method + ' ' + path, r.status === 403 && errOf(r).code === 'app_token_required' && errOf(r).message === message, r.status + r.body);}for (const [method, path] of [['POST', `/api/pulls/${n3}/reviews`], ['PUT', '/api/statuses/' + s3]]) {for (const token of [null, 'gtr_' + 'a'.repeat(40)]) {const r = await api(token, method, path, {});check('W51 missing or unknown user token stays 401: ' + method, r.status === 401 && errOf(r).code === 'unauthorized', r.status + r.body);}}check('W49 unknown app token retains old message', /missing, unknown or expired token/.test(errOf(await api('gat_unknown', 'GET', paths[0])).message || ''));const kSecond = await face(A, 'gitoriaAppAdd', ['mm', 'Second', `http://127.0.0.1:${RPORT}/b`]);const tSecond = JSON.parse((await api(kSecond.key, 'POST', '/api/apps/token')).body).token;const review2 = await api(tSecond, 'POST', `/api/pulls/${n3}/reviews`, { head: s3, verdict: 'comment', body: 'second review', comments: [{ path: 'f3.txt', line: 1, body: 'second inline' }] });check('W49 another app posts its review and thread', review2.status === 201);for (const kind of ['reviews', 'threads']) {const path = `/api/pulls/${n3}/${kind}`;const member = JSON.parse((await api(tB, 'GET', path)).body), appOne = JSON.parse((await api(tApp, 'GET', path)).body), appTwo = JSON.parse((await api(tSecond, 'GET', path)).body);check('W49 member sees both apps; each app retains own ' + kind, member[kind].length === 2 && appOne[kind].length === 1 && appTwo[kind].length === 1 && appOne[kind][0].id !== appTwo[kind][0].id);const first = JSON.parse((await api(tB, 'GET', path + '?limit=1')).body);const next = JSON.parse((await api(tB, 'GET', path + '?limit=1&cursor=' + encodeURIComponent(first.next))).body);check('W49 member pagination has distinct stable ids: ' + kind, first[kind].length === 1 && next[kind].length === 1 && first[kind][0].id !== next[kind][0].id);}const m1 = await merge(tA, n1);const j1 = (() => { try { return JSON.parse(m1.body); } catch { return {}; } })();check('the OWNER merges PR 1 with her gtr_ token: 200 { merged, mergeCommit, pull }', m1.status === 200 && j1.merged === true && /^[0-9a-f]{40}$/.test(j1.mergeCommit || '') && j1.pull && j1.pull.number === n1 && j1.pull.state === 'merged', m1.status + m1.body.slice(0, 300));check('PR 1: mergeCommit is the tip of main, author = her display name', j1.mergeCommit === bare('rev-parse', 'refs/heads/main') && bare('log', '-1', '--format=%an', 'main') === 'Alice', bare('log', '-1', '--format=%an', 'main'));const btn = await face(B, 'gitoriaMergePull', ['mm', s2]);check('the MEMBER merges PR 2 with the button (server face)', btn && !btn.error && btn.result, J(btn).slice(0, 200));check('PR 2 is merged; author of the merge commit = Bob', bare('log', '-1', '--format=%an', 'main') === 'Bob', '');const strangerFace = await face(C, 'gitoriaMergePull', ['mm', s3]);check('the button\'s face refuses a stranger and a signed-out caller', strangerFace && /only the owner and the members/.test(strangerFace.error || '') && !!((await face(null, 'gitoriaMergePull', ['mm', s3])) || {}).error);// ---- 2. required checkconst rq = await face(A, 'gitoriaRequiredAdd', ['mm', idK, 'ci']);check('the owner requires Kunibert · ci', rq && rq.rows && rq.rows.length === 1, J(rq));const before = bare('rev-parse', 'refs/heads/main');const checkDetails = (r, state) => J(errOf(r).details) === J([{ app: { id: idK, name: 'Kunibert' }, context: 'ci', state }]);const r0 = await merge(tB, n3);check('member, status not set → 422 checks_failed naming app and ci', r0.status === 422 && errOf(r0).code === 'checks_failed' && checkDetails(r0, 'missing') && /ci \(not set\)/.test(errOf(r0).message || ''), r0.status + r0.body.slice(0, 200));await put(s3, 'pending');const r1 = await merge(tB, n3);check('member, status pending → 422, main unchanged', r1.status === 422 && errOf(r1).code === 'checks_failed' && checkDetails(r1, 'pending') && /ci \(pending\)/.test(errOf(r1).message || '') && bare('rev-parse', 'refs/heads/main') === before, r1.status + r1.body.slice(0, 200));await put(s3, 'failure');const r2 = await merge(tB, n3);check('member, status failure → 422, main unchanged', r2.status === 422 && errOf(r2).code === 'checks_failed' && checkDetails(r2, 'failure') && /ci \(failure\)/.test(errOf(r2).message || '') && bare('rev-parse', 'refs/heads/main') === before, r2.status + r2.body.slice(0, 200));const rOwn = await merge(tA, n3);check('the owner is held by the same required check (422)', rOwn.status === 422 && errOf(rOwn).code === 'checks_failed', rOwn.status);// ---- 3. who may notawait put(s3, 'success');const rApp = await merge(tApp, n3);check('an app token (gat_) → 403 forbidden "apps cannot merge", even with the status green', rApp.status === 403 && errOf(rApp).code === 'forbidden' && errOf(rApp).message === 'apps cannot merge', rApp.status + rApp.body);const rC = await merge(tC, n3);check('a signed-in non-member (gtr_) → 403', rC.status === 403 && errOf(rC).code === 'forbidden', rC.status + rC.body);const rNo = await merge(null, n3), rBad = await merge('gtr_' + 'a'.repeat(40), n3), rJunk = await merge('nonsense', n3);check('no token / an unknown gtr_ / junk → 401', rNo.status === 401 && rBad.status === 401 && rJunk.status === 401, [rNo.status, rBad.status, rJunk.status].join());check('GET on the merge route → 405', (await raw('GET', `/api/pulls/${n3}/merge`, { host: HOST, headers: { authorization: 'Bearer ' + tB } })).status === 405);const r404 = await merge(tB, 999);check('unknown PR → 404 not_found', r404.status === 404 && errOf(r404).code === 'not_found', r404.status);check('PR 3 still open after all refusals', bare('rev-parse', 'refs/heads/main') === before);// ---- 4. the button: visible for owner + member, hidden for othersconst listBtn = async (who) => { const b = (await get('/pulls', { host: HOST, cookie: who && who.cookie })).body; return (b.match(/<button class="([^"]*)" type="button" value="[0-9a-f]{40}">Merge/g) || []).map(x => x.match(/class="([^"]*)"/)[1]); };const pageBtn = async (who, num) => { const b = (await get('/pulls/' + num, { host: HOST, cookie: who && who.cookie })).body; return (b.match(/<button id="mergepull" class="([^"]*)"/) || [])[1]; };const lb = await listBtn(B), lc = await listBtn(C), ln = await listBtn(null), la = await listBtn(A);check('/pulls: Bob (member) and Alice see a visible Merge button on the green PR (quiet mergepr)', lb.includes('quiet mergepr') && la.includes('quiet mergepr'), J([lb, la]));check('/pulls: Carol and the signed-out viewer see no visible Merge button', !lc.includes('quiet mergepr') && !ln.includes('quiet mergepr'), J([lc, ln]));const pb = await pageBtn(B, n3), pa = await pageBtn(A, n3), pc = await pageBtn(C, n3), pn = await pageBtn(null, n3);check('/pulls/N: Bob and Alice get the Merge button (mergepr), Carol and signed-out get nomerge', pb === 'mergepr' && pa === 'mergepr' && pc === 'nomerge' && pn === 'nomerge', J([pb, pa, pc, pn]));const pageFace = await face(C, 'gitoriaPrMerge', ['mm', '' + n3]);check('the PR page\'s merge face refuses a stranger', pageFace && /only the owner and the members/.test(pageFace.error || ''), J(pageFace));// ---- 5. stale head, then the member merges (event with sender = Bob)const stale = await merge(tB, n3, J({ head: 'f'.repeat(40) }));check('a head that is not the current head → 409, nothing merged', stale.status === 409 && errOf(stale).code === 'conflict' && errOf(stale).details?.reason === 'head_mismatch' && /head/.test(errOf(stale).message || '') && bare('rev-parse', 'refs/heads/main') === before, stale.status + stale.body.slice(0, 200));check('a malformed head → 422', (await merge(tB, n3, J({ head: 'abc' }))).status === 422);check('a body that is not JSON → 400', (await merge(tB, n3, 'nope')).status === 400);const k = got.length;const ok = await merge(tB, n3, J({ head: s3 }));const jo = (() => { try { return JSON.parse(ok.body); } catch { return {}; } })();check('the MEMBER merges PR 3 (status success, the right head): 200 { merged, mergeCommit, pull }', ok.status === 200 && jo.merged === true && jo.mergeCommit === bare('rev-parse', 'refs/heads/main') && jo.pull.state === 'merged' && jo.pull.number === n3, ok.status + ok.body.slice(0, 300));check('the merge commit author = Bob', bare('log', '-1', '--format=%an', 'main') === 'Bob');for (let i = 0; i < 100 && !got.slice(k).some(x => x.body.includes('"merged"')); i++) await sleep(100);const ev = got.slice(k).map(x => { try { return JSON.parse(x.body); } catch { return {}; } }).find(x => x.event === 'pull_request' && x.action === 'merged' && x.pull && x.pull.number === n3);check('the pull_request merged event reached the app: sender = Bob, mergeCommit = the new tip', ev && ev.sender && ev.sender.name === 'Bob' && ev.mergeCommit === jo.mergeCommit, J(ev).slice(0, 300));const again = await merge(tB, n3);check('merging it again → 409 already merged', again.status === 409 && errOf(again).code === 'conflict' && errOf(again).details?.reason === 'already_merged' && /already merged/.test(errOf(again).message || ''), again.status + again.body.slice(0, 200));check('the stored PR reads as merged with GET /api/pulls/N', JSON.parse((await raw('GET', '/api/pulls/' + n3, { host: HOST, headers: { authorization: 'Bearer ' + tApp } })).body).state === 'merged');// the PR page's own Merge button (its face) merges for the owner and answers the page read againawait put(s4, 'success');const pm = await face(A, 'gitoriaPrMerge', ['mm', '' + n4]);check('the PR page\'s Merge face merges PR 4 for the owner: the view says merged, the button hides', pm && pm.view && pm.view.pr.state === 'merged' && pm.view.mergeClass === 'nomerge' && bare('merge-base', '--is-ancestor', s4, 'main') === '', J(pm).slice(0, 200));// W51b: a containing branch belongs to more than one marker; never deduplicate by branch.const refreshMain = () => { g('fetch', '-q', `http://a:${tA}@mm.localhost:${PORT}/mm.git`, 'main'); g('checkout', '-q', 'main'); g('reset', '-q', '--hard', 'FETCH_HEAD'); };const pullRows = async () => ((await get('/pulls', { host: HOST, cookie: B.cookie })).body.match(/<li>[\s\S]*?<\/li>/g) || []);const rowFor = (rows, number) => rows.find(row => row.includes('href="/pulls/' + number + '"')) || '';refreshMain();const shaA = mkPr('a', 'W51b A'), numA = await prNum(shaA);await put(shaA, 'success');check('W51b PR A on a merges', (await merge(tB, numA)).status === 200);refreshMain();const shaB = mkPr('z', 'W51b B'), numB = await prNum(shaB);g('branch', '0-merged-descendant', 'z'); push('0-merged-descendant');let rows = await pullRows();check('W51b merged A remains listed with stored source a after B branches from main', /class="merged">merged/.test(rowFor(rows, numA)) && /class="source" href="\/branch\/a">a</.test(rowFor(rows, numA)), rowFor(rows, numA));check('W51b B keeps source z although an alphabetically earlier alias contains it', /class="source" href="\/branch\/z">z</.test(rowFor(rows, numB)), rowFor(rows, numB));const mergedA = await merge(tB, numA);check('W51b merging A again returns 409 conflict already_merged after B', mergedA.status === 409 && errOf(mergedA).code === 'conflict' && errOf(mergedA).details?.reason === 'already_merged', mergedA.status + mergedA.body);const shaC = mkPr('c', 'W51b C'), numC = await prNum(shaC);g('commit', '-q', '--allow-empty', '-m', 'C head after its marker'); const headC = sha(); push('c');g('checkout', '-q', '-b', '0-open-descendant'); writeFileSync(join(W, 'later.txt'), 'later\n'); g('add', '-A'); g('commit', '-q', '-m', '|||PR W51b D');const shaD = sha(); push('0-open-descendant'); const numD = await prNum(shaD);await put(headC, 'success');rows = await pullRows();check('W51b open C remains listed and mergeable with stored source c', /class="open">open/.test(rowFor(rows, numC)) && /class="source" href="\/branch\/c">c</.test(rowFor(rows, numC)) && rowFor(rows, numC).includes('class="quiet mergepr"'), rowFor(rows, numC));const cObject = JSON.parse((await api(tB, 'GET', '/api/pulls/' + numC)).body);check('W51b GET agrees on C source and updated head despite the later containing branch', cObject.source === 'c' && cObject.head === headC && cObject.state === 'open', J(cObject));const cMerge = await face(B, 'gitoriaMergePull', ['mm', shaC]);check('W51b C merges through the list button face using only its own head', cMerge && !cMerge.error && bare('merge-base', '--is-ancestor', headC, 'main') === '' && bare('rev-parse', 'main^2') === headC, J(cMerge).slice(0, 200));const dObject = JSON.parse((await api(tB, 'GET', '/api/pulls/' + numD)).body);check('W51b later PR D remains open after C merges', dObject.state === 'open' && dObject.head === shaD, J(dObject));// a member who is removed can merge no moreconst s5 = mkPr('f5', 'five'), n5 = await prNum(s5);await put(s5, 'success');await face(A, 'gitoriaChangeMember', ['mm', 'Bob', false]);check('Bob removed → his token no longer merges (403)', (await merge(tB, n5)).status === 403);for (const path of paths) check('W49 removed member loses read: ' + path, (await api(tB, 'GET', path)).status === 404);const pbGone = await pageBtn(B, n5);check('and his Merge button is gone', pbGone === 'nomerge', pbGone);// The merged record must answer even after git can no longer place its marker in the branch list.for (const branch of bare('for-each-ref', '--contains', shaA, '--format=%(refname)', 'refs/heads').split('\n').filter(Boolean)) bare('update-ref', '-d', branch);const archivedA = await merge(tA, numA);check('W51b merged record returns already_merged even when no branch contains its marker', archivedA.status === 409 && errOf(archivedA).code === 'conflict' && errOf(archivedA).details?.reason === 'already_merged', archivedA.status + archivedA.body);} catch (e) {check('the gate ran without an exception', false, String(e && e.stack || e));} finally {await stop().catch(() => {});try { receiver.close(); } catch {}try { ident && ident.stop && await ident.stop(); } catch {}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