gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitbdcbbaa9bdcbbaa9gitoria#47: rate limits, status read route, statuses + required on the pull (merge w47-limits)mrebdcbbaa9/tests/status.mjs

18.5 KB

  1. // tests/status.mjs — GATE OF THE STATUS AN APP SETS (gitoria#46): PUT {api}/statuses/<sha> (store, replace, validation, unknown sha 422, foreign repo / no token),
  2. // the owner's "required before merge" (Settings, owner only), the Merge refused on the server until every required context is success on the PR's CURRENT head
  3. // (a push after success blocks again), the badges on /pulls. Real HTTP and the real `git`.
  4. // node tests/status.mjs (GITORIA_STATUS_PORT default 8730, GITORIA_STATUS_IDENT_PORT default 8731)
  5. import { spawn, execFileSync } from 'node:child_process';
  6. import { request } from 'node:http';
  7. import { mkdirSync, rmSync, writeFileSync, existsSync } from 'node:fs';
  8. import { dirname, join, resolve } from 'node:path';
  9. import { fileURLToPath } from 'node:url';
  10. import { startIdent } from './identkit.mjs';
  11. const HERE = dirname(fileURLToPath(import.meta.url));
  12. const APP = resolve(HERE, '..');
  13. const PORT = Number(process.env.GITORIA_STATUS_PORT || 8730), IDENT_PORT = Number(process.env.GITORIA_STATUS_IDENT_PORT || 8731);
  14. 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')));
  15. const STORE = join(APP, '.scratch/status-store');
  16. const LIFE = 3000;
  17. const J = JSON.stringify, sleep = (ms) => new Promise(r => setTimeout(r, ms));
  18. let passes = 0, failures = 0;
  19. const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; };
  20. function raw(method, path, { host = `localhost:${PORT}`, headers = {}, body = null, cookie = null } = {}) {
  21. return new Promise((res, rej) => {
  22. const h = { host, ...headers }; if (cookie) h.cookie = cookie;
  23. if (body !== null) h['content-length'] = Buffer.byteLength(body);
  24. 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('latin1') })); });
  25. r.on('error', rej); if (body !== null) r.write(body); r.end();
  26. });
  27. }
  28. const get = (path, o = {}) => raw('GET', path, o);
  29. const at = (label, path, method = 'GET', o = {}) => raw(method, path, { host: `${label}.localhost:${PORT}`, ...o });
  30. const errCode = (r) => { try { return JSON.parse(r.body).error.code; } catch { return null; } };
  31. let server = null, log = '';
  32. function startServer(env) {
  33. log = '';
  34. const p = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],
  35. env: { ...process.env, GITORIA_PORT: String(PORT), GITORIA_WATCH: '0', GITORIA_PUBLIC_URL: `http://localhost:${PORT}`, GITORIA_SSH_SECRET: 'sshsecret-status-gate', GITORIA_TICKETS_URL: 'http://127.0.0.1:1', GITORIA_APP_TOKEN_LIFE_MS: String(LIFE), ...env } });
  36. p.stdout.on('data', d => log += d); p.stderr.on('data', d => log += d);
  37. server = p; return p;
  38. }
  39. 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); }
  40. const stop = async () => { if (server) { const p = server; server = null; p.kill(); await new Promise(r => p.once('exit', r)); } };
  41. let ident;
  42. try {
  43. rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });
  44. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  45. const alice = await ident.signIn('[email protected]');
  46. const BASE = `http://localhost:${PORT}`;
  47. const app = await ident.registerApp(alice, 'gitoria (status gate)', [BASE]);
  48. const ENV = { GITORIA_STORAGE: join(STORE, 'mpackdb'), GITORIA_SESSIONS: join(STORE, 'sessions') + '/', GITORIA_GIT: join(STORE, 'git'), IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base, IDENT_API_KEY: app.key, IDENT_API_SECRET: app.secret };
  49. startServer(ENV); await up();
  50. const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;
  51. const ck0 = cookieOf(await get('/'));
  52. const cb = await get('/login/callback?ident_code=' + await ident.selectorCode(alice, app, BASE) + '&next=%2F', { cookie: ck0 });
  53. const A = { cookie: cookieOf(cb) || ck0 };
  54. let n = 0;
  55. const face = async (event, payload, cookie = A.cookie) => {
  56. const r = await raw('POST', '/__hl/emit', { headers: { 'content-type': 'application/json' }, cookie, body: J({ t: 'emit', i: ++n, event, payload }) });
  57. let j = null; try { j = JSON.parse(r.body); } catch {}
  58. return j && j.value;
  59. };
  60. await face('gitoriaSaveName', ['Alice']);
  61. const tA = (await face('gitoriaMakeToken', ['a'])).token;
  62. const W = join(STORE, 'work'); mkdirSync(W, { recursive: true });
  63. 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' };
  64. const g = (...a) => execFileSync('git', a, { cwd: W, encoding: 'utf8', env: genv, stdio: ['ignore', 'pipe', 'pipe'] });
  65. const sh = (fn) => { try { return fn(); } catch (e) { return null; } };
  66. const urlOf = (host, path) => `http://a:${tA}@${host}.localhost:${PORT}/${path}`;
  67. const push = (host, path, ...refs) => sh(() => { g('push', '-q', urlOf(host, path), ...refs); return true; });
  68. const sha = () => g('rev-parse', 'HEAD').trim();
  69. g('init', '-q', '-b', 'main'); writeFileSync(join(W, 'README.md'), '# t\n'); g('add', '-A'); g('commit', '-q', '-m', 'init');
  70. const mainSha = sha();
  71. check('alice creates "pub" and "other"', !!(await face('gitoriaCreate', ['pub', 'p'])).repo && !!(await face('gitoriaCreate', ['other', 'o'])).repo);
  72. check('alice pushes main to pub and to other', push('pub', 'pub.git', 'main') === true && push('other', 'other.git', 'main') === true);
  73. // a pull request on pub: branch feat with a |||PR commit
  74. g('checkout', '-q', '-b', 'feat'); writeFileSync(join(W, 'a.txt'), 'a\n'); g('add', '-A'); g('commit', '-q', '-m', '|||PR Add a');
  75. const prCommit = sha(), h1 = sha();
  76. check('alice pushes the branch feat with a |||PR commit', push('pub', 'pub.git', 'feat') === true);
  77. g('checkout', '-q', 'main'); g('checkout', '-q', '-b', 'lone'); writeFileSync(join(W, 'o.txt'), 'o\n'); g('add', '-A'); g('commit', '-q', '-m', 'only on other');
  78. const otherSha = sha();
  79. check('a commit that exists only in the repo "other"', push('other', 'other.git', 'lone') === true);
  80. const addApp = (slug, name) => face('gitoriaAppAdd', [slug, name, 'https://kunibert.worldapi.org/hook']);
  81. const kPub = await addApp('pub', 'Kunibert'), kOther = await addApp('other', 'Otto');
  82. check('apps added with keys', /^gak_/.test(kPub.key || '') && /^gak_/.test(kOther.key || ''), J([kPub, kOther]).slice(0, 200));
  83. const tok = async (host, key) => JSON.parse((await raw('POST', '/api/apps/token', { host: `${host}.localhost:${PORT}`, headers: { authorization: 'Bearer ' + key } })).body).token;
  84. const tPub = await tok('pub', kPub.key), tOther = await tok('other', kOther.key);
  85. const put = (host, token, shaArg, body, path = '/api/statuses/') => raw('PUT', path + shaArg, { host: `${host}.localhost:${PORT}`, headers: { ...(token ? { authorization: 'Bearer ' + token } : {}), 'content-type': 'application/json' }, body: typeof body === 'string' ? body : J(body) });
  86. const ok = (r) => { try { return JSON.parse(r.body).status; } catch { return null; } };
  87. const st = (context, state, extra = {}) => ({ context, state, title: 'a title', summary: '**md**', url: null, ...extra });
  88. const pullsHtml = async () => { const b = (await get('/pulls', { host: `pub.localhost:${PORT}`, cookie: A.cookie })).body; writeFileSync(join(STORE, 'pulls.html'), b); return b; };
  89. const mergeClass = (html) => (html.match(/<button class="([^"]*)" type="button" value="[0-9a-f]{40}">Merge/) || [])[1];
  90. // ---- 1. the PUT ------------------------------------------------------------------------------------------------------------------
  91. const r1 = await put('pub', tPub, h1, st('kunibert', 'pending'));
  92. const s1 = ok(r1);
  93. check('PUT statuses/<sha>: 200 { status } with sha, context, state, title, summary, url, app, updated', r1.status === 200 && s1 && s1.sha === h1 && s1.context === 'kunibert' && s1.state === 'pending' && s1.title === 'a title' && s1.summary === '**md**' && s1.url === null && s1.app.name === 'Kunibert' && /^\d{4}-.*Z$/.test(s1.updated), r1.status + r1.body);
  94. await sleep(20);
  95. const r2 = await put('pub', tPub, h1, st('kunibert', 'failure', { title: 'second', url: 'https://kunibert.worldapi.org/r/1' }));
  96. const s2 = ok(r2);
  97. check('a newer PUT of the same (sha, context) replaces it: new state, title and https url, newer time', r2.status === 200 && s2.state === 'failure' && s2.title === 'second' && s2.url === 'https://kunibert.worldapi.org/r/1' && Date.parse(s2.updated) >= Date.parse(s1.updated), r2.body);
  98. let html = await pullsHtml();
  99. check('/pulls shows ONE badge for it (replaced, not added): failure, "Kunibert: kunibert", the title as text', (html.match(/<span class="label">Kunibert: kunibert<\/span>/g) || []).length === 1 && /<span class="badge failure"><span class="state">failure<\/span>/.test(html) && /<span class="muted">second<\/span>/.test(html) && !/<span class="muted">a title<\/span>/.test(html), html.slice(html.indexOf('pulllist'), html.indexOf('pulllist') + 900));
  100. const big = await put('pub', tPub, h1, st('big', 'success', { summary: 'x'.repeat(65536) }));
  101. check('a summary of exactly 65,536 characters is accepted', big.status === 200, big.status + big.body.slice(0, 100));
  102. const bigger = await put('pub', tPub, h1, st('big', 'success', { summary: 'x'.repeat(65537) }));
  103. check('a summary of 65,537 characters → 422 invalid', bigger.status === 422 && errCode(bigger) === 'invalid', bigger.status);
  104. for (const [label, body] of [['an unknown state', st('c', 'done')], ['no context', st('', 'success')], ['an http url', st('c', 'success', { url: 'http://x.worldapi.org/' })], ['a javascript: url', st('c', 'success', { url: 'javascript:alert(1)' })], ['a two-line context', st('a\nb', 'success')]]) {
  105. const r = await put('pub', tPub, h1, body);
  106. check(`${label} → 422 invalid with details`, r.status === 422 && errCode(r) === 'invalid' && Array.isArray(JSON.parse(r.body).error.details), r.status + r.body.slice(0, 120));
  107. }
  108. check('a body that is not JSON → 400 invalid_json', errCode(await put('pub', tPub, h1, 'nope')) === 'invalid_json');
  109. check('no token → 401, an unknown token → 401', (await put('pub', null, h1, st('c', 'success'))).status === 401 && (await put('pub', 'gat_' + 'a'.repeat(40), h1, st('c', 'success'))).status === 401);
  110. check('POST on the status route → 405', (await raw('POST', '/api/statuses/' + h1, { host: `pub.localhost:${PORT}`, headers: { authorization: 'Bearer ' + tPub }, body: '{}' })).status === 405);
  111. // ---- 2. foreign repo, unknown sha ----------------------------------------------------------------------------------------------
  112. check('the token of the app of "other" on the address of pub → 404 not_found', (await put('pub', tOther, h1, st('c', 'success'))).status === 404 && errCode(await put('pub', tOther, h1, st('c', 'success'))) === 'not_found');
  113. check('an address that names no repo → 404', (await put('nosuch', tPub, h1, st('c', 'success'))).status === 404);
  114. const u1 = await put('pub', tPub, '0'.repeat(40), st('c', 'success'));
  115. check('a well-formed sha that is no object → 422 invalid', u1.status === 422 && errCode(u1) === 'invalid', u1.status + u1.body.slice(0, 120));
  116. check('a commit that exists only in ANOTHER repo → 422 (and nothing is stored)', (await put('pub', tPub, otherSha, st('c', 'success'))).status === 422);
  117. check('a short sha and garbage → 422', (await put('pub', tPub, h1.slice(0, 8), st('c', 'success'))).status === 422 && (await put('pub', tPub, 'zz%20zz', st('c', 'success'))).status === 422);
  118. check('the other app sets a status on its own repo (200)', (await put('other', tOther, otherSha, st('lint', 'success'))).status === 200);
  119. check('a tree/blob sha of pub is no commit → 422', (await put('pub', tPub, g('rev-parse', mainSha + '^{tree}').trim(), st('c', 'success'))).status === 422);
  120. // ---- 3. required before merge --------------------------------------------------------------------------------------------------
  121. html = await pullsHtml();
  122. check('before anything is required the Merge button is on', mergeClass(html) === 'quiet mergepr', mergeClass(html));
  123. check('Settings: nobody signed in cannot require a context', ((await face('gitoriaRequiredAdd', ['pub', 'kunibert'], null)) || {}).error != null);
  124. const bob = await ident.signIn('[email protected]');
  125. const ckb0 = cookieOf(await get('/'));
  126. const cbb = await get('/login/callback?ident_code=' + await ident.selectorCode(bob, app, BASE) + '&next=%2F', { cookie: ckb0 });
  127. const B = cookieOf(cbb) || ckb0;
  128. check('Settings: a signed-in person who does not own the repo cannot require a context', ((await face('gitoriaRequiredAdd', ['pub', 'kunibert'], B)) || {}).error != null);
  129. const sBob = (await get('/settings', { host: `pub.localhost:${PORT}`, cookie: B })).body;
  130. writeFileSync(join(STORE, 'settings-bob.html'), sBob);
  131. check('Settings page: the owner sees "Required before merge", another person does not', !/<h2>Required before merge/.test(sBob) && /id="requiredform"/.test((await get('/settings', { host: `pub.localhost:${PORT}`, cookie: A.cookie })).body));
  132. const rq = await face('gitoriaRequiredAdd', ['pub', 'kunibert']);
  133. check('the owner requires the context "kunibert"', rq && rq.rows && rq.rows.length === 1 && rq.rows[0].name === 'kunibert', J(rq));
  134. check('requiring it twice keeps one row', ((await face('gitoriaRequiredAdd', ['pub', 'kunibert'])).rows || []).length === 1);
  135. const sOwn = (await get('/settings', { host: `pub.localhost:${PORT}`, cookie: A.cookie })).body;
  136. check('Settings page lists it after a reload', />kunibert</.test(sOwn.slice(sOwn.indexOf('id="requiredlist"'))));
  137. html = await pullsHtml();
  138. check('/pulls: the status on the head is failure → the Merge button is off and says what it waits for', mergeClass(html) === 'nomerge' && /Merge waits for: kunibert \(failure\)/.test(html), mergeClass(html));
  139. const m1 = await face('gitoriaMergePull', ['pub', prCommit]);
  140. check('server: Merge is refused while the context is failure, and the refusal names it', m1 && /kunibert \(failure\)/.test(m1.error || '') && /Not merged/.test(m1.error), J(m1));
  141. await put('pub', tPub, h1, st('kunibert', 'pending'));
  142. check('server: pending still refuses', /kunibert \(pending\)/.test(((await face('gitoriaMergePull', ['pub', prCommit])) || {}).error || ''));
  143. await put('pub', tPub, h1, st('kunibert', 'error', { title: 'could not run' }));
  144. html = await pullsHtml();
  145. check('server: error does not count as success; /pulls shows it as its own badge (class "badge error")', /kunibert \(error\)/.test(((await face('gitoriaMergePull', ['pub', prCommit])) || {}).error || '') && /class="badge error"/.test(html) && />could not run</.test(html));
  146. await put('pub', tPub, h1, st('kunibert', 'success', { title: 'all fine' }));
  147. html = await pullsHtml();
  148. check('success on the current head → /pulls: badge "success", the Merge button is on again', /class="badge success"/.test(html) && mergeClass(html) === 'quiet mergepr' && />all fine</.test(html), mergeClass(html));
  149. // a push after success: a new head
  150. g('checkout', '-q', 'feat'); writeFileSync(join(W, 'b.txt'), 'b\n'); g('add', '-A'); g('commit', '-q', '-m', 'more work');
  151. const h2 = sha();
  152. check('alice pushes one more commit to feat (a new head)', push('pub', 'pub.git', 'feat') === true && h2 !== h1);
  153. html = await pullsHtml();
  154. check('after the push the success of the OLD head does not count: no badge, the Merge button is off again', mergeClass(html) === 'nomerge' && !/class="badge success"/.test(html) && /kunibert \(not set\)/.test(html), mergeClass(html));
  155. const m2 = await face('gitoriaMergePull', ['pub', prCommit]);
  156. check('server: Merge is refused on the new head ("not set")', m2 && /kunibert \(not set\)/.test(m2.error || ''), J(m2));
  157. check('a status for the NEW head: 200', (await put('pub', tPub, h2, st('kunibert', 'success'))).status === 200);
  158. html = await pullsHtml();
  159. check('success on the new head: its badge shows, the button is on', /class="badge success"/.test(html) && mergeClass(html) === 'quiet mergepr');
  160. // two contexts: both must be success
  161. await face('gitoriaRequiredAdd', ['pub', 'lint']);
  162. const m3 = await face('gitoriaMergePull', ['pub', prCommit]);
  163. check('a second required context ("lint") that was never set refuses the merge too, and names only it', m3 && /lint \(not set\)/.test(m3.error || '') && !/kunibert \(/.test(m3.error || ''), J(m3));
  164. await put('pub', tPub, h2, st('lint', 'success'));
  165. const m4 = await face('gitoriaMergePull', ['pub', prCommit]);
  166. check('every required context success on the current head → the Merge goes through', m4 && m4.error == null && m4.result, J(m4).slice(0, 200));
  167. check('the merge really happened on the server (main moved, feat is in it)', sh(() => { g('fetch', '-q', urlOf('pub', 'pub.git'), 'main:refs/remotes/pub/main'); return g('merge-base', '--is-ancestor', h2, 'refs/remotes/pub/main') === ''; }) === true);
  168. const rm = await face('gitoriaRequiredRemove', ['pub', rq.rows[0].id]);
  169. check('the owner can drop a requirement again', rm && rm.rows && rm.rows.length === 1 && rm.rows[0].name === 'lint', J(rm));
  170. check('the key and a token never appear in the server log', ![kPub.key, kOther.key, tPub, tOther].some(s => log.includes(s)));
  171. await stop();
  172. // ---- 4. a restart: statuses and requirements are stored -----------------------------------------------------------------------------
  173. startServer(ENV); await up();
  174. const rr = await put('pub', tPub, h2, st('kunibert', 'failure'));
  175. const htmlR = await pullsHtml();
  176. check('after a restart the token still works, the PUT replaces the stored row (one badge, now failure)', rr.status === 200 && (htmlR.match(/<span class="label">Kunibert: kunibert<\/span>/g) || []).length === 1 && /class="badge failure"/.test(htmlR) && !/<span class="badge success"><span class="state">success<\/span><span class="label">Kunibert: kunibert/.test(htmlR));
  177. const again = await face('gitoriaRequiredAdd', ['pub', 'lint'], A.cookie);
  178. check('after a restart the requirement "lint" is still stored (adding it again keeps one row)', again && again.rows && again.rows.length === 1, J(again));
  179. } catch (e) {
  180. check('the gate ran without an exception', false, String(e && e.stack || e));
  181. } finally {
  182. await stop().catch(() => {});
  183. try { ident && ident.stop && await ident.stop(); } catch {}
  184. console.log(`\n${passes} passed, ${failures} failed`);
  185. process.exit(failures ? 1 : 0);
  186. }

Branches

Latest commits

  • bdcbbaa9gitoria#47: rate limits, status read route, statuses + required on the pull (merge w47-limits)mre
  • 772c401fgitoria#45: W45 report, logmre
  • b6b793afgitoria#45: PR page with reviews, threads, conversation, Review again (merge w45-pr-page)mre
  • fb9e7554gitoria#45: browser gate: a /pulls title links to the PR pagemre
  • f7198131gitoria#45: tests/pr-page.mjs gatemre
  • 483141d0gitoria#45: Settings shows the Apps heading only to the ownermre
  • e2eff8f6gitoria#45: the PR page /pulls/N with reviews, threads, verdicts, conversation, comment, reply, resolve and Review againmre
  • 7a602839gitoria#45: raiseEvent can send to one app only; people's comments, replies and resolving in reviews.hlmre
  • 5de7f578gitoria#47: rate limits per app (429, Retry-After), status read route, statuses and required on the pull, one JSON check for every write routemre
  • 19edc1f5gitoria#44: contract v1.3.1, what outdated meansmre
  • 7c2277ccgitoria#38: worker reports W40–W46, logmre
  • 1c3fa842gitoria#45 #47: worker briefsmre
  • 0a46bf7dgitoria#47: apps API contract v1.3 (status read route, statuses + required on the pull)mre
  • 3373f7c3gitoria#38: push API contract v1.2.1, reviews, worker briefs and logmre
  • 34143d2cgitoria#46: closing brace of appComments lost in the mergemre
  • 54927c9cgitoria#46: PR statuses and required checks before merge (merge w46-status)mre
  • 187e1871gitoria#46: badges without decorative bordersmre
  • 6b022798gitoria#46: tests/status.mjs in GATESmre
  • c6162f00gitoria#46: status badges on /pulls, Required before merge in Settingsmre
  • e5a0b64egitoria#46: PUT statuses/<sha>, required contexts block the merge on the servermre