gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmainfe209ffeMerge branch 'w56-owner-members' into mainGitoriamain/tests/security.mjs

25.0 KB

  1. import { requiredPort } from './gate-ports.mjs';
  2. // tests/security.mjs — SECURITY GATE of gitoria.worldapi.org (mission SG): real HTTP requests against a real local
  3. // gitoria + its own ident (tests/identkit.mjs). Who may do what (signed out / another user / owner) on every route, API
  4. // endpoint and face; injection; the session cookie; the answer headers; the open /__hl/upload.
  5. // node tests/security.mjs (GITORIA_SEC_PORT required, GITORIA_SEC_PORT2 required = the https-configured server,
  6. // GITORIA_SEC_IDENT_PORT required)
  7. // Known hl:web gaps (page security headers, the 404 page echoing the path, no Origin check on emit) are PRINTED as `known:` lines, not counted.
  8. import { spawn, execFileSync } from 'node:child_process';
  9. import { request } from 'node:http';
  10. import { mkdirSync, rmSync, writeFileSync, existsSync, readdirSync } from 'node:fs';
  11. import { dirname, join, resolve } from 'node:path';
  12. import { fileURLToPath } from 'node:url';
  13. import { startIdent } from './identkit.mjs';
  14. const HERE = dirname(fileURLToPath(import.meta.url));
  15. const APP = resolve(HERE, '..');
  16. const PORT = requiredPort('GITORIA_SEC_PORT'), PORT2 = requiredPort('GITORIA_SEC_PORT2'), IDENT_PORT = requiredPort('GITORIA_SEC_IDENT_PORT');
  17. const IDENT_DIR = process.env.GITORIA_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/WorldAPI/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));
  18. const STORE = join(APP, '.scratch/sec-store');
  19. const SSH_SECRET = 'sshsecret-for-the-security-gate';
  20. const J = JSON.stringify, sleep = (ms) => new Promise(r => setTimeout(r, ms));
  21. let passes = 0, failures = 0;
  22. const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; };
  23. const known = (label) => console.log('known: ' + label);
  24. function raw(port, method, path, { host = `localhost:${port}`, headers = {}, body = null, cookie = null } = {}) {
  25. return new Promise((res, rej) => {
  26. const h = { host, ...headers }; if (cookie) h.cookie = cookie;
  27. if (body !== null) h['content-length'] = Buffer.byteLength(body);
  28. const r = request({ host: '127.0.0.1', port, method, path, headers: h }, (m) => { const c = []; m.on('data', d => c.push(d)); m.on('end', () => res({ status: m.statusCode, headers: m.headers, body: Buffer.concat(c).toString('latin1') })); });
  29. r.on('error', rej); if (body !== null) r.write(body); r.end();
  30. });
  31. }
  32. const get = (path, o = {}) => raw(PORT, 'GET', path, o);
  33. const procs = [];
  34. function spawnServer(port, base, env) {
  35. let log = '';
  36. const p = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],
  37. env: { ...process.env, GITORIA_PORT: String(port), GITORIA_WATCH: '0', GITORIA_PUBLIC_URL: base, GITORIA_SSH_SECRET: SSH_SECRET, GITORIA_TICKETS_URL: 'http://127.0.0.1:1', ...env } });
  38. p.stdout.on('data', d => log += d); p.stderr.on('data', d => log += d); procs.push(p);
  39. return { p, log: () => log };
  40. }
  41. async function up(port, srv) {
  42. for (let i = 0; i < 960; i++) { try { if ((await raw(port, 'GET', '/api/repos')).status === 200) return; } catch {} await sleep(250); }
  43. throw new Error('gitoria did not come up\n' + srv.log());
  44. }
  45. let ident;
  46. try {
  47. rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });
  48. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  49. const alice = await ident.signIn('[email protected]'), bob = await ident.signIn('[email protected]');
  50. const BASE = `http://localhost:${PORT}`;
  51. const app = await ident.registerApp(alice, 'gitoria (security gate)', [BASE]);
  52. const BASE2 = `https://localhost:${PORT2}`;
  53. const app2 = await ident.registerApp(alice, 'gitoria (security gate, https)', [BASE2]);
  54. const env = (d, a = app) => ({ GITORIA_STORAGE: join(STORE, d, 'mpackdb'), GITORIA_SESSIONS: join(STORE, d, 'sessions') + '/', GITORIA_GIT: join(STORE, d, 'git'), IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base, IDENT_API_KEY: a.key, IDENT_API_SECRET: a.secret });
  55. const s1 = spawnServer(PORT, BASE, env('one'));
  56. const s2 = spawnServer(PORT2, BASE2, env('two', app2)); // https public URL: the cookie must be Secure
  57. await Promise.all([up(PORT, s1), up(PORT2, s2)]);
  58. const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;
  59. const login = async (who, pre = null, next = '/') => {
  60. const first = pre ? { cookie: pre } : null;
  61. const ck = pre || cookieOf(await get('/'));
  62. const code = await ident.selectorCode(who, app, BASE);
  63. const cb = await get('/login/callback?ident_code=' + code + '&next=' + encodeURIComponent(next), { cookie: ck });
  64. return { cookie: cookieOf(cb) || ck, cb, pre: ck };
  65. };
  66. let n = 0;
  67. const face = async (who, event, payload) => {
  68. const r = await raw(PORT, 'POST', '/__hl/emit', { headers: { 'content-type': 'application/json' }, cookie: who && who.cookie, body: J({ t: 'emit', i: ++n, event, payload }) });
  69. let j = null; try { j = JSON.parse(r.body); } catch {}
  70. return { status: r.status, value: j && j.value, error: j && j.error };
  71. };
  72. const A = await login(alice), B = await login(bob);
  73. await face(A, 'gitoriaSaveName', ['Alice']); await face(B, 'gitoriaSaveName', ['Bob']);
  74. // ---- 1. authz: the faces (who may, result) --------------------------------------------------------------------
  75. const mk = await face(A, 'gitoriaCreate', ['alpha', 'a <b>repo</b>']);
  76. check('face gitoriaCreate: owner creates', !!(mk.value && mk.value.repo && mk.value.repo.slug === 'alpha'), J(mk.value));
  77. check('face gitoriaCreate: signed out refused', !!(await face(null, 'gitoriaCreate', ['zeta', 'x'])).value.error);
  78. check('face gitoriaCreate: a slug with .. or / refused', !!(await face(B, 'gitoriaCreate', ['../x', 'x'])).value.error && !!(await face(B, 'gitoriaCreate', ['a/b', 'x'])).value.error);
  79. const tk = await face(A, 'gitoriaMakeToken', ['laptop']);
  80. check('face gitoriaMakeToken: signed-in user makes one', !!(tk.value && /^gtr_[0-9a-f]{40}$/.test(tk.value.token || '')), J(tk.value));
  81. check('face gitoriaMakeToken: signed out refused', !!(await face(null, 'gitoriaMakeToken', ['x'])).value.error);
  82. check('face gitoriaRemoveToken: another user cannot remove it', (await face(B, 'gitoriaRemoveToken', [tk.value.row.id])).value.error === 'no such token');
  83. check('face gitoriaRemoveToken: signed out refused', !!(await face(null, 'gitoriaRemoveToken', [tk.value.row.id])).value.error);
  84. check('face gitoriaAddKey / gitoriaRemoveKey: signed out refused', !!(await face(null, 'gitoriaAddKey', ['k', 'ssh-ed25519 AAAA'])).value.error && !!(await face(null, 'gitoriaRemoveKey', ['1'])).value.error);
  85. for (const [w, wn] of [[null, 'signed out'], [B, 'another user']]) {
  86. check(`face gitoriaSetBranch: ${wn} refused`, !!(await face(w, 'gitoriaSetBranch', ['alpha', 'main', 'code', ''])).value.error);
  87. check(`face gitoriaDisconnectTickets: ${wn} refused`, !!(await face(w, 'gitoriaDisconnectTickets', ['alpha'])).value.error);
  88. check(`face gitoriaMergePull: ${wn} refused`, !!(await face(w, 'gitoriaMergePull', ['alpha', 'a'.repeat(40)])).value.error);
  89. }
  90. check('face gitoriaOpenTicket: signed out refused', !!(await face(null, 'gitoriaOpenTicket', ['alpha', 's', 't'])).value.error);
  91. check('face gitoriaSaveName: signed out refused', !!(await face(null, 'gitoriaSaveName', ['x'])).value.error);
  92. check('face gitoriaSaveName: the name is asked ONCE (a second set refused)', !!(await face(A, 'gitoriaSaveName', ['Other'])).value.error);
  93. check('face gitoriaLogin: a junk code is refused', !!(await face(B, 'gitoriaLogin', ['not a code'])).value.error);
  94. check('client-side events cannot be called by a peer', !(await face(null, 'repoCreated', [{ slug: 'evil' }])).value);
  95. // ---- 1b. authz: routes ----------------------------------------------------------------------------------------------
  96. const apiRow = JSON.parse((await get('/api/repos/alpha')).body);
  97. check('API /api/repos/:slug: public read, no secret field', !('tktKey' in apiRow) && !('tktApi' in apiRow) && !('owner_id' in apiRow) && !('identity' in apiRow), J(Object.keys(apiRow)));
  98. check('API: POST without a token refused (401)', (await raw(PORT, 'POST', '/api/repos', { body: '{}' })).status === 401);
  99. check('/settings/connect: signed out is sent to /settings (no nonce)', (await get('/settings/connect', { host: `alpha.localhost:${PORT}` })).headers.location === '/settings');
  100. check('/settings/connect: another user is sent to /settings (no redirect to tickets)', (await get('/settings/connect', { host: `alpha.localhost:${PORT}`, cookie: B.cookie })).headers.location === '/settings');
  101. check('/settings/connect: the owner is sent on to tickets', /\/connect\?app=gitoria/.test((await get('/settings/connect', { host: `alpha.localhost:${PORT}`, cookie: A.cookie })).headers.location || ''));
  102. check('/settings/connected: another user is sent to /settings, nothing stored', (await get('/settings/connected?code=abc&state=x', { host: `alpha.localhost:${PORT}`, cookie: B.cookie })).headers.location === '/settings');
  103. // gitoria#36: a failed return from tickets is SEEN (a note on the settings page, one log line) and exchanges nothing
  104. const HA = `alpha.localhost:${PORT}`;
  105. const back = await get('/settings/connected?code=SECRETCODE1&state=SECRETSTATE1', { host: HA });
  106. const backCk = cookieOf(back);
  107. check('gitoria#36 /settings/connected with no cookie: sent to /settings with a fresh session cookie', back.headers.location === '/settings' && !!backCk, J(back.headers));
  108. const backPage = backCk ? await get('/settings', { host: HA, cookie: backCk }) : { body: '' };
  109. check('gitoria#36 no cookie: the settings page shows the note that the connection did not finish', /id="connectnote"[^>]*>[^<]*did not finish/.test(backPage.body) || /did not finish: this browser is not signed in/.test(backPage.body));
  110. const asB = await get('/settings/connected?code=SECRETCODE2&state=SECRETSTATE2', { host: HA, cookie: B.cookie });
  111. const bPage = await get('/settings', { host: HA, cookie: B.cookie });
  112. check('gitoria#36 signed in as a non-owner: sent to /settings and shown the note', asB.headers.location === '/settings' && /did not finish: this browser is not signed in/.test(bPage.body));
  113. const logLines = s1.log();
  114. check('gitoria#36 the log has one line per refused return with repo, reason and state presence', /connect-back alpha refused reason=no-session state=present/.test(logLines) && /connect-back alpha refused reason=not-owner state=present/.test(logLines), logLines.slice(-400));
  115. check('gitoria#36 the log never holds the code or the state value', !/SECRETCODE|SECRETSTATE/.test(logLines));
  116. const mism = await get('/settings/connected?code=SECRETCODE3&state=SECRETSTATE3', { host: HA, cookie: A.cookie });
  117. check('gitoria#36 the owner with a state that was not started here: note, and a state-mismatch log line', /state-mismatch state=present/.test(s1.log()) && mism.headers.location === '/settings');
  118. const q = '/__git/access?user=x&slug=alpha&write=1';
  119. check('/__git/access: no secret → 403', (await get(q)).status === 403);
  120. check('/__git/access: wrong secret → 403', (await get(q, { headers: { 'x-gitoria-secret': 'nope' } })).status === 403);
  121. check('/__git/access: right secret through the proxy (X-Forwarded-For) → 403', (await get(q, { headers: { 'x-gitoria-secret': SSH_SECRET, 'x-forwarded-for': '1.2.3.4' } })).status === 403);
  122. check('/__git/access: right secret, a non-owner write → 403', (await get(q, { headers: { 'x-gitoria-secret': SSH_SECRET } })).status === 403);
  123. check('/__git/keys: no secret → 403', (await get('/__git/keys?type=ssh-ed25519&key=AAAA')).status === 403);
  124. // ---- 1c. git over HTTPS: who may push -------------------------------------------------------------------------------
  125. const tokB = (await face(B, 'gitoriaMakeToken', ['bobs'])).value.token;
  126. const W = join(STORE, 'work'); mkdirSync(W, { recursive: true });
  127. const genv = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_GLOBAL: '/dev/null', GIT_AUTHOR_NAME: 'a', GIT_AUTHOR_EMAIL: 'a@a', GIT_COMMITTER_NAME: 'a', GIT_COMMITTER_EMAIL: 'a@a' };
  128. const g = (...a) => execFileSync('git', a, { cwd: W, encoding: 'utf8', env: genv, stdio: ['ignore', 'pipe', 'pipe'] });
  129. g('init', '-q', '-b', 'main');
  130. writeFileSync(join(W, 'README.md'), '# T\n\n[js](javascript:alert(1)) [d](data:text/html,x) [ok](https://example.org/a) <script>window.__x=1</script> [p](//evil.com)\n');
  131. writeFileSync(join(W, '<img src=x onerror=alert(1)>.txt'), 'hello <script>alert(1)</script>\n');
  132. g('add', '-A'); g('commit', '-q', '-m', 'init <script>alert(1)</script>'); g('branch', 'feat<b>x');
  133. const url = (t) => `http://u:${t}@alpha.localhost:${PORT}/alpha.git`;
  134. const push = (t) => { try { g('push', '-q', url(t), 'main'); return true; } catch { return false; } };
  135. check('git push: another user\'s valid token refused', !push(tokB));
  136. check('git push: a made-up token refused', !push('gtr_' + '0'.repeat(40)));
  137. try { g('push', '-q', `http://alpha.localhost:${PORT}/alpha.git`, 'main'); check('git push: without credentials refused', false); } catch { check('git push: without credentials refused', true); }
  138. check('git push: the owner\'s token works', push(tk.value.token));
  139. g('push', '-q', url(tk.value.token), 'feat<b>x');
  140. const adv = await get('/alpha.git/info/refs?service=git-receive-pack', { host: `alpha.localhost:${PORT}` });
  141. check('git receive-pack advertisement needs a token (401)', adv.status === 401);
  142. check('git clone/ls-remote needs no login (public)', /refs\/heads\/main/.test(g('ls-remote', `http://alpha.localhost:${PORT}/alpha.git`)));
  143. check('git transport on the main address / a foreign repo name: 404', (await get('/alpha.git/info/refs?service=git-upload-pack')).status === 404 && (await get('/beta.git/info/refs?service=git-upload-pack', { host: `alpha.localhost:${PORT}` })).status === 404);
  144. // ---- 2. injection ---------------------------------------------------------------------------------------------------
  145. const own = (b) => b.replace(/<script type="application\/json" id="hl-seed">[\s\S]*?<\/script>/, '');
  146. for (const p of ['/', '/code', '/branch/' + encodeURIComponent('feat<b>x'), '/code/' + encodeURIComponent('<img src=x onerror=alert(1)>.txt')]) {
  147. const r = await get(p, { host: `alpha.localhost:${PORT}` });
  148. check(`page ${p.slice(0, 30)}: no repo text lands as HTML (script / img / bold)`, !/<script>(alert|window\.__x)|<img src=x|<b>repo<\/b>|<b>x</.test(own(r.body)), J(own(r.body).match(/<script>(alert|window\.__x)|<img src=x|<b>repo<\/b>|<b>x</)));
  149. check(`page ${p.slice(0, 30)}: the page data seed cannot close its script tag`, !/<\/script/i.test((r.body.match(/id="hl-seed">([\s\S]*?)<\/script>/) || [, ''])[1]));
  150. }
  151. const home = own((await get('/', { host: `alpha.localhost:${PORT}` })).body);
  152. const hrefs = [...home.matchAll(/<a [^>]*href="([^"]*)"/g)].map(m => m[1]);
  153. check('Markdown: no javascript: / data: / protocol-relative link in the README page', !hrefs.some(h => /^(javascript|data|vbscript):/i.test(h) || h.startsWith('//')), J(hrefs));
  154. check('Markdown: the safe https link stays a link', hrefs.includes('https://example.org/a'));
  155. const nextOf = async (nx) => (await get('/login/callback?ident_code=' + await ident.selectorCode(bob, app, BASE) + '&next=' + encodeURIComponent(nx))).headers.location;
  156. let ok = true; const bad = [];
  157. for (const nx of ['//evil.com', '/\\evil.com', 'http://evil.com/', 'javascript:alert(1)', 'http://x.localhost:' + PORT + '@evil.com/', 'http://alpha.localhost:' + PORT + '.evil.com/']) { const l = await nextOf(nx); if (l !== '/') { ok = false; bad.push(nx + ' → ' + l); } }
  158. check('login ?next=: no open redirect (//, backslash, other host, javascript:, userinfo / suffix tricks)', ok, bad.join('; '));
  159. check('login ?next=: a repo address of this system is allowed', (await nextOf(`http://alpha.localhost:${PORT}/code`)) === `http://alpha.localhost:${PORT}/code`);
  160. const header = await get('/login/callback?ident_code=x&next=' + encodeURIComponent('/a\r\nSet-Cookie: x=1'));
  161. check('login ?next=: no header injection', !J(header.headers['set-cookie'] || '').includes('x=1') && !('x' in header.headers) && header.headers.location === '/login/failed', J(header.headers));
  162. check('files: source, storage, .env, .git are not served', (await Promise.all(['/.env', '/project.hl', '/lib/users.hl', '/storage/mpackdb/users.db', '/.git/config', '/icons/%2e%2e/project.hl', '/%2e%2e/%2e%2e/etc/passwd', '/docker-compose.yml'].map(p => get(p)))).every(r => r.status === 404));
  163. const mod = await get('/components/main.hl');
  164. check('served client modules hold no secret (ident secret, ssh secret)', !mod.body.includes(app.secret) && !mod.body.includes(SSH_SECRET));
  165. for (const w of [A, B]) {
  166. const r = await get('/settings', { host: `alpha.localhost:${PORT}`, cookie: w.cookie }); const r2 = await get('/', { cookie: w.cookie });
  167. check('pages carry no secret (app secret, ssh secret, session id, token, ident identity)', ![r.body, r2.body].some(b => b.includes(app.secret) || b.includes(SSH_SECRET) || b.includes(w.cookie.split('=')[1]) || b.includes(tk.value.token) || /"identity"/.test(b)), J([r.body, r2.body].map(b => [b.includes(app.secret), b.includes(SSH_SECRET), b.includes(w.cookie.split('=')[1]), b.includes(tk.value.token), /"identity"/.test(b)])));
  168. }
  169. // ---- 3. uploads -----------------------------------------------------------------------------------------------------
  170. const upl = await raw(PORT, 'POST', '/__hl/upload', { headers: { 'content-type': 'application/json' }, body: J({ name: 'x', type: 'text/plain', size: 900000000 }) });
  171. check('/__hl/upload: a signed-out visitor cannot start a 900 MB upload (no face takes a file) → 413', upl.status === 413, upl.status + " " + upl.body.slice(0, 100));
  172. // ---- 4. sessions and cookies ----------------------------------------------------------------------------------------
  173. // hl:web creates sessions lazily: a plain GET sends no cookie at all (nothing to track a visitor by). The cookie flags are checked on
  174. // the cookie the login hands out, on both servers.
  175. const plain = await get('/');
  176. check('a plain GET sends no Set-Cookie (sessions are created lazily, a visitor who does nothing gets no cookie)', !plain.headers['set-cookie'], J(plain.headers['set-cookie']));
  177. const c1 = (await login(bob)).cb.headers['set-cookie'][0];
  178. check('cookie: HttpOnly, SameSite=Lax, Path=/', /HttpOnly/.test(c1) && /SameSite=Lax/.test(c1) && /Path=\//.test(c1), c1);
  179. const cb2 = await raw(PORT2, 'GET', '/login/callback?ident_code=' + await ident.selectorCode(bob, app2, BASE2));
  180. const c2 = (cb2.headers['set-cookie'] || [''])[0];
  181. check('cookie: Secure when the public address is https', /; Secure/.test(c2), c2 + ' ' + cb2.status);
  182. const pre = 'gitoriasid=' + 'ab'.repeat(16); // a cookie planted by an attacker before the login
  183. const fixed = await login(bob, pre);
  184. check('login rotates the session id (a cookie planted before login is not the logged-in one)', fixed.cookie !== pre, 'same cookie ' + pre);
  185. const mkAsPre = await face({ cookie: pre }, 'gitoriaMakeToken', ['fixation']);
  186. check('the pre-login cookie does not act as the user', !!(mkAsPre.value && mkAsPre.value.error), J(mkAsPre.value));
  187. check('the new session acts as the user', !!(await face(fixed, 'gitoriaMakeToken', ['after'])).value.token);
  188. // SO28G (ident#28): the callback never signs out the session it finds; a good code signs THAT session in, the cookie value stays
  189. // gitoria#25: a cookieless failed login mints no session, sets no cookie; with a session the reason is kept and shown
  190. const sdir = join(STORE, 'one', 'sessions'), nFiles = () => existsSync(sdir) ? readdirSync(sdir).length : 0;
  191. const n0 = nFiles();
  192. const noCode = await get('/login/callback');
  193. const badNoCookie = await get('/login/callback?ident_code=' + 'ef'.repeat(24));
  194. const postNoCookie = await raw(PORT, 'POST', '/login/callback', { body: '' });
  195. check('a cookieless failed login (no code, bad code, POST): 302 /login/failed, no Set-Cookie, no session file', [noCode, badNoCookie, postNoCookie].every(r => r.status === 302 && r.headers.location === '/login/failed' && !r.headers['set-cookie']) && nFiles() === n0, J([noCode.headers, badNoCookie.headers]) + ' files ' + n0 + '→' + nFiles());
  196. const failedNoCookie = await get('/login/failed');
  197. check('/login/failed without a session shows the generic text', failedNoCookie.status === 200 && failedNoCookie.body.includes('the login did not finish'), failedNoCookie.status);
  198. const anon = (await login(bob)).cookie;
  199. await face({ cookie: anon }, 'gitoriaLogOut', []); // the same cookie, now an anonymous session
  200. const anonCb = await get('/login/callback?ident_code=' + 'ef'.repeat(24), { cookie: anon });
  201. const anonFailed = await get('/login/failed', { cookie: anon });
  202. check('with a session, a failed login keeps the reason in it and /login/failed shows it', anonCb.headers.location === '/login/failed' && anonFailed.body.includes('ident refused the login') && !anonFailed.body.includes('the login did not finish'), J(anonCb.headers) + anonFailed.body.slice(-600));
  203. const kept = await get('/login/callback?ident_code=' + await ident.selectorCode(bob, app, BASE), { cookie: anon });
  204. const keptSet = kept.headers['set-cookie'] || [];
  205. check('login keeps the session: a good code on an anonymous session leaves the same cookie value, and it is now signed in', cookieOf(kept) === anon && !!(await face({ cookie: anon }, 'gitoriaMakeToken', ['kept'])).value.token, J(keptSet) + ' vs ' + anon);
  206. check('login Set-Cookie: same cookie name, one cookie', keptSet.length === 1 && keptSet[0].split(';')[0] === anon, J(keptSet));
  207. const signedIn = (await login(alice)).cookie;
  208. const again2 = await login(bob, signedIn);
  209. const asNew = await face({ cookie: signedIn }, 'gitoriaMakeToken', ['same']);
  210. check('a good code on a signed-in session: the same cookie works, signed in as the new user, the old session was not made anonymous', again2.cookie === signedIn && !!(asNew.value && asNew.value.token), J(again2.cb.headers) + J(asNew.value));
  211. const badCb = await get('/login/callback?ident_code=' + 'cd'.repeat(24), { cookie: signedIn });
  212. check('a bad code changes nothing: the signed-in session stays signed in', badCb.headers.location === '/login/failed' && !!((await face({ cookie: signedIn }, 'gitoriaMakeToken', ['bad'])).value || {}).token);
  213. const usedCode = await ident.selectorCode(alice, app, BASE);
  214. await get('/login/callback?ident_code=' + usedCode);
  215. const reuse = await get('/login/callback?ident_code=' + usedCode, { cookie: signedIn });
  216. check('a reused code changes nothing: the signed-in session stays signed in as before', reuse.headers.location === '/login/failed' && !!((await face({ cookie: signedIn }, 'gitoriaMakeToken', ['reuse'])).value || {}).token);
  217. const C = await login(bob);
  218. await face(C, 'gitoriaLogOut', []);
  219. check('logout: the same cookie is signed out afterwards', !!(await face(C, 'gitoriaMakeToken', ['x'])).value.error);
  220. const code2 = await ident.selectorCode(bob, app, BASE);
  221. await get('/login/callback?ident_code=' + code2); const again = await get('/login/callback?ident_code=' + code2);
  222. check('a login code works once (reuse → /login/failed)', again.headers.location === '/login/failed');
  223. // ---- 6. headers on the function routes (pages: known gap) ------------------------------------------------------------
  224. const nos = async (label, r) => check(`X-Content-Type-Options: nosniff — ${label}`, (r.headers['x-content-type-options'] || '') === 'nosniff', J(r.headers));
  225. await nos('/api/repos', await get('/api/repos'));
  226. await nos('/api/repos/alpha (markdown)', await get('/api/repos/alpha', { headers: { accept: 'text/markdown' } }));
  227. await nos('/login/callback redirect', await get('/login/callback?ident_code=zz'));
  228. await nos('/settings/connect redirect', await get('/settings/connect', { host: `alpha.localhost:${PORT}` }));
  229. await nos('/__git/access', await get(q));
  230. await nos('git info/refs', await get('/alpha.git/info/refs?service=git-upload-pack', { host: `alpha.localhost:${PORT}` }));
  231. await nos('git 401', adv);
  232. const page = await get('/');
  233. for (const h of ['content-security-policy', 'x-content-type-options', 'x-frame-options', 'referrer-policy']) if (!page.headers[h]) known(`page answers carry no ${h} (hl:web has no hook for page headers — .scratch/SG-hlweb-gaps.md)`);
  234. const nf = await get('/nope%3Cscript%3Ealert(1)%3C/script%3E');
  235. if (/<script>alert/.test(nf.body) && /html/.test(nf.headers['content-type'])) known('hl:web 404 page echoes the decoded path as text/html: reflected XSS (.scratch/SG-hlweb-gaps.md)');
  236. const ev = await raw(PORT, 'POST', '/__hl/emit', { headers: { 'content-type': 'text/plain', origin: 'https://evil.example' }, cookie: A.cookie, body: J({ t: 'emit', i: 999, event: 'gitoriaMakeToken', payload: ['csrf'] }) });
  237. if (/"ok":true/.test(ev.body)) known('/__hl/emit does not check Origin (SameSite=Lax is the only CSRF guard; faces cannot read headers) (.scratch/SG-hlweb-gaps.md)');
  238. } catch (e) {
  239. check('the security gate ran to its end', false, String(e && e.stack || e));
  240. } finally {
  241. for (const p of procs) { try { p.kill('SIGTERM'); } catch {} }
  242. if (ident) await ident.stop();
  243. await sleep(500);
  244. console.log(`\n${passes} passed, ${failures} failed`);
  245. process.exit(failures ? 1 : 0);
  246. }

Branches

Latest commits

  • fe209ffeMerge branch 'w56-owner-members' into mainGitoria
  • fa0754c8|||PR repository owner transfer and members API (#55)mre
  • 8862e537Merge branch 'w55-rename-org' into mainGitoria
  • 014d2b7fOne immutable readers snapshot per move for the left-organization event (#53)mre
  • 1859d506Decide who hears a repo left its organization by its readers before the move (#53)mre
  • 499f25f2Review fixes for the Settings organization move (#53)mre
  • ed3b922b|||PR move a repository into an organization in Settings (#53)mre
  • 74ec2af8Merge branch 'w54-repo-rename-pr' into mainGitoria
  • 9f7ce8d8Preserve rename compatibility and live page titlesmre
  • c3d95b6e|||PR separate names and addresses, rename repositories in Settings (#53)mre
  • ce08920dMerge branch 'w52c-header-phone' into mainGitoria
  • 0bab9e46|||PR header: ident status wraps on phones instead of clippingmre
  • e7af3eceMerge branch 'w52b-approval-followup' into mainGitoria
  • c01e66c6|||PR approvals follow-up: live Merge after status writes, helpers (#52)mre
  • 841da497Merge branch 'w53-pulls-speed-pr' into mainGitoria
  • 80307ae2|||PR pulls page cache: live PR numbers, complete scans onlymre
  • 69141f65|||PR pulls page: cache the git part per repo by branch tipsmre
  • 155861f6Merge branch 'w52-person-approval' into mainGitoria
  • b5435de8|||PR person approvals: second Kunibert round (#52)mre
  • 3a8b2fb8|||PR person approvals: Kunibert review fixes (#52)mre