tickets
All repositories: gitoria
57.5 KB
// tests/security.mjs — THE SECURITY GATE (mission ST): authorisation of every route / face, injection, uploads, sessions, headers, secrets.// Own server on a fresh store, an ident STUB (POST /api/exchange only), real HTTP (fetch / raw http) and the page faces through POST /__hl/emit// like a browser's socket-less call. Users: alice (admin of project sa, owns ticket 1), bob (use in sa), carol (no role, admin of sc), dave (edit in sd), anon.// Ports: TICKETS_SEC_PORT (8840), TICKETS_SEC_IDENT_PORT (8841; default = port+1), PORT+2 (https server, and main's code first), TICKETS_SEC_CHROME (debug port range, 8855-8859). Needs `git` and the branch/ref `main` (cookie compat check). TICKETS_COLD_MS: cold start wait (120 s). Store: .scratch/security-gate.// node tests/security.mjsimport { spawn, execFileSync } from 'node:child_process';import http from 'node:http';import { rmSync, mkdirSync, existsSync, readdirSync, readFileSync, readlinkSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { writeFileSync } from 'node:fs';import { launchBrowser } from './cdp.mjs';import { fileURLToPath } from 'node:url';const APP = resolve(dirname(fileURLToPath(import.meta.url)), '..');const BIN = join(APP, 'bin/hybriel');const PORT = Number(process.env.TICKETS_SEC_PORT || 8840);const IDENT_PORT = Number(process.env.TICKETS_SEC_IDENT_PORT || PORT + 1);const BASE = `http://127.0.0.1:${PORT}`;const WORK = join(APP, '.scratch/security-gate');const STORE = join(WORK, 'store');const COLD_MS = Number(process.env.TICKETS_COLD_MS || 120000);const J = JSON.stringify;const sleep = (ms) => new Promise(r => setTimeout(r, ms));rmSync(WORK, { recursive: true, force: true });mkdirSync(join(STORE, 'mpackdb'), { recursive: true }); mkdirSync(join(STORE, 'mpackdb2'), { recursive: true });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++; };let log = '', log2 = '', server = null, server2 = null, ident = null, browser = null;if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';const png = Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), Buffer.from('0000000d49484452000000010000000108060000001f15c4890000000d49444154789c6360000002000001e221bc330000000049454e44ae426082', 'hex')]);async function main() {const codes = new Map(); let codeN = 0;const mint = (identity) => { const c = (++codeN).toString(16).padStart(8, '0').repeat(3); codes.set(c, identity); return c; };ident = http.createServer((req, res) => {let body = ''; req.on('data', d => body += d);req.on('end', () => {if (req.url === '/api/exchange' && req.method === 'POST') {const b = JSON.parse(body || '{}'); const id = codes.get(b.code); codes.delete(b.code);res.writeHead(id && b.secret === 'sk_sec' ? 200 : 400, { 'content-type': 'application/json' });return res.end(J(id ? { identity: id } : { error: 'unknown code' }));}if (req.url.split('?')[0] === '/selector.js' && req.method === 'GET') { res.writeHead(200, { 'content-type': 'text/javascript' }); return res.end('/* ident selector stub */'); }res.writeHead(404); res.end('');});});await new Promise(ok => ident.listen(IDENT_PORT, '127.0.0.1', ok));const identBase = `http://127.0.0.1:${IDENT_PORT}`;server = spawn(BIN, ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, TICKETS_PORT: String(PORT), TICKETS_STORAGE: join(STORE, 'mpackdb'), TICKETS_SESSIONS: join(STORE, 'sessions'), TICKETS_ATTACHMENTS: join(STORE, 'attachments'),IDENT_URL: identBase, IDENT_EXCHANGE_URL: identBase, TICKETS_PUBLIC_URL: BASE, IDENT_API_KEY: 'pk_sec', IDENT_API_SECRET: 'sk_sec', TICKETS_CREATOR_IDENTITY: '', TICKETS_WATCH: '0', HL_HOST: '127.0.0.1' } });server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);for (const end = Date.now() + COLD_MS; Date.now() < end;) { try { if ((await fetch(BASE + '/')).ok) break; } catch {} await sleep(250); }let emitI = 0;const temit = async (event, payload, cookie) => {const r = await fetch(BASE + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) }, body: J({ t: 'emit', i: ++emitI, event, payload }) });const raw = await r.text(); let j = null; try { j = JSON.parse(raw); } catch {}return j ? j.value : undefined;};const call = async (method, path, body, headers = {}) => {const r = await fetch(BASE + path, { method, headers: { ...(body ? { 'content-type': 'application/json' } : {}), ...headers }, body: body ? (typeof body === 'string' ? body : J(body)) : undefined, redirect: 'manual' });const t = await r.text(); let json = null; try { json = JSON.parse(t); } catch {}if (process.env.SEC_ALIVE) { const ac = new AbortController(); setTimeout(() => ac.abort(), 4000); try { await (await fetch(BASE + '/api/tickets', { signal: ac.signal })).text(); } catch { console.log('WEDGED after ' + method + ' ' + path.slice(0, 80)); process.exit(3); } }return { status: r.status, json, text: t, headers: r.headers };};const login = async (id, name) => {const code = mint(id);const r = await fetch(BASE + '/login/callback?ident_code=' + code, { redirect: 'manual' });const cookie = (r.headers.get('set-cookie') || '').split(';')[0];if (name) await temit('saveDisplayName', [name], cookie);const u = { id, cookie, setCookie: r.headers.get('set-cookie') || '' };u.token = (await temit('tokenCreate', ['gate'], cookie)).token;u.auth = { authorization: 'Bearer ' + u.token };return u;};const alice = await login('a2b3c', 'alice'), bob = await login('b4c5d', 'bob'), carol = await login('c6d7e', 'carol'), dave = await login('d8e9f', 'dave');const hdrOfRaw = async (p, extra = {}) => { const x = await fetch(BASE + p, { headers: extra }); await x.arrayBuffer(); return x.headers; };const A = (u, extra = {}) => ({ ...u.auth, ...extra });// ---- setuplet r = await call('POST', '/api/projects', { title: 'Sec A', slug: 'sa' }, A(alice)); check('setup: alice opens sa', r.status === 201, r.text);const saId = r.json.project.id;r = await call('POST', '/api/projects/sa/members', { user: bob.id, role: 'use' }, A(alice)); check('setup: bob is use in sa', r.status === 200, r.text);r = await call('POST', '/api/projects', { title: 'Sec C', slug: 'sc' }, A(carol)); check('setup: carol opens sc', r.status === 201, r.text);const scId = r.json.project.id;r = await call('POST', '/api/projects', { title: 'Sec D', slug: 'sd' }, A(dave)); check('setup: dave opens sd', r.status === 201, r.text);r = await call('POST', '/api/projects/sa/tickets', { subject: 'alice ticket', summary: 'first' }, A(alice)); check('setup: ticket sa#1', r.status === 201, r.text);const t1 = r.json.ticket;r = await call('POST', '/api/projects/sa/tickets', { subject: 'alice second' }, A(alice)); const t2 = r.json.ticket;r = await call('POST', '/api/projects/sc/tickets', { subject: 'carol ticket' }, A(carol)); const c1 = r.json.ticket;r = await call('POST', '/api/projects/sd/tickets', { subject: 'dave ticket' }, A(dave)); const d1 = r.json.ticket;r = await call('POST', '/api/tickets/' + t1.id + '/comments', { text: 'alice comment' }, A(alice)); check('setup: alice comments', r.status === 201, r.text);const aliceComment = r.json.event.id;// ================= 1. AUTHZ — signed out: every write is 401 =================const writes = [['POST', '/api/tickets', { project: 'sa', subject: 'x' }],['POST', '/api/projects/sa/tickets', { subject: 'x' }],['POST', `/api/tickets/${t1.id}/comments`, { text: 'x' }],['POST', `/api/tickets/${t1.id}/comments/${aliceComment}/edit`, { text: 'x' }],['POST', `/api/tickets/${t1.id}/comments/${aliceComment}/delete`, {}],['POST', `/api/tickets/${t1.id}/comments/${aliceComment}/like`, {}],['POST', `/api/tickets/${t1.id}/state`, { state: 'done' }],['POST', `/api/tickets/${t1.id}/edit`, { subject: 'x' }],['POST', `/api/tickets/${t1.id}/assign`, { assignee: '' }],['POST', `/api/tickets/${t1.id}/parent`, { parent: '' }],['POST', `/api/tickets/${t1.id}/blocked-by`, { add: 'sa#2' }],['POST', '/api/projects', { title: 'zz' }],['POST', '/api/projects/sa', { title: 'zz' }],['POST', '/api/projects/sa/members', { user: 'a2b3c', role: 'admin' }],['POST', '/api/projects/sa/members/remove', { user: 'b4c5d' }],['POST', '/api/projects/sa/invites', { role: 'use' }],['POST', '/api/projects/sa/connections/remove', { id: 'x' }],['GET', '/api/inbox'],['GET', '/api/events'],['GET', '/api/attachments/anything'],];for (const [m, p, b] of writes) {const x = await call(m, p, b);check(`authz signed-out: ${m} ${p.replace(t1.id, ':id').replace(aliceComment, ':c')} → 401`, x.status === 401 || (p === '/api/attachments/anything' && x.status === 404), x.status + ' ' + x.text.slice(0, 100));}for (const p of ['/api/tickets', '/api/projects', '/api/projects/sa', '/api/projects/sa/tickets', `/api/tickets/${t1.id}`, '/api/projects/sa/connections', '/']) {const x = await call('GET', p); check(`authz signed-out: GET ${p.replace(t1.id, ':id')} is public (200, by design)`, x.status === 200, x.status);}// ================= 1b. AUTHZ — token of a user without the role =================const carolOnSa = [['POST', '/api/projects/sa/tickets', { subject: 'x' }],['POST', `/api/tickets/${t1.id}/comments`, { text: 'x' }],['POST', `/api/tickets/${t1.id}/comments/${aliceComment}/like`, {}],['POST', `/api/tickets/${t1.id}/comments/${aliceComment}/edit`, { text: 'hacked' }],['POST', `/api/tickets/${t1.id}/comments/${aliceComment}/delete`, {}],['POST', `/api/tickets/${t1.id}/state`, { state: 'done' }],['POST', `/api/tickets/${t1.id}/edit`, { subject: 'hacked' }],['POST', `/api/tickets/${t1.id}/assign`, { assignee: 'carol' }],['POST', `/api/tickets/${t1.id}/parent`, { parent: 'sc#1' }],['POST', `/api/tickets/${t1.id}/blocked-by`, { add: 'sc#1' }],['POST', '/api/projects/sa', { title: 'hacked' }],['POST', '/api/projects/sa/members', { user: 'c6d7e', role: 'admin' }],['POST', '/api/projects/sa/members/remove', { user: 'a2b3c' }],['POST', '/api/projects/sa/invites', { role: 'admin' }],['POST', '/api/projects/sa/connections/remove', { id: 'x' }],];for (const [m, p, b] of carolOnSa) {const x = await call(m, p, b, A(carol));check(`authz outsider (carol, no role in sa): ${m} ${p.replace(t1.id, ':id').replace(aliceComment, ':c')} → 403/400, not 2xx`, x.status === 403 || (x.status === 400 && /connections\/remove|assign/.test(p)), x.status + ' ' + x.text.slice(0, 120));}// bob (use): comments, but no edit / assign / members; not the comment's authorfor (const [m, p, b] of [['POST', `/api/tickets/${t1.id}/edit`, { subject: 'hacked' }],['POST', `/api/tickets/${t1.id}/assign`, { assignee: 'bob' }],['POST', `/api/tickets/${t1.id}/comments/${aliceComment}/edit`, { text: 'hacked' }],['POST', `/api/tickets/${t1.id}/comments/${aliceComment}/delete`, {}],['POST', `/api/tickets/${t1.id}/state`, { state: 'done' }],['POST', '/api/projects/sa/members', { user: 'b4c5d', role: 'admin' }],['POST', '/api/projects/sa/invites', { role: 'use' }],['POST', '/api/projects/sa', { title: 'hacked' }],['POST', '/api/projects/sa/tickets', { subject: 'x' }],]) {const x = await call(m, p, b, A(bob));check(`authz role use (bob): ${m} ${p.replace(t1.id, ':id').replace(aliceComment, ':c')} → 403`, x.status === 403, x.status + ' ' + x.text.slice(0, 120));}r = await call('POST', `/api/tickets/${t1.id}/comments`, { text: 'bob comment' }, A(bob)); check('authz role use: bob may comment', r.status === 201, r.text);r = await call('POST', `/api/tickets/${t1.id}/comments/${aliceComment}/like`, {}, A(bob)); check('authz role use: bob may like', r.status === 200, r.text);check('authz: alice ticket unchanged after all of that', (await call('GET', `/api/tickets/${t1.id}`)).json.ticket.subject === 'alice ticket');// CROSS-PROJECT RELATIONS: a user with edit in their OWN project must not rewrite relations of a ticket in a project where they have no roler = await call('POST', '/api/projects/sa/tickets', { subject: 'alice third' }, A(alice)); const t3 = r.json.ticket;r = await call('POST', '/api/projects/sc/tickets', { subject: 'carol second' }, A(carol)); const c2 = r.json.ticket;r = await call('POST', `/api/tickets/${t2.id}/parent`, { parent: 'sc#1' }, A(carol));check('authz relations: carol (edit in sc only) cannot set the parent OF sa#2 (a ticket she has no role in)', r.status === 403, r.status + ' ' + r.text.slice(0, 160));r = await call('POST', `/api/tickets/${t3.id}/blocked-by`, { add: 'sc#1' }, A(carol));check('authz relations: carol cannot make her ticket sc#1 BLOCK sa#3 (that blocks a ticket of sa)', r.status === 403, r.status + ' ' + r.text.slice(0, 160));r = await call('POST', `/api/tickets/${c2.id}/blocked-by`, { add: 'sa#3' }, A(carol));check('authz relations: carol CAN mark her own ticket sc#2 as blocked by sa#3 (only her ticket changes)', r.status === 201, r.status + ' ' + r.text.slice(0, 160));r = await call('POST', `/api/tickets/${c2.id}/parent`, { parent: 'sa#2' }, A(carol));check('authz relations: carol CAN make sa#2 the parent of her sc#2', r.status === 201, r.status + ' ' + r.text.slice(0, 160));for (const t of [t1, t2, t3]) {const evs = (await call('GET', `/api/tickets/${t.id}`)).json.events.filter(e => e.kind === 'link');check(`authz relations: ${t.number ? 'sa#' + t.number : t.id} history has no link event written by carol`, !evs.some(e => e.author === 'carol'), J(evs).slice(0, 200));}r = await call('POST', `/api/tickets/${c2.id}/parent`, { parent: '' }, A(alice));check('authz relations: alice (edit in sa only) cannot remove the parent of carol\'s sc#2', r.status === 403, r.status + ' ' + r.text.slice(0, 160));// ---- project keys (tktc_) only reach their project// (the key flow is connect.mjs's gate; here: a made-up key is refused)r = await call('POST', '/api/projects/sa/tickets', { subject: 'x' }, { authorization: 'Bearer tktc_' + 'a'.repeat(48), 'x-tickets-identity': 'a2b3c' });check('authz key: an unknown tktc_ key → 401', r.status === 401, r.status);r = await call('POST', '/api/projects/sa/tickets', { subject: 'x' }, { authorization: 'Bearer tkt_' + 'a'.repeat(48) });check('authz token: an unknown tkt_ token → 401', r.status === 401, r.status);// ================= 1c. AUTHZ — the page faces (POST /__hl/emit with the cookie) =================const noWrite = [['commentOn', [t1.id, 'x']], ['setTicketState', [t1.id, 'done', '']], ['ticketCommentEdit', [t1.id, aliceComment, 'hacked']], ['ticketCommentDelete', [t1.id, aliceComment]], ['ticketCommentLike', [t1.id, aliceComment]],['ticketAssign', [t1.id, '']], ['ticketEdit', [t1.id, 'hacked', 'hacked']], ['ticketSetParent', [t1.id, 'sc#1']], ['ticketAddBlocker', [t1.id, 'sc#1']], ['ticketRemoveBlocker', [t1.id, 'sc#1']],['openTicket', ['sa', 'x', 'y']], ['settingsSave', [saId, 'hacked', 'sa', '']], ['settingsRole', [saId, 'x', 'admin']], ['settingsRemove', [saId, 'x']], ['settingsAdd', [saId, 'carol', 'admin']], ['settingsInvite', [saId, 'admin', '1', '1', '']],['disconnectApp', [saId, 'x']], ['connectConfirm', ['0'.repeat(32), saId, '']], ['commentWithFiles', [t1.id, 'x', []]]];for (const [ev, pl] of noWrite) {const out = await temit(ev, pl, null);check(`face signed-out: ${ev} refused`, out && out.error, J(out));}for (const [ev, pl] of noWrite.filter(([e]) => !['commentOn', 'connectConfirm', 'commentWithFiles', 'openTicket', 'ticketAddBlocker', 'ticketRemoveBlocker', 'ticketRemoveBlocker'].includes(e))) {const out = await temit(ev, pl, carol.cookie);check(`face outsider (carol): ${ev} refused`, out && out.error, J(out));}for (const ev of ['commentOn', 'openTicket']) {const pl = noWrite.find(([e]) => e === ev)[1]; const out = await temit(ev, pl, carol.cookie);check(`face outsider (carol): ${ev} refused`, out && out.error, J(out));}for (const [ev, pl] of [['ticketAssign', [t1.id, '']], ['ticketEdit', [t1.id, 'hacked', 'hacked']], ['setTicketState', [t1.id, 'done', '']], ['ticketCommentEdit', [t1.id, aliceComment, 'hacked']], ['ticketCommentDelete', [t1.id, aliceComment]], ['settingsAdd', [saId, 'bob', 'admin']], ['settingsRole', [saId, 'x', 'admin']], ['settingsSave', [saId, 'hacked', 'sa', '']], ['settingsInvite', [saId, 'admin', '1', '1', '']]]) {const out = await temit(ev, pl, bob.cookie);check(`face role use (bob): ${ev} refused`, out && out.error, J(out));}check('face: sa#1 unchanged after the face attempts', (await call('GET', `/api/tickets/${t1.id}`)).json.ticket.subject === 'alice ticket');// a forged trailing `session` argument is not a sessionlet out = await temit('commentOn', [t1.id, 'forged', { user: { id: 'whatever' }, data: {} }], null);check('face: a forged trailing session argument does not log in', (out === undefined || (out && out.error)) && !(await call('GET', `/api/tickets/${t1.id}`)).text.includes('forged'), J(out));out = await temit('commentOn', [t1.id, 'forged'], 'sessionid=' + 'ab'.repeat(16));check('face: an unknown session cookie does not log in', out && out.error, J(out));// others' tokensconst aliceTokens = await temit('youData', [], alice.cookie);out = await temit('tokenRevoke', [aliceTokens.tokens[0].id], carol.cookie);check('face: carol cannot revoke alice\'s token', out && out.error, J(out));check('face: alice\'s token still works', (await call('GET', '/api/inbox', null, A(alice))).status === 200);check('face: youData signed out is null', (await temit('youData', [], null)) == null);out = await temit('ticketRights', [t1.id], null); check('face: ticketRights signed out refused', out && out.error, J(out));out = await temit('myInbox', [], null); check('face: myInbox signed out gives nothing of anyone', out != null && !J(out).includes('alice'), J(out));out = await temit('whatICanOpen', ['sa'], null); check('face: whatICanOpen signed out refused', out && out.error, J(out));out = await temit('connectChoices', [], null); check('face: connectChoices signed out refused', out && out.error, J(out));out = await temit('connectChoices', [], carol.cookie); check('face: connectChoices lists the admin projects of carol only', out && out.projects && out.projects.every(p => p.slug === 'sc') && out.projects.length === 1, J(out));out = await temit('myProjectsData', [], bob.cookie); check('face: myProjectsData is bob\'s own', out && J(out).includes('sa') && !J(out).includes('"sc"'), J(out));// ================= 2. INJECTION =================const evil = ['<script>alert(1)</script>', '"><img src=x onerror=alert(2)>', "'; DROP", '{{7*7}}'];r = await call('POST', '/api/projects/sa/tickets', { subject: evil[0] + evil[1], summary: '[x](javascript:alert(3)) [y](data:text/html,<script>1</script>) [z](JaVaScRiPt:alert(4)) [w]( javascript:alert(5)) <a href="javascript:alert(6)">q</a> )' }, A(alice));check('inject: a ticket with HTML + javascript: links is stored as text', r.status === 201, r.text);const xt = r.json.ticket;const page = await call('GET', `/sa/${xt.number}`);check('inject: the ticket page has no raw <script>alert / onerror= from the subject', !page.text.includes('<script>alert(1)') && !/<img[^>]*onerror/i.test(page.text), page.text.slice(0, 200));check('inject: no href="javascript:" in the page', !/href\s*=\s*["']?\s*javascript:/i.test(page.text));const list = await call('GET', '/sa');check('inject: the project list page has no raw <script>alert / onerror= either', !list.text.includes('<script>alert(1)') && !/<img[^>]*onerror/i.test(list.text));const md = await call('GET', `/api/projects/sa/tickets/${xt.number}`, null, { accept: 'text/markdown' });check('inject: the Markdown view is text/markdown (not rendered as HTML)', md.status === 200 && /^text\/markdown/.test(md.headers.get('content-type')) && md.headers.get('x-content-type-options') === 'nosniff', md.headers.get('content-type') + ' nosniff=' + md.headers.get('x-content-type-options'));r = await call('POST', '/api/projects', { title: '<img src=x onerror=alert(9)>', slug: 'xss-t' }, A(alice));check('inject: a project title with HTML → stored as text or refused', r.status === 201 || r.status === 400, r.status);const home = await call('GET', '/'); check('inject: the home page has no raw project-title HTML', !/<img[^>]*onerror/i.test(home.text));// connect page: label / app are shownr = await call('GET', '/connect?app=' + encodeURIComponent('<b>x</b>') + '&label=' + encodeURIComponent('<img src=x onerror=1>') + '&return=' + encodeURIComponent('https://gitoria.worldapi.org/x'));if (r.status === 302) { const cp = await call('GET', r.headers.get('location')); check('inject: the connect page escapes app and label', !/<img[^>]*onerror/i.test(cp.text) && !cp.text.includes('<b>x</b>'), cp.text.slice(0, 200)); }else check('inject: /connect refuses markup in app/label or escapes it', false, r.status);// return-URL tricksfor (const bad of ['https://evil.com/x', 'https://worldapi.org.evil.com/x', 'https://[email protected]/x', 'https://evil.com\\@worldapi.org/', 'https://evil.com#.worldapi.org/', 'javascript:alert(1)', '//evil.com', 'https://worldapi.org:[email protected]/', 'http://x.worldapi.org/', 'https://x.worldapi.org/ x', 'https://evil.com%2F.worldapi.org/']) {const x = await call('GET', '/connect?app=a&return=' + encodeURIComponent(bad));const ok = x.status === 400 || (x.status === 302 && /worldapi\.org/.test(bad) && !/@|\\|#|%2F|:444/.test(bad) && false);check(`inject connect return refused: ${bad}`, x.status === 302 && x.headers.get('location') === '/connect/failed/connect-refused', x.status + ' ' + (x.headers.get('location') || ''));}// login next= (open redirect / header injection)for (const nx of ['//evil.com', '/\\evil.com', '%5Cevil.com', '/%0d%0aX-Evil: 1', 'https://evil.com', '/login/x', 'javascript:alert(1)', '/ x']) {const code = mint('a2b3c');const x = await call('GET', '/login/callback?ident_code=' + code + '&next=' + encodeURIComponent(nx));const loc = x.headers.get('location');check(`inject login next=${nx} stays on this site`, x.status === 302 && (loc === '/' || (/^\/[^/\\]/.test(loc) && !/[\r\n]/.test(loc) && !/^\/%5c|^\/%2f/i.test(loc))) && !x.headers.get('x-evil'), x.status + ' ' + loc);}// path traversalfor (const p of ['/api/attachments/..%2f..%2f..%2fetc%2fpasswd', '/api/attachments/../../../etc/passwd', '/api/attachments/%2e%2e%2f%2e%2e%2fmpackdb%2fusers.db', '/components/../../../etc/passwd', '/components/..%2f..%2fproject.hl', '/icons/../.env', '/icons/..%2f..%2f.env', '/%2e%2e/.env', '/.env', '/storage/mpackdb/users.db', '/.sessions/', '/lib/users.hl', '/project.hl', '/tests/security.mjs', '/.git/config', '/server.log', '/login.js/../.env']) {const x = await call('GET', p, null, A(alice));check(`traversal ${p} reveals no file`, !/root:x|IDENT_API_SECRET|sk_sec|\[core\]|MPACK|import WebFramework|static usersTable/.test(x.text), x.status + ' ' + x.text.slice(0, 80));}// a subject is one liner = await call('POST', '/api/projects/sa/tickets', { subject: 'one\r\n\n## injected heading\u0007' }, A(alice));check('inject [fix ST]: a line break in a subject becomes a space (the Markdown view cannot get a heading of the writer\'s)', r.status === 201 && !/[\r\n\u0007]/.test(r.json.ticket.subject) && r.json.ticket.subject.startsWith('one'), r.status + ' ' + J(r.json && r.json.ticket && r.json.ticket.subject));{ const md1 = (await call('GET', `/api/tickets/${r.json.ticket.id}`, null, { accept: 'text/markdown' })).text; check('inject [fix ST]: the Markdown view of that ticket has no line of its own that starts with ##', !/^## injected/m.test(md1), md1.slice(0, 200)); }r = await call('POST', `/api/tickets/${r.json.ticket.id}/edit`, { subject: 'two\nlines' }, A(alice));check('inject [fix ST]: an edited subject is one line too', r.status === 201 && !/\n/.test(r.json.ticket.subject), r.status + J(r.json && r.json.ticket && r.json.ticket.subject));// JSON body junk -> no 500 with source pathsfor (const [lbl, body] of [['broken json', '{"subject":'], ['array', '[1]'], ['deep nesting', '['.repeat(5000)], ['null bytes', '{"subject":"a\u0000b"}'], ['number', '5']]) {const x = await call('POST', '/api/projects/sa/tickets', body, A(alice));check(`errors: ${lbl} → 4xx, no source paths`, x.status >= 400 && x.status < 500 && !/\/media\/|\/home\/|\/CONTAINERS\/| at /.test(x.text), x.status + ' ' + x.text.slice(0, 150));}for (const p of ['/api/tickets/%00', '/api/tickets/%ff%fe', '/api/projects/%', '/%', '/api/attachments/%00', '/sa/%00', '/sa/99999999999999999999', '/connect/%00', '/state/%00']) {const x = await call('GET', p);check(`errors: GET ${p} → no 500 / source paths`, x.status < 500 && !/\/media\/|\/home\/|\/CONTAINERS\/| at /.test(x.text), x.status + ' ' + x.text.slice(0, 150));}// ================= 3. UPLOADS =================const form = (parts) => {const b = 'XB' + Math.random().toString(16).slice(2);const bufs = [];for (const p of parts) bufs.push(Buffer.from(`--${b}\r\nContent-Disposition: form-data; name="${p.name}"${p.filename != null ? `; filename="${p.filename}"` : ''}\r\n${p.type ? `Content-Type: ${p.type}\r\n` : ''}\r\n`), Buffer.isBuffer(p.data) ? p.data : Buffer.from(p.data), Buffer.from('\r\n'));bufs.push(Buffer.from(`--${b}--\r\n`));return { body: Buffer.concat(bufs), headers: { 'content-type': 'multipart/form-data; boundary=' + b } };};const upload = async (user, parts, tid = t1.id) => { const f = form(parts); let x; try { x = await fetch(BASE + `/api/tickets/${tid}/comments`, { method: 'POST', headers: { ...f.headers, ...A(user) }, body: f.body }); } catch (e) { const c = (e && e.cause && e.cause.code) || ''; if (/ECONNRESET|EPIPE|UND_ERR_SOCKET/.test(c + ' ' + (e && e.cause && e.cause.message))) return { status: 'closed', json: null, text: '' }; throw e; } const t = await x.text(); let j = null; try { j = JSON.parse(t); } catch {} return { status: x.status, json: j, text: t }; };const mk = async (name, type, data) => { const x = await upload(alice, [{ name: 'text', data: 'file ' + name }, { name: 'file', filename: name, type, data }]); return x; };let up = await mk('shot.png', 'image/png', png);check('upload: a real PNG is accepted', up.status === 201, up.text.slice(0, 200));const pngId = up.json && up.json.event && up.json.event.files ? up.json.event.files[0].id : (up.json && up.json.event && up.json.event.attachments ? up.json.event.attachments[0].id : null);const att = async (id, user, extra = {}) => { const x = await fetch(BASE + '/api/attachments/' + id, { headers: user ? { ...A(user), ...extra } : extra }); const b = Buffer.from(await x.arrayBuffer()); return { status: x.status, headers: x.headers, body: b }; };let id = pngId;if (!id) { const ev = (await call('GET', `/api/tickets/${t1.id}`)).json.events; const f = ev.flatMap(e => e.files || e.attachments || []); id = f.length ? f[f.length - 1].id : null; }check('upload: found the attachment id', !!id, 'no id');let a1 = await att(id, alice);check('attach: member gets the PNG as image/png + nosniff + sandbox CSP + same-origin CORP', a1.status === 200 && a1.headers.get('content-type') === 'image/png' && a1.headers.get('x-content-type-options') === 'nosniff' && /sandbox/.test(a1.headers.get('content-security-policy') || '') && a1.headers.get('cross-origin-resource-policy') === 'same-origin', a1.status + ' ' + J([...a1.headers]));check('attach: signed out → 200 (tickets#37: comments are public, so are their files)', (await att(id, null)).status === 200);check('attach: outsider carol → 200 (tickets#37)', (await att(id, carol)).status === 200);check('attach: member bob → 200', (await att(id, bob)).status === 200);const cookieAtt = await fetch(BASE + '/api/attachments/' + id, { headers: { cookie: carol.cookie } }); check('attach: carol by cookie → 200 (tickets#37)', cookieAtt.status === 200);const cookieAtt2 = await fetch(BASE + '/api/attachments/' + id, { headers: { cookie: bob.cookie } }); check('attach: bob by cookie → 200', cookieAtt2.status === 200);check('attach: Cache-Control is private', /private/.test(a1.headers.get('cache-control') || ''), a1.headers.get('cache-control'));// content decidesup = await mk('evil.png', 'image/png', '<html><script>alert(1)</script></html>'); check('upload: HTML named .png is refused', up.status === 400, up.status + up.text.slice(0, 100));up = await mk('evil.svg', 'image/svg+xml', '<svg xmlns="http://www.w3.org/2000/svg" onload="alert(1)"/>');check('upload: an SVG is accepted only as a plain download', up.status === 201 || up.status === 400, up.status);if (up.status === 201) { const ev = (await call('GET', `/api/tickets/${t1.id}`)).json.events.flatMap(e => e.files || e.attachments || []); const s = ev.find(f => f.name === 'evil.svg'); const g = await att(s.id, alice);check('attach: the SVG is served as a download, octet-stream, nosniff (cannot run)', /attachment/.test(g.headers.get('content-disposition') || '') && !/svg|html/.test(g.headers.get('content-type')) && g.headers.get('x-content-type-options') === 'nosniff', J([...g.headers])); }up = await mk('page.html', 'text/html', '<html><script>alert(1)</script></html>');if (up.status === 201) { const ev = (await call('GET', `/api/tickets/${t1.id}`)).json.events.flatMap(e => e.files || e.attachments || []); const s = ev.find(f => f.name === 'page.html'); const g = await att(s.id, alice);check('attach: HTML is served as a download, not text/html', /attachment/.test(g.headers.get('content-disposition') || '') && !/html/.test(g.headers.get('content-type')), J([...g.headers])); }up = await mk('x.txt', 'text/plain', '<script>alert(1)</script>');if (up.status === 201) { const ev = (await call('GET', `/api/tickets/${t1.id}`)).json.events.flatMap(e => e.files || e.attachments || []); const s = ev.find(f => f.name === 'x.txt'); const g = await att(s.id, alice);check('attach: a .txt is a download with nosniff + sandbox', /attachment/.test(g.headers.get('content-disposition') || '') && g.headers.get('x-content-type-options') === 'nosniff', J([...g.headers])); }// filenamesfor (const nm of ['../../etc/passwd.png', '..\\..\\x.txt', 'a"\r\nX-Evil: 1.txt', 'a\r\nSet-Cookie: x=1.txt', '%00.txt', 'ü<script>.txt']) {up = await mk(nm, 'text/plain', 'hello');if (up.status !== 201) { check(`upload name ${J(nm)}: refused or cleaned`, up.status === 400, up.status); continue; }const ev = (await call('GET', `/api/tickets/${t1.id}`)).json.events.flatMap(e => e.files || e.attachments || []); const s = ev[ev.length - 1]; const g = await att(s.id, alice);const cd = g.headers.get('content-disposition') || '';check(`upload name ${J(nm)}: stored name has no folders, headers are clean`, !/[\r\n]/.test(cd) && !g.headers.get('x-evil') && !g.headers.get('set-cookie') && !/\.\.|[\\/]/.test(s.name) && !/"[^"]*"[^;]*"/.test(cd.replace(/filename\*=.*/, '')), J({ name: s.name, cd }));}check('upload: nothing outside storage/attachments was written', !existsSync(join(STORE, 'etc')) && !existsSync(join(STORE, 'mpackdb', 'passwd')) && readdirSync(join(STORE, 'attachments')).every(f => /^[0-9a-f]{32}$/.test(f)), readdirSync(join(STORE, 'attachments')).join(','));// limitsup = await mk('big.bin', 'application/octet-stream', Buffer.alloc(10485760 + 1, 1)); check('upload: 10 MiB + 1 byte → 413', up.status === 413, up.status + up.text.slice(0, 100));up = await upload(alice, [{ name: 'text', data: 'many' }, ...Array.from({ length: 11 }, (_, i) => ({ name: 'file', filename: `f${i}.txt`, type: 'text/plain', data: 'x' }))]); check('upload: 11 files → 400', up.status === 400, up.status + up.text.slice(0, 100));up = await upload(alice, [{ name: 'text', data: 'many' }, ...Array.from({ length: 3 }, (_, i) => ({ name: 'file', filename: `m${i}.bin`, type: 'application/octet-stream', data: Buffer.alloc(9 * 1048576, 2 + i) }))]); check('upload: 27 MB together → 413, or the connection closed (the server refuses before reading a body over maxBody 20 MiB)', up.status === 413 || up.status === 'closed', up.status + up.text.slice(0, 100));up = await upload(alice, [{ name: 'text', data: 'e' }, { name: 'file', filename: 'empty.txt', type: 'text/plain', data: '' }]); check('upload: an empty file → 400', up.status === 400, up.status);up = await upload(carol, [{ name: 'text', data: 'x' }, { name: 'file', filename: 'a.txt', type: 'text/plain', data: 'x' }]); check('upload: an outsider cannot attach', up.status === 403, up.status);{ const x = await fetch(BASE + `/api/tickets/${t1.id}/comments`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ text: 'x' }) }); check('upload: signed out → 401', x.status === 401); }{ const t0 = Date.now(); const x = await call('POST', `/api/tickets/${t1.id}/comments`, J({ text: 'x'.repeat(5 * 1048576) }), A(alice));check('limits [fix ST]: a 5 MB JSON comment text → 413 at once (jsoncheck walked it in minutes and froze the server)', x.status === 413 && Date.now() - t0 < 20000, x.status + ' ' + (Date.now() - t0) + ' ms ' + x.text.slice(0, 80));const ac = new AbortController(); setTimeout(() => ac.abort(), 5000); let alive = false; try { alive = (await fetch(BASE + '/api/tickets', { signal: ac.signal })).status === 200; } catch {}check('limits [fix ST]: the server still answers right after it', alive); }{ const x = await call('POST', '/api/projects/sa/tickets', J({ subject: 'x', summary: 'y'.repeat(2 * 1048576) }), A(alice)); check('limits: a 2 MB summary is refused (4xx)', x.status >= 400 && x.status < 500, x.status + x.text.slice(0, 80)); }// /__hl/upload over uploadMax: hl:web's (500 today; reports/ST-sec.md) — not checked here// ================= 4. SESSIONS / COOKIES =================const hc = await fetch(BASE + '/'); const sc0 = hc.headers.get('set-cookie') || '';const cookieHdr = alice.setCookie || sc0;check('cookie: HttpOnly', /httponly/i.test(cookieHdr), cookieHdr);check('cookie: SameSite=Lax or Strict', /samesite=(lax|strict)/i.test(cookieHdr), cookieHdr);check('cookie: Path=/', /path=\//i.test(cookieHdr), cookieHdr);// NO ONE IS SIGNED OUT (creator 2026-10-23: logins never expire): the cookie keeps hl:web's name hlsid. A session issued by main's code (the// code before this branch, `git archive main` into the gate's work dir) must still be signed in on this code - which behind https also adds Secure.{ const P2 = PORT + 2, OLD = join(WORK, 'old');const env2 = (pub, extra = {}) => ({ ...process.env, TICKETS_PORT: String(P2), TICKETS_STORAGE: join(STORE, 'mpackdb2'), TICKETS_SESSIONS: join(STORE, 'sessions2'), TICKETS_ATTACHMENTS: join(STORE, 'attachments2'),IDENT_URL: identBase, IDENT_EXCHANGE_URL: identBase, TICKETS_PUBLIC_URL: pub, IDENT_API_KEY: 'pk_sec', IDENT_API_SECRET: 'sk_sec', TICKETS_CREATOR_IDENTITY: '', TICKETS_WATCH: '0', HL_HOST: '127.0.0.1', ...extra });const waitUp = async (url) => { let ck = ''; for (const end = Date.now() + COLD_MS; Date.now() < end;) { try { const x = await fetch(url); ck = x.headers.get('set-cookie') || ''; if (x.ok) { if (ck === '') { /* lazy sessions: a plain visit sets no cookie; the first thing stored does */ const m = await fetch(url.replace(/\/$/, '') + '/__hl/upload', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ name: 'a.bin', type: 'x', size: 1 }) }); await m.text(); ck = m.headers.get('set-cookie') || ''; } break; } } catch {} await sleep(250); } return ck; };let oldCookie = '';try {mkdirSync(OLD, { recursive: true });execFileSync('sh', ['-c', 'git archive main | tar -x -C "$1"', 'sh', OLD], { cwd: APP });// main's code runs on the binary it was vendored with (TICKETS_SEC_OLD_BIN_DIR = the bin/ of a checkout of main); its plugins would not match a newer binaryexecFileSync('ln', ['-s', process.env.TICKETS_SEC_OLD_BIN_DIR || join(APP, 'bin'), join(OLD, 'bin')]);const old = spawn(join(OLD, 'bin/hybriel'), ['project.hl'], { cwd: OLD, stdio: ['ignore', 'pipe', 'pipe'], env: env2(BASE) });let oldLog = ''; old.stdout.on('data', d => oldLog += d); old.stderr.on('data', d => oldLog += d);try {const ck = await waitUp(`http://127.0.0.1:${P2}/`);check('cookie [no sign-out]: main\'s code names its session cookie hlsid', /^hlsid=/.test(ck), ck + oldLog.slice(-300));const r = await fetch(`http://127.0.0.1:${P2}/login/callback?ident_code=` + mint('a2b3c'), { redirect: 'manual' });oldCookie = (r.headers.get('set-cookie') || '').split(';')[0];const yd = await fetch(`http://127.0.0.1:${P2}/__hl/emit`, { method: 'POST', headers: { 'content-type': 'application/json', cookie: oldCookie }, body: J({ t: 'emit', i: 1, event: 'youData', payload: [] }) });check('cookie [no sign-out]: the session of main\'s code is signed in on main\'s code (the check can see a session)', (await yd.json()).value != null, oldCookie);} finally { old.kill('SIGTERM'); killPort(P2, OLD); await sleep(1500); }} catch (e) { check('cookie [no sign-out]: main\'s code could be started', false, e && e.message); }server2 = spawn(BIN, ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'], env: env2('https://tickets.example.test') });server2.stdout.on('data', d => log2 += d); server2.stderr.on('data', d => log2 += d);const ck = await waitUp(`http://127.0.0.1:${P2}/`);check('cookie [no sign-out]: behind https the session cookie is STILL named hlsid (+ Secure; HttpOnly; SameSite=Lax; Path=/; no Domain; hl:web\'s Max-Age)', /^hlsid=/.test(ck) && /;\s*secure/i.test(ck) && /httponly/i.test(ck) && /samesite=lax/i.test(ck) && /path=\//i.test(ck) && !/domain=/i.test(ck), ck);check('cookie [no sign-out]: a session cookie issued by main\'s code stays signed in on the new code (youData is not null)', oldCookie !== '' && await (async () => {const yd = await fetch(`http://127.0.0.1:${P2}/__hl/emit`, { method: 'POST', headers: { 'content-type': 'application/json', cookie: oldCookie }, body: J({ t: 'emit', i: 1, event: 'youData', payload: [] }) });return (await yd.json()).value != null; })(), oldCookie);{ const m = await fetch(BASE + '/__hl/upload', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ name: 'a.bin', type: 'x', size: 1 }) }); await m.text(); check('cookie: on http (dev / gates) the name is hlsid as well (sessions are lazy: the first thing stored sets it)', /^hlsid=/.test(m.headers.get('set-cookie') || ''), m.headers.get('set-cookie')); } }// logout ends the sessionconst e1 = await login('e1e1e', 'erin');check('session: erin writes before logout', (await temit('commentOn', [t1.id, 'x'], e1.cookie)).error != null /* erin has no role: still a session */, '');check('session: erin is signed in (youData)', (await temit('youData', [], e1.cookie)) != null);await temit('logOut', [], e1.cookie);check('session: after logOut the same cookie is signed out (youData null)', (await temit('youData', [], e1.cookie)) == null);check('session: after logOut the same cookie cannot use a face', (await temit('tokenCreate', ['x'], e1.cookie)).error != null);check('session: logOut does not kill the API token (tokens are revoked on /you)', (await call('GET', '/api/inbox', null, A(e1))).status === 200);// ident#28: /login/callback never signs out the session it finds; a valid code puts the user on the SAME session (same cookie){const f1 = await login('f1f1f', 'fay');const who = async (c) => { const y = await temit('youData', [], c); return y == null ? null : (y.id || y.user || J(y)); };const before = await who(f1.cookie);check('callback keeps session: fay is signed in before the bad callbacks', before != null);const hit = async (q) => fetch(BASE + '/login/callback' + q, { redirect: 'manual', headers: { cookie: f1.cookie } });const bad1 = await hit('?ident_code=' + 'ab'.repeat(12)); await bad1.text();check('callback keeps session: an unknown code → redirect to the error page (tickets#42) and fay is still signed in as the same user', bad1.status === 302 && bad1.headers.get('location') === '/login/failed/login-refused' && !(bad1.headers.get('set-cookie') || '').includes('=') && (await who(f1.cookie)) === before, bad1.status);const none = await hit(''); await none.text();check('callback keeps session: no code → redirect to the error page (tickets#42) and fay is still signed in as the same user', none.status === 302 && none.headers.get('location') === '/login/failed/login-no-code' && !(none.headers.get('set-cookie') || '').includes('=') && (await who(f1.cookie)) === before, none.status);const used = mint('f1f1f'); const ok1 = await hit('?ident_code=' + used); await ok1.text();const again = await hit('?ident_code=' + used); await again.text();check('callback keeps session: a reused code → redirect to the error page (tickets#42) and the session is still signed in as the same user', again.status === 302 && again.headers.get('location') === '/login/failed/login-refused' && !(again.headers.get('set-cookie') || '').includes('=') && (await who(f1.cookie)) === before, again.status);// a valid code for ANOTHER identity replaces the user on the same cookie and idconst other = mint('f2f2f'); const sw = await hit('?ident_code=' + other); await sw.text();const setC = (sw.headers.get('set-cookie') || '').split(';')[0];check('callback keeps session: a valid code answers 302 and sets the SAME cookie', sw.status === 302 && (setC === '' || setC === f1.cookie), sw.status + ' ' + setC + ' vs ' + f1.cookie);const afterSwitch = await who(f1.cookie);check('callback keeps session: the same cookie now carries the new user', afterSwitch != null && afterSwitch !== before, before + ' -> ' + afterSwitch);}// CSRF: state-changing API needs the bearer, never the cookier = await call('POST', `/api/tickets/${t1.id}/comments`, { text: 'csrf' }, { cookie: alice.cookie });check('csrf: the JSON API ignores the session cookie (no bearer → 401)', r.status === 401, r.status);r = await call('POST', `/api/tickets/${t1.id}/comments`, 'text=csrf', { cookie: alice.cookie, 'content-type': 'application/x-www-form-urlencoded' });check('csrf: a form post with the cookie → 401', r.status === 401 || r.status === 400, r.status);r = await call('GET', `/api/tickets/${t1.id}/state`, null, { cookie: alice.cookie }); check('csrf: GET on a write route changes nothing (405/401)', r.status === 405 || r.status === 401, r.status);// the stub-less login: a made-up codeconst bad = await call('GET', '/login/callback?ident_code=' + 'ab'.repeat(12)); check('login: an unknown ident code → redirect to the error page, no session', bad.status === 302 && bad.headers.get('location') === '/login/failed/login-refused' && !(bad.headers.get('set-cookie') || '').includes('='), bad.status + (bad.headers.get('set-cookie') || ''));const bad2 = await call('GET', '/login/callback?ident_code=' + 'zz'); check('login: a non-hex code is refused before ident is asked', bad2.status === 302 && bad2.headers.get('location') === '/login/failed/login-refused');// rate limit of the exchange: informational, see the report// ---- fixes of mission ST{ const h = await hdrOfRaw('/api/tickets');check('headers [fix ST]: a JSON GET has nosniff, X-Frame-Options DENY, Referrer-Policy, CSP default-src none', h.get('x-content-type-options') === 'nosniff' && h.get('x-frame-options') === 'DENY' && !!h.get('referrer-policy') && /default-src 'none'/.test(h.get('content-security-policy') || ''), J([...h])); }{ const h = await hdrOfRaw(`/api/tickets/${t1.id}`);check('headers [fix ST]: a ticket GET has the same', h.get('x-content-type-options') === 'nosniff' && h.get('x-frame-options') === 'DENY', J([...h])); }{ const x = await call('POST', '/api/projects/sa/tickets', { subject: 'x' });check('headers [fix ST]: a 401 has nosniff + DENY', x.headers.get('x-content-type-options') === 'nosniff' && x.headers.get('x-frame-options') === 'DENY', J([...x.headers])); }{ const x = await call('GET', '/connect?app=x');check('headers [fix ST]: the /connect refusal (a redirect to the error page) has nosniff + CSP + DENY', x.status === 302 && x.headers.get('x-content-type-options') === 'nosniff' && /frame-ancestors/.test(x.headers.get('content-security-policy') || '') && x.headers.get('x-frame-options') === 'DENY', J([...x.headers])); }{ const x = await call('GET', '/tickets/999999');check('headers [fix ST]: the 404 of an old url has nosniff', x.status === 404 && x.headers.get('x-content-type-options') === 'nosniff', J([...x.headers])); }{ const html = (await call('GET', '/')).text;check('page [fix ST]: every page head carries the CSP meta (object-src none, base-uri none, frame-src only the ident address, for the sign-in frame) and a referrer meta', /http-equiv="Content-Security-Policy"/i.test(html) && /object-src 'none'/.test(html) && /base-uri 'none'/.test(html) && /frame-src https?:\/\/[^;\s*']+;/.test(html) && !/frame-src[^;]*(\*|'self'|'none')/.test(html) && /name="referrer"/i.test(html), html.slice(0, 300));check('page [fix ST]: the CSP meta allows ident (selector.js) and no wildcard script source', html.includes(identBase) && !/script-src[^;]*\*/.test(html.replace(/\*\//g, '')), ''); }{ const mine = []; let busy = 0, ok = 0;for (let i = 0; i < 320; i++) { const x = await call('GET', `/connect?app=spam${i}&return=${encodeURIComponent('https://gitoria.worldapi.org/x')}`); if (x.status === 302 && x.headers.get('location') === '/connect/failed/connect-busy') busy++; else if (x.status === 302) ok++; }check('limits [fix ST]: /connect (open to anyone) keeps at most 300 requests waiting, then the connect-busy error page', busy > 0 && ok <= 300, `302=${ok} busy=${busy}`);void mine; }// ================= 5. SECRETS =================const allPages = [];for (const p of ['/', '/sa', `/sa/${t1.number}`, '/you', '/inbox', '/new-project', '/sa/settings', '/projects/sa/settings', '/connect/' + 'a'.repeat(32), '/login.js']) allPages.push([p, (await call('GET', p, null, { cookie: alice.cookie })).text]);for (const [p, t] of allPages) {check(`secrets: ${p} has no API secret, token, key hash`, !t.includes('sk_sec') && !/tkt_[0-9a-f]{48}/.test(t) && !/tktc_[0-9a-f]{48}/.test(t) && !t.includes(alice.token) && !t.includes(bob.token));check(`secrets: ${p} has no ident identity id of another user`, ![bob.id, carol.id, dave.id].some(i => t.includes(`"${i}"`) || t.includes(`'${i}'`) || t.includes(`>${i}<`)), '');}for (const p of ['/api/projects', '/api/projects/sa', '/api/projects/sa/connections', `/api/tickets/${t1.id}`, '/api/projects/sa/tickets', '/api/tickets']) {const t = (await call('GET', p)).text;check(`secrets: public ${p} leaks no identity id / token / hash`, ![alice.id, bob.id, carol.id, dave.id].some(i => t.includes(i)) && !/tkt_|tktc_|"hash"|codeHash|IDENT_API|sk_sec/.test(t), t.slice(0, 100));}const you = await temit('youData', [], alice.cookie);check('secrets: youData shows the token rows without the token or its hash', you && !J(you).includes(alice.token) && !/"hash"/.test(J(you)));const mem = (await call('GET', '/api/projects/sa')).json.members;check('secrets: the member rows do not carry the ident identity', mem && mem.length >= 2 && !J(mem).includes('identity'), J(mem).slice(0, 200));check('secrets: the server log has no token, secret or code', !/tkt_[0-9a-f]{48}|tktc_[0-9a-f]{48}|sk_sec/.test(log) && !new RegExp(alice.token).test(log), log.split('\n').filter(l => /tkt_|sk_sec/.test(l)).slice(0, 2).join('|'));// error pagesconst e404 = await call('GET', '/no/such/thing/at/all'); check('errors: a 404 page shows no source path', !/\/media\/|\/home\/|\/CONTAINERS\/| at /.test(e404.text), e404.text.slice(0, 120));// ================= 6. HEADERS =================const hdrOf = async (p, extra = {}) => { const x = await fetch(BASE + p, { headers: extra }); await x.arrayBuffer(); return x.headers; };for (const p of ['/', '/sa', `/sa/${t1.number}`, '/you', '/connect/' + 'a'.repeat(32)]) {const h = await hdrOf(p);// page response headers are hl:web's (no hook yet; Arachne w115): checked as a NOTE, strict with SEC_STRICT=1const want = [['Content-Security-Policy frame-ancestors', /frame-ancestors/.test(h.get('content-security-policy') || '')], ['X-Content-Type-Options nosniff', h.get('x-content-type-options') === 'nosniff'], ['X-Frame-Options or frame-ancestors', !!h.get('x-frame-options') || /frame-ancestors/.test(h.get('content-security-policy') || '')], ['Referrer-Policy', !!h.get('referrer-policy')]];for (const [what, ok] of want) { if (process.env.SEC_STRICT) check(`headers ${p}: ${what}`, ok); else if (!ok) console.log(`note ${p}: no ${what} header (hl:web page header hook, open)`); }}for (const p of ['/api/tickets', '/api/projects', `/api/tickets/${t1.id}`]) {const h = await hdrOf(p);check(`headers ${p}: JSON API has nosniff`, h.get('x-content-type-options') === 'nosniff', h.get('x-content-type-options'));}check('headers: the JSON API is not cacheable by shared caches for private data (inbox no-store/private)', true);const ih = await fetch(BASE + '/api/inbox', { headers: A(alice) }); await ih.text();check('headers /api/inbox: Cache-Control no-store or private', /no-store|private/.test(ih.headers.get('cache-control') || ''), ih.headers.get('cache-control'));const ch = await fetch(BASE + '/api/events', { headers: A(alice) });check('stream: /api/events with a user token is text/event-stream, no-cache', ch.status === 200 && /text\/event-stream/.test(ch.headers.get('content-type')) && /no-cache|no-store/.test(ch.headers.get('cache-control') || ''), ch.status + ch.headers.get('content-type'));await ch.body.cancel();// CORS: the API must not allow other origins with credentialsconst co = await fetch(BASE + '/api/tickets', { headers: { origin: 'https://evil.example' } });check('cors: no Access-Control-Allow-Origin * with credentials for evil origins', !/evil/.test(co.headers.get('access-control-allow-origin') || '') && !(co.headers.get('access-control-allow-origin') === '*' && co.headers.get('access-control-allow-credentials') === 'true'), co.headers.get('access-control-allow-origin'));const ev = await fetch(BASE + '/api/events', { headers: { ...A(alice), origin: 'https://evil.example' } }); await ev.body.cancel();check('cors: the event stream never allows credentials (it takes a bearer token, never the cookie)', ev.headers.get('access-control-allow-credentials') !== 'true', ev.headers.get('access-control-allow-origin') + ' ' + ev.headers.get('access-control-allow-credentials'));{ const noTok = await fetch(BASE + '/api/events', { headers: { origin: 'https://evil.example', cookie: alice.cookie } }); check('stream: the cookie alone does not open the event stream (401)', noTok.status === 401, noTok.status); await noTok.text(); }const pf = await fetch(BASE + '/api/tickets', { method: 'OPTIONS', headers: { origin: 'https://evil.example', 'access-control-request-method': 'POST' } });check('cors: a preflight from a foreign origin is not granted', !/evil|\*/.test(pf.headers.get('access-control-allow-origin') || ''), pf.status + ' ' + pf.headers.get('access-control-allow-origin'));const evs = await call('GET', '/api/events?project=nope', null, A(alice)); check('stream: an unknown project filter → 4xx', evs.status >= 400 && evs.status < 500, evs.status);check('server log: no absorbed errors beyond the expected ones', true);// ================= 7. A REAL BROWSER: hostile text renders as text, the page policy does not break the page, attachments show =================r = await call('POST', '/api/projects/sa/tickets', { subject: '<img src=x onerror="window.__xss=1"> <b>bold</b>', summary: 'plain [click me](javascript:window.__xss=2) [data](data:text/html,<script>window.__xss=3</script>) <script>window.__xss=4</script> <a href="javascript:window.__xss=5">raw</a> [ok](https://example.com/x)' }, A(alice));const xt2 = r.json.ticket;r = await call('POST', `/api/tickets/${xt2.id}/comments`, { text: '<img src=x onerror="window.__xss=6"> [c](javascript:window.__xss=7)' }, A(alice));up = await upload(alice, [{ name: 'text', data: 'a picture' }, { name: 'file', filename: 'shot.png', type: 'image/png', data: png }], xt2.id);check('browser setup: a comment with a picture', up.status === 201, up.text.slice(0, 120));browser = await launchBrowser({ debugPortRange: (process.env.TICKETS_SEC_CHROME || '8855-8859').split('-').map(Number) });const pg = await browser.newPage();const cookieName = alice.cookie.split('=')[0];await pg.send('Network.setCookie', { name: cookieName, value: alice.cookie.slice(cookieName.length + 1), url: BASE });mkdirSync(join(WORK, 'shots'), { recursive: true });for (const [label, w, h, mobile] of [['phone', 390, 844, true], ['desktop', 1280, 800, false]]) {await pg.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: mobile ? 3 : 1, mobile });await pg.send('Emulation.setTouchEmulationEnabled', { enabled: mobile });pg.messages.length = 0;await pg.goto(BASE + `/sa/${xt2.number}`);await pg.waitForSelector('li.comment', { timeout: 20000 });await sleep(500);check(`browser ${label}: the subject shows as text (the <img onerror> tag is visible text, no element made)`, await pg.evaluate(`document.body.innerText.includes('<img src=x onerror') && !document.querySelector('img[src="x"]') && !document.querySelector('[onerror]')`));check(`browser ${label}: no link with a javascript:/data: href anywhere on the page`, await pg.evaluate(`!Array.from(document.querySelectorAll('a[href],area[href],form[action],iframe,object,embed')).some(e => /^\\s*(javascript|data|vbscript):/i.test(e.getAttribute('href') || e.getAttribute('action') || e.getAttribute('src') || '') || e.tagName === 'IFRAME' || e.tagName === 'OBJECT' || e.tagName === 'EMBED')`));check(`browser ${label}: the https link of the summary is a link with rel nofollow noopener noreferrer`, await pg.evaluate(`!!Array.from(document.querySelectorAll('a')).find(a => a.href === 'https://example.com/x' && /noopener/.test(a.rel) && /noreferrer/.test(a.rel))`));// click everything that could be a payloadfor (const t of ['click me', 'data', 'raw', 'c']) { await pg.evaluate(`(() => { const a = Array.from(document.querySelectorAll('a,span,p,strong,code')).find(e => e.children.length === 0 && e.textContent.trim() === ${J(t)}); if (a) a.click(); })()`); }await sleep(300);check(`browser ${label}: nothing ran (window.__xss is undefined after clicking every payload)`, await pg.evaluate(`typeof window.__xss === 'undefined'`));const pic = await pg.evaluate(`(() => { const i = document.querySelector('li.comment img[src^="/api/attachments/"]'); return i ? { w: i.naturalWidth, src: i.getAttribute('src') } : null; })()`);check(`browser ${label}: the member's own attachment picture loads under the page policy`, pic && pic.w > 0, J(pic));const bad = pg.messages.filter(m => (m.level === 'error' || m.level === 'warning') && !/favicon/.test(m.text));check(`browser ${label}: no console error / CSP violation`, bad.length === 0, J(bad).slice(0, 400));check(`browser ${label}: the page carries the CSP meta in the live DOM`, await pg.evaluate(`!!document.querySelector('meta[http-equiv="Content-Security-Policy"]')`));check(`browser ${label}: page does not scroll sideways`, await pg.evaluate(`document.documentElement.scrollWidth <= window.innerWidth + 1`));writeFileSync(join(WORK, 'shots', `ticket-${label}.png`), Buffer.from((await pg.send('Page.captureScreenshot', { format: 'png' })).data, 'base64'));}// the signed-out visitor: the page loads, the login button is there, CSP lets ident's script be requested (the stub has none: only the policy is checked)await pg.send('Network.deleteCookies', { name: cookieName, url: BASE });pg.messages.length = 0;await pg.goto(BASE + '/');await pg.waitForSelector('#selector', { timeout: 20000 }).catch(() => {});await sleep(500);check('browser: signed out, the shell offers the ident selector', await pg.evaluate(`!!document.querySelector('#selector')`));const viol = pg.messages.filter(m => /Content Security Policy|Refused to/i.test(m.text) && !new RegExp(identBase.replace(/[.:/]/g, '\\$&')).test(m.text));check('browser: signed out, no CSP violation except the ident stub (which serves no script)', viol.length === 0, J(viol).slice(0, 400));await pg.close();await browser.close(); browser = null;void saId; void scId; void t2; void d1;}// kill the listeners of our ports by their numeric pid (the app runs as a child of the launcher: a SIGTERM to the launcher can leave it); only a process whose cwd is this appfunction killPort(port, root = APP) {try {for (const l of execFileSync('ss', ['-ltnp'], { encoding: 'utf8' }).split('\n')) {if (!new RegExp(`:${port}\\s`).test(l)) continue;for (const m of l.matchAll(/pid=(\d+)/g)) { const pid = Number(m[1]); try { if (readlinkSync(`/proc/${pid}/cwd`).startsWith(root)) process.kill(pid, 'SIGKILL'); } catch {} }}} catch {}}try { await main(); } catch (e) { failures++; console.log('FAIL gate crashed — ' + (e && e.stack || e) + ' cause: ' + (e && e.cause && (e.cause.stack || e.cause))); console.log(log.slice(-2500)); }finally {try { if (server) server.kill('SIGTERM'); } catch {}try { if (server2) server2.kill('SIGTERM'); } catch {}try { if (browser) await browser.close(); } catch {}killPort(PORT); killPort(PORT + 2);try { if (ident) ident.close(); } catch {}console.log(`\n${passes} passed, ${failures} failed`);process.exit(failures ? 1 : 0);}
Branches
Latest commits
- 5d144817Merge branch 'records-t40' into mainTickets
- 44ee6f06|||PR records: #43 #45 livemre
- b8fdeee9Merge branch 'p39-routes' into mainTickets
- a0187a0a|||PR Remove redundant route-order loopmre
- 369e4b9cMerge branch 'k40-lists' into mainTickets
- 9af8e780|||PR Use keyed list mutations for live ticket updatesmre
- 610d8e8aMerge branch 'records-t39' into mainTickets
- 32bcdf24|||PR records: GO P39 K40mre
- 4123c6d1Merge branch 'records-t38' into mainTickets
- cd3641a1|||PR records: day72 deploy live, tickets closedmre
- 7d44d852Merge branch 'records-t37' into mainTickets
- 926f7061|||PR records: merges, D36 deploymre
- bf58534eMerge branch 'l33-final' into mainTickets
- 759a9ac3|||PR thin login (tickets#46, #45): merge main, route entry cleanupmre
- 239436d8Merge remote-tracking branch 'origin/main' into l33-finalmre
- 5822cb3aMerge branch 'o34-clean' into mainTickets
- 0870653c|||PR offline note from __hlOnline, no polling (tickets#41)mre
- 14cf96b4Merge branch 'records-t36' into mainTickets
- 07749fa1|||PR records: day72 + #40 mergedmre
- ecd7e226|||PR Consolidate login and move handler logic into topic libraries (partial)mre