gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit6c18de766c18de76fix: preserve pull sources across containing branchesmre6c18de76/tests/create-api.mjs

14.6 KB

  1. // tests/create-api.mjs — gitoria#39: user-token creation through the shared web path.
  2. // Own ident/server/storage; real git pushes and the same SSH authorization door as private.mjs.
  3. // GITORIA_CREATE_PORT (8720) and GITORIA_CREATE_IDENT_PORT (8721); Chrome uses PORT+3..9.
  4. import { spawn, execFileSync } from 'node:child_process';
  5. import { request } from 'node:http';
  6. import { mkdirSync, rmSync, writeFileSync, existsSync, readdirSync } from 'node:fs';
  7. import { dirname, join, resolve } from 'node:path';
  8. import { fileURLToPath } from 'node:url';
  9. import { launchBrowser } from './cdp.mjs';
  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_CREATE_PORT || 8720), IDENT_PORT = Number(process.env.GITORIA_CREATE_IDENT_PORT || 8721);
  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 = process.env.GITORIA_CREATE_STORE || join(APP, '.scratch/create-api-store');
  16. const SSH_SECRET = 'sshsecret-for-the-private-gate';
  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 g404 = (r) => r.status === 404 || /No such repository/.test(r.body);
  30. const at = (label, path = '/', o = {}) => get(path, { host: `${label}.localhost:${PORT}`, ...o });
  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: SSH_SECRET, GITORIA_TICKETS_URL: 'http://127.0.0.1:1', ...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, browser, page;
  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]'), bob = await ident.signIn('[email protected]'), carol = await ident.signIn('[email protected]');
  46. const BASE = `http://localhost:${PORT}`;
  47. const app = await ident.registerApp(alice, 'gitoria (private 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 login = async (who) => {
  52. const ck = cookieOf(await get('/'));
  53. const code = await ident.selectorCode(who, app, BASE);
  54. const cb = await get('/login/callback?ident_code=' + code + '&next=%2F', { cookie: ck });
  55. return { cookie: cookieOf(cb) || ck };
  56. };
  57. let n = 0;
  58. const face = async (who, event, payload) => {
  59. const r = await raw('POST', '/__hl/emit', { headers: { 'content-type': 'application/json' }, cookie: who && who.cookie, body: J({ t: 'emit', i: ++n, event, payload }) });
  60. let j = null; try { j = JSON.parse(r.body); } catch {}
  61. return { status: r.status, value: j && j.value, error: j && j.error };
  62. };
  63. const A = await login(alice), B = await login(bob), C = await login(carol);
  64. const unnamed = await ident.signIn('[email protected]'), U = await login(unnamed);
  65. const tU = (await face(U, 'gitoriaMakeToken', ['unnamed'])).value.token;
  66. await face(A, 'gitoriaSaveName', ['Alice']); await face(B, 'gitoriaSaveName', ['Bob']); await face(C, 'gitoriaSaveName', ['Carol']);
  67. const tok = async (who, name) => (await face(who, 'gitoriaMakeToken', [name])).value.token;
  68. const tA = await tok(A, 'a'), tB = await tok(B, 'b'), tC = await tok(C, 'c');
  69. // ---- the working copy to push ----------------------------------------------------------------------------------------------
  70. const W = join(STORE, 'work'); mkdirSync(W, { recursive: true });
  71. 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' };
  72. const g = (...a) => execFileSync('git', a, { cwd: W, encoding: 'utf8', env: genv, stdio: ['ignore', 'pipe', 'pipe'] });
  73. g('init', '-q', '-b', 'main');
  74. writeFileSync(join(W, 'README.md'), '# Hidden\n\nSECRETREADME-7f3a\n');
  75. writeFileSync(join(W, 'file.txt'), 'SECRETFILE-9c1d\n');
  76. g('add', '-A'); g('commit', '-q', '-m', 'init SECRETCOMMIT-5b2e');
  77. const SHA = g('rev-parse', 'HEAD').trim();
  78. const urlOf = (t, host, path) => `http://u:${t}@${host}.localhost:${PORT}/${path}`;
  79. const pushTo = (t, host, path) => { try { g('push', '-q', urlOf(t, host, path), 'main'); return true; } catch { return false; } };
  80. const lsRemote = (t, host, path) => { try { return g('ls-remote', t ? urlOf(t, host, path) : `http://${host}.localhost:${PORT}/${path}`); } catch { return null; } };
  81. const json = r => JSON.parse(r.body);
  82. const create = (input, token = tA, extra = {}) => raw('POST', '/api/repos', { headers: token ? { authorization: 'Bearer ' + token } : {}, body: typeof input === 'string' ? input : J(input), ...extra });
  83. const error = async (label, input, token, status, code) => {
  84. const r = await create(input, token);
  85. const e = json(r).error;
  86. check(label, r.status === status && e.code === code && typeof e.message === 'string' && !!e.message && 'details' in e);
  87. };
  88. // hybriel#280: malformed object JSON still aborts JSON.parse until set day38.
  89. // Exercise invalid_json with a non-object body only, as on the existing write routes.
  90. await error('non-object body: 400 invalid_json', 'hello', tA, 400, 'invalid_json');
  91. await error('no token: 401 unauthorized', { name: 'no-token' }, null, 401, 'unauthorized');
  92. await error('unknown user token: 401 unauthorized', { name: 'unknown-token' }, 'gtr_' + 'a'.repeat(40), 401, 'unauthorized');
  93. await error('user without display name: 422 invalid', { name: 'unnamed' }, tU, 422, 'invalid');
  94. for (const name of ['', 'a', 'Bad', 'a--b', 'api', '../repo', 'x'.repeat(41), 42]) {
  95. await error('bad name ' + J(name) + ': 422 invalid', { name }, tA, 422, 'invalid');
  96. }
  97. await error('unknown org: 403 forbidden', { name: 'outside', org: 'missing' }, tA, 403, 'forbidden');
  98. await error('unknown member: 422 invalid', { name: 'atomic', members: ['Bob', 'Nobody'] }, tA, 422, 'invalid');
  99. check('unknown member created neither row nor git directory', (await get('/api/repos/atomic')).status === 404 && !existsSync(join(STORE, 'git/atomic.git')));
  100. await error('over 1 MB: 413 too_large', { name: 'oversize', description: 'x'.repeat(1048576) }, tA, 413, 'too_large');
  101. for (const input of [{ name: 'bad-desc', description: 42 }, { name: 'bad-private', private: 'yes' }, { name: 'bad-members', members: 'Bob' }]) {
  102. await error('bad input: 422 invalid', input, tA, 422, 'invalid');
  103. }
  104. browser = await launchBrowser({ debugPortRange: [PORT + 3, PORT + 9] });
  105. page = await browser.newPage();
  106. await page.goto((process.env.GITORIA_CREATE_BROWSER_URL || BASE) + '/');
  107. await page.waitFor(`!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1`, { timeout: 30000 });
  108. const r = await create({ name: 'api-repo', description: 'Created by API', private: false, members: ['Bob'] });
  109. check('create: 201 with token owner and requested description', r.status === 201 && json(r).owner === 'Alice' && json(r).slug === 'api-repo' && json(r).description === 'Created by API');
  110. const one = await get('/api/repos/api-repo');
  111. check('201 JSON exactly equals public GET (no extra fields)', one.status === 200 && r.body === one.body);
  112. check('public GET list includes created repo without a token', json(await get('/api/repos')).repos.some(r => r.slug === 'api-repo'));
  113. await page.waitFor(`document.querySelector('#repos').textContent.includes('api-repo')`, { timeout: 20000 });
  114. check('already-open list receives the new repo live', await page.evaluate(`document.querySelectorAll('#repos li').length === 1`));
  115. await page.goto((process.env.GITORIA_CREATE_BROWSER_URL || BASE) + '/');
  116. await page.waitFor(`!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1`, { timeout: 30000 });
  117. check('second visit keeps the stored repo in the list', await page.evaluate(`document.querySelector('#repos').textContent.includes('api-repo')`));
  118. if (process.env.GITORIA_CREATE_PROOF) {
  119. for (const [width, height] of [[390, 844], [800, 1280], [1280, 800], [1280, 900]]) {
  120. await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 });
  121. const name = `proof-${width}-${height}`;
  122. check(`${width}x${height}: API creates while list stays open`, (await create({ name, description: 'Live API creation' })).status === 201);
  123. await page.waitFor(`document.querySelector('#repos').textContent.includes(${J(name)})`, { timeout: 20000 });
  124. check(`${width}x${height}: list fits viewport`, await page.evaluate(`document.documentElement.scrollWidth <= ${width}`));
  125. const { data } = await page.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  126. writeFileSync(join(STORE, `proof-${width}-${height}.png`), Buffer.from(data, 'base64'));
  127. }
  128. }
  129. await error('duplicate name: 409 conflict', { name: 'api-repo' }, tA, 409, 'conflict');
  130. const key = (await face(A, 'gitoriaAppAdd', ['api-repo', 'Create Gate', 'https://example.worldapi.org/hook'])).value.key;
  131. const appToken = json(await raw('POST', '/api/apps/token', { host: `api-repo.localhost:${PORT}`, headers: { authorization: 'Bearer ' + key } })).token;
  132. await error('live gat_ app token: 403 forbidden', { name: 'app-created' }, appToken, 403, 'forbidden');
  133. check('app token made nothing', (await get('/api/repos/app-created')).status === 404);
  134. check('owner gtr_ pushes to API repo', pushTo(tA, 'api-repo', 'api-repo.git'));
  135. check('member gtr_ pushes to API repo', pushTo(tB, 'api-repo', 'api-repo.git'));
  136. check('stranger cannot push to API repo', !pushTo(tC, 'api-repo', 'api-repo.git'));
  137. const web = (await face(A, 'gitoriaCreateRepo', ['web-repo', 'Web comparison', '', false])).value.repo;
  138. const member = (await face(A, 'gitoriaChangeMember', ['web-repo', 'Bob', true])).value.members[0];
  139. const acc = (slug, user, write) => get(`/__git/access?slug=${encodeURIComponent(slug)}&user=${user}&write=${write}`, { headers: { 'x-gitoria-secret': SSH_SECRET } });
  140. for (const [uid, write] of [[member.id, 0], [member.id, 1], ['nobody', 0], ['nobody', 1]]) {
  141. const a = await acc('api-repo', uid, write), w = await acc('web-repo', uid, write);
  142. check('SSH rule matches web-created repo for ' + (uid === member.id ? 'member' : 'stranger') + ' write=' + write, a.status === w.status && (uid !== member.id || a.status === 200));
  143. }
  144. check('HTTPS membership matches web-created repo', pushTo(tB, 'web-repo', 'web-repo.git') && !pushTo(tC, 'web-repo', 'web-repo.git'));
  145. const shortId = await ident.exchange(app, await ident.selectorCode(bob, app, BASE));
  146. const priv = await create({ name: 'private-api', private: true, members: [shortId, 'Bob'] });
  147. check('private API repo resolves identity short id and duplicate member', priv.status === 201 && json(priv).isPrivate);
  148. check('private API row equals owner GET', priv.body === (await get('/api/repos/private-api', { cookie: A.cookie })).body);
  149. check('private repo hidden from public GET and list', (await get('/api/repos/private-api')).status === 404 && !json(await get('/api/repos')).repos.some(r => r.slug === 'private-api'));
  150. check('private member sees, clones and pushes', (await get('/api/repos/private-api', { cookie: B.cookie })).status === 200 && pushTo(tB, 'private-api', 'private-api.git') && /refs\/heads\/main/.test(lsRemote(tB, 'private-api', 'private-api.git') || ''));
  151. check('private stranger SSH read denied', (await acc('private-api', 'nobody', 0)).status === 404);
  152. await face(A, 'gitoriaCreateOrg', ['acme', false]);
  153. await error('non-member org: 403 forbidden', { name: 'intruder', org: 'acme' }, tC, 403, 'forbidden');
  154. await face(A, 'gitoriaChangeOrgMember', ['acme', 'Bob', true]);
  155. const org = await create({ name: 'org-repo', org: 'acme' }, tB);
  156. check('org member creates with token user as owner', org.status === 201 && json(org).slug === 'acme/org-repo' && json(org).owner === 'Bob');
  157. await error('duplicate org slug: 409 conflict', { name: 'org-repo', org: 'acme' }, tA, 409, 'conflict');
  158. check('org owner and creator push using normal org transport', pushTo(tA, 'acme', 'org-repo.git') && pushTo(tB, 'acme', 'org-repo.git'));
  159. check('GET list stays public despite a bogus Authorization header', (await get('/api/repos', { headers: { authorization: 'Bearer bogus' } })).status === 200);
  160. await stop(); startServer(ENV); await up();
  161. check('after server restart the repo and membership persist', (await get('/api/repos/api-repo')).status === 200 && pushTo(tB, 'private-api', 'private-api.git'));
  162. check('no token values in the server log', ![tA, tB, tC, tU, appToken, key].some(t => log.includes(t)));
  163. } catch (e) {
  164. check('gate completes', false, String(e.message).replace(/gtr_[0-9a-f]+|gat_[0-9a-f]+|gak_[0-9a-f]+/g, '[redacted]'));
  165. } finally {
  166. if (page) await page.close().catch(() => {});
  167. if (browser) await browser.close().catch(() => {});
  168. await stop().catch(() => {});
  169. if (ident) await ident.stop().catch(() => {});
  170. }
  171. console.log(`\n${passes} passed, ${failures} failed`);
  172. process.exit(failures ? 1 : 0);

Branches

Latest commits

  • 6c18de76fix: preserve pull sources across containing branchesmre
  • fc36fa2elog: W51b pull source bugmre
  • 56bc1220log: v1.5.1 livemre
  • 845fc0aareport: W51mre
  • 83127391fix: return v1.5.1 app and merge error detailsmre
  • b07d0e97log: W51 v1.5.1 startedmre
  • 0b417d06docs: apps-api v1.5 user tokens (#48, W49)mre
  • d046940alog: vinzenz contract note sentmre
  • db443456log: vinzenz note retry 2mre
  • 802f229alog: kunibert repo ping provenmre
  • 2d2eaa92log: Kunibert connected to kunibert repomre
  • 65d5f80alogmre
  • dab74b0dW49 report, logmre
  • fd4fc028Exercise member status reads with a populated check statemre
  • 536ca6f9Allow repository members to read pull workflow APIs with user tokensmre
  • 705dd834W49 missionmre
  • b554cd5flogmre
  • f4c9440ddeploy.sh: tar --hard-dereference for the live data backupmre
  • 1a687b15Merge branch 'w48-member-merge'mre
  • 166c775fW48 report, logmre