gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitea2e440eea2e440esecurity audit (ST): JSON body cap, relation rights, login session rotation, __Host- Secure cookie, API security headers, CSP+referrer meta, /connect cap, one-line subjects, tests/security.mjs, reportmreea2e440e/tests/security.mjs

51.9 KB

  1. // tests/security.mjs — THE SECURITY GATE (mission ST): authorisation of every route / face, injection, uploads, sessions, headers, secrets.
  2. // 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
  3. // 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.
  4. // Ports: TICKETS_SEC_PORT (8840), TICKETS_SEC_IDENT_PORT (8841). TICKETS_COLD_MS: cold start wait (120 s). Store: .scratch/security-gate.
  5. // node tests/security.mjs
  6. import { spawn, execFileSync } from 'node:child_process';
  7. import http from 'node:http';
  8. import { rmSync, mkdirSync, existsSync, readdirSync, readFileSync, readlinkSync } from 'node:fs';
  9. import { dirname, join, resolve } from 'node:path';
  10. import { writeFileSync } from 'node:fs';
  11. import { launchBrowser } from './cdp.mjs';
  12. import { fileURLToPath } from 'node:url';
  13. const APP = resolve(dirname(fileURLToPath(import.meta.url)), '..');
  14. const BIN = join(APP, 'bin/hybriel');
  15. const PORT = Number(process.env.TICKETS_SEC_PORT || 8840);
  16. const IDENT_PORT = Number(process.env.TICKETS_SEC_IDENT_PORT || 8841);
  17. const BASE = `http://127.0.0.1:${PORT}`;
  18. const WORK = join(APP, '.scratch/security-gate');
  19. const STORE = join(WORK, 'store');
  20. const COLD_MS = Number(process.env.TICKETS_COLD_MS || 120000);
  21. const J = JSON.stringify;
  22. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  23. rmSync(WORK, { recursive: true, force: true });
  24. mkdirSync(join(STORE, 'mpackdb'), { recursive: true }); mkdirSync(join(STORE, 'mpackdb2'), { recursive: true });
  25. let passes = 0, failures = 0;
  26. const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + String(detail).slice(0, 400)}`); if (ok) passes++; else failures++; };
  27. let log = '', log2 = '', server = null, server2 = null, ident = null, browser = null;
  28. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  29. const png = Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), Buffer.from('0000000d49484452000000010000000108060000001f15c4890000000d49444154789c6360000002000001e221bc330000000049454e44ae426082', 'hex')]);
  30. async function main() {
  31. const codes = new Map(); let codeN = 0;
  32. const mint = (identity) => { const c = (++codeN).toString(16).padStart(8, '0').repeat(3); codes.set(c, identity); return c; };
  33. ident = http.createServer((req, res) => {
  34. let body = ''; req.on('data', d => body += d);
  35. req.on('end', () => {
  36. if (req.url === '/api/exchange' && req.method === 'POST') {
  37. const b = JSON.parse(body || '{}'); const id = codes.get(b.code); codes.delete(b.code);
  38. res.writeHead(id && b.secret === 'sk_sec' ? 200 : 400, { 'content-type': 'application/json' });
  39. return res.end(J(id ? { identity: id } : { error: 'unknown code' }));
  40. }
  41. res.writeHead(404); res.end('');
  42. });
  43. });
  44. await new Promise(ok => ident.listen(IDENT_PORT, '127.0.0.1', ok));
  45. const identBase = `http://127.0.0.1:${IDENT_PORT}`;
  46. 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'),
  47. 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' } });
  48. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  49. for (const end = Date.now() + COLD_MS; Date.now() < end;) { try { if ((await fetch(BASE + '/')).ok) break; } catch {} await sleep(250); }
  50. let emitI = 0;
  51. const temit = async (event, payload, cookie) => {
  52. const r = await fetch(BASE + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) }, body: J({ t: 'emit', i: ++emitI, event, payload }) });
  53. const raw = await r.text(); let j = null; try { j = JSON.parse(raw); } catch {}
  54. return j ? j.value : undefined;
  55. };
  56. const call = async (method, path, body, headers = {}) => {
  57. 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' });
  58. const t = await r.text(); let json = null; try { json = JSON.parse(t); } catch {}
  59. 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); } }
  60. return { status: r.status, json, text: t, headers: r.headers };
  61. };
  62. const login = async (id, name) => {
  63. const code = mint(id);
  64. const r = await fetch(BASE + '/login/callback?ident_code=' + code, { redirect: 'manual' });
  65. const cookie = (r.headers.get('set-cookie') || '').split(';')[0];
  66. if (name) await temit('saveDisplayName', [name], cookie);
  67. const u = { id, cookie, setCookie: r.headers.get('set-cookie') || '' };
  68. u.token = (await temit('tokenCreate', ['gate'], cookie)).token;
  69. u.auth = { authorization: 'Bearer ' + u.token };
  70. return u;
  71. };
  72. const alice = await login('a2b3c', 'alice'), bob = await login('b4c5d', 'bob'), carol = await login('c6d7e', 'carol'), dave = await login('d8e9f', 'dave');
  73. const hdrOfRaw = async (p, extra = {}) => { const x = await fetch(BASE + p, { headers: extra }); await x.arrayBuffer(); return x.headers; };
  74. const A = (u, extra = {}) => ({ ...u.auth, ...extra });
  75. // ---- setup
  76. let r = await call('POST', '/api/projects', { title: 'Sec A', slug: 'sa' }, A(alice)); check('setup: alice opens sa', r.status === 201, r.text);
  77. const saId = r.json.project.id;
  78. 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);
  79. r = await call('POST', '/api/projects', { title: 'Sec C', slug: 'sc' }, A(carol)); check('setup: carol opens sc', r.status === 201, r.text);
  80. const scId = r.json.project.id;
  81. r = await call('POST', '/api/projects', { title: 'Sec D', slug: 'sd' }, A(dave)); check('setup: dave opens sd', r.status === 201, r.text);
  82. 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);
  83. const t1 = r.json.ticket;
  84. r = await call('POST', '/api/projects/sa/tickets', { subject: 'alice second' }, A(alice)); const t2 = r.json.ticket;
  85. r = await call('POST', '/api/projects/sc/tickets', { subject: 'carol ticket' }, A(carol)); const c1 = r.json.ticket;
  86. r = await call('POST', '/api/projects/sd/tickets', { subject: 'dave ticket' }, A(dave)); const d1 = r.json.ticket;
  87. r = await call('POST', '/api/tickets/' + t1.id + '/comments', { text: 'alice comment' }, A(alice)); check('setup: alice comments', r.status === 201, r.text);
  88. const aliceComment = r.json.event.id;
  89. // ================= 1. AUTHZ — signed out: every write is 401 =================
  90. const writes = [
  91. ['POST', '/api/tickets', { project: 'sa', subject: 'x' }],
  92. ['POST', '/api/projects/sa/tickets', { subject: 'x' }],
  93. ['POST', `/api/tickets/${t1.id}/comments`, { text: 'x' }],
  94. ['POST', `/api/tickets/${t1.id}/comments/${aliceComment}/edit`, { text: 'x' }],
  95. ['POST', `/api/tickets/${t1.id}/comments/${aliceComment}/delete`, {}],
  96. ['POST', `/api/tickets/${t1.id}/comments/${aliceComment}/like`, {}],
  97. ['POST', `/api/tickets/${t1.id}/state`, { state: 'done' }],
  98. ['POST', `/api/tickets/${t1.id}/edit`, { subject: 'x' }],
  99. ['POST', `/api/tickets/${t1.id}/assign`, { assignee: '' }],
  100. ['POST', `/api/tickets/${t1.id}/parent`, { parent: '' }],
  101. ['POST', `/api/tickets/${t1.id}/blocked-by`, { add: 'sa#2' }],
  102. ['POST', '/api/projects', { title: 'zz' }],
  103. ['POST', '/api/projects/sa', { title: 'zz' }],
  104. ['POST', '/api/projects/sa/members', { user: 'a2b3c', role: 'admin' }],
  105. ['POST', '/api/projects/sa/members/remove', { user: 'b4c5d' }],
  106. ['POST', '/api/projects/sa/invites', { role: 'use' }],
  107. ['POST', '/api/projects/sa/connections/remove', { id: 'x' }],
  108. ['GET', '/api/inbox'],
  109. ['GET', '/api/events'],
  110. ['GET', '/api/attachments/anything'],
  111. ];
  112. for (const [m, p, b] of writes) {
  113. const x = await call(m, p, b);
  114. 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));
  115. }
  116. for (const p of ['/api/tickets', '/api/projects', '/api/projects/sa', '/api/projects/sa/tickets', `/api/tickets/${t1.id}`, '/api/projects/sa/connections', '/']) {
  117. 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);
  118. }
  119. // ================= 1b. AUTHZ — token of a user without the role =================
  120. const carolOnSa = [
  121. ['POST', '/api/projects/sa/tickets', { subject: 'x' }],
  122. ['POST', `/api/tickets/${t1.id}/comments`, { text: 'x' }],
  123. ['POST', `/api/tickets/${t1.id}/comments/${aliceComment}/like`, {}],
  124. ['POST', `/api/tickets/${t1.id}/comments/${aliceComment}/edit`, { text: 'hacked' }],
  125. ['POST', `/api/tickets/${t1.id}/comments/${aliceComment}/delete`, {}],
  126. ['POST', `/api/tickets/${t1.id}/state`, { state: 'done' }],
  127. ['POST', `/api/tickets/${t1.id}/edit`, { subject: 'hacked' }],
  128. ['POST', `/api/tickets/${t1.id}/assign`, { assignee: 'carol' }],
  129. ['POST', `/api/tickets/${t1.id}/parent`, { parent: 'sc#1' }],
  130. ['POST', `/api/tickets/${t1.id}/blocked-by`, { add: 'sc#1' }],
  131. ['POST', '/api/projects/sa', { title: 'hacked' }],
  132. ['POST', '/api/projects/sa/members', { user: 'c6d7e', role: 'admin' }],
  133. ['POST', '/api/projects/sa/members/remove', { user: 'a2b3c' }],
  134. ['POST', '/api/projects/sa/invites', { role: 'admin' }],
  135. ['POST', '/api/projects/sa/connections/remove', { id: 'x' }],
  136. ];
  137. for (const [m, p, b] of carolOnSa) {
  138. const x = await call(m, p, b, A(carol));
  139. 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));
  140. }
  141. // bob (use): comments, but no edit / assign / members; not the comment's author
  142. for (const [m, p, b] of [
  143. ['POST', `/api/tickets/${t1.id}/edit`, { subject: 'hacked' }],
  144. ['POST', `/api/tickets/${t1.id}/assign`, { assignee: 'bob' }],
  145. ['POST', `/api/tickets/${t1.id}/comments/${aliceComment}/edit`, { text: 'hacked' }],
  146. ['POST', `/api/tickets/${t1.id}/comments/${aliceComment}/delete`, {}],
  147. ['POST', `/api/tickets/${t1.id}/state`, { state: 'done' }],
  148. ['POST', '/api/projects/sa/members', { user: 'b4c5d', role: 'admin' }],
  149. ['POST', '/api/projects/sa/invites', { role: 'use' }],
  150. ['POST', '/api/projects/sa', { title: 'hacked' }],
  151. ['POST', '/api/projects/sa/tickets', { subject: 'x' }],
  152. ]) {
  153. const x = await call(m, p, b, A(bob));
  154. 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));
  155. }
  156. 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);
  157. 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);
  158. check('authz: alice ticket unchanged after all of that', (await call('GET', `/api/tickets/${t1.id}`)).json.ticket.subject === 'alice ticket');
  159. // 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 role
  160. r = await call('POST', '/api/projects/sa/tickets', { subject: 'alice third' }, A(alice)); const t3 = r.json.ticket;
  161. r = await call('POST', '/api/projects/sc/tickets', { subject: 'carol second' }, A(carol)); const c2 = r.json.ticket;
  162. r = await call('POST', `/api/tickets/${t2.id}/parent`, { parent: 'sc#1' }, A(carol));
  163. 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));
  164. r = await call('POST', `/api/tickets/${t3.id}/blocked-by`, { add: 'sc#1' }, A(carol));
  165. 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));
  166. r = await call('POST', `/api/tickets/${c2.id}/blocked-by`, { add: 'sa#3' }, A(carol));
  167. 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));
  168. r = await call('POST', `/api/tickets/${c2.id}/parent`, { parent: 'sa#2' }, A(carol));
  169. check('authz relations: carol CAN make sa#2 the parent of her sc#2', r.status === 201, r.status + ' ' + r.text.slice(0, 160));
  170. for (const t of [t1, t2, t3]) {
  171. const evs = (await call('GET', `/api/tickets/${t.id}`)).json.events.filter(e => e.kind === 'link');
  172. 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));
  173. }
  174. r = await call('POST', `/api/tickets/${c2.id}/parent`, { parent: '' }, A(alice));
  175. 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));
  176. // ---- project keys (tktc_) only reach their project
  177. // (the key flow is connect.mjs's gate; here: a made-up key is refused)
  178. r = await call('POST', '/api/projects/sa/tickets', { subject: 'x' }, { authorization: 'Bearer tktc_' + 'a'.repeat(48), 'x-tickets-identity': 'a2b3c' });
  179. check('authz key: an unknown tktc_ key → 401', r.status === 401, r.status);
  180. r = await call('POST', '/api/projects/sa/tickets', { subject: 'x' }, { authorization: 'Bearer tkt_' + 'a'.repeat(48) });
  181. check('authz token: an unknown tkt_ token → 401', r.status === 401, r.status);
  182. // ================= 1c. AUTHZ — the page faces (POST /__hl/emit with the cookie) =================
  183. const noWrite = [['commentOn', [t1.id, 'x']], ['setTicketState', [t1.id, 'done', '']], ['ticketCommentEdit', [t1.id, aliceComment, 'hacked']], ['ticketCommentDelete', [t1.id, aliceComment]], ['ticketCommentLike', [t1.id, aliceComment]],
  184. ['ticketAssign', [t1.id, '']], ['ticketEdit', [t1.id, 'hacked', 'hacked']], ['ticketSetParent', [t1.id, 'sc#1']], ['ticketAddBlocker', [t1.id, 'sc#1']], ['ticketRemoveBlocker', [t1.id, 'sc#1']],
  185. ['openTicket', ['sa', 'x', 'y']], ['settingsSave', [saId, 'hacked', 'sa', '']], ['settingsRole', [saId, 'x', 'admin']], ['settingsRemove', [saId, 'x']], ['settingsAdd', [saId, 'carol', 'admin']], ['settingsInvite', [saId, 'admin', '1', '1', '']],
  186. ['disconnectApp', [saId, 'x']], ['connectConfirm', ['0'.repeat(32), saId, '']], ['commentWithFiles', [t1.id, 'x', []]]];
  187. for (const [ev, pl] of noWrite) {
  188. const out = await temit(ev, pl, null);
  189. check(`face signed-out: ${ev} refused`, out && out.error, J(out));
  190. }
  191. for (const [ev, pl] of noWrite.filter(([e]) => !['commentOn', 'connectConfirm', 'commentWithFiles', 'openTicket', 'ticketAddBlocker', 'ticketRemoveBlocker', 'ticketRemoveBlocker'].includes(e))) {
  192. const out = await temit(ev, pl, carol.cookie);
  193. check(`face outsider (carol): ${ev} refused`, out && out.error, J(out));
  194. }
  195. for (const ev of ['commentOn', 'openTicket']) {
  196. const pl = noWrite.find(([e]) => e === ev)[1]; const out = await temit(ev, pl, carol.cookie);
  197. check(`face outsider (carol): ${ev} refused`, out && out.error, J(out));
  198. }
  199. 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', '']]]) {
  200. const out = await temit(ev, pl, bob.cookie);
  201. check(`face role use (bob): ${ev} refused`, out && out.error, J(out));
  202. }
  203. check('face: sa#1 unchanged after the face attempts', (await call('GET', `/api/tickets/${t1.id}`)).json.ticket.subject === 'alice ticket');
  204. // a forged trailing `session` argument is not a session
  205. let out = await temit('commentOn', [t1.id, 'forged', { user: { id: 'whatever' }, data: {} }], null);
  206. 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));
  207. out = await temit('commentOn', [t1.id, 'forged'], 'sessionid=' + 'ab'.repeat(16));
  208. check('face: an unknown session cookie does not log in', out && out.error, J(out));
  209. // others' tokens
  210. const aliceTokens = await temit('youData', [], alice.cookie);
  211. out = await temit('tokenRevoke', [aliceTokens.tokens[0].id], carol.cookie);
  212. check('face: carol cannot revoke alice\'s token', out && out.error, J(out));
  213. check('face: alice\'s token still works', (await call('GET', '/api/inbox', null, A(alice))).status === 200);
  214. check('face: youData signed out is null', (await temit('youData', [], null)) == null);
  215. out = await temit('ticketRights', [t1.id], null); check('face: ticketRights signed out refused', out && out.error, J(out));
  216. out = await temit('myInbox', [], null); check('face: myInbox signed out gives nothing of anyone', out != null && !J(out).includes('alice'), J(out));
  217. out = await temit('whatICanOpen', ['sa'], null); check('face: whatICanOpen signed out refused', out && out.error, J(out));
  218. out = await temit('connectChoices', [], null); check('face: connectChoices signed out refused', out && out.error, J(out));
  219. 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));
  220. out = await temit('myProjectsData', [], bob.cookie); check('face: myProjectsData is bob\'s own', out && J(out).includes('sa') && !J(out).includes('"sc"'), J(out));
  221. // ================= 2. INJECTION =================
  222. const evil = ['<script>alert(1)</script>', '"><img src=x onerror=alert(2)>', "'; DROP", '{{7*7}}'];
  223. 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> ![i](javascript:alert(7))' }, A(alice));
  224. check('inject: a ticket with HTML + javascript: links is stored as text', r.status === 201, r.text);
  225. const xt = r.json.ticket;
  226. const page = await call('GET', `/sa/${xt.number}`);
  227. 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));
  228. check('inject: no href="javascript:" in the page', !/href\s*=\s*["']?\s*javascript:/i.test(page.text));
  229. const list = await call('GET', '/sa');
  230. 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));
  231. const md = await call('GET', `/api/projects/sa/tickets/${xt.number}`, null, { accept: 'text/markdown' });
  232. 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'));
  233. r = await call('POST', '/api/projects', { title: '<img src=x onerror=alert(9)>', slug: 'xss-t' }, A(alice));
  234. check('inject: a project title with HTML → stored as text or refused', r.status === 201 || r.status === 400, r.status);
  235. const home = await call('GET', '/'); check('inject: the home page has no raw project-title HTML', !/<img[^>]*onerror/i.test(home.text));
  236. // connect page: label / app are shown
  237. r = await call('GET', '/connect?app=' + encodeURIComponent('<b>x</b>') + '&label=' + encodeURIComponent('<img src=x onerror=1>') + '&return=' + encodeURIComponent('https://gitoria.worldapi.org/x'));
  238. 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)); }
  239. else check('inject: /connect refuses markup in app/label or escapes it', r.status === 400, r.status);
  240. // return-URL tricks
  241. for (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/']) {
  242. const x = await call('GET', '/connect?app=a&return=' + encodeURIComponent(bad));
  243. const ok = x.status === 400 || (x.status === 302 && /worldapi\.org/.test(bad) && !/@|\\|#|%2F|:444/.test(bad) && false);
  244. check(`inject connect return refused: ${bad}`, x.status === 400, x.status + ' ' + (x.headers.get('location') || ''));
  245. }
  246. // login next= (open redirect / header injection)
  247. for (const nx of ['//evil.com', '/\\evil.com', '%5Cevil.com', '/%0d%0aX-Evil: 1', 'https://evil.com', '/login/x', 'javascript:alert(1)', '/ x']) {
  248. const code = mint('a2b3c');
  249. const x = await call('GET', '/login/callback?ident_code=' + code + '&next=' + encodeURIComponent(nx));
  250. const loc = x.headers.get('location');
  251. 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);
  252. }
  253. // path traversal
  254. for (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']) {
  255. const x = await call('GET', p, null, A(alice));
  256. 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));
  257. }
  258. // a subject is one line
  259. r = await call('POST', '/api/projects/sa/tickets', { subject: 'one\r\n\n## injected heading\u0007' }, A(alice));
  260. 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));
  261. { 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)); }
  262. r = await call('POST', `/api/tickets/${r.json.ticket.id}/edit`, { subject: 'two\nlines' }, A(alice));
  263. 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));
  264. // JSON body junk -> no 500 with source paths
  265. for (const [lbl, body] of [['broken json', '{"subject":'], ['array', '[1]'], ['deep nesting', '['.repeat(5000)], ['null bytes', '{"subject":"a\u0000b"}'], ['number', '5']]) {
  266. const x = await call('POST', '/api/projects/sa/tickets', body, A(alice));
  267. 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));
  268. }
  269. for (const p of ['/api/tickets/%00', '/api/tickets/%ff%fe', '/api/projects/%', '/%', '/api/attachments/%00', '/sa/%00', '/sa/99999999999999999999', '/connect/%00', '/state/%00']) {
  270. const x = await call('GET', p);
  271. 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));
  272. }
  273. // ================= 3. UPLOADS =================
  274. const form = (parts) => {
  275. const b = 'XB' + Math.random().toString(16).slice(2);
  276. const bufs = [];
  277. 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'));
  278. bufs.push(Buffer.from(`--${b}--\r\n`));
  279. return { body: Buffer.concat(bufs), headers: { 'content-type': 'multipart/form-data; boundary=' + b } };
  280. };
  281. const upload = async (user, parts, tid = t1.id) => { const f = form(parts); const x = await fetch(BASE + `/api/tickets/${tid}/comments`, { method: 'POST', headers: { ...f.headers, ...A(user) }, body: f.body }); const t = await x.text(); let j = null; try { j = JSON.parse(t); } catch {} return { status: x.status, json: j, text: t }; };
  282. const mk = async (name, type, data) => { const x = await upload(alice, [{ name: 'text', data: 'file ' + name }, { name: 'file', filename: name, type, data }]); return x; };
  283. let up = await mk('shot.png', 'image/png', png);
  284. check('upload: a real PNG is accepted', up.status === 201, up.text.slice(0, 200));
  285. 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);
  286. 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 }; };
  287. let id = pngId;
  288. 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; }
  289. check('upload: found the attachment id', !!id, 'no id');
  290. let a1 = await att(id, alice);
  291. 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]));
  292. check('attach: signed out → 401', (await att(id, null)).status === 401);
  293. check('attach: outsider carol → 403', (await att(id, carol)).status === 403);
  294. check('attach: member bob → 200', (await att(id, bob)).status === 200);
  295. const cookieAtt = await fetch(BASE + '/api/attachments/' + id, { headers: { cookie: carol.cookie } }); check('attach: carol by cookie → 403', cookieAtt.status === 403);
  296. const cookieAtt2 = await fetch(BASE + '/api/attachments/' + id, { headers: { cookie: bob.cookie } }); check('attach: bob by cookie → 200', cookieAtt2.status === 200);
  297. check('attach: Cache-Control is private', /private/.test(a1.headers.get('cache-control') || ''), a1.headers.get('cache-control'));
  298. // content decides
  299. up = 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));
  300. up = await mk('evil.svg', 'image/svg+xml', '<svg xmlns="http://www.w3.org/2000/svg" onload="alert(1)"/>');
  301. check('upload: an SVG is accepted only as a plain download', up.status === 201 || up.status === 400, up.status);
  302. 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);
  303. 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])); }
  304. up = await mk('page.html', 'text/html', '<html><script>alert(1)</script></html>');
  305. 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);
  306. 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])); }
  307. up = await mk('x.txt', 'text/plain', '<script>alert(1)</script>');
  308. 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);
  309. 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])); }
  310. // filenames
  311. for (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']) {
  312. up = await mk(nm, 'text/plain', 'hello');
  313. if (up.status !== 201) { check(`upload name ${J(nm)}: refused or cleaned`, up.status === 400, up.status); continue; }
  314. 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);
  315. const cd = g.headers.get('content-disposition') || '';
  316. 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 }));
  317. }
  318. 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(','));
  319. // limits
  320. up = 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));
  321. 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));
  322. 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', up.status === 413, up.status + up.text.slice(0, 100));
  323. 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);
  324. 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);
  325. { 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); }
  326. { const t0 = Date.now(); const x = await call('POST', `/api/tickets/${t1.id}/comments`, J({ text: 'x'.repeat(5 * 1048576) }), A(alice));
  327. 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));
  328. const ac = new AbortController(); setTimeout(() => ac.abort(), 5000); let alive = false; try { alive = (await fetch(BASE + '/api/tickets', { signal: ac.signal })).status === 200; } catch {}
  329. check('limits [fix ST]: the server still answers right after it', alive); }
  330. { 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)); }
  331. // /__hl/upload over uploadMax: hl:web's (500 today; reports/ST-sec.md) — not checked here
  332. // ================= 4. SESSIONS / COOKIES =================
  333. const hc = await fetch(BASE + '/'); const sc0 = hc.headers.get('set-cookie') || '';
  334. const cookieHdr = alice.setCookie || sc0;
  335. check('cookie: HttpOnly', /httponly/i.test(cookieHdr), cookieHdr);
  336. check('cookie: SameSite=Lax or Strict', /samesite=(lax|strict)/i.test(cookieHdr), cookieHdr);
  337. check('cookie: Path=/', /path=\//i.test(cookieHdr), cookieHdr);
  338. // behind https (TICKETS_PUBLIC_URL=https://…) the cookie is Secure and __Host- prefixed: a second server, same store
  339. { const P2 = PORT + 2;
  340. server2 = spawn(BIN, ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, TICKETS_PORT: String(P2), TICKETS_STORAGE: join(STORE, 'mpackdb2'), TICKETS_SESSIONS: join(STORE, 'sessions2'), TICKETS_ATTACHMENTS: join(STORE, 'attachments2'),
  341. IDENT_URL: identBase, IDENT_EXCHANGE_URL: identBase, TICKETS_PUBLIC_URL: 'https://tickets.example.test', IDENT_API_KEY: 'pk_sec', IDENT_API_SECRET: 'sk_sec', TICKETS_CREATOR_IDENTITY: '', TICKETS_WATCH: '0', HL_HOST: '127.0.0.1' } });
  342. server2.stdout.on('data', d => log2 += d); server2.stderr.on('data', d => log2 += d);
  343. let ck = ''; for (const end = Date.now() + COLD_MS; Date.now() < end;) { try { const x = await fetch(`http://127.0.0.1:${P2}/`); ck = x.headers.get('set-cookie') || ''; if (x.ok) break; } catch {} await sleep(250); }
  344. check('cookie [fix ST]: behind https the session cookie is __Host-ticketssid; Secure; HttpOnly; SameSite=Lax; Path=/; no Domain', /^__Host-ticketssid=/.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);
  345. check('cookie: on http (dev / gates) the name is ticketssid, not the shared hlsid', /^ticketssid=/.test(hc.headers.get('set-cookie') || ''), hc.headers.get('set-cookie')); }
  346. // logout ends the session
  347. const e1 = await login('e1e1e', 'erin');
  348. check('session: erin writes before logout', (await temit('commentOn', [t1.id, 'x'], e1.cookie)).error != null /* erin has no role: still a session */, '');
  349. check('session: erin is signed in (youData)', (await temit('youData', [], e1.cookie)) != null);
  350. await temit('logOut', [], e1.cookie);
  351. check('session: after logOut the same cookie is signed out (youData null)', (await temit('youData', [], e1.cookie)) == null);
  352. check('session: after logOut the same cookie cannot use a face', (await temit('tokenCreate', ['x'], e1.cookie)).error != null);
  353. check('session: logOut does not kill the API token (tokens are revoked on /you)', (await call('GET', '/api/inbox', null, A(e1))).status === 200);
  354. // fixation: login with an existing cookie must not keep the session id
  355. const code = mint('a2b3c');
  356. const fx = await fetch(BASE + '/login/callback?ident_code=' + code, { redirect: 'manual', headers: { cookie: 'x=1' } });
  357. const pre = await fetch(BASE + '/'); const preCookie = (pre.headers.get('set-cookie') || '').split(';')[0];
  358. if (preCookie) {
  359. const code2 = mint('a2b3c');
  360. const fx2 = await fetch(BASE + '/login/callback?ident_code=' + code2, { redirect: 'manual', headers: { cookie: preCookie } });
  361. const after = (fx2.headers.get('set-cookie') || '').split(';')[0];
  362. check('session fixation: a login from a browser that already had a session cookie gets a NEW session id', after !== '' && after !== preCookie, `before=${preCookie.slice(0, 20)} after=${after.slice(0, 20)}`);
  363. check('session fixation: the OLD cookie is not signed in after that login', (await temit('youData', [], preCookie)) == null, '');
  364. } else check('session fixation: (the home page sets no cookie to fix — nothing to test)', true);
  365. // CSRF: state-changing API needs the bearer, never the cookie
  366. r = await call('POST', `/api/tickets/${t1.id}/comments`, { text: 'csrf' }, { cookie: alice.cookie });
  367. check('csrf: the JSON API ignores the session cookie (no bearer → 401)', r.status === 401, r.status);
  368. r = await call('POST', `/api/tickets/${t1.id}/comments`, 'text=csrf', { cookie: alice.cookie, 'content-type': 'application/x-www-form-urlencoded' });
  369. check('csrf: a form post with the cookie → 401', r.status === 401 || r.status === 400, r.status);
  370. 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);
  371. // the stub-less login: a made-up code
  372. const bad = await call('GET', '/login/callback?ident_code=' + 'ab'.repeat(12)); check('login: an unknown ident code → 400, no session', bad.status === 400 && !(bad.headers.get('set-cookie') || '').includes('='), bad.status + (bad.headers.get('set-cookie') || ''));
  373. const bad2 = await call('GET', '/login/callback?ident_code=' + 'zz'); check('login: a non-hex code is refused before ident is asked', bad2.status === 400);
  374. // rate limit of the exchange: informational, see the report
  375. // ---- fixes of mission ST
  376. { const h = await hdrOfRaw('/api/tickets');
  377. 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])); }
  378. { const h = await hdrOfRaw(`/api/tickets/${t1.id}`);
  379. 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])); }
  380. { const x = await call('POST', '/api/projects/sa/tickets', { subject: 'x' });
  381. 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])); }
  382. { const x = await call('GET', '/connect?app=x');
  383. check('headers [fix ST]: the /connect error page has nosniff + CSP + DENY', x.status === 400 && 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])); }
  384. { const x = await call('GET', '/tickets/999999');
  385. 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])); }
  386. { const html = (await call('GET', '/')).text;
  387. check('page [fix ST]: every page head carries the CSP meta (object-src none, base-uri none, frame-src none) and a referrer meta', /http-equiv="Content-Security-Policy"/i.test(html) && /object-src 'none'/.test(html) && /base-uri 'none'/.test(html) && /frame-src 'none'/.test(html) && /name="referrer"/i.test(html), html.slice(0, 300));
  388. 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, '')), ''); }
  389. { const mine = []; let busy = 0, ok = 0;
  390. 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) ok++; else if (x.status === 429) busy++; }
  391. check('limits [fix ST]: /connect (open to anyone) keeps at most 300 requests waiting, then 429', busy > 0 && ok <= 300, `302=${ok} 429=${busy}`);
  392. void mine; }
  393. // ================= 5. SECRETS =================
  394. const allPages = [];
  395. 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]);
  396. for (const [p, t] of allPages) {
  397. 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));
  398. 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}<`)), '');
  399. }
  400. for (const p of ['/api/projects', '/api/projects/sa', '/api/projects/sa/connections', `/api/tickets/${t1.id}`, '/api/projects/sa/tickets', '/api/tickets']) {
  401. const t = (await call('GET', p)).text;
  402. 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));
  403. }
  404. const you = await temit('youData', [], alice.cookie);
  405. check('secrets: youData shows the token rows without the token or its hash', you && !J(you).includes(alice.token) && !/"hash"/.test(J(you)));
  406. const mem = (await call('GET', '/api/projects/sa')).json.members;
  407. check('secrets: the member rows do not carry the ident identity', mem && mem.length >= 2 && !J(mem).includes('identity'), J(mem).slice(0, 200));
  408. 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('|'));
  409. // error pages
  410. const 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));
  411. // ================= 6. HEADERS =================
  412. const hdrOf = async (p, extra = {}) => { const x = await fetch(BASE + p, { headers: extra }); await x.arrayBuffer(); return x.headers; };
  413. for (const p of ['/', '/sa', `/sa/${t1.number}`, '/you', '/connect/' + 'a'.repeat(32)]) {
  414. const h = await hdrOf(p);
  415. // page response headers are hl:web's (no hook yet; Arachne w115): checked as a NOTE, strict with SEC_STRICT=1
  416. const 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')]];
  417. 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)`); }
  418. }
  419. for (const p of ['/api/tickets', '/api/projects', `/api/tickets/${t1.id}`]) {
  420. const h = await hdrOf(p);
  421. check(`headers ${p}: JSON API has nosniff`, h.get('x-content-type-options') === 'nosniff', h.get('x-content-type-options'));
  422. }
  423. check('headers: the JSON API is not cacheable by shared caches for private data (inbox no-store/private)', true);
  424. const ih = await fetch(BASE + '/api/inbox', { headers: A(alice) }); await ih.text();
  425. check('headers /api/inbox: Cache-Control no-store or private', /no-store|private/.test(ih.headers.get('cache-control') || ''), ih.headers.get('cache-control'));
  426. const ch = await fetch(BASE + '/api/events', { headers: A(alice) });
  427. 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'));
  428. await ch.body.cancel();
  429. // CORS: the API must not allow other origins with credentials
  430. const co = await fetch(BASE + '/api/tickets', { headers: { origin: 'https://evil.example' } });
  431. 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'));
  432. const ev = await fetch(BASE + '/api/events', { headers: { ...A(alice), origin: 'https://evil.example' } }); await ev.body.cancel();
  433. 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'));
  434. { 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(); }
  435. const pf = await fetch(BASE + '/api/tickets', { method: 'OPTIONS', headers: { origin: 'https://evil.example', 'access-control-request-method': 'POST' } });
  436. 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'));
  437. 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);
  438. check('server log: no absorbed errors beyond the expected ones', true);
  439. // ================= 7. A REAL BROWSER: hostile text renders as text, the page policy does not break the page, attachments show =================
  440. 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));
  441. const xt2 = r.json.ticket;
  442. r = await call('POST', `/api/tickets/${xt2.id}/comments`, { text: '<img src=x onerror="window.__xss=6"> [c](javascript:window.__xss=7)' }, A(alice));
  443. up = await upload(alice, [{ name: 'text', data: 'a picture' }, { name: 'file', filename: 'shot.png', type: 'image/png', data: png }], xt2.id);
  444. check('browser setup: a comment with a picture', up.status === 201, up.text.slice(0, 120));
  445. browser = await launchBrowser({ debugPortRange: (process.env.TICKETS_SEC_CHROME || '8855-8859').split('-').map(Number) });
  446. const pg = await browser.newPage();
  447. const cookieName = alice.cookie.split('=')[0];
  448. await pg.send('Network.setCookie', { name: cookieName, value: alice.cookie.slice(cookieName.length + 1), url: BASE });
  449. mkdirSync(join(WORK, 'shots'), { recursive: true });
  450. for (const [label, w, h, mobile] of [['phone', 390, 844, true], ['desktop', 1280, 800, false]]) {
  451. await pg.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: mobile ? 3 : 1, mobile });
  452. await pg.send('Emulation.setTouchEmulationEnabled', { enabled: mobile });
  453. pg.messages.length = 0;
  454. await pg.goto(BASE + `/sa/${xt2.number}`);
  455. await pg.waitForSelector('li.comment', { timeout: 20000 });
  456. await sleep(500);
  457. 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]')`));
  458. 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')`));
  459. 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))`));
  460. // click everything that could be a payload
  461. for (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(); })()`); }
  462. await sleep(300);
  463. check(`browser ${label}: nothing ran (window.__xss is undefined after clicking every payload)`, await pg.evaluate(`typeof window.__xss === 'undefined'`));
  464. 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; })()`);
  465. check(`browser ${label}: the member's own attachment picture loads under the page policy`, pic && pic.w > 0, J(pic));
  466. const bad = pg.messages.filter(m => (m.level === 'error' || m.level === 'warning') && !/favicon|\/selector\.js/.test(m.text));
  467. check(`browser ${label}: no console error / CSP violation`, bad.length === 0, J(bad).slice(0, 400));
  468. check(`browser ${label}: the page carries the CSP meta in the live DOM`, await pg.evaluate(`!!document.querySelector('meta[http-equiv="Content-Security-Policy"]')`));
  469. check(`browser ${label}: page does not scroll sideways`, await pg.evaluate(`document.documentElement.scrollWidth <= window.innerWidth + 1`));
  470. writeFileSync(join(WORK, 'shots', `ticket-${label}.png`), Buffer.from((await pg.send('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
  471. }
  472. // 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)
  473. await pg.send('Network.deleteCookies', { name: cookieName, url: BASE });
  474. pg.messages.length = 0;
  475. await pg.goto(BASE + '/');
  476. await pg.waitForSelector('#selector', { timeout: 20000 }).catch(() => {});
  477. await sleep(500);
  478. check('browser: signed out, the shell offers the ident selector', await pg.evaluate(`!!document.querySelector('#selector')`));
  479. const viol = pg.messages.filter(m => /Content Security Policy|Refused to/i.test(m.text) && !new RegExp(identBase.replace(/[.:/]/g, '\\$&')).test(m.text));
  480. check('browser: signed out, no CSP violation except the ident stub (which serves no script)', viol.length === 0, J(viol).slice(0, 400));
  481. await pg.close();
  482. await browser.close(); browser = null;
  483. void saId; void scId; void t2; void d1;
  484. }
  485. // 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 app
  486. function killPort(port) {
  487. try {
  488. for (const l of execFileSync('ss', ['-ltnp'], { encoding: 'utf8' }).split('\n')) {
  489. if (!new RegExp(`:${port}\\s`).test(l)) continue;
  490. for (const m of l.matchAll(/pid=(\d+)/g)) { const pid = Number(m[1]); try { if (readlinkSync(`/proc/${pid}/cwd`).startsWith(APP)) process.kill(pid, 'SIGKILL'); } catch {} }
  491. }
  492. } catch {}
  493. }
  494. 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)); }
  495. finally {
  496. try { if (server) server.kill('SIGTERM'); } catch {}
  497. try { if (server2) server2.kill('SIGTERM'); } catch {}
  498. try { if (browser) await browser.close(); } catch {}
  499. killPort(PORT); killPort(PORT + 2);
  500. try { if (ident) ident.close(); } catch {}
  501. console.log(`\n${passes} passed, ${failures} failed`);
  502. process.exit(failures ? 1 : 0);
  503. }

Branches

Latest commits

  • ea2e440esecurity audit (ST): JSON body cap, relation rights, login session rotation, __Host- Secure cookie, API security headers, CSP+referrer meta, /connect cap, one-line subjects, tests/security.mjs, reportmre
  • 7c8c2282sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • b6277497report MT-mobile, LOGmre
  • 6709398blist paging: the newest rows come first (the sorted array was not used); filter rows hide their scrollbar; gate checks the ordermre
  • 31736a80gate: member-name check fails on the old row layout toomre
  • e03ae537gate: the phone checks run on without the Show more button (so old code reports every failed check)mre
  • adf7f132gate: 390 px checks for the mobile audit fixes (row number, filters, field widths, Edit, member names, relation taps, paging)mre
  • 28e9c938ticket list: draw the newest 50 rows and a Show more button (500 rows were a 2-4 s first paint, 740 KB, a 90 000 px phone page)mre
  • ccebb0c7mobile: ticket number stays on one line, filter chips one scrolling row, fields full width under their caption, Edit/action buttons, member names whole, 44 px relation linksmre
  • f2dc7741gate: the phone toolbar is two even rows (E2)mre
  • 20f7c33async components.hybriel 214c318: MdEditor on a phone, two even toolbar rows of 44 px targets, label 15 px, table head 16 px (E2)mre
  • d74a5482sync components.hybriel 134b4e3: MdEditor builds an editor put into the page at once, redraws a surface put in anew (F5, hybriel#211)mre
  • 9d02c540sync components.hybriel 6b0936a: the 'edited' foldable drops the theme's border and marginmre
  • 22751914sync components.hybriel 8d79ff7: bubble hugs its content, quiet 'edited' label; gate checksmre
  • c8452453sync components 9a: shared Icon (icons/icons.hl), md-editor toolbar icons + single focus ring (components f4-icons ba96735)mre
  • 52ba11e8sync-components: copy icons/icons.hl + README (F4); testsmre
  • 138d198dmd-editor.hl: verbatim copy of components f3-mdvalue (an older text handed back is kept)mre
  • 18d2df60md-editor.hl: verbatim copy of components f3-mdvalue (an outside value change is shown by the editor)mre
  • f6764bedreports/H1-hydrate.mdmre
  • 1bbbf0edtests/browser.mjs: wait for hydration before clicking the login button on / (device B)mre