gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit2f2959c52f2959c5|||PR apps API: broken JSON body gives 400 invalid_json, not 500mre2f2959c5/tests/status-keyed.mjs

10.6 KB

  1. // tests/status-keyed.mjs — GATE OF gitoria#46 / contract v1.4 (statuses keyed by app + context). Real HTTP, real git, and the OLD code (the commit before the change, 9678a8f,
  2. // taken with `git archive`) on the SAME storage: a status row written in the OLD shape (one row per sha + context, key without the app id) must still be read after the
  3. // new code starts, and must be replaced correctly by the SAME app's next PUT (no one-off script, no migration); another app on the same context gets its own row.
  4. // node tests/status-keyed.mjs (GITORIA_KEYED_PORT default 8722, GITORIA_KEYED_IDENT_PORT default 8723)
  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_KEYED_PORT || 8722), IDENT_PORT = Number(process.env.GITORIA_KEYED_IDENT_PORT || 8723);
  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/keyed-store');
  16. const LIFE = 60000; // the token is minted once and must outlive two restarts (day37 restarts take ~2 s each)
  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('utf8') })); });
  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, dir = APP) {
  33. log = '';
  34. const p = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: dir, 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. const OLD = join(STORE, 'oldapp'); mkdirSync(OLD, { recursive: true });
  45. execFileSync('sh', ['-c', `git -C '${APP}' archive 9678a8f | tar -x -C '${OLD}' && ln -s '${join(APP, 'bin')}' '${OLD}/bin'; true`]);
  46. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  47. const alice = await ident.signIn('[email protected]');
  48. const BASE = `http://localhost:${PORT}`;
  49. const app = await ident.registerApp(alice, 'gitoria (status gate)', [BASE]);
  50. 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 };
  51. startServer(ENV, OLD); await up();
  52. const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;
  53. const ck0 = cookieOf(await get('/'));
  54. const cb = await get('/login/callback?ident_code=' + await ident.selectorCode(alice, app, BASE) + '&next=%2F', { cookie: ck0 });
  55. const A = { cookie: cookieOf(cb) || ck0 };
  56. let n = 0;
  57. const face = async (event, payload, cookie = A.cookie) => {
  58. const r = await raw('POST', '/__hl/emit', { headers: { 'content-type': 'application/json' }, cookie, body: J({ t: 'emit', i: ++n, event, payload }) });
  59. let j = null; try { j = JSON.parse(r.body); } catch {}
  60. return j && j.value;
  61. };
  62. await face('gitoriaSaveName', ['Alice']);
  63. const tA = (await face('gitoriaMakeToken', ['a'])).token;
  64. const W = join(STORE, 'work'); mkdirSync(W, { recursive: true });
  65. 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' };
  66. const g = (...a) => execFileSync('git', a, { cwd: W, encoding: 'utf8', env: genv, stdio: ['ignore', 'pipe', 'pipe'] });
  67. const sh = (fn) => { try { return fn(); } catch (e) { return null; } };
  68. const urlOf = (host, path) => `http://a:${tA}@${host}.localhost:${PORT}/${path}`;
  69. const push = (host, path, ...refs) => sh(() => { g('push', '-q', urlOf(host, path), ...refs); return true; });
  70. const sha = () => g('rev-parse', 'HEAD').trim();
  71. g('init', '-q', '-b', 'main'); writeFileSync(join(W, 'README.md'), '# t\n'); g('add', '-A'); g('commit', '-q', '-m', 'init');
  72. const mainSha = sha();
  73. check('alice creates "pub" and "other"', !!(await face('gitoriaCreate', ['pub', 'p'])).repo && !!(await face('gitoriaCreate', ['other', 'o'])).repo);
  74. check('alice pushes main to pub and to other', push('pub', 'pub.git', 'main') === true && push('other', 'other.git', 'main') === true);
  75. // a pull request on pub: branch feat with a |||PR commit
  76. g('checkout', '-q', '-b', 'feat'); writeFileSync(join(W, 'a.txt'), 'a\n'); g('add', '-A'); g('commit', '-q', '-m', '|||PR Add a');
  77. const prCommit = sha(), h1 = sha();
  78. check('alice pushes the branch feat with a |||PR commit', push('pub', 'pub.git', 'feat') === true);
  79. 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');
  80. const otherSha = sha();
  81. check('a commit that exists only in the repo "other"', push('other', 'other.git', 'lone') === true);
  82. // the OLD code is the one in OLD (commit 9678a8f), the NEW code is this tree; both on ENV's storage
  83. const addApp = (slug, name) => face('gitoriaAppAdd', [slug, name, 'https://kunibert.worldapi.org/hook']);
  84. const idOf = (r, name) => ((r.rows || []).find(x => x.name === name) || {}).id;
  85. const H = (host) => `${host}.localhost:${PORT}`;
  86. const tok = async (host, key) => JSON.parse((await raw('POST', '/api/apps/token', { host: H(host), headers: { authorization: 'Bearer ' + key } })).body).token;
  87. const put = (token, shaArg, body) => raw('PUT', '/api/statuses/' + shaArg, { host: H('pub'), headers: { authorization: 'Bearer ' + token, 'content-type': 'application/json' }, body: J(body) });
  88. const list = async (token) => JSON.parse((await raw('GET', '/api/statuses/' + h1, { host: H('pub'), headers: { authorization: 'Bearer ' + token } })).body).statuses;
  89. const st = (context, state, title) => ({ context, state, title, summary: '', url: null });
  90. const kK = await addApp('pub', 'Kunibert'); const kM = await addApp('pub', 'Mallory');
  91. const tK = await tok('pub', kK.key), tM = await tok('pub', kM.key);
  92. check('(old code) apps added', !!tK && !!tM);
  93. // ---- the OLD code writes the old shape ----
  94. check('(old code) Kunibert sets kunibert=success', (await put(tK, h1, st('kunibert', 'success', 'old row'))).status === 200);
  95. check('(old code, the bug) Mallory\'s PUT replaces it: one row, app Mallory', await (async () => { const r = await put(tM, h1, st('kunibert', 'failure', 'fake')); const l = (JSON.parse(r.body).status) ; return r.status === 200 && l.app.name === 'Mallory'; })());
  96. check('(old code) Kunibert sets it again (old key: sha + context)', await (async () => { await put(tK, h1, st('kunibert', 'success', 'old row')); return true; })());
  97. await stop();
  98. // ---- the NEW code on the same storage ----
  99. startServer(ENV, APP); await up();
  100. let l = await list(tK);
  101. check('(new code) the old-shape row is read: ONE kunibert status, app Kunibert, success, title "old row"', l.length === 1 && l[0].app.name === 'Kunibert' && l[0].state === 'success' && l[0].title === 'old row', J(l));
  102. check('(new code) pull.statuses shows it too', await (async () => { const p = JSON.parse((await raw('GET', '/api/pulls/1', { host: H('pub'), headers: { authorization: 'Bearer ' + tK } })).body); return p.statuses.length === 1 && p.statuses[0].app.name === 'Kunibert' && Array.isArray(p.required) && p.required.length === 0; })());
  103. check('(new code) Mallory sets the same context: gets her OWN row, Kunibert\'s old row is untouched', (await put(tM, h1, st('kunibert', 'failure', 'mal'))).status === 200 && await (async () => { l = await list(tK); return l.length === 2 && l.find(x => x.app.name === 'Kunibert').state === 'success' && l.find(x => x.app.name === 'Kunibert').title === 'old row' && l.find(x => x.app.name === 'Mallory').state === 'failure'; })(), J(l));
  104. check('(new code) Kunibert\'s next PUT REPLACES its old-shape row (still two rows, not three): now failure, title "new"', (await put(tK, h1, st('kunibert', 'failure', 'new'))).status === 200 && await (async () => { l = await list(tK); const k = l.filter(x => x.app.name === 'Kunibert'); return l.length === 2 && k.length === 1 && k[0].state === 'failure' && k[0].title === 'new' && l.find(x => x.app.name === 'Mallory').title === 'mal'; })(), J(l));
  105. await put(tK, h1, st('kunibert', 'success', 'again'));
  106. await stop(); startServer(ENV, APP); await up();
  107. l = await list(tK);
  108. check('(new code, after another restart) two rows, Kunibert success "again", Mallory failure "mal"', l.length === 2 && l.find(x => x.app.name === 'Kunibert').title === 'again' && l.find(x => x.app.name === 'Mallory').title === 'mal', J(l));
  109. } catch (e) {
  110. check('the gate ran without an exception', false, String(e && e.stack || e));
  111. } finally {
  112. await stop().catch(() => {});
  113. try { ident && ident.stop && await ident.stop(); } catch {}
  114. console.log(`\n${passes} passed, ${failures} failed`);
  115. process.exit(failures ? 1 : 0);
  116. }

Branches

Latest commits

  • 2f2959c5|||PR apps API: broken JSON body gives 400 invalid_json, not 500mre
  • f7c6ca07Merge branch 'ident-chooser-selector' into mainGitoria
  • 691abb8e|||PR tests: find ident identity choice without the removed .choose classmre
  • 16a3530fMerge branch 'heap-revert' into mainGitoria
  • 220a80e0|||PR Remove temporary /__heap route and heap helper; logmre
  • 13f0c342Merge branch 'hl25-records' into mainGitoria
  • a002ecb7|||PR records: HL25 report, heap helper, logmre
  • 2492a55cTemporary keyed /__heap route for the live memory snapshotmre
  • fefaedd2log: tracker PR-only, HL25 startedmre
  • 21aa57calog: parkmre
  • e9f950a8reports: G25c soakmre
  • a7783686log: deploy 9f41ffcmre
  • 9f41ffc1log: W30b mergedmre
  • bef635c1Merge branch 'w30b'mre
  • 15b996a5Org list: keyed rows by @id, newest first, concat instead of hand loopmre
  • c4f6d9e3reports: G25c growth huntmre
  • b88e39f1log: privacy cleanup donemre
  • bfd7826ddocs: neutral example organisation namemre
  • 01b71c2edocs: neutral wording in missions, reports and logmre
  • 3eeea733log: 2026-11-09 PR flow plan and membersmre