gitoria
All repositories: gitoria
19.7 KB
// tests/security.mjs — SECURITY GATE of gitoria.worldapi.org (mission SG): real HTTP requests against a real local// gitoria + its own ident (tests/identkit.mjs). Who may do what (signed out / another user / owner) on every route, API// endpoint and face; injection; the session cookie; the answer headers; the open /__hl/upload.// node tests/security.mjs (GITORIA_SEC_PORT default 8914, GITORIA_SEC_PORT2 default 8915 = the https-configured server,// GITORIA_SEC_IDENT_PORT default 8913)// Known hl:web gaps (page security headers, the 404 page echoing the path, no Origin check on emit) are PRINTED as `known:` lines, not counted.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 = Number(process.env.GITORIA_SEC_PORT || 8914), PORT2 = Number(process.env.GITORIA_SEC_PORT2 || 8915), IDENT_PORT = Number(process.env.GITORIA_SEC_IDENT_PORT || 8913);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/sec-store');const SSH_SECRET = 'sshsecret-for-the-security-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++; };const known = (label) => console.log('known: ' + label);function raw(port, 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, 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(PORT, 'GET', path, o);const procs = [];function spawnServer(port, base, env) {let 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: base, 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); procs.push(p);return { p, log: () => log };}async function up(port, srv) {for (let i = 0; i < 960; i++) { try { if ((await raw(port, 'GET', '/api/repos')).status === 200) return; } catch {} await sleep(250); }throw new Error('gitoria did not come up\n' + srv.log());}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]');const BASE = `http://localhost:${PORT}`;const app = await ident.registerApp(alice, 'gitoria (security gate)', [BASE]);const BASE2 = `https://localhost:${PORT2}`;const app2 = await ident.registerApp(alice, 'gitoria (security gate, https)', [BASE2]);const env = (d, a = app) => ({ GITORIA_STORAGE: join(STORE, d, 'mpackdb'), GITORIA_SESSIONS: join(STORE, d, 'sessions') + '/', GITORIA_GIT: join(STORE, d, 'git'), IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base, IDENT_API_KEY: a.key, IDENT_API_SECRET: a.secret });const s1 = spawnServer(PORT, BASE, env('one'));const s2 = spawnServer(PORT2, BASE2, env('two', app2)); // https public URL: the cookie must be Secureawait Promise.all([up(PORT, s1), up(PORT2, s2)]);const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;const login = async (who, pre = null, next = '/') => {const first = pre ? { cookie: pre } : null;const ck = pre || cookieOf(await get('/'));const code = await ident.selectorCode(who, app, BASE);const cb = await get('/login/callback?ident_code=' + code + '&next=' + encodeURIComponent(next), { cookie: ck });return { cookie: cookieOf(cb) || ck, cb, pre: ck };};let n = 0;const face = async (who, event, payload) => {const r = await raw(PORT, '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);await face(A, 'gitoriaSaveName', ['Alice']); await face(B, 'gitoriaSaveName', ['Bob']);// ---- 1. authz: the faces (who may, result) --------------------------------------------------------------------const mk = await face(A, 'gitoriaCreate', ['alpha', 'a <b>repo</b>']);check('face gitoriaCreate: owner creates', !!(mk.value && mk.value.repo && mk.value.repo.slug === 'alpha'), J(mk.value));check('face gitoriaCreate: signed out refused', !!(await face(null, 'gitoriaCreate', ['zeta', 'x'])).value.error);check('face gitoriaCreate: a slug with .. or / refused', !!(await face(B, 'gitoriaCreate', ['../x', 'x'])).value.error && !!(await face(B, 'gitoriaCreate', ['a/b', 'x'])).value.error);const tk = await face(A, 'gitoriaMakeToken', ['laptop']);check('face gitoriaMakeToken: signed-in user makes one', !!(tk.value && /^gtr_[0-9a-f]{40}$/.test(tk.value.token || '')), J(tk.value));check('face gitoriaMakeToken: signed out refused', !!(await face(null, 'gitoriaMakeToken', ['x'])).value.error);check('face gitoriaRemoveToken: another user cannot remove it', (await face(B, 'gitoriaRemoveToken', [tk.value.row.id])).value.error === 'no such token');check('face gitoriaRemoveToken: signed out refused', !!(await face(null, 'gitoriaRemoveToken', [tk.value.row.id])).value.error);check('face gitoriaAddKey / gitoriaRemoveKey: signed out refused', !!(await face(null, 'gitoriaAddKey', ['k', 'ssh-ed25519 AAAA'])).value.error && !!(await face(null, 'gitoriaRemoveKey', ['1'])).value.error);for (const [w, wn] of [[null, 'signed out'], [B, 'another user']]) {check(`face gitoriaSetBranch: ${wn} refused`, !!(await face(w, 'gitoriaSetBranch', ['alpha', 'main', 'code', ''])).value.error);check(`face gitoriaDisconnectTickets: ${wn} refused`, !!(await face(w, 'gitoriaDisconnectTickets', ['alpha'])).value.error);check(`face gitoriaMergePull: ${wn} refused`, !!(await face(w, 'gitoriaMergePull', ['alpha', 'a'.repeat(40)])).value.error);}check('face gitoriaOpenTicket: signed out refused', !!(await face(null, 'gitoriaOpenTicket', ['alpha', 's', 't'])).value.error);check('face gitoriaSaveName: signed out refused', !!(await face(null, 'gitoriaSaveName', ['x'])).value.error);check('face gitoriaSaveName: the name is asked ONCE (a second set refused)', !!(await face(A, 'gitoriaSaveName', ['Other'])).value.error);check('face gitoriaLogin: a junk code is refused', !!(await face(B, 'gitoriaLogin', ['not a code'])).value.error);check('client-side events cannot be called by a peer', !(await face(null, 'repoCreated', [{ slug: 'evil' }])).value);// ---- 1b. authz: routes ----------------------------------------------------------------------------------------------const apiRow = JSON.parse((await get('/api/repos/alpha')).body);check('API /api/repos/:slug: public read, no secret field', !('tktKey' in apiRow) && !('tktApi' in apiRow) && !('owner_id' in apiRow) && !('identity' in apiRow), J(Object.keys(apiRow)));check('API: POST refused (405)', (await raw(PORT, 'POST', '/api/repos', { body: '{}' })).status === 405);check('/settings/connect: signed out is sent to /settings (no nonce)', (await get('/settings/connect', { host: `alpha.localhost:${PORT}` })).headers.location === '/settings');check('/settings/connect: another user is sent to /settings (no redirect to tickets)', (await get('/settings/connect', { host: `alpha.localhost:${PORT}`, cookie: B.cookie })).headers.location === '/settings');check('/settings/connect: the owner is sent on to tickets', /\/connect\?app=gitoria/.test((await get('/settings/connect', { host: `alpha.localhost:${PORT}`, cookie: A.cookie })).headers.location || ''));check('/settings/connected: another user is sent to /settings, nothing stored', (await get('/settings/connected?code=abc&state=x', { host: `alpha.localhost:${PORT}`, cookie: B.cookie })).headers.location === '/settings');const q = '/__git/access?user=x&slug=alpha&write=1';check('/__git/access: no secret → 403', (await get(q)).status === 403);check('/__git/access: wrong secret → 403', (await get(q, { headers: { 'x-gitoria-secret': 'nope' } })).status === 403);check('/__git/access: right secret through the proxy (X-Forwarded-For) → 403', (await get(q, { headers: { 'x-gitoria-secret': SSH_SECRET, 'x-forwarded-for': '1.2.3.4' } })).status === 403);check('/__git/access: right secret, a non-owner write → 403', (await get(q, { headers: { 'x-gitoria-secret': SSH_SECRET } })).status === 403);check('/__git/keys: no secret → 403', (await get('/__git/keys?type=ssh-ed25519&key=AAAA')).status === 403);// ---- 1c. git over HTTPS: who may push -------------------------------------------------------------------------------const tokB = (await face(B, 'gitoriaMakeToken', ['bobs'])).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'), '# T\n\n[js](javascript:alert(1)) [d](data:text/html,x) [ok](https://example.org/a) <script>window.__x=1</script> [p](//evil.com)\n');writeFileSync(join(W, '<img src=x onerror=alert(1)>.txt'), 'hello <script>alert(1)</script>\n');g('add', '-A'); g('commit', '-q', '-m', 'init <script>alert(1)</script>'); g('branch', 'feat<b>x');const url = (t) => `http://u:${t}@alpha.localhost:${PORT}/alpha.git`;const push = (t) => { try { g('push', '-q', url(t), 'main'); return true; } catch { return false; } };check('git push: another user\'s valid token refused', !push(tokB));check('git push: a made-up token refused', !push('gtr_' + '0'.repeat(40)));try { g('push', '-q', `http://alpha.localhost:${PORT}/alpha.git`, 'main'); check('git push: without credentials refused', false); } catch { check('git push: without credentials refused', true); }check('git push: the owner\'s token works', push(tk.value.token));g('push', '-q', url(tk.value.token), 'feat<b>x');const adv = await get('/alpha.git/info/refs?service=git-receive-pack', { host: `alpha.localhost:${PORT}` });check('git receive-pack advertisement needs a token (401)', adv.status === 401);check('git clone/ls-remote needs no login (public)', /refs\/heads\/main/.test(g('ls-remote', `http://alpha.localhost:${PORT}/alpha.git`)));check('git transport on the main address / a foreign repo name: 404', (await get('/alpha.git/info/refs?service=git-upload-pack')).status === 404 && (await get('/beta.git/info/refs?service=git-upload-pack', { host: `alpha.localhost:${PORT}` })).status === 404);// ---- 2. injection ---------------------------------------------------------------------------------------------------const own = (b) => b.replace(/<script type="application\/json" id="hl-seed">[\s\S]*?<\/script>/, '');for (const p of ['/', '/code', '/branch/' + encodeURIComponent('feat<b>x'), '/code/' + encodeURIComponent('<img src=x onerror=alert(1)>.txt')]) {const r = await get(p, { host: `alpha.localhost:${PORT}` });check(`page ${p.slice(0, 30)}: no repo text lands as HTML (script / img / bold)`, !/<script>(alert|window\.__x)|<img src=x|<b>repo<\/b>|<b>x</.test(own(r.body)), J(own(r.body).match(/<script>(alert|window\.__x)|<img src=x|<b>repo<\/b>|<b>x</)));check(`page ${p.slice(0, 30)}: the page data seed cannot close its script tag`, !/<\/script/i.test((r.body.match(/id="hl-seed">([\s\S]*?)<\/script>/) || [, ''])[1]));}const home = own((await get('/', { host: `alpha.localhost:${PORT}` })).body);const hrefs = [...home.matchAll(/<a [^>]*href="([^"]*)"/g)].map(m => m[1]);check('Markdown: no javascript: / data: / protocol-relative link in the README page', !hrefs.some(h => /^(javascript|data|vbscript):/i.test(h) || h.startsWith('//')), J(hrefs));check('Markdown: the safe https link stays a link', hrefs.includes('https://example.org/a'));const nextOf = async (nx) => (await get('/login/callback?ident_code=' + await ident.selectorCode(bob, app, BASE) + '&next=' + encodeURIComponent(nx))).headers.location;let ok = true; const bad = [];for (const nx of ['//evil.com', '/\\evil.com', 'http://evil.com/', 'javascript:alert(1)', 'http://x.localhost:' + PORT + '@evil.com/', 'http://alpha.localhost:' + PORT + '.evil.com/']) { const l = await nextOf(nx); if (l !== '/') { ok = false; bad.push(nx + ' → ' + l); } }check('login ?next=: no open redirect (//, backslash, other host, javascript:, userinfo / suffix tricks)', ok, bad.join('; '));check('login ?next=: a repo address of this system is allowed', (await nextOf(`http://alpha.localhost:${PORT}/code`)) === `http://alpha.localhost:${PORT}/code`);const header = await get('/login/callback?ident_code=x&next=' + encodeURIComponent('/a\r\nSet-Cookie: x=1'));check('login ?next=: no header injection', !J(header.headers['set-cookie'] || '').includes('x=1') && !('x' in header.headers) && header.headers.location === '/login/failed', J(header.headers));check('files: source, storage, .env, .git are not served', (await Promise.all(['/.env', '/project.hl', '/lib/users.hl', '/storage/mpackdb/users.db', '/.git/config', '/icons/%2e%2e/project.hl', '/%2e%2e/%2e%2e/etc/passwd', '/docker-compose.yml'].map(p => get(p)))).every(r => r.status === 404));const mod = await get('/components/main.hl');check('served client modules hold no secret (ident secret, ssh secret)', !mod.body.includes(app.secret) && !mod.body.includes(SSH_SECRET));for (const w of [A, B]) {const r = await get('/settings', { host: `alpha.localhost:${PORT}`, cookie: w.cookie }); const r2 = await get('/', { cookie: w.cookie });check('pages carry no secret (app secret, ssh secret, session id, token, ident identity)', ![r.body, r2.body].some(b => b.includes(app.secret) || b.includes(SSH_SECRET) || b.includes(w.cookie.split('=')[1]) || b.includes(tk.value.token) || /"identity"/.test(b)), J([r.body, r2.body].map(b => [b.includes(app.secret), b.includes(SSH_SECRET), b.includes(w.cookie.split('=')[1]), b.includes(tk.value.token), /"identity"/.test(b)])));}// ---- 3. uploads -----------------------------------------------------------------------------------------------------const upl = await raw(PORT, 'POST', '/__hl/upload', { headers: { 'content-type': 'application/json' }, body: J({ name: 'x', type: 'text/plain', size: 900000000 }) });check('/__hl/upload: a signed-out visitor cannot start a 900 MB upload (no face takes a file) → 413', upl.status === 413, upl.status + " " + upl.body.slice(0, 100));// ---- 4. sessions and cookies ----------------------------------------------------------------------------------------// hl:web creates sessions lazily: a plain GET sends no cookie at all (nothing to track a visitor by). The cookie flags are checked on// the cookie the login hands out, on both servers.const plain = await get('/');check('a plain GET sends no Set-Cookie (sessions are created lazily, a visitor who does nothing gets no cookie)', !plain.headers['set-cookie'], J(plain.headers['set-cookie']));const c1 = (await login(bob)).cb.headers['set-cookie'][0];check('cookie: HttpOnly, SameSite=Lax, Path=/', /HttpOnly/.test(c1) && /SameSite=Lax/.test(c1) && /Path=\//.test(c1), c1);const cb2 = await raw(PORT2, 'GET', '/login/callback?ident_code=' + await ident.selectorCode(bob, app2, BASE2));const c2 = (cb2.headers['set-cookie'] || [''])[0];check('cookie: Secure when the public address is https', /; Secure/.test(c2), c2 + ' ' + cb2.status);const pre = 'gitoriasid=' + 'ab'.repeat(16); // a cookie planted by an attacker before the loginconst fixed = await login(bob, pre);check('login rotates the session id (a cookie planted before login is not the logged-in one)', fixed.cookie !== pre, 'same cookie ' + pre);const mkAsPre = await face({ cookie: pre }, 'gitoriaMakeToken', ['fixation']);check('the pre-login cookie does not act as the user', !!(mkAsPre.value && mkAsPre.value.error), J(mkAsPre.value));check('the new session acts as the user', !!(await face(fixed, 'gitoriaMakeToken', ['after'])).value.token);const C = await login(bob);await face(C, 'gitoriaLogOut', []);check('logout: the same cookie is signed out afterwards', !!(await face(C, 'gitoriaMakeToken', ['x'])).value.error);const code2 = await ident.selectorCode(bob, app, BASE);await get('/login/callback?ident_code=' + code2); const again = await get('/login/callback?ident_code=' + code2);check('a login code works once (reuse → /login/failed)', again.headers.location === '/login/failed');// ---- 6. headers on the function routes (pages: known gap) ------------------------------------------------------------const nos = async (label, r) => check(`X-Content-Type-Options: nosniff — ${label}`, (r.headers['x-content-type-options'] || '') === 'nosniff', J(r.headers));await nos('/api/repos', await get('/api/repos'));await nos('/api/repos/alpha (markdown)', await get('/api/repos/alpha', { headers: { accept: 'text/markdown' } }));await nos('/login/callback redirect', await get('/login/callback?ident_code=zz'));await nos('/settings/connect redirect', await get('/settings/connect', { host: `alpha.localhost:${PORT}` }));await nos('/__git/access', await get(q));await nos('git info/refs', await get('/alpha.git/info/refs?service=git-upload-pack', { host: `alpha.localhost:${PORT}` }));await nos('git 401', adv);const page = await get('/');for (const h of ['content-security-policy', 'x-content-type-options', 'x-frame-options', 'referrer-policy']) if (!page.headers[h]) known(`page answers carry no ${h} (hl:web has no hook for page headers — .scratch/SG-hlweb-gaps.md)`);const nf = await get('/nope%3Cscript%3Ealert(1)%3C/script%3E');if (/<script>alert/.test(nf.body) && /html/.test(nf.headers['content-type'])) known('hl:web 404 page echoes the decoded path as text/html: reflected XSS (.scratch/SG-hlweb-gaps.md)');const ev = await raw(PORT, 'POST', '/__hl/emit', { headers: { 'content-type': 'text/plain', origin: 'https://evil.example' }, cookie: A.cookie, body: J({ t: 'emit', i: 999, event: 'gitoriaMakeToken', payload: ['csrf'] }) });if (/"ok":true/.test(ev.body)) known('/__hl/emit does not check Origin (SameSite=Lax is the only CSRF guard; faces cannot read headers) (.scratch/SG-hlweb-gaps.md)');} catch (e) {check('the security gate ran to its end', false, String(e && e.stack || e));} finally {for (const p of procs) { try { p.kill('SIGTERM'); } catch {} }if (ident) await ident.stop();await sleep(500);console.log(`\n${passes} passed, ${failures} failed`);process.exit(failures ? 1 : 0);}
Branches
- f1-broken-json
- f2-api-bugs
- gp-gate-ports
- heap-revert
- hl25-records
- ident-chooser-selector
- mainmain branch
- p51-public-pr-reads
- records-1112
- s25-no-session-on-login-error
- v59
- w52-person-approval
- w52b-approval-followup
- w52c-header-phone
- w53-pulls-speed-pr
- w54-repo-rename-pr
- w55-rename-org
- w56-owner-members
- w62-pr-close
- w63-force-push
- w64-org-slash
Latest commits
- 90b4f728gitoria#25: restore the homepage cache and the parsed-blocks cache (they store data under immutable keys, no HTML); the page key, the framework readme key and the textHash key stay removedmre
- a487248cgitoria#25: remove every cache that hid the page build (page key, Markdown render key, homepage cache, parsed-blocks cache) and the gate that only tested themmre
- 12f2f4fegitoria: re-vendor Hybriel set-day27b, a startup fault in on Error exits 1mre
- c21c084egitoria: write the standby service out in full so the boot gate can read the main servicemre
- e307d69agitoria: say what is per process during the hand-overmre
- f0cbe6a6gitoria: standby service on port 45014 and a deploy that hands over through it without a gapmre
- 727cd083gitoria#25: README: vendor notes for Hybriel c1b1010f and the page cachemre
- 61b72dedgitoria#25: re-vendor Hybriel master c1b1010f (W149 page cache), key the repo Readme page by slug and main commit, extend the readme-cache gatemre
- 5b0b4b9ereadme-cache gate: use the security gate's ports when no own ports are givenmre
- bc8f20d9gitoria#25: re-vendor Hybriel c09538bb with the W141 render cache, cache the homepage per commit, add the readme-cache gatemre
- 9feebbd3Re-vendor Hybriel to ded47c13 (W145: Firefox start script fix)mre
- 28ed41e5gitoria#24: one sign-in comes from hl:web batch 20, the /session/share workaround is gonemre
- 3b2669e4gs: drop the unbuildable legacy check, fix pwa fetchmre
- 2a2fdd77gs: C2 check before cookie experimentsmre
- 76e0587aWIP gs 2mre
- a80da7bdWIP gs: security gate for lazy sessions, g24 browser checksmre
- 23fb05d8re-vendor Hybriel aaa39e69 (hl:web batch 20: login emit and Sessions.mint, tab follows a login, signed-in session cookie wins among duplicates and is re-issued with the Domain, W85 faster render, lazy sessions)mre
- a0727ca3ident#31: the selector's sign-in returns to the page the user started on (return attribute = the login callback with next), gate checkmre
- a06975f9gitoria: a gap between your name and Log out in the phone header (they touched); gate checks itmre
- 32ba9d59gitoria: leave the host-only cookie experiment out of the browser gate (gitoria#24 is a separate mission)mre