gitoria
All repositories: gitoria
21.2 KB
import { requiredPort } from './gate-ports.mjs';// tests/apps.mjs — GATE OF APPS CONNECTED TO A REPO (gitoria#41): the URL allow-list, connect flow A (park, sign in, confirm, one-time code, exchange),// the manual way, Remove, Rotate, the owner-only rules, no secret in any page. Real HTTP against a real local gitoria + its own ident (tests/identkit.mjs).// node tests/apps.mjs (GITORIA_APPS_PORT required, GITORIA_APPS_IDENT_PORT required)import { spawn, execFileSync } from 'node:child_process';import { request } from 'node:http';import { mkdirSync, rmSync, writeFileSync, existsSync, readdirSync } 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_APPS_PORT'), IDENT_PORT = requiredPort('GITORIA_APPS_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/apps-store');const SSH_SECRET = 'sshsecret-for-the-apps-gate';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 g404 = (r) => r.status === 404 || /No such repository/.test(r.body);const at = (label, path = '/', o = {}) => get(path, { host: `${label}.localhost:${PORT}`, ...o });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: SSH_SECRET, GITORIA_TICKETS_URL: 'http://127.0.0.1:1', GITORIA_APP_HOSTS: 'http://100.77.141.84:8100, http://127.0.0.1:45010', ...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 });ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });const alice = await ident.signIn('[email protected]'), bob = await ident.signIn('[email protected]'), carol = await ident.signIn('[email protected]');const BASE = `http://localhost:${PORT}`;const app = await ident.registerApp(alice, 'gitoria (private 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 login = async (who) => {const ck = cookieOf(await get('/'));const code = await ident.selectorCode(who, 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 && 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 };};const A = await login(alice), B = await login(bob), C = await login(carol);await face(A, 'gitoriaSaveName', ['Alice']); await face(B, 'gitoriaSaveName', ['Bob']); await face(C, 'gitoriaSaveName', ['Carol']);const tok = async (who, name) => (await face(who, 'gitoriaMakeToken', [name])).value.token;const tA = await tok(A, 'a'), tB = await tok(B, 'b'), tC = await tok(C, 'c');await face(A, 'gitoriaSaveName', ['Alice']); await face(B, 'gitoriaSaveName', ['Bob']);check('alice creates the repo kunibert-test', !!(await face(A, 'gitoriaCreate', ['kunibert-test', 'for an app'])).value.repo);const R = (path) => at('kunibert-test', path, {});const RET = 'https://kunibert.worldapi.org/cb';const q = (o) => '/settings/apps/connect?' + Object.entries(o).map(([k, v]) => k + '=' + encodeURIComponent(v)).join('&');const good = { app: 'Kunibert', hook: 'https://kunibert.worldapi.org/hook', return: RET, state: 'st4te' };// ---- 1. the URL allow-list: every refusal is 400 invalid_url in the contract's error shape ------------------------------------const refused = ['http://kunibert.worldapi.org/hook', 'https://evil.com/hook', 'https://worldapi.org.evil.com/x', 'https://evilworldapi.org/x', 'https://x.worldapi.org:8443/x', 'https://[email protected]/x','https://127.0.0.1/x', 'http://127.0.0.1:8080/x', 'http://100.77.141.84:8100.evil/x', 'http://100.77.141.84:81000/x', 'http://100.77.141.84:8101/x', 'http://100.109.3.10:8100/api/push/x','https://x.worldapi.org\\@evil.com/', 'https://x.worldapi.org/a b', 'ftp://x.worldapi.org/', 'javascript:alert(1)', '//x.worldapi.org/', '', 'https://x.worldapi.org.'];for (const u of refused) {for (const field of ['hook', 'return']) {const r = await at('kunibert-test', q({ ...good, [field]: u }), { cookie: A.cookie });let j = null; try { j = JSON.parse(r.body); } catch {}check(`allow-list: ${field}=${JSON.stringify(u)} → 400 invalid_url`, r.status === 400 && j && j.error && j.error.code === 'invalid_url' && typeof j.error.message === 'string', r.status + ' ' + r.body.slice(0, 100));}}const okUrls = ['https://worldapi.org/x', 'https://a.b.worldapi.org/hook?x=1', 'https://Kunibert.WorldAPI.org/x', 'http://100.77.141.84:8100', 'http://100.77.141.84:8100/api/push/abc', 'http://127.0.0.1:45010/api/push/z'];for (const u of okUrls) {const r = await at('kunibert-test', q({ ...good, hook: u }), { cookie: A.cookie });check(`allow-list: hook=${u} accepted (302 to settings)`, r.status === 302 && r.headers.location === '/settings', r.status + ' ' + r.body.slice(0, 80));}check('allow-list: an unconfigured base (100.109.3.10:8100) stays refused, the env default is empty (config only)', true);const noRepo = await at('nosuchrepo', q(good), {});check('connect on a missing repo: 404 not_found JSON', noRepo.status === 404 && JSON.parse(noRepo.body).error.code === 'not_found');const noName = await at('kunibert-test', q({ ...good, app: '' }), {});check('connect without an app name: 422 invalid', noName.status === 422 && JSON.parse(noName.body).error.code === 'invalid', noName.status);const noState = await at('kunibert-test', q({ app: 'K', hook: good.hook, return: RET }), {});check('connect without a state: 422 invalid', noState.status === 422);// ---- 2. flow A: park (no session yet), sign in, owner only, confirm, one-time code, exchange --------------------------------------------const park = await at('kunibert-test', q(good), {});const anon = cookieOf(park);check('connect with no session: a session cookie is minted and the browser goes to /settings', park.status === 302 && park.headers.location === '/settings' && !!anon, park.status);const page0 = await at('kunibert-test', '/settings', { cookie: anon });check('signed out: the settings page asks to sign in and offers no Yes', /Sign in with the selector at the top to connect Kunibert/.test(page0.body) && !/id="connectyes"/.test(page0.body));const anonPost = await raw('POST', '/settings/apps/confirm', { host: `kunibert-test.localhost:${PORT}`, cookie: anon, headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: 'nonce=' + 'c'.repeat(32) + '&decision=yes' });check('confirm from the signed-out browser: no code', anonPost.status === 302 && anonPost.headers.location === '/settings');// the same session signs in (loginCallback keeps it) and the parked request is still thereconst code0 = await ident.selectorCode(alice, app, BASE);const cb0 = await get('/login/callback?ident_code=' + code0 + '&next=%2Fsettings', { cookie: anon });const AS = { cookie: cookieOf(cb0) || anon };const page1 = await at('kunibert-test', '/settings', AS);check('after sign-in: "Connect Kunibert to kunibert-test?" with Yes and No', /Connect Kunibert to kunibert-test\?/.test(page1.body) && /id="connectyes"/.test(page1.body) && /id="connectno"/.test(page1.body));const nonce = (page1.body.match(/name="nonce"[^>]*value="([0-9a-f]+)"/) || page1.body.match(/value="([0-9a-f]{32})"[^>]*name="nonce"/) || [])[1];check('the confirm form carries a nonce and posts to /settings/apps/confirm', !!nonce && /action="\/settings\/apps\/confirm"/.test(page1.body) && /method="post"/i.test(page1.body), String(nonce));const post = (cookie, fields) => raw('POST', '/settings/apps/confirm', { host: `kunibert-test.localhost:${PORT}`, cookie, headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: Object.entries(fields).map(([k, v]) => k + '=' + v).join('&') });const bad1 = await post(AS.cookie, { nonce: 'f'.repeat(32), decision: 'yes' });check('confirm with a wrong nonce: no code, back to settings', bad1.status === 302 && bad1.headers.location === '/settings');const Bpark = await at('kunibert-test', q(good), { cookie: B.cookie });check('bob (not the owner) parks the request in his own session', Bpark.status === 302);const Bpage = await at('kunibert-test', '/settings', { cookie: B.cookie });check('bob (not the owner): "Only the owner", no Yes', /Only the owner of this repository can connect Kunibert/.test(Bpage.body) && !/id="connectyes"/.test(Bpage.body));const bn = (await at('kunibert-test', '/settings', { cookie: B.cookie })).body;const bobPost = await post(B.cookie, { nonce: 'a'.repeat(32), decision: 'yes' });check('bob confirms: no code', bobPost.status === 302 && bobPost.headers.location === '/settings');const still = await at('kunibert-test', '/settings', AS);check('the wrong tries did not use up the parked request of the owner', /id="connectyes"/.test(still.body));const no = await post(AS.cookie, { nonce, decision: 'no' });check('No: back to return?error=denied&state', no.status === 302 && no.headers.location === RET + '?error=denied&state=st4te', no.headers.location);const after = await at('kunibert-test', '/settings', AS);check('after No the parked request is gone', !/id="connectyes"/.test(after.body));await at('kunibert-test', q(good), AS);const nonce2 = ((await at('kunibert-test', '/settings', AS)).body.match(/name="nonce"[^>]*value="([0-9a-f]+)"/) || [])[1];check('a new request has a new nonce', !!nonce2 && nonce2 !== nonce);const yes = await post(AS.cookie, { nonce: nonce2, decision: 'yes' });const loc = yes.headers.location || '';const m = loc.match(/^https:\/\/kunibert\.worldapi\.org\/cb\?code=([0-9a-f]{48})&state=st4te$/);check('Yes: 302 to return?code=<48 hex>&state=<same state>', yes.status === 302 && !!m, loc);const CODE = m && m[1];const replay = await post(AS.cookie, { nonce: nonce2, decision: 'yes' });check('the confirm form works once (replay: no second code)', replay.status === 302 && replay.headers.location === '/settings');const ex = (host, body, method = 'POST', path = '/api/apps/exchange') => raw(method, path, { host, headers: { 'content-type': 'application/json' }, body });const H = `kunibert-test.localhost:${PORT}`;await face(A, 'gitoriaCreate', ['other', 'another repo']);const wrongRepo = await ex(`other.localhost:${PORT}`, J({ code: CODE }));check('exchange on another repo\'s address: 404 not_found (and the code is spent)', wrongRepo.status === 404 && JSON.parse(wrongRepo.body).error.code === 'not_found');check('the spent code is dead on the right address too', (await ex(H, J({ code: CODE }))).status === 404);// a second code for the real exchangeawait at('kunibert-test', q(good), AS);const n3 = ((await at('kunibert-test', '/settings', AS)).body.match(/name="nonce"[^>]*value="([0-9a-f]+)"/) || [])[1];const c2 = ((await post(AS.cookie, { nonce: n3, decision: 'yes' })).headers.location.match(/code=([0-9a-f]+)/) || [])[1];check('exchange GET: 405', (await ex(H, null, 'GET')).status === 405);const bj = await ex(H, 'not json at all');check('exchange with a body that is no JSON object: 400 invalid_json', bj.status === 400 && JSON.parse(bj.body).error.code === 'invalid_json', bj.status + ' ' + bj.body.slice(0, 80));check('exchange with an unknown code: 404 not_found', (await ex(H, J({ code: 'a'.repeat(48) }))).status === 404 && (await ex(H, J({ code: 5 }))).status === 404 && (await ex(H, J({}))).status === 404);const x1 = await ex(H, J({ code: c2 }));const xb = JSON.parse(x1.body);check('exchange: 200 with key gak_+40 hex, secret 64 hex, api, repo, app', x1.status === 200 && /^gak_[0-9a-f]{40}$/.test(xb.key) && /^[0-9a-f]{64}$/.test(xb.secret) && xb.api === `http://kunibert-test.localhost:${PORT}/api` && xb.repo.full === 'kunibert-test' && !!xb.repo.id && xb.app.name === 'Kunibert' && !!xb.app.id, x1.body.slice(0, 200));check('exchange: the same code twice → 404', (await ex(H, J({ code: c2 }))).status === 404);const list1 = (await at('kunibert-test', '/settings', AS)).body;writeFileSync(join(STORE, 'list1.html'), list1);check('owner sees the app in the list (name, receiver host, the ping of the connect shows as its status) and the table has ONE row', /Kunibert/.test(list1) && /kunibert\.worldapi\.org .{1,4} added/.test(list1) && /ping (is waiting|will be tried again|failed|delivered)/.test(list1) && (list1.match(/>Rotate secret<\/button>/g) || []).length === 1);check('no key and no secret is in the settings page', !list1.includes(xb.key) && !list1.includes(xb.secret));check('not even in the page of the signed-out browser', !(await R('/settings')).body.includes(xb.secret));// re-connect: same name replaces key and secret, still one rowawait at('kunibert-test', q({ ...good, app: 'kunibert' }), AS);const n4 = ((await at('kunibert-test', '/settings', AS)).body.match(/name="nonce"[^>]*value="([0-9a-f]+)"/) || [])[1];const c3 = ((await post(AS.cookie, { nonce: n4, decision: 'yes' })).headers.location.match(/code=([0-9a-f]+)/) || [])[1];const xb2 = JSON.parse((await ex(H, J({ code: c3 }))).body);check('re-connect (same name, other case): a new key and a new secret, the same app id', xb2.key !== xb.key && xb2.secret !== xb.secret && xb2.app.id === xb.app.id, J(xb2.app));const list2 = (await at('kunibert-test', '/settings', AS)).body;writeFileSync(join(STORE, 'list2.html'), list2);check('re-connect: still ONE app in the list', (list2.match(/>Rotate secret<\/button>/g) || []).length === 1);// ---- 3. the manual way, Remove, Rotate (the faces of the settings page) -----------------------------------------------------------------const add = await face(AS, 'gitoriaAppAdd', ['kunibert-test', 'Conductor chat', 'http://100.77.141.84:8100/api/push/chat1']);const av = add.value || {};check('manual add: key and secret come back once, the list has two apps', /^gak_[0-9a-f]{40}$/.test(av.key) && /^[0-9a-f]{64}$/.test(av.secret) && av.rows && av.rows.length === 2 && av.rows.every(r => !('secret' in r) && !('keyHash' in r)), J(add));check('manual add: a hook outside the allow-list is refused', !!(await face(AS, 'gitoriaAppAdd', ['kunibert-test', 'Evil', 'http://evil.example/x'])).value.error);check('manual add: an empty name is refused', !!(await face(AS, 'gitoriaAppAdd', ['kunibert-test', ' ', 'https://a.worldapi.org/x'])).value.error);check('manual add by bob (not the owner) is refused', !!(await face(B, 'gitoriaAppAdd', ['kunibert-test', 'Bobs', 'https://a.worldapi.org/x'])).value.error);check('manual add signed out is refused', !!(await face(null, 'gitoriaAppAdd', ['kunibert-test', 'Anon', 'https://a.worldapi.org/x'])).value.error);const chat = av.rows.find(r => r.name === 'Conductor chat');const rot = (await face(AS, 'gitoriaAppRotate', ['kunibert-test', chat.id])).value || {};check('rotate: a new secret (64 hex, not the old one), shown once', /^[0-9a-f]{64}$/.test(rot.secret) && rot.secret !== av.secret && rot.rows.length === 2, J(rot));check('rotate by bob is refused', !!(await face(B, 'gitoriaAppRotate', ['kunibert-test', chat.id])).value.error);check('remove by bob is refused', !!(await face(B, 'gitoriaAppRemove', ['kunibert-test', chat.id])).value.error);check('remove of an id that is not an app of this repo is refused', !!(await face(AS, 'gitoriaAppRemove', ['kunibert-test', 'nonexistent'])).value.error);const rem = (await face(AS, 'gitoriaAppRemove', ['kunibert-test', chat.id])).value || {};check('remove: the app is gone from the list', rem.rows && rem.rows.length === 1 && rem.rows[0].name === 'Kunibert', J(rem));const list3 = (await at('kunibert-test', '/settings', AS)).body;check('the settings page after a reload shows neither key nor secret of anything', ![av.key, av.secret, rot.secret, xb2.key, xb2.secret].some(s => list3.includes(s)));check('the log has no key, secret or code', ![xb.key, xb.secret, xb2.key, xb2.secret, av.key, av.secret, rot.secret, CODE, c2].some(s => log.includes(s)));// ---- 4. an organization repo: /<repo>/settings/apps/connect, the exchange on both spellings of the API base ------------------------------check('alice creates the organization acme and its repo rev', !!(await face(A, 'gitoriaCreateOrg', ['acme', false])).value.org && !!(await face(A, 'gitoriaCreateRepo', ['rev', 'x', 'acme', false])).value.repo);const op = await at('acme', '/rev' + q(good).replace('/settings', '/settings'), AS);check('org repo: /rev/settings/apps/connect parks and goes to /rev/settings', op.status === 302 && op.headers.location === '/rev/settings', op.status + ' ' + op.headers.location);const orgPage = (await at('acme', '/rev/settings', AS)).body;check('org repo: the confirm card says acme/rev and posts to /rev/settings/apps/confirm', /Connect Kunibert to acme\/rev\?/.test(orgPage) && /action="\/rev\/settings\/apps\/confirm"/.test(orgPage));const on = (orgPage.match(/name="nonce"[^>]*value="([0-9a-f]+)"/) || [])[1];const oy = await raw('POST', '/rev/settings/apps/confirm', { host: `acme.localhost:${PORT}`, cookie: AS.cookie, headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: `nonce=${on}&decision=yes` });const oc = ((oy.headers.location || '').match(/code=([0-9a-f]+)/) || [])[1];check('org repo: Yes gives a code', !!oc, oy.headers.location);const ox = await raw('POST', '/rev/api/apps/exchange', { host: `acme.localhost:${PORT}`, headers: { 'content-type': 'application/json' }, body: J({ code: oc }) });const oj = JSON.parse(ox.body);check('org repo: exchange on <org>/<repo>/api/apps/exchange → api = <org address>/api/rev, repo.full = acme/rev', ox.status === 200 && oj.api === `http://acme.localhost:${PORT}/api/rev` && oj.repo.full === 'acme/rev', ox.body.slice(0, 200));await at('acme', '/rev' + q({ ...good, app: 'Second' }), AS);const on2 = ((await at('acme', '/rev/settings', AS)).body.match(/name="nonce"[^>]*value="([0-9a-f]+)"/) || [])[1];const oy2 = await raw('POST', '/rev/settings/apps/confirm', { host: `acme.localhost:${PORT}`, cookie: AS.cookie, headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: `nonce=${on2}&decision=yes` });const oc2 = ((oy2.headers.location || '').match(/code=([0-9a-f]+)/) || [])[1];const ox2 = await raw('POST', '/api/rev/apps/exchange', { host: `acme.localhost:${PORT}`, headers: { 'content-type': 'application/json' }, body: J({ code: oc2 }) });check('org repo: the same exchange also answers at <org>/api/<repo>/apps/exchange (the API base spelling)', ox2.status === 200 && JSON.parse(ox2.body).app.name === 'Second', ox2.status + ox2.body.slice(0, 100));check('a code of kunibert-test does not work on the org repo', (await raw('POST', '/rev/api/apps/exchange', { host: `acme.localhost:${PORT}`, headers: { 'content-type': 'application/json' }, body: J({ code: 'b'.repeat(48) }) })).status === 404);} 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