gitoria

gitoria

All repositories: gitoria

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

29.7 KB

  1. import { requiredPort, requiredPortRange } from './gate-ports.mjs';
  2. // 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
  3. // — 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
  4. // 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.
  5. // Real HTTP, the real `git`, its own storage under .scratch/member-merge-store.
  6. // node tests/member-merge.mjs (GITORIA_MM_PORT required = gitoria, +1 event receiver, +4 ident)
  7. import { spawn, execFileSync } from 'node:child_process';
  8. import { request, createServer } from 'node:http';
  9. import { mkdirSync, rmSync, writeFileSync, existsSync } from 'node:fs';
  10. import { dirname, join, resolve } from 'node:path';
  11. import { fileURLToPath } from 'node:url';
  12. import { startIdent } from './identkit.mjs';
  13. import { launchBrowser } from './cdp.mjs';
  14. const HERE = dirname(fileURLToPath(import.meta.url));
  15. const APP = resolve(HERE, '..');
  16. const CHROME = requiredPortRange('GITORIA_GATE_CHROME');
  17. const PORT = requiredPort('GITORIA_MM_PORT'), RPORT = PORT + 1, IDENT_PORT = process.env.GITORIA_MM_IDENT_PORT ? requiredPort('GITORIA_MM_IDENT_PORT') : PORT + 4;
  18. 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')));
  19. const STORE = join(APP, '.scratch/member-merge-store');
  20. const J = JSON.stringify, sleep = (ms) => new Promise(r => setTimeout(r, ms));
  21. let passes = 0, failures = 0;
  22. const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; };
  23. const got = [];
  24. 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(); }); });
  25. await new Promise(r => receiver.listen(RPORT, '127.0.0.1', r));
  26. function raw(method, path, { host = `localhost:${PORT}`, headers = {}, body = null, cookie = null } = {}) {
  27. return new Promise((res, rej) => {
  28. const h = { host, ...headers }; if (cookie) h.cookie = cookie;
  29. if (body !== null) h['content-length'] = Buffer.byteLength(body);
  30. 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') })); });
  31. r.on('error', rej); if (body !== null) r.write(body); r.end();
  32. });
  33. }
  34. const get = (path, o = {}) => raw('GET', path, o);
  35. const errOf = (r) => { try { return JSON.parse(r.body).error; } catch { return {}; } };
  36. let server = null, log = '';
  37. 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); }
  38. const stop = async () => { if (server) { const p = server; server = null; p.kill(); await new Promise(r => p.once('exit', r)); } };
  39. let ident;
  40. try {
  41. rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });
  42. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  43. const alice = await ident.signIn('[email protected]'), bob = await ident.signIn('[email protected]'), carol = await ident.signIn('[email protected]');
  44. const BASE = `http://localhost:${PORT}`;
  45. const app = await ident.registerApp(alice, 'gitoria (member-merge gate)', [BASE]);
  46. const GIT = join(STORE, 'git');
  47. 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 };
  48. server = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],
  49. 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 } });
  50. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  51. await up();
  52. const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;
  53. 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 }; };
  54. let n = 0;
  55. 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; };
  56. const A = await login(alice), B = await login(bob), C = await login(carol);
  57. await face(A, 'gitoriaSaveName', ['Alice']); await face(B, 'gitoriaSaveName', ['Bob']); await face(C, 'gitoriaSaveName', ['Carol']);
  58. const tA = (await face(A, 'gitoriaMakeToken', ['a'])).token, tB = (await face(B, 'gitoriaMakeToken', ['b'])).token, tC = (await face(C, 'gitoriaMakeToken', ['c'])).token;
  59. const W = join(STORE, 'work'); mkdirSync(W, { recursive: true });
  60. 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' };
  61. const g = (...a) => execFileSync('git', a, { cwd: W, encoding: 'utf8', env: genv, stdio: ['ignore', 'pipe', 'pipe'] });
  62. const bare = (...a) => execFileSync('git', a, { cwd: join(GIT, 'mm.git'), encoding: 'utf8', env: genv, stdio: ['ignore', 'pipe', 'pipe'] }).trim();
  63. const push = (...refs) => { try { g('push', '-q', `http://a:${tA}@mm.localhost:${PORT}/mm.git`, ...refs); return true; } catch { return false; } };
  64. const sha = () => g('rev-parse', 'HEAD').trim();
  65. 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; };
  66. g('init', '-q', '-b', 'main'); writeFileSync(join(W, 'README.md'), '# t\n'); g('add', '-A'); g('commit', '-q', '-m', 'init');
  67. check('alice creates "mm", pushes main', !!(await face(A, 'gitoriaCreate', ['mm', 'm'])).repo && push('main'));
  68. const added = await face(A, 'gitoriaChangeMember', ['mm', 'Bob', true]);
  69. check('alice adds Bob as a member (Carol is not)', added && added.members && added.members.length === 1, J(added));
  70. const kApp = await face(A, 'gitoriaAppAdd', ['mm', 'Kunibert', `http://127.0.0.1:${RPORT}/a`]);
  71. const tApp = JSON.parse((await raw('POST', '/api/apps/token', { host: `mm.localhost:${PORT}`, headers: { authorization: 'Bearer ' + kApp.key } })).body).token;
  72. const idK = (kApp.rows.find(x => x.name === 'Kunibert') || {}).id;
  73. check('an app (Kunibert) is connected to mm and has a token', /^gak_/.test(kApp.key || '') && !!tApp && !!idK);
  74. const HOST = `mm.localhost:${PORT}`;
  75. const merge = (token, num, body = null) => raw('POST', `/api/pulls/${num}/merge`, { host: HOST, headers: { ...(token ? { authorization: 'Bearer ' + token } : {}), 'content-type': 'application/json' }, body });
  76. 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 }) });
  77. 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; };
  78. // ---- 1. nothing required yet: the owner merges (API), a member merges through the button's face
  79. const s1 = mkPr('f1', 'one'), s2 = mkPr('f2', 'two'), s3 = mkPr('f3', 'three'), s4 = mkPr('f4', 'four');
  80. const n1 = await prNum(s1), n2 = await prNum(s2), n3 = await prNum(s3), n4 = await prNum(s4);
  81. 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]));
  82. // W49: member reads share the app body shape; only apps can write or inspect deliveries.
  83. 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) });
  84. 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' }] });
  85. check('W49 app still posts a review with an inline thread', review.status === 201, review.body);
  86. const threadId = JSON.parse(review.body).threads[0].id;
  87. check('W49 app still posts a conversation comment', (await api(tApp, 'POST', `/api/pulls/${n3}/comments`, { body: 'conversation' })).status === 201);
  88. await put(s4, 'pending');
  89. const paths = ['/api/pulls?state=all', `/api/pulls/${n3}`, `/api/pulls/${n3}/reviews`, `/api/pulls/${n3}/threads`, `/api/pulls/${n3}/comments`, '/api/statuses/' + s4];
  90. for (const path of paths) {
  91. const a = await api(tApp, 'GET', path), b = await api(tB, 'GET', path), owner = await api(tA, 'GET', path);
  92. 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());
  93. const stranger = await api(tC, 'GET', path), anon = await api(null, 'GET', path), bad = await api('gtr_' + 'a'.repeat(40), 'GET', path);
  94. const anonOpen = path === `/api/pulls/${n3}` || path === '/api/statuses/' + s4;
  95. 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());
  96. }
  97. // ---- gitoria#51: anonymous reads of public repos (no Authorization header at all), only GET pulls/N and GET statuses/<sha>
  98. const anonPull = await api(null, 'GET', `/api/pulls/${n3}`), anonSt = await api(null, 'GET', '/api/statuses/' + s4);
  99. 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));
  100. 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));
  101. const anon404 = await api(null, 'GET', '/api/pulls/999'), anonSha = await api(null, 'GET', '/api/statuses/' + 'e'.repeat(40));
  102. 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);
  103. 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));
  104. 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);
  105. const missing = await raw('GET', `/api/pulls/${n3}`, { host: `nosuchrepo.localhost:${PORT}` });
  106. check('#51 a missing repo → 404 not_found', missing.status === 404 && errOf(missing).code === 'not_found', missing.status + missing.body);
  107. const goPriv = await face(A, 'gitoriaSetPrivate', ['mm', true]);
  108. 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));
  109. 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');
  110. 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);
  111. 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);
  112. await face(A, 'gitoriaSetPrivate', ['mm', false]);
  113. check('#51 public again: anonymous GET pulls/N → 200', (await api(null, 'GET', `/api/pulls/${n3}`)).status === 200);
  114. if (process.env.W49_REAL_CDP) {
  115. process.env.HL_CDP_URL = process.env.W49_REAL_CDP;
  116. const before = (await (await fetch(process.env.HL_CDP_URL + '/json/list')).json()).filter(t => t.type === 'page');
  117. writeFileSync(join(APP, '.scratch/w49/chrome-before.json'), J(before));
  118. const browser = await launchBrowser({ debugPortRange: CHROME }); let page;
  119. try {
  120. page = await browser.newPage();
  121. await page.goto(`http://mm.localhost:${PORT}/pulls/${n3}`);
  122. for (const [width, height] of [[390, 844], [800, 1280], [1280, 800], [1280, 900]]) {
  123. await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width === 390 });
  124. for (const path of paths) {
  125. 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() }; })()`);
  126. check(`W49 real Chrome ${width}x${height} member reads ${path}`, got.status === 200, got.status);
  127. }
  128. await page.send('Page.reload');
  129. await page.waitForSelector('#pullpage');
  130. const shot = await page.send('Page.captureScreenshot', { format: 'png' });
  131. writeFileSync(join(APP, `.scratch/w49/chrome-${width}x${height}.png`), Buffer.from(shot.data, 'base64'));
  132. }
  133. } finally {
  134. try { if (page) await page.close(); } finally { browser.conn.close(); }
  135. const after = (await (await fetch(process.env.HL_CDP_URL + '/json/list')).json()).filter(t => t.type === 'page');
  136. writeFileSync(join(APP, '.scratch/w49/chrome-after.json'), J(after));
  137. check('W49 real Chrome leaves only original page targets', J(after.map(t => t.id).sort()) === J(before.map(t => t.id).sort()));
  138. delete process.env.HL_CDP_URL;
  139. }
  140. }
  141. 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';
  142. 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']]) {
  143. const r = await api(tB, method, path, {});
  144. 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);
  145. }
  146. for (const [method, path] of [['POST', `/api/pulls/${n3}/reviews`], ['PUT', '/api/statuses/' + s3]]) {
  147. for (const token of [null, 'gtr_' + 'a'.repeat(40)]) {
  148. const r = await api(token, method, path, {});
  149. check('W51 missing or unknown user token stays 401: ' + method, r.status === 401 && errOf(r).code === 'unauthorized', r.status + r.body);
  150. }
  151. }
  152. check('W49 unknown app token retains old message', /missing, unknown or expired token/.test(errOf(await api('gat_unknown', 'GET', paths[0])).message || ''));
  153. const kSecond = await face(A, 'gitoriaAppAdd', ['mm', 'Second', `http://127.0.0.1:${RPORT}/b`]);
  154. const tSecond = JSON.parse((await api(kSecond.key, 'POST', '/api/apps/token')).body).token;
  155. 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' }] });
  156. check('W49 another app posts its review and thread', review2.status === 201);
  157. for (const kind of ['reviews', 'threads']) {
  158. const path = `/api/pulls/${n3}/${kind}`;
  159. 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);
  160. 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);
  161. const first = JSON.parse((await api(tB, 'GET', path + '?limit=1')).body);
  162. const next = JSON.parse((await api(tB, 'GET', path + '?limit=1&cursor=' + encodeURIComponent(first.next))).body);
  163. 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);
  164. }
  165. const m1 = await merge(tA, n1);
  166. const j1 = (() => { try { return JSON.parse(m1.body); } catch { return {}; } })();
  167. 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));
  168. 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'));
  169. const btn = await face(B, 'gitoriaMergePull', ['mm', s2]);
  170. check('the MEMBER merges PR 2 with the button (server face)', btn && !btn.error && btn.result, J(btn).slice(0, 200));
  171. check('PR 2 is merged; author of the merge commit = Bob', bare('log', '-1', '--format=%an', 'main') === 'Bob', '');
  172. const strangerFace = await face(C, 'gitoriaMergePull', ['mm', s3]);
  173. 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);
  174. // ---- 2. required check
  175. const rq = await face(A, 'gitoriaRequiredAdd', ['mm', idK, 'ci']);
  176. check('the owner requires Kunibert · ci', rq && rq.rows && rq.rows.length === 1, J(rq));
  177. const before = bare('rev-parse', 'refs/heads/main');
  178. const checkDetails = (r, state) => J(errOf(r).details) === J([{ app: { id: idK, name: 'Kunibert' }, context: 'ci', state }]);
  179. const r0 = await merge(tB, n3);
  180. 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));
  181. await put(s3, 'pending');
  182. const r1 = await merge(tB, n3);
  183. 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));
  184. await put(s3, 'failure');
  185. const r2 = await merge(tB, n3);
  186. 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));
  187. const rOwn = await merge(tA, n3);
  188. check('the owner is held by the same required check (422)', rOwn.status === 422 && errOf(rOwn).code === 'checks_failed', rOwn.status);
  189. // ---- 3. who may not
  190. await put(s3, 'success');
  191. const rApp = await merge(tApp, n3);
  192. 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);
  193. const rC = await merge(tC, n3);
  194. check('a signed-in non-member (gtr_) → 403', rC.status === 403 && errOf(rC).code === 'forbidden', rC.status + rC.body);
  195. const rNo = await merge(null, n3), rBad = await merge('gtr_' + 'a'.repeat(40), n3), rJunk = await merge('nonsense', n3);
  196. check('no token / an unknown gtr_ / junk → 401', rNo.status === 401 && rBad.status === 401 && rJunk.status === 401, [rNo.status, rBad.status, rJunk.status].join());
  197. check('GET on the merge route → 405', (await raw('GET', `/api/pulls/${n3}/merge`, { host: HOST, headers: { authorization: 'Bearer ' + tB } })).status === 405);
  198. const r404 = await merge(tB, 999);
  199. check('unknown PR → 404 not_found', r404.status === 404 && errOf(r404).code === 'not_found', r404.status);
  200. check('PR 3 still open after all refusals', bare('rev-parse', 'refs/heads/main') === before);
  201. // ---- 4. the button: visible for owner + member, hidden for others
  202. const 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]); };
  203. 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]; };
  204. const lb = await listBtn(B), lc = await listBtn(C), ln = await listBtn(null), la = await listBtn(A);
  205. 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]));
  206. check('/pulls: Carol and the signed-out viewer see no visible Merge button', !lc.includes('quiet mergepr') && !ln.includes('quiet mergepr'), J([lc, ln]));
  207. const pb = await pageBtn(B, n3), pa = await pageBtn(A, n3), pc = await pageBtn(C, n3), pn = await pageBtn(null, n3);
  208. 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]));
  209. const pageFace = await face(C, 'gitoriaPrMerge', ['mm', '' + n3]);
  210. check('the PR page\'s merge face refuses a stranger', pageFace && /only the owner and the members/.test(pageFace.error || ''), J(pageFace));
  211. // ---- 5. stale head, then the member merges (event with sender = Bob)
  212. const stale = await merge(tB, n3, J({ head: 'f'.repeat(40) }));
  213. 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));
  214. check('a malformed head → 422', (await merge(tB, n3, J({ head: 'abc' }))).status === 422);
  215. check('a body that is not JSON → 400', (await merge(tB, n3, 'nope')).status === 400);
  216. const k = got.length;
  217. const ok = await merge(tB, n3, J({ head: s3 }));
  218. const jo = (() => { try { return JSON.parse(ok.body); } catch { return {}; } })();
  219. 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));
  220. check('the merge commit author = Bob', bare('log', '-1', '--format=%an', 'main') === 'Bob');
  221. for (let i = 0; i < 100 && !got.slice(k).some(x => x.body.includes('"merged"')); i++) await sleep(100);
  222. 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);
  223. 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));
  224. const again = await merge(tB, n3);
  225. 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));
  226. 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');
  227. // the PR page's own Merge button (its face) merges for the owner and answers the page read again
  228. await put(s4, 'success');
  229. const pm = await face(A, 'gitoriaPrMerge', ['mm', '' + n4]);
  230. 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));
  231. // W51b: a containing branch belongs to more than one marker; never deduplicate by branch.
  232. const refreshMain = () => { g('fetch', '-q', `http://a:${tA}@mm.localhost:${PORT}/mm.git`, 'main'); g('checkout', '-q', 'main'); g('reset', '-q', '--hard', 'FETCH_HEAD'); };
  233. const pullRows = async () => ((await get('/pulls', { host: HOST, cookie: B.cookie })).body.match(/<li>[\s\S]*?<\/li>/g) || []);
  234. const rowFor = (rows, number) => rows.find(row => row.includes('href="/pulls/' + number + '"')) || '';
  235. refreshMain();
  236. const shaA = mkPr('a', 'W51b A'), numA = await prNum(shaA);
  237. await put(shaA, 'success');
  238. check('W51b PR A on a merges', (await merge(tB, numA)).status === 200);
  239. refreshMain();
  240. const shaB = mkPr('z', 'W51b B'), numB = await prNum(shaB);
  241. g('branch', '0-merged-descendant', 'z'); push('0-merged-descendant');
  242. let rows = await pullRows();
  243. 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));
  244. 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));
  245. const mergedA = await merge(tB, numA);
  246. 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);
  247. const shaC = mkPr('c', 'W51b C'), numC = await prNum(shaC);
  248. g('commit', '-q', '--allow-empty', '-m', 'C head after its marker'); const headC = sha(); push('c');
  249. g('checkout', '-q', '-b', '0-open-descendant'); writeFileSync(join(W, 'later.txt'), 'later\n'); g('add', '-A'); g('commit', '-q', '-m', '|||PR W51b D');
  250. const shaD = sha(); push('0-open-descendant'); const numD = await prNum(shaD);
  251. await put(headC, 'success');
  252. rows = await pullRows();
  253. 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));
  254. const cObject = JSON.parse((await api(tB, 'GET', '/api/pulls/' + numC)).body);
  255. 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));
  256. const cMerge = await face(B, 'gitoriaMergePull', ['mm', shaC]);
  257. 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));
  258. const dObject = JSON.parse((await api(tB, 'GET', '/api/pulls/' + numD)).body);
  259. check('W51b later PR D remains open after C merges', dObject.state === 'open' && dObject.head === shaD, J(dObject));
  260. // a member who is removed can merge no more
  261. const s5 = mkPr('f5', 'five'), n5 = await prNum(s5);
  262. await put(s5, 'success');
  263. await face(A, 'gitoriaChangeMember', ['mm', 'Bob', false]);
  264. check('Bob removed → his token no longer merges (403)', (await merge(tB, n5)).status === 403);
  265. for (const path of paths) check('W49 removed member loses read: ' + path, (await api(tB, 'GET', path)).status === 404);
  266. const pbGone = await pageBtn(B, n5);
  267. check('and his Merge button is gone', pbGone === 'nomerge', pbGone);
  268. // The merged record must answer even after git can no longer place its marker in the branch list.
  269. for (const branch of bare('for-each-ref', '--contains', shaA, '--format=%(refname)', 'refs/heads').split('\n').filter(Boolean)) bare('update-ref', '-d', branch);
  270. const archivedA = await merge(tA, numA);
  271. 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);
  272. } catch (e) {
  273. check('the gate ran without an exception', false, String(e && e.stack || e));
  274. } finally {
  275. await stop().catch(() => {});
  276. try { receiver.close(); } catch {}
  277. try { ident && ident.stop && await ident.stop(); } catch {}
  278. console.log(`\n${passes} passed, ${failures} failed`);
  279. process.exit(failures ? 1 : 0);
  280. }

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