gitoria
All repositories: gitoria
16.1 KB
import { requiredPort } from './gate-ports.mjs';// 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// 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// 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`.// node tests/app-token.mjs (GITORIA_TOKEN_PORT required, GITORIA_TOKEN_IDENT_PORT required)import { spawn, execFileSync } from 'node:child_process';import { request } from 'node:http';import { mkdirSync, rmSync, writeFileSync, existsSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import { startIdent } from './identkit.mjs';const HERE = dirname(fileURLToPath(import.meta.url));const APP = resolve(HERE, '..');const PORT = requiredPort('GITORIA_TOKEN_PORT'), IDENT_PORT = requiredPort('GITORIA_TOKEN_IDENT_PORT');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')));const STORE = join(APP, '.scratch/app-token-store');const LIFE = 3000;const J = JSON.stringify, sleep = (ms) => new Promise(r => setTimeout(r, ms));let passes = 0, failures = 0;const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; };function raw(method, path, { host = `localhost:${PORT}`, headers = {}, body = null, cookie = null } = {}) {return new Promise((res, rej) => {const h = { host, ...headers }; if (cookie) h.cookie = cookie;if (body !== null) h['content-length'] = Buffer.byteLength(body);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') })); });r.on('error', rej); if (body !== null) r.write(body); r.end();});}const get = (path, o = {}) => raw('GET', path, o);const at = (label, path, method = 'GET', o = {}) => raw(method, path, { host: `${label}.localhost:${PORT}`, ...o });const errCode = (r) => { try { return JSON.parse(r.body).error.code; } catch { return null; } };let server = null, log = '';function startServer(env) {log = '';const p = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],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 } });p.stdout.on('data', d => log += d); p.stderr.on('data', d => log += d);server = p; return p;}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); }const stop = async () => { if (server) { const p = server; server = null; p.kill(); await new Promise(r => p.once('exit', r)); } };let ident;try {rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });// ---- 0. appOfRequest (lib/app-auth.hl) called directly: no apps API route uses it yet (#44) ---------------------------------------------const unitStore = join(STORE, 'unit'); mkdirSync(unitStore, { recursive: true });let unit = '';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 || ''); }const u = Object.fromEntries(unit.split('\n').filter(l => /^[a-z-]+ /.test(l)).map(l => [l.split(' ')[0], l.slice(l.indexOf(' ') + 1).trim()]));check('appOfRequest: a live token on its repo\'s address → { app, repo }', u.good === 'ok A one', unit.slice(0, 300));check('appOfRequest: no token / unknown token → 401 unauthorized', u.none === '401 unauthorized' && u.unknown === '401 unauthorized', J(u));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));check('appOfRequest: after dropTokensOfApp, and with the app row gone → 401', u.dropped === '401 unauthorized' && u['app-gone'] === '401 unauthorized', J(u));ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });const alice = await ident.signIn('[email protected]');const BASE = `http://localhost:${PORT}`;const app = await ident.registerApp(alice, 'gitoria (token gate)', [BASE]);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 };startServer(ENV); await up();const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;const ck0 = cookieOf(await get('/'));const cb = await get('/login/callback?ident_code=' + await ident.selectorCode(alice, app, BASE) + '&next=%2F', { cookie: ck0 });const A = { cookie: cookieOf(cb) || ck0 };let n = 0;const face = async (event, payload) => {const r = await raw('POST', '/__hl/emit', { headers: { 'content-type': 'application/json' }, cookie: A.cookie, body: J({ t: 'emit', i: ++n, event, payload }) });let j = null; try { j = JSON.parse(r.body); } catch {}return j && j.value;};await face('gitoriaSaveName', ['Alice']);const tA = (await face('gitoriaMakeToken', ['a'])).token;// the working copyconst W = join(STORE, 'work'); mkdirSync(W, { recursive: true });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' };const g = (...a) => execFileSync('git', a, { cwd: W, encoding: 'utf8', env: genv, stdio: ['ignore', 'pipe', 'pipe'] });g('init', '-q', '-b', 'main'); writeFileSync(join(W, 'README.md'), '# t\n'); g('add', '-A'); g('commit', '-q', '-m', 'init');const urlOf = (pw, host, path, user = 'app') => `http://${user}:${pw}@${host}.localhost:${PORT}/${path}`;const sh = (fn) => { try { return fn(); } catch (e) { return null; } };const lsRemote = (pw, host, path) => sh(() => g('ls-remote', urlOf(pw, host, path)));const clone = (pw, host, path, dir) => sh(() => { g('clone', '-q', urlOf(pw, host, path), join(STORE, dir)); return true; });const push = (pw, host, path) => sh(() => { g('push', '-q', urlOf(pw, host, path), 'main'); return true; });// two repos: priv (private), pub (public); an organization acme with the repo rev (private by the org)check('alice creates private "priv" and public "pub"', !!(await face('gitoriaCreateRepo', ['priv', 'p', '', true])).repo && !!(await face('gitoriaCreate', ['pub', 'p'])).repo);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);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);const addApp = async (slug, name) => { const r = await face('gitoriaAppAdd', [slug, name, 'https://kunibert.worldapi.org/hook']); return r; };const k1 = await addApp('priv', 'Kunibert'), kPub = await addApp('pub', 'Pubby'), kOrg = await addApp('acme/rev', 'Orgy');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));const tokenOf = (host, path, key, method = 'POST') => raw(method, path, { host: `${host}.localhost:${PORT}`, headers: key === undefined ? {} : { authorization: 'Bearer ' + key } });// ---- 1. issue ---------------------------------------------------------------------------------------------------------------const t0 = Date.now();const r1 = await tokenOf('priv', '/api/apps/token', k1.key);const b1 = JSON.parse(r1.body);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);check('the expiry is the configured life from now (3 s here)', Math.abs(Date.parse(b1.expires) - (t0 + LIFE)) < 2500, b1.expires);const rB = await tokenOf('priv', '/api/apps/token', k1.key);check('a second token: another one, both exist', rB.status === 200 && JSON.parse(rB.body).token !== b1.token);check('token route: GET → 405 in the contract shape', errCode(await tokenOf('priv', '/api/apps/token', k1.key, 'GET')) === 'invalid');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']]) {const r = await tokenOf('priv', '/api/apps/token', key);check(`token route: ${label} → 401 unauthorized`, r.status === 401 && errCode(r) === 'unauthorized', r.status + r.body.slice(0, 80));}const rw = await tokenOf('pub', '/api/apps/token', k1.key);check('the key of priv on the address of pub → 404 not_found', rw.status === 404 && errCode(rw) === 'not_found', rw.status);check('a key on an address that names no repo → 404', (await tokenOf('nosuch', '/api/apps/token', k1.key)).status === 404);const ro = await tokenOf('acme', '/rev/api/apps/token', kOrg.key), ro2 = await tokenOf('acme', '/api/rev/apps/token', kOrg.key);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);const tOrg = JSON.parse(ro.body).token;// ---- 2. git with the token -----------------------------------------------------------------------------------------------------const T = b1.token;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'))) || ''));check('git clone of the private repo with the token', clone(T, 'priv', 'priv.git', 'c1') === true && existsSync(join(STORE, 'c1/README.md')));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);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);check('a PUSH with the token is refused (403)', push(T, 'priv', 'priv.git') === null);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' });const prInfo = await at('priv', '/priv.git/info/refs?service=git-receive-pack', 'GET', { headers: { authorization: 'Basic ' + Buffer.from('app:' + T).toString('base64') } });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);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);check('the token of priv on the PUBLIC repo pub: plain anonymous read as before', /refs\/heads\/main/.test(lsRemote(T, 'pub', 'pub.git') || ''));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);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);check('the org repo token on priv: nothing', lsRemote(tOrg, 'priv', 'priv.git') === null);// ---- 3. expiry -----------------------------------------------------------------------------------------------------------------const early = Date.now() - t0;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);await sleep(Math.max(0, LIFE + 500 - (Date.now() - t0)));check('after the life: git with the expired token fails on the private repo', lsRemote(T, 'priv', 'priv.git') === null);// an issue sweeps the expired rows (no timer): the table still answers fine and a new token worksconst r2 = await tokenOf('priv', '/api/apps/token', k1.key);const T2 = JSON.parse(r2.body).token;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);// ---- 4. removed app, re-connect -----------------------------------------------------------------------------------------------const k2 = await addApp('priv', 'Kunibert'); // re-connect, same name: a NEW keycheck('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);const T3 = JSON.parse((await tokenOf('priv', '/api/apps/token', k2.key)).body).token;check('the new key makes a token that works', /refs\/heads\/main/.test(lsRemote(T3, 'priv', 'priv.git') || ''));const appRows = k2.rows || [];const rid = (appRows.find(r => r.name === 'Kunibert') || {}).id;check('the app has a row id', !!rid, J(appRows));const rm = await face('gitoriaAppRemove', ['priv', rid]);check('the owner removes the app', !!(rm && rm.rows), J(rm));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);// ---- 5. the key in a URL is never logged -----------------------------------------------------------------------------------------lsRemote(k2.key, 'priv', 'priv.git'); lsRemote(k1.key, 'pub', 'pub.git');await raw('GET', `/api/repos?key=${k2.key}`);await sleep(300);const secrets = [k1.key, k2.key, kPub.key, kOrg.key, T, T2, T3, tOrg];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));await stop();// ---- 6. a restart: tokens are in the store (not in memory) and expiry still holds --------------------------------------------------startServer(ENV); await up();const T4 = JSON.parse((await tokenOf('acme', '/rev/api/apps/token', kOrg.key)).body).token;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') || ''));} catch (e) {check('the gate ran without an exception', false, String(e && e.stack || e));} finally {await stop().catch(() => {});try { ident && ident.stop && await ident.stop(); } catch {}console.log(`\n${passes} passed, ${failures} failed`);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