gitoria
All repositories: gitoria
12.2 KB
import { requiredPort } from './gate-ports.mjs';// tests/ident-access-gitoria.mjs — GATE: gitoria takes an ident access key (idt_…, ident#27, app side) as the git password.// A LOCAL ident (tests/identkit.mjs) with the app 'gitoria' and identities given keys through ident's own API; a LOCAL gitoria started with that// app's key and secret; the real `git` binary clones and pushes over http. Checked: a write key of a member pushes (and the commit is in the repo),// a read key clones and its push is 403, a private repo with a key that has no access is 404, a revoked / unknown / foreign key is 401 (with the Basic// realm), ident down is 503 and nothing is pushed, a gtr_ token still clones and pushes.// node tests/ident-access-gitoria.mjs (GITORIA_IDA_PORT 8760, GITORIA_IDA_IDENT_PORT 8761)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 APP = resolve(dirname(fileURLToPath(import.meta.url)), '..');const PORT = requiredPort('GITORIA_IDA_PORT'), IDENT_PORT = requiredPort('GITORIA_IDA_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/ida-store');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 ? '' : ' — ' + String(detail).slice(0, 400)}`); 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);let server = null, log = '', ident = null;function startServer(env) {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-for-the-ida-gate', GITORIA_TICKETS_URL: 'http://127.0.0.1:1', ...env } });p.stdout.on('data', d => log += d); p.stderr.on('data', d => log += d);server = 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); }process.on('exit', () => { try { server && server.kill(); } catch {} try { ident && ident.proc.kill(); } catch {} });try {rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });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 (ida gate)', [BASE]); app.id = app.raw.app.id;const other = await ident.registerApp(alice, 'otherapp', ['http://127.0.0.1:1']); other.id = other.raw.app.id;const give = async (name, apps, level) => {const r = await ident.emit('accGiveAccess', [{ newName: name, apps, level, label: name }], alice.cookie);if (!r.value || !r.value.key) throw new Error('give failed: ' + r.raw);return r.value;};const writer = await give('Hermes', [app.id], 'write'), reader = await give('Reader', [app.id], 'read');const stranger = await give('Stranger', [other.id], 'write'), victim = await give('Victim', [app.id], 'write'), nobody = await give('Nobody', [app.id], 'write');startServer({ 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 });await up();const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;const A = await (async () => { const ck = cookieOf(await get('/')); const code = await ident.selectorCode(alice, app, BASE); const cb = await get('/login/callback?ident_code=' + code + '&next=%2F', { cookie: ck }); return { cookie: cookieOf(cb) || ck }; })();let n = 0;const face = async (who, event, payload) => {const r = await raw('POST', '/__hl/emit', { headers: { 'content-type': 'application/json' }, cookie: who.cookie, body: J({ t: 'emit', i: ++n, event, payload }) });let j = null; try { j = JSON.parse(r.body); } catch {}return { status: r.status, value: j && j.value, error: j && j.error };};await face(A, 'gitoriaSaveName', ['Alice']);const tA = (await face(A, 'gitoriaMakeToken', ['a'])).value.token;const 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'), '# Ida\n'); g('add', '-A'); g('commit', '-q', '-m', 'init');const urlOf = (t, host, path) => `http://u:${t}@${host}.localhost:${PORT}/${path}`;const pushTo = (t, host, path, ref = 'main') => { try { g('push', '-q', urlOf(t, host, path), ref); return true; } catch { return false; } };const lsRemote = (t, host, path) => { try { return g('ls-remote', urlOf(t, host, path)); } catch { return null; } };const cloneTo = (t, host, path, dir) => { try { execFileSync('git', ['clone', '-q', urlOf(t, host, path), join(STORE, dir)], { env: genv, stdio: 'pipe' }); return existsSync(join(STORE, dir, 'README.md')); } catch { return false; } };const basic = (k) => ({ authorization: 'Basic ' + Buffer.from('x:' + k).toString('base64') });const refs = (k, host, slug, svc = 'git-upload-pack') => get(`/${slug}.git/info/refs?service=${svc}`, { host: `${host}.localhost:${PORT}`, headers: k ? basic(k) : {} });const headOf = (host, slug) => { try { return execFileSync('git', ['ls-remote', urlOf(tA, host, slug + '.git'), 'main'], { env: genv, encoding: 'utf8' }).split('\t')[0]; } catch { return null; } };// Hermes uses his key once (a public clone) so his gitoria user exists, named Hermes; then Alice adds him by name to her private repoconsole.log('# a write key');await face(A, 'gitoriaCreate', ['pubrepo', 'public']);await face(A, 'gitoriaCreateRepo', ['secretrepo', 'private', '', true]);check('setup: Alice pushes both repos with her gtr_ token', pushTo(tA, 'pubrepo', 'pubrepo.git') && pushTo(tA, 'secretrepo', 'secretrepo.git'));check('a write key clones a public repo', cloneTo(writer.key, 'pubrepo', 'pubrepo.git', 'c1'));let r = await refs(writer.key, 'secretrepo', 'secretrepo');check('a write key that is not a member: private repo is 404, as for a name that does not exist', r.status === 404, r.status);const add = await face(A, 'gitoriaChangeMember', ['secretrepo', 'Hermes', true]);check('Alice adds Hermes (the key\'s identity, named by ident) as a member', !!(add.value && add.value.members && add.value.members.some(m => m.name === 'Hermes')), J(add.value));check('the member key clones the private repo', cloneTo(writer.key, 'secretrepo', 'secretrepo.git', 'c2'));writeFileSync(join(W, 'viakey.txt'), 'pushed with an idt_ key\n'); g('add', '-A'); g('commit', '-q', '-m', 'pushed with an idt_ key');const sha = g('rev-parse', 'HEAD').trim();check('the member write key pushes', pushTo(writer.key, 'secretrepo', 'secretrepo.git'));check('…and the commit is the repo\'s head', headOf('secretrepo', 'secretrepo') === sha);check('the key made no second gitoria user (the member list still names one Hermes)', (await face(A, 'gitoriaChangeMember', ['secretrepo', 'Hermes', true])).value.members.filter(m => m.name === 'Hermes').length === 1);r = await refs(writer.key, 'pubrepo', 'pubrepo', 'git-receive-pack');check('a write key that is not a member may not push to Alice\'s public repo: 403', r.status === 403, r.status);console.log('# a read key');check('a read key clones a public repo', cloneTo(reader.key, 'pubrepo', 'pubrepo.git', 'c3'));r = await refs(reader.key, 'pubrepo', 'pubrepo', 'git-receive-pack');check('a read key: the push advertisement is 403', r.status === 403, r.status);writeFileSync(join(W, 'nope.txt'), 'x\n'); g('add', '-A'); g('commit', '-q', '-m', 'by a read key');const before = headOf('pubrepo', 'pubrepo');check('a read key: git push fails', !pushTo(reader.key, 'pubrepo', 'pubrepo.git'));check('…and nothing was pushed', headOf('pubrepo', 'pubrepo') === before);r = await refs(reader.key, 'secretrepo', 'secretrepo');check('a read key that is no member: private repo is 404', r.status === 404, r.status);r = await refs(nobody.key, 'secretrepo', 'secretrepo', 'git-receive-pack');check('a write key with no access to the private repo: 404 for the push too', r.status === 404, r.status);console.log('# refused keys');r = await refs(stranger.key, 'pubrepo', 'pubrepo');check('a key for another app: 401 with the Basic realm', r.status === 401 && /Basic/.test(r.headers['www-authenticate'] || ''), r.status);r = await refs('idt_' + '0'.repeat(48), 'pubrepo', 'pubrepo');check('an unknown well-formed key: 401', r.status === 401, r.status);r = await refs('idt_abc', 'pubrepo', 'pubrepo');check('a malformed idt_ key: 401', r.status === 401, r.status);check('git clone of a private repo with an unknown key fails (git sends the key only after the 401)', !cloneTo('idt_' + '0'.repeat(48), 'secretrepo', 'secretrepo.git', 'c4'));check('before the revoke the victim key clones', cloneTo(victim.key, 'pubrepo', 'pubrepo.git', 'c5'));await ident.emit('accRevokeCell', [victim.identity, app.id], alice.cookie);r = await refs(victim.key, 'pubrepo', 'pubrepo');check('revoked: 401 at the very next call', r.status === 401 && !r.body.includes(victim.key), r.status);console.log('# the old way');check('a gtr_ token still clones a private repo', cloneTo(tA, 'secretrepo', 'secretrepo.git', 'c6'));check('a gtr_ token still pushes (the owner)', pushTo(tA, 'secretrepo', 'secretrepo.git'));r = await refs(null, 'secretrepo', 'secretrepo');check('no credentials, private repo: the same 401 as before', r.status === 401, r.status);r = await refs('gtr_' + '0'.repeat(40), 'secretrepo', 'secretrepo');check('an unknown gtr_ token: 404 as before', r.status === 404, r.status);console.log('# ident down');await ident.stop();const head0 = headOf('secretrepo', 'secretrepo');r = await refs(writer.key, 'pubrepo', 'pubrepo');check('ident down: a valid key is refused with 503 (not 401, not served)', r.status === 503 && !r.body.includes(writer.key) && !r.body.includes(app.secret), r.status);writeFileSync(join(W, 'down.txt'), 'x\n'); g('add', '-A'); g('commit', '-q', '-m', 'while ident is down');check('ident down: git push with a key fails', !pushTo(writer.key, 'secretrepo', 'secretrepo.git'));check('ident down: nothing was pushed', headOf('secretrepo', 'secretrepo') === head0);check('ident down: a gtr_ token still pushes', pushTo(tA, 'secretrepo', 'secretrepo.git'));check('ident down: anonymous clone of a public repo still works', !!execFileSync('git', ['ls-remote', `http://pubrepo.localhost:${PORT}/pubrepo.git`], { env: genv, encoding: 'utf8' }));} catch (e) {failures++; console.log('FAIL gate error: ' + (e.stack || e) + '\n' + log.slice(-1500));} finally {try { server && server.kill(); } catch {} try { ident && 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