gitoria

gitoria

All repositories: gitoria

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

16.1 KB

  1. import { requiredPort } from './gate-ports.mjs';
  2. // tests/app-token.mjs — GATE OF AN APP'S TOKEN (gitoria#42): POST {api}/apps/token with the key, the 1-hour token (a 3 s life through
  3. // GITORIA_APP_TOKEN_LIFE_MS here, tests only), expiry, wrong repo 404, a removed or re-connected app 401, the token as the git password on a
  4. // private repo (clone, ls-remote, the org address), a push refused 403, the key never in the server log. Real HTTP and the real `git`.
  5. // node tests/app-token.mjs (GITORIA_TOKEN_PORT required, GITORIA_TOKEN_IDENT_PORT required)
  6. import { spawn, execFileSync } from 'node:child_process';
  7. import { request } from 'node:http';
  8. import { mkdirSync, rmSync, writeFileSync, existsSync } from 'node:fs';
  9. import { dirname, join, resolve } from 'node:path';
  10. import { fileURLToPath } from 'node:url';
  11. import { startIdent } from './identkit.mjs';
  12. const HERE = dirname(fileURLToPath(import.meta.url));
  13. const APP = resolve(HERE, '..');
  14. const PORT = requiredPort('GITORIA_TOKEN_PORT'), IDENT_PORT = requiredPort('GITORIA_TOKEN_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 = join(APP, '.scratch/app-token-store');
  17. const LIFE = 3000;
  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 at = (label, path, method = 'GET', o = {}) => raw(method, path, { host: `${label}.localhost:${PORT}`, ...o });
  31. const errCode = (r) => { try { return JSON.parse(r.body).error.code; } catch { return null; } };
  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: 'sshsecret-token-gate', GITORIA_TICKETS_URL: 'http://127.0.0.1:1', GITORIA_APP_TOKEN_LIFE_MS: String(LIFE), ...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;
  43. try {
  44. rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });
  45. // ---- 0. appOfRequest (lib/app-auth.hl) called directly: no apps API route uses it yet (#44) ---------------------------------------------
  46. const unitStore = join(STORE, 'unit'); mkdirSync(unitStore, { recursive: true });
  47. let unit = '';
  48. try { unit = execFileSync(join(APP, 'bin/hybriel'), ['tests/app-auth-unit.hl'], { cwd: APP, encoding: 'utf8', timeout: 300000, env: { ...process.env, GITORIA_STORAGE: unitStore, GITORIA_PUBLIC_URL: 'http://localhost:1' } }); } catch (e) { unit = String(e.stdout || '') + String(e.stderr || ''); }
  49. const u = Object.fromEntries(unit.split('\n').filter(l => /^[a-z-]+ /.test(l)).map(l => [l.split(' ')[0], l.slice(l.indexOf(' ') + 1).trim()]));
  50. check('appOfRequest: a live token on its repo\'s address → { app, repo }', u.good === 'ok A one', unit.slice(0, 300));
  51. check('appOfRequest: no token / unknown token → 401 unauthorized', u.none === '401 unauthorized' && u.unknown === '401 unauthorized', J(u));
  52. check('appOfRequest: the token on another repo\'s address or on none → 404 not_found', u['other-repo'] === '404 not_found' && u['no-repo'] === '404 not_found', J(u));
  53. check('appOfRequest: after dropTokensOfApp, and with the app row gone → 401', u.dropped === '401 unauthorized' && u['app-gone'] === '401 unauthorized', J(u));
  54. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  55. const alice = await ident.signIn('[email protected]');
  56. const BASE = `http://localhost:${PORT}`;
  57. const app = await ident.registerApp(alice, 'gitoria (token gate)', [BASE]);
  58. 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 };
  59. startServer(ENV); await up();
  60. const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;
  61. const ck0 = cookieOf(await get('/'));
  62. const cb = await get('/login/callback?ident_code=' + await ident.selectorCode(alice, app, BASE) + '&next=%2F', { cookie: ck0 });
  63. const A = { cookie: cookieOf(cb) || ck0 };
  64. let n = 0;
  65. const face = async (event, payload) => {
  66. const r = await raw('POST', '/__hl/emit', { headers: { 'content-type': 'application/json' }, cookie: A.cookie, body: J({ t: 'emit', i: ++n, event, payload }) });
  67. let j = null; try { j = JSON.parse(r.body); } catch {}
  68. return j && j.value;
  69. };
  70. await face('gitoriaSaveName', ['Alice']);
  71. const tA = (await face('gitoriaMakeToken', ['a'])).token;
  72. // the working copy
  73. const W = join(STORE, 'work'); mkdirSync(W, { recursive: true });
  74. 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' };
  75. const g = (...a) => execFileSync('git', a, { cwd: W, encoding: 'utf8', env: genv, stdio: ['ignore', 'pipe', 'pipe'] });
  76. g('init', '-q', '-b', 'main'); writeFileSync(join(W, 'README.md'), '# t\n'); g('add', '-A'); g('commit', '-q', '-m', 'init');
  77. const urlOf = (pw, host, path, user = 'app') => `http://${user}:${pw}@${host}.localhost:${PORT}/${path}`;
  78. const sh = (fn) => { try { return fn(); } catch (e) { return null; } };
  79. const lsRemote = (pw, host, path) => sh(() => g('ls-remote', urlOf(pw, host, path)));
  80. const clone = (pw, host, path, dir) => sh(() => { g('clone', '-q', urlOf(pw, host, path), join(STORE, dir)); return true; });
  81. const push = (pw, host, path) => sh(() => { g('push', '-q', urlOf(pw, host, path), 'main'); return true; });
  82. // two repos: priv (private), pub (public); an organization acme with the repo rev (private by the org)
  83. check('alice creates private "priv" and public "pub"', !!(await face('gitoriaCreateRepo', ['priv', 'p', '', true])).repo && !!(await face('gitoriaCreate', ['pub', 'p'])).repo);
  84. check('alice creates the private organization acme and its repo rev', !!(await face('gitoriaCreateOrg', ['acme', true])).org && !!(await face('gitoriaCreateRepo', ['rev', 'r', 'acme', false])).repo);
  85. for (const [h, p] of [['priv', 'priv.git'], ['pub', 'pub.git'], ['acme', 'rev.git']]) check(`alice pushes main to ${h}`, push(tA, h, p) === true);
  86. const addApp = async (slug, name) => { const r = await face('gitoriaAppAdd', [slug, name, 'https://kunibert.worldapi.org/hook']); return r; };
  87. const k1 = await addApp('priv', 'Kunibert'), kPub = await addApp('pub', 'Pubby'), kOrg = await addApp('acme/rev', 'Orgy');
  88. check('apps added with keys', /^gak_[0-9a-f]{40}$/.test(k1.key) && /^gak_[0-9a-f]{40}$/.test(kPub.key) && /^gak_[0-9a-f]{40}$/.test(kOrg.key), J([k1, kPub, kOrg]).slice(0, 200));
  89. const tokenOf = (host, path, key, method = 'POST') => raw(method, path, { host: `${host}.localhost:${PORT}`, headers: key === undefined ? {} : { authorization: 'Bearer ' + key } });
  90. // ---- 1. issue ---------------------------------------------------------------------------------------------------------------
  91. const t0 = Date.now();
  92. const r1 = await tokenOf('priv', '/api/apps/token', k1.key);
  93. const b1 = JSON.parse(r1.body);
  94. check('POST /api/apps/token with the key: 200 { token gat_+40 hex, expires ISO }', r1.status === 200 && /^gat_[0-9a-f]{40}$/.test(b1.token) && !isNaN(Date.parse(b1.expires)) && /Z$/.test(b1.expires) && Object.keys(b1).length === 2, r1.status + r1.body);
  95. check('the expiry is the configured life from now (3 s here)', Math.abs(Date.parse(b1.expires) - (t0 + LIFE)) < 2500, b1.expires);
  96. const rB = await tokenOf('priv', '/api/apps/token', k1.key);
  97. check('a second token: another one, both exist', rB.status === 200 && JSON.parse(rB.body).token !== b1.token);
  98. check('token route: GET → 405 in the contract shape', errCode(await tokenOf('priv', '/api/apps/token', k1.key, 'GET')) === 'invalid');
  99. for (const [label, key] of [['no Authorization', undefined], ['an unknown key', 'gak_' + 'a'.repeat(40)], ['a token instead of the key', b1.token], ['junk', 'x']]) {
  100. const r = await tokenOf('priv', '/api/apps/token', key);
  101. check(`token route: ${label} → 401 unauthorized`, r.status === 401 && errCode(r) === 'unauthorized', r.status + r.body.slice(0, 80));
  102. }
  103. const rw = await tokenOf('pub', '/api/apps/token', k1.key);
  104. check('the key of priv on the address of pub → 404 not_found', rw.status === 404 && errCode(rw) === 'not_found', rw.status);
  105. check('a key on an address that names no repo → 404', (await tokenOf('nosuch', '/api/apps/token', k1.key)).status === 404);
  106. const ro = await tokenOf('acme', '/rev/api/apps/token', kOrg.key), ro2 = await tokenOf('acme', '/api/rev/apps/token', kOrg.key);
  107. check('org repo: the token route answers on /<repo>/api/… and on /api/<repo>/… (both spellings)', ro.status === 200 && ro2.status === 200 && /^gat_/.test(JSON.parse(ro.body).token) && /^gat_/.test(JSON.parse(ro2.body).token), ro.status + '/' + ro2.status);
  108. const tOrg = JSON.parse(ro.body).token;
  109. // ---- 2. git with the token -----------------------------------------------------------------------------------------------------
  110. const T = b1.token;
  111. check('git ls-remote of the private repo with the token (any user name)', /refs\/heads\/main/.test(lsRemote(T, 'priv', 'priv.git') || '') && /refs\/heads\/main/.test(sh(() => g('ls-remote', urlOf(T, 'priv', 'priv.git', 'whoever'))) || ''));
  112. check('git clone of the private repo with the token', clone(T, 'priv', 'priv.git', 'c1') === true && existsSync(join(STORE, 'c1/README.md')));
  113. check('git fetch with the token (protocol v2)', sh(() => { g('-C', join(STORE, 'c1'), '-c', 'protocol.version=2', 'fetch', '--depth', '1', urlOf(T, 'priv', 'priv.git'), 'main'); return true; }) === true);
  114. check('the private repo without a token or with a key as password: no access', lsRemote(null, 'priv', 'priv.git') === null && lsRemote(k1.key, 'priv', 'priv.git') === null);
  115. check('a PUSH with the token is refused (403)', push(T, 'priv', 'priv.git') === null);
  116. const pr = await at('priv', '/priv.git/git-receive-pack', 'POST', { headers: { authorization: 'Basic ' + Buffer.from('app:' + T).toString('base64'), 'content-type': 'application/x-git-receive-pack-request' }, body: '0000' });
  117. const prInfo = await at('priv', '/priv.git/info/refs?service=git-receive-pack', 'GET', { headers: { authorization: 'Basic ' + Buffer.from('app:' + T).toString('base64') } });
  118. check('push over HTTP: info/refs?service=git-receive-pack and the POST are both 403', pr.status === 403 && prInfo.status === 403, pr.status + '/' + prInfo.status);
  119. check('the token of priv on ANOTHER private repo (acme/rev): 404, the repo does not exist for it', (await at('acme', '/rev.git/info/refs?service=git-upload-pack', 'GET', { headers: { authorization: 'Basic ' + Buffer.from('app:' + T).toString('base64') } })).status === 404 && lsRemote(T, 'acme', 'rev.git') === null);
  120. check('the token of priv on the PUBLIC repo pub: plain anonymous read as before', /refs\/heads\/main/.test(lsRemote(T, 'pub', 'pub.git') || ''));
  121. check('the public repo\'s own token reads pub, a push to pub with it is refused', /refs\/heads\/main/.test(lsRemote(JSON.parse((await tokenOf('pub', '/api/apps/token', kPub.key)).body).token, 'pub', 'pub.git') || '') && push(JSON.parse((await tokenOf('pub', '/api/apps/token', kPub.key)).body).token, 'pub', 'pub.git') === null);
  122. check('org address: the token of acme/rev clones and ls-remotes the private org repo, no push', /refs\/heads\/main/.test(lsRemote(tOrg, 'acme', 'rev.git') || '') && clone(tOrg, 'acme', 'rev.git', 'c2') === true && push(tOrg, 'acme', 'rev.git') === null);
  123. check('the org repo token on priv: nothing', lsRemote(tOrg, 'priv', 'priv.git') === null);
  124. // ---- 3. expiry -----------------------------------------------------------------------------------------------------------------
  125. const early = Date.now() - t0;
  126. check('the first token still works before it expires (old tokens survive a newer one)', early < LIFE - 300 ? /refs\/heads\/main/.test(lsRemote(T, 'priv', 'priv.git') || '') : true);
  127. await sleep(Math.max(0, LIFE + 500 - (Date.now() - t0)));
  128. check('after the life: git with the expired token fails on the private repo', lsRemote(T, 'priv', 'priv.git') === null);
  129. // an issue sweeps the expired rows (no timer): the table still answers fine and a new token works
  130. const r2 = await tokenOf('priv', '/api/apps/token', k1.key);
  131. const T2 = JSON.parse(r2.body).token;
  132. check('a new token after the expiry works, the expired one stays dead', r2.status === 200 && /refs\/heads\/main/.test(lsRemote(T2, 'priv', 'priv.git') || '') && lsRemote(T, 'priv', 'priv.git') === null);
  133. // ---- 4. removed app, re-connect -----------------------------------------------------------------------------------------------
  134. const k2 = await addApp('priv', 'Kunibert'); // re-connect, same name: a NEW key
  135. check('re-connect (same name): a new key, the old key and the old token die at once', k2.key !== k1.key && (await tokenOf('priv', '/api/apps/token', k1.key)).status === 401 && lsRemote(T2, 'priv', 'priv.git') === null);
  136. const T3 = JSON.parse((await tokenOf('priv', '/api/apps/token', k2.key)).body).token;
  137. check('the new key makes a token that works', /refs\/heads\/main/.test(lsRemote(T3, 'priv', 'priv.git') || ''));
  138. const appRows = k2.rows || [];
  139. const rid = (appRows.find(r => r.name === 'Kunibert') || {}).id;
  140. check('the app has a row id', !!rid, J(appRows));
  141. const rm = await face('gitoriaAppRemove', ['priv', rid]);
  142. check('the owner removes the app', !!(rm && rm.rows), J(rm));
  143. check('removed app: its token is 401/no access at once, its key 401', lsRemote(T3, 'priv', 'priv.git') === null && (await tokenOf('priv', '/api/apps/token', k2.key)).status === 401);
  144. // ---- 5. the key in a URL is never logged -----------------------------------------------------------------------------------------
  145. lsRemote(k2.key, 'priv', 'priv.git'); lsRemote(k1.key, 'pub', 'pub.git');
  146. await raw('GET', `/api/repos?key=${k2.key}`);
  147. await sleep(300);
  148. const secrets = [k1.key, k2.key, kPub.key, kOrg.key, T, T2, T3, tOrg];
  149. check('no key or token appears in the server log', secrets.every(s => !log.includes(s)) && !log.includes(k1.key.slice(4)), log.split('\n').filter(l => secrets.some(s => l.includes(s))).join('|').slice(0, 200));
  150. await stop();
  151. // ---- 6. a restart: tokens are in the store (not in memory) and expiry still holds --------------------------------------------------
  152. startServer(ENV); await up();
  153. const T4 = JSON.parse((await tokenOf('acme', '/rev/api/apps/token', kOrg.key)).body).token;
  154. check('after a restart the app key still works and a new token reads the org repo', /refs\/heads\/main/.test(lsRemote(T4, 'acme', 'rev.git') || ''));
  155. } catch (e) {
  156. check('the gate ran without an exception', false, String(e && e.stack || e));
  157. } finally {
  158. await stop().catch(() => {});
  159. try { ident && ident.stop && await ident.stop(); } catch {}
  160. console.log(`\n${passes} passed, ${failures} failed`);
  161. process.exit(failures ? 1 : 0);
  162. }

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