gitoria

gitoria

All repositories: gitoria

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

14.7 KB

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