gitoria
All repositories: gitoria
14.7 KB
import { requiredPort, requiredPortRange } from './gate-ports.mjs';// tests/create-api.mjs — gitoria#39: user-token creation through the shared web path.// Own ident/server/storage; real git pushes and the same SSH authorization door as private.mjs.// GITORIA_CREATE_PORT (8720) and GITORIA_CREATE_IDENT_PORT (8721); Chrome uses PORT+3..9.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 { launchBrowser } from './cdp.mjs';import { startIdent } from './identkit.mjs';const HERE = dirname(fileURLToPath(import.meta.url));const APP = resolve(HERE, '..');const PORT = requiredPort('GITORIA_CREATE_PORT'), IDENT_PORT = requiredPort('GITORIA_CREATE_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 = process.env.GITORIA_CREATE_STORE || join(APP, '.scratch/create-api-store');const SSH_SECRET = 'sshsecret-for-the-private-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', ...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, browser, page;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);const unnamed = await ident.signIn('[email protected]'), U = await login(unnamed);const tU = (await face(U, 'gitoriaMakeToken', ['unnamed'])).value.token;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');// ---- the working copy to push ----------------------------------------------------------------------------------------------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'), '# Hidden\n\nSECRETREADME-7f3a\n');writeFileSync(join(W, 'file.txt'), 'SECRETFILE-9c1d\n');g('add', '-A'); g('commit', '-q', '-m', 'init SECRETCOMMIT-5b2e');const SHA = g('rev-parse', 'HEAD').trim();const urlOf = (t, host, path) => `http://u:${t}@${host}.localhost:${PORT}/${path}`;const pushTo = (t, host, path) => { try { g('push', '-q', urlOf(t, host, path), 'main'); return true; } catch { return false; } };const lsRemote = (t, host, path) => { try { return g('ls-remote', t ? urlOf(t, host, path) : `http://${host}.localhost:${PORT}/${path}`); } catch { return null; } };const json = r => JSON.parse(r.body);const create = (input, token = tA, extra = {}) => raw('POST', '/api/repos', { headers: token ? { authorization: 'Bearer ' + token } : {}, body: typeof input === 'string' ? input : J(input), ...extra });const error = async (label, input, token, status, code) => {const r = await create(input, token);const e = json(r).error;check(label, r.status === status && e.code === code && typeof e.message === 'string' && !!e.message && 'details' in e);};// hybriel#280: malformed object JSON still aborts JSON.parse until set day38.// Exercise invalid_json with a non-object body only, as on the existing write routes.await error('non-object body: 400 invalid_json', 'hello', tA, 400, 'invalid_json');await error('no token: 401 unauthorized', { name: 'no-token' }, null, 401, 'unauthorized');await error('unknown user token: 401 unauthorized', { name: 'unknown-token' }, 'gtr_' + 'a'.repeat(40), 401, 'unauthorized');await error('user without display name: 422 invalid', { name: 'unnamed' }, tU, 422, 'invalid');for (const name of ['', 'a', 'Bad', 'a--b', 'api', '../repo', 'x'.repeat(41), 42]) {await error('bad name ' + J(name) + ': 422 invalid', { name }, tA, 422, 'invalid');}await error('unknown org: 403 forbidden', { name: 'outside', org: 'missing' }, tA, 403, 'forbidden');await error('unknown member: 422 invalid', { name: 'atomic', members: ['Bob', 'Nobody'] }, tA, 422, 'invalid');check('unknown member created neither row nor git directory', (await get('/api/repos/atomic')).status === 404 && !existsSync(join(STORE, 'git/atomic.git')));await error('over 1 MB: 413 too_large', { name: 'oversize', description: 'x'.repeat(1048576) }, tA, 413, 'too_large');for (const input of [{ name: 'bad-desc', description: 42 }, { name: 'bad-private', private: 'yes' }, { name: 'bad-members', members: 'Bob' }]) {await error('bad input: 422 invalid', input, tA, 422, 'invalid');}browser = await launchBrowser({ debugPortRange: requiredPortRange('GITORIA_GATE_CHROME') });page = await browser.newPage();await page.goto((process.env.GITORIA_CREATE_BROWSER_URL || BASE) + '/');await page.waitFor(`!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1`, { timeout: 30000 });const r = await create({ name: 'api-repo', description: 'Created by API', private: false, members: ['Bob'] });check('create: 201 with token owner and requested description', r.status === 201 && json(r).owner === 'Alice' && json(r).slug === 'api-repo' && json(r).description === 'Created by API');const one = await get('/api/repos/api-repo');check('201 JSON exactly equals public GET (no extra fields)', one.status === 200 && r.body === one.body);check('public GET list includes created repo without a token', json(await get('/api/repos')).repos.some(r => r.slug === 'api-repo'));await page.waitFor(`document.querySelector('#repos').textContent.includes('api-repo')`, { timeout: 20000 });check('already-open list receives the new repo live', await page.evaluate(`document.querySelectorAll('#repos li').length === 1`));await page.goto((process.env.GITORIA_CREATE_BROWSER_URL || BASE) + '/');await page.waitFor(`!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1`, { timeout: 30000 });check('second visit keeps the stored repo in the list', await page.evaluate(`document.querySelector('#repos').textContent.includes('api-repo')`));if (process.env.GITORIA_CREATE_PROOF) {for (const [width, height] of [[390, 844], [800, 1280], [1280, 800], [1280, 900]]) {await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 });const name = `proof-${width}-${height}`;check(`${width}x${height}: API creates while list stays open`, (await create({ name, description: 'Live API creation' })).status === 201);await page.waitFor(`document.querySelector('#repos').textContent.includes(${J(name)})`, { timeout: 20000 });check(`${width}x${height}: list fits viewport`, await page.evaluate(`document.documentElement.scrollWidth <= ${width}`));const { data } = await page.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });writeFileSync(join(STORE, `proof-${width}-${height}.png`), Buffer.from(data, 'base64'));}}await error('duplicate name: 409 conflict', { name: 'api-repo' }, tA, 409, 'conflict');const key = (await face(A, 'gitoriaAppAdd', ['api-repo', 'Create Gate', 'https://example.worldapi.org/hook'])).value.key;const appToken = json(await raw('POST', '/api/apps/token', { host: `api-repo.localhost:${PORT}`, headers: { authorization: 'Bearer ' + key } })).token;await error('live gat_ app token: 403 forbidden', { name: 'app-created' }, appToken, 403, 'forbidden');check('app token made nothing', (await get('/api/repos/app-created')).status === 404);check('owner gtr_ pushes to API repo', pushTo(tA, 'api-repo', 'api-repo.git'));check('member gtr_ pushes to API repo', pushTo(tB, 'api-repo', 'api-repo.git'));check('stranger cannot push to API repo', !pushTo(tC, 'api-repo', 'api-repo.git'));const web = (await face(A, 'gitoriaCreateRepo', ['web-repo', 'Web comparison', '', false])).value.repo;const member = (await face(A, 'gitoriaChangeMember', ['web-repo', 'Bob', true])).value.members[0];const acc = (slug, user, write) => get(`/__git/access?slug=${encodeURIComponent(slug)}&user=${user}&write=${write}`, { headers: { 'x-gitoria-secret': SSH_SECRET } });for (const [uid, write] of [[member.id, 0], [member.id, 1], ['nobody', 0], ['nobody', 1]]) {const a = await acc('api-repo', uid, write), w = await acc('web-repo', uid, write);check('SSH rule matches web-created repo for ' + (uid === member.id ? 'member' : 'stranger') + ' write=' + write, a.status === w.status && (uid !== member.id || a.status === 200));}check('HTTPS membership matches web-created repo', pushTo(tB, 'web-repo', 'web-repo.git') && !pushTo(tC, 'web-repo', 'web-repo.git'));const shortId = await ident.exchange(app, await ident.selectorCode(bob, app, BASE));const priv = await create({ name: 'private-api', private: true, members: [shortId, 'Bob'] });check('private API repo resolves identity short id and duplicate member', priv.status === 201 && json(priv).isPrivate);check('private API row equals owner GET', priv.body === (await get('/api/repos/private-api', { cookie: A.cookie })).body);check('private repo hidden from public GET and list', (await get('/api/repos/private-api')).status === 404 && !json(await get('/api/repos')).repos.some(r => r.slug === 'private-api'));check('private member sees, clones and pushes', (await get('/api/repos/private-api', { cookie: B.cookie })).status === 200 && pushTo(tB, 'private-api', 'private-api.git') && /refs\/heads\/main/.test(lsRemote(tB, 'private-api', 'private-api.git') || ''));check('private stranger SSH read denied', (await acc('private-api', 'nobody', 0)).status === 404);await face(A, 'gitoriaCreateOrg', ['acme', false]);await error('non-member org: 403 forbidden', { name: 'intruder', org: 'acme' }, tC, 403, 'forbidden');await face(A, 'gitoriaChangeOrgMember', ['acme', 'Bob', true]);const org = await create({ name: 'org-repo', org: 'acme' }, tB);check('org member creates with token user as owner', org.status === 201 && json(org).slug === 'acme/org-repo' && json(org).owner === 'Bob');await error('duplicate org slug: 409 conflict', { name: 'org-repo', org: 'acme' }, tA, 409, 'conflict');check('org owner and creator push using normal org transport', pushTo(tA, 'acme', 'org-repo.git') && pushTo(tB, 'acme', 'org-repo.git'));check('GET list stays public despite a bogus Authorization header', (await get('/api/repos', { headers: { authorization: 'Bearer bogus' } })).status === 200);await stop(); startServer(ENV); await up();check('after server restart the repo and membership persist', (await get('/api/repos/api-repo')).status === 200 && pushTo(tB, 'private-api', 'private-api.git'));check('no token values in the server log', ![tA, tB, tC, tU, appToken, key].some(t => log.includes(t)));} catch (e) {check('gate completes', false, String(e.message).replace(/gtr_[0-9a-f]+|gat_[0-9a-f]+|gak_[0-9a-f]+/g, '[redacted]'));} finally {if (page) await page.close().catch(() => {});if (browser) await browser.close().catch(() => {});await stop().catch(() => {});if (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