tracker
All repositories: gitoria
21.3 KB
// tests/security.mjs — THE SECURITY GATE (mission SK, reports/SK-sec.md): real HTTP against a running tracker with a throw-away ident,// two users (alice = the owner and the editor, bob = another user) and anonymous callers. Proves, per area:// headers the files and text answers the app makes itself carry nosniff, images a sandbox policy// authz every face and route for anon / bob / alice: who may, what comes back (the matrix is printed)// faces no peer-sent `session`; ids a peer sends are checked (an episode of THIS show, an adult title nobody follows)// input HTML in every text field of a title / person / genre / season / episode never reaches a page raw; path traversal; the// login's `next=`; wrong types make no 500 that names the source// login cookie flags, a NEW session at login (fixation), a used code is refused, a request budget per caller, logout ends it// secrets no key, secret, token, identity id, session id, absolute path in any page; none in the log// budget the anonymous /person/tmdb/<id> that asks TMDB is capped per hour// On the OLD code (`TRACKER_APP_DIR=<old tree> node tests/security.mjs`) the checks named FIX in their label fail.//// node tests/security.mjs (TRACKER_GATE_PORT 8900, TRACKER_GATE_IDENT_PORT 8901, TRACKER_GATE_TMDB_PORT 8902)import { boot, J, BASE } from './seckit.mjs';let failures = 0, passes = 0;const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + String(detail).slice(0, 400)}`); if (ok) passes++; else failures++; };const SLUG = 'gate-test-show', EP1 = 'ep0000000000ep0e1', EP2 = 'ep0000000000ep0e2', SE1 = 'se000000000se0s1', ADULT = 'adult-gate-movie', MOVIE = 'gate-test-movie';let k;try {k = await boot({ TRACKER_LOGIN_PER_MINUTE: '5', TRACKER_GUEST_FALLBACK_PER_HOUR: '4', TRACKER_IMPORT_PER_HOUR: '3' });const A = k.aliceSession.cookie, B = k.bobSession.cookie;const err = (r) => r.value && r.value.error;const refused = (r) => r.value != null && r.value.error != null;const matrix = [];const face = async (ev, args, who) => { const r = await k.emit(ev, args, who === 'alice' ? A : who === 'bob' ? B : null); matrix.push(`${ev.padEnd(20)} ${who.padEnd(5)} ${r.status} ${(err(r) || (r.value && r.value.ok ? 'ok' : 'data')).slice(0, 50)}`); return r; };// ---- headersconst hdr = async (p, h = {}) => { const r = await k.get(p, null, h); return r; };const img = await hdr('/posters/none'), ph = await hdr('/profiles/none'), bad = await hdr('/posters/a%00.png');check('FIX headers: an image answer carries X-Content-Type-Options: nosniff and a sandbox CSP (a stored svg opened as a page runs nothing)',[img, ph].every(r => r.headers.get('x-content-type-options') === 'nosniff' && /sandbox/.test(r.headers.get('content-security-policy') || '') && /default-src 'none'/.test(r.headers.get('content-security-policy') || '')), J([...img.headers.entries()]));const t404 = await hdr('/nope%3Cscript%3E'), find = await hdr('/find?q=x'), sid = await hdr('/abcde'), moved = await hdr('/unwatched');check('FIX headers: the plain-text answers (404, 301/302 redirects, bad name 400) carry nosniff',[t404, find, sid, moved, bad].every(r => r.headers.get('x-content-type-options') === 'nosniff'), J([t404, find, sid, moved, bad].map(r => r.status + ':' + r.headers.get('x-content-type-options'))));// ---- authz: pagesconst pages = ['/', '/movies', '/series', '/shows', '/genres', '/people', '/settings', '/my/movies', '/my/unwatched', '/my/schedule', '/my/series', '/franchises', '/franchises/edit', '/search/gate', '/series/gate-test-show'];let pageBad = [];for (const p of pages) for (const [n, c] of [['anon', null], ['bob', B], ['alice', A]]) {const r = await k.get(p, c);if (r.status !== 200) pageBad.push(`${p} ${n} ${r.status}`);if (n !== 'alice' && (/Adult Gate Movie/.test(r.body))) pageBad.push(`${p} ${n} shows alice's adult follow`);}check('authz pages: every page answers 200 to anon / bob / alice, and alice\'s followed adult title is on no page of anon or bob', pageBad.length === 0, pageBad.join('; '));const adultPage = await Promise.all([null, B, A].map(c => k.get('/movies/' + ADULT, c)));check('authz: the adult title\'s page names the title for its follower only (anon, bob: not found)', !/Adult Gate Movie/.test(adultPage[0].body) && !/Adult Gate Movie/.test(adultPage[1].body) && /Adult Gate Movie/.test(adultPage[2].body));const mine = await Promise.all([null, B, A].map(c => k.get('/my/unwatched', c)));check('authz: /my/unwatched lists alice\'s unwatched episodes for alice only (anon, bob: none of them)', /Second/.test(mine[2].body) && !/Pilot|Second/.test(mine[0].body) && !/Pilot|Second/.test(mine[1].body), J(mine.map(r => /Second/.test(r.body))));const fe = await Promise.all([null, B, A].map(c => k.get('/franchises/edit', c)));check('authz: the franchise editor page shows its form (fe-create) to the creator only; anon and bob are told "Only the creator"', /id="fe-create"/.test(fe[2].body) && !/id="fe-create"/.test(fe[0].body) && !/id="fe-create"/.test(fe[1].body) && /edit-refused/.test(fe[1].body), J(fe.map(r => [/id="fe-create"/.test(r.body), /edit-refused/.test(r.body)])));// ---- authz: facesconst personal = [['unwatchedToggle', [EP1]], ['showToggleEpisode', [SLUG, EP1, {}, false]], ['showToggleSeason', [SLUG, SE1, {}, false]], ['showToggleMovie', [MOVIE]], ['showToggleFollow', [SLUG]], ['searchImport', ['movie', 5001]]];for (const [ev, args] of personal) {const a = await face(ev, args, 'anon');check(`authz: ${ev} signed out is refused`, refused(a), a.raw);}const editor = [['fedCreateFranchise', ['Gate F', 'x']], ['fedCreateTimeline', ['Gate T']], ['tedSetFranchise', ['t', 'f']], ['tedMove', ['t', 's', 1]], ['tedRemove', ['t', 's']], ['tedAdd', ['t', 's']]];for (const [ev, args] of editor) {const a = await face(ev, args, 'anon'), b = await face(ev, args, 'bob');check(`authz: ${ev} (the creator's) is refused to anon and to another user (bob)`, refused(a) && refused(b) && /only the creator/.test(err(a) + err(b)), J([a.value, b.value]));}const cf = await face('fedCreateFranchise', ['Gate F', 'x'], 'alice');check('authz: the creator (alice) creates a franchise', cf.value && cf.value.ok === true, cf.raw);const pub = [['searchDb', ['gate']], ['showComplete', [SLUG]], ['showSeasonEpisodes', [SE1]], ['fedFindTimelines', ['ga']], ['tedSearch', ['t', 'gate']], ['showRows', [SLUG, {}]]];let pubBad = [];for (const [ev, args] of pub) for (const w of ['anon', 'bob', 'alice']) { const r = await face(ev, args, w); if (r.status !== 200 || refused(r)) pubBad.push(`${ev} ${w}: ${r.raw.slice(0, 80)}`); }check('authz: the public faces (search, title parts, season episodes, timeline finder) answer anon / bob / alice', pubBad.length === 0, pubBad.join('; '));const adultRows = [await face('showRows', [ADULT, {}], 'anon'), await face('showRows', [ADULT, {}], 'bob'), await face('showRows', [ADULT, {}], 'alice')];check('authz: showRows of the adult title: "no such show" for anon and bob, the rows for its follower', refused(adultRows[0]) && refused(adultRows[1]) && adultRows[2].value.ok === true, J(adultRows.map(r => r.value && (r.value.error || 'ok'))));const sc = await face('showSeasonEpisodes', ['nope'], 'bob');check('authz: showSeasonEpisodes of an unknown season is "no such season"', refused(sc));// bob's own dataconst own = [];for (const [ev, args] of [['showToggleEpisode', [SLUG, EP1, {}, false]], ['showToggleSeason', [SLUG, SE1, {}, false]], ['showToggleMovie', [MOVIE]], ['showToggleFollow', [SLUG]], ['unwatchedToggle', [EP2]]]) {const r = await face(ev, args, 'bob'); own.push(r.value && r.value.ok === true);}check('authz: a signed-in user (bob) can toggle his own episode / season / movie / follow / unwatched', own.every(Boolean), J(own));const aliceUnw = await k.get('/my/unwatched', A);check('authz: bob\'s watches did not touch alice\'s lists (alice still has her unwatched "Second")', /Second/.test(aliceUnw.body));// ---- faces: a peer's session / idsconst inj = await k.emit('showToggleFollow', [SLUG, { user: { id: 'gateu0000000000u1' } }], null);const inj2 = await k.emit('fedCreateFranchise', ['Inj', 'x', { user: { id: 'gateu0000000000u1' } }], B);check('faces: a `session` sent by the peer is refused (anonymous and bob cannot become alice by sending her user)', /never by the peer/.test(inj.raw) && /never by the peer/.test(inj2.raw), inj.raw + inj2.raw);const junk = await face('unwatchedToggle', ['junk-not-an-episode'], 'bob');check('FIX faces: unwatchedToggle with text that is no episode is refused (it stored a watch row for any text)', refused(junk), J(junk.value));const junk2 = await face('unwatchedToggle', [{ a: 1 }], 'bob');check('FIX faces: unwatchedToggle with an object is refused', refused(junk2) && junk2.status === 200, junk2.raw);const otherShow = await face('showToggleEpisode', ['unwatched-gate-show', EP1, {}, false], 'bob');check('FIX faces: showToggleEpisode with an episode of ANOTHER show is refused', refused(otherShow), J(otherShow.value));const otherSeason = await face('showToggleSeason', ['unwatched-gate-show', SE1, {}, false], 'bob');check('FIX faces: showToggleSeason with a season of ANOTHER show is refused', refused(otherSeason), J(otherSeason.value));const junk3 = await face('showToggleEpisode', [SLUG, 'junk', {}, false], 'bob');check('FIX faces: showToggleEpisode with text that is no episode is refused', refused(junk3), J(junk3.value));const bobFollowAdult = await face('showToggleFollow', [ADULT], 'bob');const bobSees = await k.get('/movies/' + ADULT, B);check('FIX faces: bob cannot follow alice\'s adult title by its slug (that opened the title\'s page to anyone who guessed it)', refused(bobFollowAdult) && !/Adult Gate Movie/.test(bobSees.body), J(bobFollowAdult.value) + bobSees.body.length);const bobUnwAdult = await face('unwatchedToggle', ['ad00000000epfl'], 'bob');const bobEpAdult = await face('showToggleEpisode', [ADULT, EP1, {}, false], 'bob');check('faces: the adult title\'s faces answer "no such …" to bob', refused(bobEpAdult), J(bobEpAdult.value));const aliceUnfollow = await face('showToggleFollow', [ADULT], 'alice');check('faces: alice (the follower) can unfollow her adult title', aliceUnfollow.value && aliceUnfollow.value.ok === true && aliceUnfollow.value.following === false, J(aliceUnfollow.value));const aliceAgain = await face('showToggleFollow', [ADULT], 'alice');check('faces: after her unfollow the title is hidden from alice too — she cannot follow it again by slug', refused(aliceAgain), J(aliceAgain.value));// ---- imports: a budget per user, a type check on the idconst imp = [];for (let i = 0; i < 5; i++) { const r = await k.emit('searchImport', ['movie', 5001], B); imp.push(r.value && r.value.ok === true ? 'ok' : (err(r) || 'none').slice(0, 20)); }const impAlice = await k.emit('searchImport', ['movie', 5001], A);const impObj = await k.emit('searchImport', ['movie', { a: 1 }], A);check('FIX imports: a signed-in user\'s imports are budgeted (TRACKER_IMPORT_PER_HOUR=3): 3 pass, the rest "too many imports"; another user (alice) is not held back by bob\'s', imp.slice(0, 3).every(x => x === 'ok') && imp.slice(3).every(x => /too many imports/.test(x)) && impAlice.value.ok === true, J(imp) + J(impAlice.value));check('FIX imports: a TMDB id that is neither a number nor text is refused without a 500', impObj.status === 200 && refused(impObj), impObj.raw);// ---- input: wrong types make no 500const obj = { a: 1 };const typed = [['showComplete', [obj]], ['searchDb', [obj]], ['searchDb', [[1]]], ['searchWeb', [obj]], ['personFill', [obj]], ['fedFindTimelines', [obj]], ['tedSearch', ['t', obj]]];let t500 = [];for (const [ev, args] of typed) { const r = await k.emit(ev, args, B); if (r.status !== 200 || /\.hl:\d/.test(r.raw)) t500.push(`${ev} ${r.status} ${r.raw.slice(0, 90).replace(/\n/g, ' ')}`); }check('FIX input: a list or an object where a face wants text is answered without a 500 that names the source file and line', t500.length === 0, t500.join(' | '));// ---- input: HTML in every text fieldconst evilPages = ['/series/xss-title', '/person/xss-person', '/genres/xss-genre', '/series', '/people', '/genres', '/search/xss', '/search/%3Cimg%20src%3Dx%20onerror%3D1%3E', '/movies/%3Cimg%20src%3Dx%3E'];let raw = [];for (const p of evilPages) { const r = await k.get(p, null); const b = r.body;if (/<img src=x onerror|<svg onload|<\/script><img|"><img src=x|href="javascript:/i.test(b)) raw.push(p); }check('input: HTML / script in a title, summary, tagline, cast, season, episode, person, genre and in the path never reaches a page raw (title page, person, genre, lists, search)', raw.length === 0, raw.join(' '));const links = (await k.get('/series/xss-title')).body;check('input: a stored homepage javascript: URL is not a link on the title page (external links are built from ids on fixed hosts)', !/javascript:/i.test(links.replace(/<script[\s\S]*?<\/script>/g, '')));const trav = ['/posters/..%2f..%2f.env', '/posters/%2e%2e/x', '/posters/a%00.png', '/profiles/..%5c..%5cx', '/posters/%2fetc%2fpasswd', '/__hl/../project.hl', '/%2e%2e/%2e%2e/etc/passwd', '/project.hl', '/.env', '/storage/mpackdb/users.db', '/lib/users.hl', '/tests/seckit.mjs'];let travBad = [];for (const p of trav) { const r = await k.get(p, null); if (r.status === 200 || /root:|TRACKER_SECRET|static identSecret/.test(r.body)) travBad.push(p + ' ' + r.status); }check('input: path traversal in /posters, /profiles and the source/data paths: never a 200, never file content', travBad.length === 0, travBad.join(' '));let nextBad = [];for (const nx of ['//evil.com', '/\\evil.com', 'https://evil.com', 'javascript:alert(1)', '/login/x', '/a%0d%0aSet-Cookie:%20x=1', '/a b']) {const code = await k.ident.selectorCode(k.alice, k.app, BASE);const r = await fetch(BASE + '/login/callback?ident_code=' + code + '&next=' + nx, { redirect: 'manual', headers: { 'x-client-ip': '10.1.1.' + nextBad.length + Math.floor(Math.random() * 99) } });const loc = r.headers.get('location') || '';if (!(loc === '/' || /^\/[A-Za-z0-9\-._~\/?&=%+,;@!$()*:]*$/.test(loc)) || /[\r\n]/.test(loc) || r.headers.get('x-evil') || /^x=1/.test(r.headers.get('set-cookie') || '')) nextBad.push(nx + ' → ' + loc);}check('input: the login\'s ?next= goes only to a same-site path (no //host, no scheme, no CR/LF)', nextBad.length === 0, nextBad.join(' | '));const f1 = await k.get('/find?q=a%0d%0aX-Evil:1'), f2 = await k.get('/find?q=%2F%2Fevil.com');check('input: /find?q= with CR/LF or // is a /search/<encoded> redirect, no header injection', f1.status === 302 && !f1.headers.get('x-evil') && /^\/search\/[^\r\n]*$/.test(f1.headers.get('location')) && /^\/search\//.test(f2.headers.get('location')), f1.headers.get('location') + ' ' + f2.headers.get('location'));// ---- login / session// RV28 (tracker#50): a visitor WITHOUT a cookie gets no session, no file and no cookie, on the start page and on an unknown /shows/ slugconst anon1 = await fetch(BASE + '/', { redirect: 'manual' }), anon2 = await fetch(BASE + '/shows/no-such-slug-rv28', { redirect: 'manual' });check('sessions: a request without a cookie sets no cookie (start page and unknown /shows/ slug) — no session file for bots (tracker#50)', !anon1.headers.get('set-cookie') && !anon2.headers.get('set-cookie') && anon2.status === 200, `${anon1.headers.get('set-cookie')} | ${anon2.status} ${anon2.headers.get('set-cookie')}`);// a session that gets something stored (here the reason of a failed login) gets its cookieconst fresh = await fetch(BASE + '/login/callback?ident_code=', { redirect: 'manual', headers: { 'x-client-ip': '10.2.2.1' } });const sc0 = fresh.headers.get('set-cookie') || '';check('login: the session cookie is HttpOnly, SameSite=Lax, path /, 14 days (Secure is hl:web\'s gap, recorded)', /^trackersid=[0-9a-f]{32};/.test(sc0) && /HttpOnly/.test(sc0) && /SameSite=Lax/.test(sc0) && /Path=\//.test(sc0), sc0);const planted = sc0.split(';')[0];const lg = await k.login(k.bob, { 'x-client-ip': '10.2.2.2' }, planted);const stillPlanted = await k.emit('showToggleFollow', [SLUG], planted);check('FIX login: a login brings a NEW session — the session id planted in the browser before it (fixation) stays signed out', lg.cookie != null && lg.cookie !== planted && refused(stillPlanted), `${lg.cookie} vs ${planted} / ${J(stillPlanted.value)}`);const fixedNew = await k.emit('showToggleFollow', [SLUG], lg.cookie);check('login: the new session is signed in as bob', fixedNew.value && fixedNew.value.ok === true, fixedNew.raw);const code = await k.ident.selectorCode(k.alice, k.app, BASE);await fetch(BASE + '/login/callback?ident_code=' + code, { redirect: 'manual', headers: { 'x-client-ip': '10.2.2.3' } });const replay = await fetch(BASE + '/login/callback?ident_code=' + code, { redirect: 'manual', headers: { 'x-client-ip': '10.2.2.3' } });check('login: a used login code cannot be used again', replay.headers.get('location') === '/login/failed');const post = await fetch(BASE + '/login/callback?ident_code=' + code, { method: 'POST', redirect: 'manual', headers: { 'x-client-ip': '10.2.2.4' } });check('login: the callback answers GET only (a POST is a failed login, no session)', post.headers.get('location') === '/login/failed');// the budgetconst stat = [];let lastCookie = null;for (let i = 0; i < 9; i++) {const r = await fetch(BASE + '/login/callback?ident_code=' + 'ab'.repeat(24), { redirect: 'manual', headers: { 'x-client-ip': '10.3.3.3' } });const ck = (r.headers.get('set-cookie') || '').split(';')[0] || lastCookie; lastCookie = ck;const page = await fetch(BASE + '/login/failed', { headers: { cookie: ck } }); const txt = await page.text();stat.push(/too many login attempts/.test(txt) ? 'limited' : 'tried');}check('FIX login: more than 5 tries a minute from one address (TRACKER_LOGIN_PER_MINUTE=5) are refused without asking ident — "too many login attempts"', stat.slice(0, 5).every(s => s === 'tried') && stat.slice(6).every(s => s === 'limited'), stat.join(','));const other = await k.login(k.alice, { 'x-client-ip': '10.3.3.4' });check('login: another address is not held back by it, and the real login works', other.cookie != null && other.location === '/', J(other));const faceStat = [];for (let i = 0; i < 8; i++) { const r = await k.emit('trackerLogin', ['ab'.repeat(24)], other.cookie); faceStat.push(/too many/.test(err(r) || '') ? 'limited' : 'tried'); }check('FIX login: the header selector\'s face trackerLogin is budgeted per session too (5 tries a minute)', faceStat.slice(0, 5).every(s => s === 'tried') && faceStat.slice(6).every(s => s === 'limited'), faceStat.join(','));// logoutconst al = await k.login(k.alice, { 'x-client-ip': '10.4.4.4' });const pre = await k.emit('showToggleFollow', [SLUG], al.cookie);const lo = await k.emit('trackerLogOut', [], al.cookie);const post2 = await k.emit('showToggleFollow', [SLUG], al.cookie);const pg = await k.get('/my/series', al.cookie);check('login: logout ends the session — the same cookie is signed out afterwards (face refused, /my page empty)', pre.value.ok === true && lo.value.ok === true && refused(post2) && !/Gate Test Show/.test(pg.body), J([pre.value, lo.value, post2.value]));// ---- secretsconst secrets = { identSecret: k.app.secret, aliceIdentity: k.aliceIdentity, bobIdentity: k.bobIdentity, tmdbToken: 'gate-token', aliceCookie: A.split('=')[1], bobCookie: B.split('=')[1] };let leaks = [];for (const p of ['/', '/settings', '/my/movies', '/my/series', '/my/unwatched', '/series/gate-test-show', '/movies/' + ADULT, '/franchises/edit', '/login/failed', '/search/gate', '/person/Test-Actor', '/components/main.hl', '/components/show.hl', '/__hl/app.css', '/__hl/sw.js', '/__hl/manifest.webmanifest', '/login.js']) {for (const c of [null, A, B]) {const r = await k.get(p, c);for (const [n, v] of Object.entries(secrets)) if (r.body.includes(v)) leaks.push(`${p}:${n}`);if (/sk_[0-9a-f]{20}/.test(r.body) || /\/media\/|\/home\//.test(r.body)) leaks.push(`${p}:key-or-path`);}}check('secrets: no app secret, TMDB token, identity id (any user\'s), session id or absolute path in any page, component module or asset (the public ident key pk_… is in the login link by design)', leaks.length === 0, leaks.join(' '));const log = k.logs.server;check('secrets: none of them in the server log either', Object.entries(secrets).every(([, v]) => !log.includes(v)));// ---- budget: the anonymous TMDB-asking guest linkconst before = k.tmdb.personRequests.length;for (let i = 0; i < 10; i++) await fetch(BASE + '/person/tmdb/' + (700 + i), { redirect: 'manual' });const asked = k.tmdb.personRequests.length - before;check('FIX budget: an anonymous GET /person/tmdb/<id> without ?show= asks TMDB — at most 4 an hour in all (TRACKER_GUEST_FALLBACK_PER_HOUR=4), not one per request', asked > 0 && asked <= 4, `asked TMDB ${asked} times for 10 requests`);console.log('\n--- face matrix (who, status, answer)\n' + matrix.join('\n'));check('the server did not crash or panic through all of it', !/panic|SIGSEGV|Segmentation/i.test(log), log.slice(-300));} catch (e) {check('no exception', false, String(e && e.stack || e));} finally {if (k) await k.stop();}console.log(`\n${passes} passed, ${failures} failed`);process.exit(failures ? 1 : 0);
Branches
Latest commits
- d2e6d26bMerge branch 'records-park55' into mainTracker
- f567f025|||PR records: park #55, no Claude workers ruleTracker
- c21aff6bMerge branch 'records-hm55c' into mainTracker
- 9ba258d3|||PR records: HM55b resultTracker
- 64f2d300Merge branch 'records-hm55b2' into mainTracker
- ae3b80dc|||PR records: HM55b briefTracker
- 7ef3cb3bMerge branch 'records-st55' into mainTracker
- fec2e080|||PR records: STATUS HM55Tracker
- 8e174918Merge branch 'records-hm55b' into mainTracker
- b1ecee57|||PR records: HM55 stateTracker
- 28eab08cMerge branch 'records-hm55' into mainTracker
- d3edaa05|||PR records: HM55 start, PROCEDURES.mdTracker
- 3059f86cMerge branch 'records-design-rule' into mainTracker
- 421a4809|||PR records: his-design rule (Apollo 2026-11-13)Tracker
- d1390692Merge branch 'records-dp75b' into mainTracker
- a4d1a7d2|||PR records: later steps checked, branch auditTracker
- e070e16fMerge branch 'records-dp75' into mainTracker
- 642b4fa8|||PR records: DP75 day62 live, AP62 briefTracker
- bfc4ea4dMerge branch 'ap62' into mainTracker
- 2c95ac46|||PR AP62: re-vendor Hybriel set day62 (source 70341ad2, bin a54f5f08)Tracker