gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit477d7bdc477d7bdcMerge branch 'p50'mre477d7bdc/tests/app-token.mjs

16.1 KB

  1. // 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
  2. // 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
  3. // 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`.
  4. // node tests/app-token.mjs (GITORIA_TOKEN_PORT default 8732, GITORIA_TOKEN_IDENT_PORT default 8733)
  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_TOKEN_PORT || 8732), IDENT_PORT = Number(process.env.GITORIA_TOKEN_IDENT_PORT || 8733);
  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/app-token-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-token-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. // ---- 0. appOfRequest (lib/app-auth.hl) called directly: no apps API route uses it yet (#44) ---------------------------------------------
  45. const unitStore = join(STORE, 'unit'); mkdirSync(unitStore, { recursive: true });
  46. let unit = '';
  47. 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 || ''); }
  48. const u = Object.fromEntries(unit.split('\n').filter(l => /^[a-z-]+ /.test(l)).map(l => [l.split(' ')[0], l.slice(l.indexOf(' ') + 1).trim()]));
  49. check('appOfRequest: a live token on its repo\'s address → { app, repo }', u.good === 'ok A one', unit.slice(0, 300));
  50. check('appOfRequest: no token / unknown token → 401 unauthorized', u.none === '401 unauthorized' && u.unknown === '401 unauthorized', J(u));
  51. 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));
  52. check('appOfRequest: after dropTokensOfApp, and with the app row gone → 401', u.dropped === '401 unauthorized' && u['app-gone'] === '401 unauthorized', J(u));
  53. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  54. const alice = await ident.signIn('[email protected]');
  55. const BASE = `http://localhost:${PORT}`;
  56. const app = await ident.registerApp(alice, 'gitoria (token gate)', [BASE]);
  57. 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 };
  58. startServer(ENV); await up();
  59. const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;
  60. const ck0 = cookieOf(await get('/'));
  61. const cb = await get('/login/callback?ident_code=' + await ident.selectorCode(alice, app, BASE) + '&next=%2F', { cookie: ck0 });
  62. const A = { cookie: cookieOf(cb) || ck0 };
  63. let n = 0;
  64. const face = async (event, payload) => {
  65. const r = await raw('POST', '/__hl/emit', { headers: { 'content-type': 'application/json' }, cookie: A.cookie, body: J({ t: 'emit', i: ++n, event, payload }) });
  66. let j = null; try { j = JSON.parse(r.body); } catch {}
  67. return j && j.value;
  68. };
  69. await face('gitoriaSaveName', ['Alice']);
  70. const tA = (await face('gitoriaMakeToken', ['a'])).token;
  71. // the working copy
  72. const W = join(STORE, 'work'); mkdirSync(W, { recursive: true });
  73. 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' };
  74. const g = (...a) => execFileSync('git', a, { cwd: W, encoding: 'utf8', env: genv, stdio: ['ignore', 'pipe', 'pipe'] });
  75. g('init', '-q', '-b', 'main'); writeFileSync(join(W, 'README.md'), '# t\n'); g('add', '-A'); g('commit', '-q', '-m', 'init');
  76. const urlOf = (pw, host, path, user = 'app') => `http://${user}:${pw}@${host}.localhost:${PORT}/${path}`;
  77. const sh = (fn) => { try { return fn(); } catch (e) { return null; } };
  78. const lsRemote = (pw, host, path) => sh(() => g('ls-remote', urlOf(pw, host, path)));
  79. const clone = (pw, host, path, dir) => sh(() => { g('clone', '-q', urlOf(pw, host, path), join(STORE, dir)); return true; });
  80. const push = (pw, host, path) => sh(() => { g('push', '-q', urlOf(pw, host, path), 'main'); return true; });
  81. // two repos: priv (private), pub (public); an organization acme with the repo rev (private by the org)
  82. check('alice creates private "priv" and public "pub"', !!(await face('gitoriaCreateRepo', ['priv', 'p', '', true])).repo && !!(await face('gitoriaCreate', ['pub', 'p'])).repo);
  83. 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);
  84. 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);
  85. const addApp = async (slug, name) => { const r = await face('gitoriaAppAdd', [slug, name, 'https://kunibert.worldapi.org/hook']); return r; };
  86. const k1 = await addApp('priv', 'Kunibert'), kPub = await addApp('pub', 'Pubby'), kOrg = await addApp('acme/rev', 'Orgy');
  87. 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));
  88. const tokenOf = (host, path, key, method = 'POST') => raw(method, path, { host: `${host}.localhost:${PORT}`, headers: key === undefined ? {} : { authorization: 'Bearer ' + key } });
  89. // ---- 1. issue ---------------------------------------------------------------------------------------------------------------
  90. const t0 = Date.now();
  91. const r1 = await tokenOf('priv', '/api/apps/token', k1.key);
  92. const b1 = JSON.parse(r1.body);
  93. 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);
  94. check('the expiry is the configured life from now (3 s here)', Math.abs(Date.parse(b1.expires) - (t0 + LIFE)) < 2500, b1.expires);
  95. const rB = await tokenOf('priv', '/api/apps/token', k1.key);
  96. check('a second token: another one, both exist', rB.status === 200 && JSON.parse(rB.body).token !== b1.token);
  97. check('token route: GET → 405 in the contract shape', errCode(await tokenOf('priv', '/api/apps/token', k1.key, 'GET')) === 'invalid');
  98. 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']]) {
  99. const r = await tokenOf('priv', '/api/apps/token', key);
  100. check(`token route: ${label} → 401 unauthorized`, r.status === 401 && errCode(r) === 'unauthorized', r.status + r.body.slice(0, 80));
  101. }
  102. const rw = await tokenOf('pub', '/api/apps/token', k1.key);
  103. check('the key of priv on the address of pub → 404 not_found', rw.status === 404 && errCode(rw) === 'not_found', rw.status);
  104. check('a key on an address that names no repo → 404', (await tokenOf('nosuch', '/api/apps/token', k1.key)).status === 404);
  105. const ro = await tokenOf('acme', '/rev/api/apps/token', kOrg.key), ro2 = await tokenOf('acme', '/api/rev/apps/token', kOrg.key);
  106. 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);
  107. const tOrg = JSON.parse(ro.body).token;
  108. // ---- 2. git with the token -----------------------------------------------------------------------------------------------------
  109. const T = b1.token;
  110. 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'))) || ''));
  111. check('git clone of the private repo with the token', clone(T, 'priv', 'priv.git', 'c1') === true && existsSync(join(STORE, 'c1/README.md')));
  112. 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);
  113. 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);
  114. check('a PUSH with the token is refused (403)', push(T, 'priv', 'priv.git') === null);
  115. 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' });
  116. const prInfo = await at('priv', '/priv.git/info/refs?service=git-receive-pack', 'GET', { headers: { authorization: 'Basic ' + Buffer.from('app:' + T).toString('base64') } });
  117. 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);
  118. 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);
  119. check('the token of priv on the PUBLIC repo pub: plain anonymous read as before', /refs\/heads\/main/.test(lsRemote(T, 'pub', 'pub.git') || ''));
  120. 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);
  121. 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);
  122. check('the org repo token on priv: nothing', lsRemote(tOrg, 'priv', 'priv.git') === null);
  123. // ---- 3. expiry -----------------------------------------------------------------------------------------------------------------
  124. const early = Date.now() - t0;
  125. 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);
  126. await sleep(Math.max(0, LIFE + 500 - (Date.now() - t0)));
  127. check('after the life: git with the expired token fails on the private repo', lsRemote(T, 'priv', 'priv.git') === null);
  128. // an issue sweeps the expired rows (no timer): the table still answers fine and a new token works
  129. const r2 = await tokenOf('priv', '/api/apps/token', k1.key);
  130. const T2 = JSON.parse(r2.body).token;
  131. 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);
  132. // ---- 4. removed app, re-connect -----------------------------------------------------------------------------------------------
  133. const k2 = await addApp('priv', 'Kunibert'); // re-connect, same name: a NEW key
  134. 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);
  135. const T3 = JSON.parse((await tokenOf('priv', '/api/apps/token', k2.key)).body).token;
  136. check('the new key makes a token that works', /refs\/heads\/main/.test(lsRemote(T3, 'priv', 'priv.git') || ''));
  137. const appRows = k2.rows || [];
  138. const rid = (appRows.find(r => r.name === 'Kunibert') || {}).id;
  139. check('the app has a row id', !!rid, J(appRows));
  140. const rm = await face('gitoriaAppRemove', ['priv', rid]);
  141. check('the owner removes the app', !!(rm && rm.rows), J(rm));
  142. 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);
  143. // ---- 5. the key in a URL is never logged -----------------------------------------------------------------------------------------
  144. lsRemote(k2.key, 'priv', 'priv.git'); lsRemote(k1.key, 'pub', 'pub.git');
  145. await raw('GET', `/api/repos?key=${k2.key}`);
  146. await sleep(300);
  147. const secrets = [k1.key, k2.key, kPub.key, kOrg.key, T, T2, T3, tOrg];
  148. 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));
  149. await stop();
  150. // ---- 6. a restart: tokens are in the store (not in memory) and expiry still holds --------------------------------------------------
  151. startServer(ENV); await up();
  152. const T4 = JSON.parse((await tokenOf('acme', '/rev/api/apps/token', kOrg.key)).body).token;
  153. 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') || ''));
  154. } catch (e) {
  155. check('the gate ran without an exception', false, String(e && e.stack || e));
  156. } finally {
  157. await stop().catch(() => {});
  158. try { ident && ident.stop && await ident.stop(); } catch {}
  159. console.log(`\n${passes} passed, ${failures} failed`);
  160. process.exit(failures ? 1 : 0);
  161. }

Branches

Latest commits

  • 477d7bdcMerge branch 'p50'mre
  • 00efc06fP50 reportmre
  • e3f85afblog: commit mention slipmre
  • 4d1a4cf4log: #25 numbersmre
  • 1af0a60ddocs: H25 run() correctionmre
  • eefa2dbcRepo setting: refuse direct pushes to the main branch (pre-receive over HTTPS and ssh)mre
  • 8c8ba2f1log: PR flow announcedmre
  • fa00cd35log: Kunibert pings provenmre
  • 3a68cfaclog: components decisionmre
  • 87de8e31log: Kunibert connected to 9 app reposmre
  • c22aff69log: PR-only rollout startedmre
  • 25309981log: STOP and paused workers 2026-11-08mre
  • 5286803alog: worker briefs and reports of 2026-11-08mre
  • 85c86605log: 2026-11-08 Arachne on list shapemre
  • cb634512log: 2026-11-08 keyed lists livemre
  • 07c98d4aLists: keyed rows with @id, remove(id) and one whole-list assignment instead of hand-rebuilt loopsmre
  • 0db0d81elog: 2026-11-08 day52 live, W30 startedmre
  • b05f6d92tests/status: the gate's 3 s app token expired during the restart; it lives 60 s like status-keyedmre
  • 1e8f4f0avendor: Hybriel set-day52 (fault-path leak fix #335, keyed rows #331)mre
  • f5f0fb7blog: 2026-11-08 day50/#29 live, H25 correction, V52 startedmre