gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commita4887ea3a4887ea3ident#47: the selector's sign-in frame no longer has a Continue button; the identity row itself is the link (gate tests/signin.mjs fails on the old code)mrea4887ea3/tests/iplimit.mjs

17.4 KB

  1. // tests/iplimit.mjs — THE PER-IP LIMIT GATE (mission 010). Starts its OWN servers (never
  2. // the dev server on :8351, mail only into sink files):
  3. // ident :8400 HL_HOST=127.0.0.1 (loopback only, as on Byrodin), IP limit 3 / 10 min,
  4. // day limit 1000; storage .scratch/iplimit-gate/main
  5. // ident :8401 short clocks: IP window 2 s, IP limit 3, day limit 5 (the long window)
  6. // and TWO real headless Chromes (debug ports 8720-8729 / 8730-8739, --disable-gpu, killed
  7. // by PID) that carry an X-Client-IP header each (CDP Network.setExtraHTTPHeaders) — what
  8. // nginx adds on Byrodin.
  9. //
  10. // node tests/iplimit.mjs
  11. //
  12. // Covers: POST /api/code per IP (two IPs via the header: the limit hits one, not the
  13. // other), X-Forwarded-For / CF-Connecting-IP / X-Real-IP never change the bucket, no
  14. // header = ONE shared bucket, IPv6 by /64, IPv4-mapped IPv6 = IPv4, the per-address limit
  15. // still applies across IPs, refused codes are not mailed, the old face `requestCode` is
  16. // gone, strict body / 405, the long (day) window and the short window's expiry, the
  17. // loopback bind (not reachable on the LAN address), and in real browsers: the refusal is
  18. // visible on the page, the other browser (other IP) still signs in.
  19. // Screenshots: .scratch/iplimit-*.png — look. Server logs: .scratch/iplimit-gate/*.log
  20. import { spawn } from 'node:child_process';
  21. import { rmSync, mkdirSync, writeFileSync, existsSync, readFileSync } from 'node:fs';
  22. import { dirname, join, resolve } from 'node:path';
  23. import { fileURLToPath } from 'node:url';
  24. import { networkInterfaces } from 'node:os';
  25. import { launchBrowser } from './cdp.mjs';
  26. // H2: a server-rendered page can be clicked before the client mounted — the click is lost (or a native form GET). Every goto() on a Hybriel
  27. // page (the SSR HTML carries #hl-seed) therefore waits until the page is live (socket open) before the test touches it.
  28. function live(page) {
  29. const goto = page.goto.bind(page);
  30. page.goto = async (url, o) => {
  31. const r = await goto(url, o);
  32. await page.waitFor("!document.getElementById('hl-seed') || (!!window.__hl && !!window.__hl.socket && window.__hl.socket.readyState === 1)", { label: 'page hydrated ' + url });
  33. return r;
  34. };
  35. return page;
  36. }
  37. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  38. const HERE = dirname(fileURLToPath(import.meta.url));
  39. const APP = resolve(HERE, '..');
  40. const BIN = join(APP, 'bin/hybriel');
  41. const SCRATCH = join(APP, '.scratch');
  42. const G = join(SCRATCH, 'iplimit-gate');
  43. rmSync(G, { recursive: true, force: true });
  44. mkdirSync(G, { recursive: true });
  45. const P_MAIN = Number(process.env.IPLIMIT_GATE_PORT || 8400), P_SHORT = P_MAIN + 1; // ident main = P, ident short = P+1; Chrome IPLIMIT_GATE_CHROME_A / _B
  46. const ID = `http://127.0.0.1:${P_MAIN}`;
  47. const IDS = `http://127.0.0.1:${P_SHORT}`;
  48. const SINK = join(G, 'main-mail.txt'), SINK_S = join(G, 'short-mail.txt');
  49. let failures = 0, passes = 0;
  50. function check(label, ok, detail = '') {
  51. console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`);
  52. if (ok) passes++; else failures++;
  53. }
  54. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  55. const J = JSON.stringify;
  56. const procs = [];
  57. function start(name, env) {
  58. let log = '';
  59. const p = spawn(BIN, ['project.hl'], { cwd: APP, env: { ...process.env, SMTP_HOST: '', SMTP_USER: '', SMTP_PASSWORD: '', ...env }, stdio: ['ignore', 'pipe', 'pipe'] });
  60. p.stdout.on('data', d => log += d); p.stderr.on('data', d => log += d);
  61. p.on('exit', () => writeFileSync(join(G, `${name}.log`), log));
  62. procs.push({ name, p, log: () => log });
  63. return p;
  64. }
  65. start('main', { IDENT_PORT: String(P_MAIN), HL_HOST: '127.0.0.1', IDENT_STORAGE: join(G, 'main'), IDENT_SESSIONS: join(G, 'main-sess') + '/', IDENT_MAIL_SINK: SINK, IDENT_IP_LIMIT: '3', IDENT_IP_DAY_LIMIT: '1000' });
  66. start('short', { IDENT_PORT: String(P_SHORT), IDENT_STORAGE: join(G, 'short'), IDENT_SESSIONS: join(G, 'short-sess') + '/', IDENT_MAIL_SINK: SINK_S, IDENT_IP_LIMIT: '3', IDENT_IP_WINDOW_MS: '2000', IDENT_IP_DAY_LIMIT: '5' });
  67. function mails(sink, email) {
  68. if (!existsSync(sink)) return [];
  69. return readFileSync(sink, 'utf8').split('\n').filter(l => l.startsWith(email + ' ')).map(l => l.split(' ')[1]);
  70. }
  71. const mailCount = (sink) => existsSync(sink) ? readFileSync(sink, 'utf8').split('\n').filter(Boolean).length : 0;
  72. // POST /api/code as a client behind nginx would arrive: `headers` are the extra ones
  73. async function code(base, email, headers = {}, raw = null) {
  74. const r = await fetch(base + '/api/code', { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: raw !== null ? raw : J({ email }) });
  75. const t = await r.text();
  76. let j = null; try { j = JSON.parse(t); } catch {}
  77. return { status: r.status, j, t };
  78. }
  79. const IPMSG = 'too many codes were requested from your network — wait a while and try again';
  80. const limited = (r) => r.status === 429 && r.j && r.j.error === IPMSG;
  81. const connected = (page, label) => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label });
  82. async function viewport(page, width, height) {
  83. await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 });
  84. await sleep(250);
  85. }
  86. async function shot(page, name) {
  87. const { data } = await page.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  88. writeFileSync(join(SCRATCH, `iplimit-${name}.png`), Buffer.from(data, 'base64'));
  89. }
  90. const noOverflow = (page) => page.evaluate('document.documentElement.scrollWidth <= window.innerWidth');
  91. async function askCode(page, email) {
  92. await page.waitForSelector('#email');
  93. await connected(page, 'socket before asking');
  94. await page.type('#email', email, { clear: true });
  95. await page.evaluate('document.querySelector("#message").textContent = ""');
  96. await page.click('#sendcode');
  97. // ident#20: a sent code navigates to the code page (/code) — wait for it to hydrate
  98. await page.waitFor('(/\\/code$/.test(location.pathname) && !!document.querySelector("#code")) || /\\S/.test(document.querySelector("#message").textContent)', { label: 'code page or message after ' + email });
  99. if (await page.evaluate('/\\/code$/.test(location.pathname)')) await connected(page, 'code page hydrated');
  100. }
  101. let A, B, a, b;
  102. try {
  103. for (const [name, url] of [['main', ID + '/'], ['short', IDS + '/']]) {
  104. let up = false;
  105. for (let i = 0; i < 80; i++) { try { const r = await fetch(url); if (r.ok) { up = true; break; } } catch {} await sleep(250); }
  106. if (!up) throw new Error(`${name} server did not come up\n` + procs.find(p => p.name === name).log());
  107. }
  108. // ---- the loopback bind (HL_HOST=127.0.0.1, as on Byrodin) ------------------------------
  109. const lan = Object.values(networkInterfaces()).flat().find(i => i && i.family === 'IPv4' && !i.internal);
  110. let lanReach = 'no LAN address';
  111. if (lan) { try { const r = await fetch(`http://${lan.address}:${P_MAIN}/`, { signal: AbortSignal.timeout(2000) }); lanReach = 'answered ' + r.status; } catch (e) { lanReach = 'refused'; } }
  112. check(`bind: HL_HOST=127.0.0.1 → not reachable on the LAN address (${lan && lan.address})`, lanReach === 'refused', lanReach);
  113. let lanShort = 'no LAN address';
  114. if (lan) { try { const r = await fetch(`http://${lan.address}:${P_SHORT}/`, { signal: AbortSignal.timeout(2000) }); lanShort = 'answered ' + r.status; } catch (e) { lanShort = 'refused'; } }
  115. check('bind: without HL_HOST → 0.0.0.0 as before (the LAN address answers 200)', lanShort === 'answered 200', lanShort);
  116. // ---- two IPs via the header: the limit hits one, not the other --------------------------
  117. let r;
  118. for (const n of [1, 2, 3]) {
  119. r = await code(ID, `x${n}@example.org`, { 'X-Client-IP': '203.0.113.7' });
  120. check(`ip 203.0.113.7: code ${n} of 3 → 200, mailed`, r.status === 200 && r.j.email === `x${n}@example.org` && mails(SINK, `x${n}@example.org`).length === 1, r.t);
  121. }
  122. r = await code(ID, '[email protected]', { 'X-Client-IP': '203.0.113.7' });
  123. check('ip 203.0.113.7: the 4th code (another address) → 429 with the reason, NOT mailed', limited(r) && mails(SINK, '[email protected]').length === 0, r.t);
  124. r = await code(ID, '[email protected]', { 'X-Client-IP': '198.51.100.9' });
  125. check('ip 198.51.100.9: the same address from another IP → 200, mailed', r.status === 200 && mails(SINK, '[email protected]').length === 1, r.t);
  126. // ---- the header cannot be bypassed with another IP header -------------------------------
  127. const before = mailCount(SINK);
  128. r = await code(ID, '[email protected]', { 'X-Client-IP': '203.0.113.7', 'X-Forwarded-For': '192.0.2.1', 'CF-Connecting-IP': '192.0.2.2', 'X-Real-IP': '192.0.2.3', 'Forwarded': 'for=192.0.2.4' });
  129. check('bypass: X-Forwarded-For / CF-Connecting-IP / X-Real-IP / Forwarded beside X-Client-IP → still 429', limited(r), r.t);
  130. r = await code(ID, '[email protected]', { 'x-client-ip': '203.0.113.7' });
  131. check('bypass: the header in lower case is the same header → 429', limited(r), r.t);
  132. r = await code(ID, '[email protected]', { 'X-Client-IP': ' 203.0.113.7 ' });
  133. check('bypass: surrounding blanks are trimmed → 429', limited(r), r.t);
  134. check('bypass: nothing was mailed by the refused requests', mailCount(SINK) === before, String(mailCount(SINK) - before));
  135. // ---- no X-Client-IP (dev, no nginx): ONE shared bucket, other headers ignored ----------
  136. const direct = [];
  137. for (const [n, fwd] of [[1, '192.0.2.11'], [2, '192.0.2.12'], [3, '192.0.2.13'], [4, '192.0.2.14']]) {
  138. direct.push(await code(ID, `d${n}@example.org`, { 'X-Forwarded-For': fwd, 'CF-Connecting-IP': fwd }));
  139. }
  140. check('no header: 3 codes pass, each with a different X-Forwarded-For / CF-Connecting-IP', direct.slice(0, 3).every(x => x.status === 200), J(direct.slice(0, 3).map(x => x.status)));
  141. check('no header: the 4th → 429 (one shared bucket; the forwarded headers do not split it)', limited(direct[3]) && mails(SINK, '[email protected]').length === 0, direct[3].t);
  142. r = await code(ID, '[email protected]', { 'X-Client-IP': '' });
  143. check('an EMPTY X-Client-IP counts as no header (shared bucket) → 429', limited(r), r.t);
  144. // ---- IPv6: one bucket per /64; IPv4-mapped = the IPv4 address ------------------------
  145. const v6 = [];
  146. for (const [n, ip] of [[1, '2001:db8:aa:1::1'], [2, '2001:0DB8:00AA:0001:ffff::2'], [3, '2001:db8:aa:1:1:2:3:4'], [4, '2001:db8:aa:1::99']]) {
  147. v6.push(await code(ID, `v${n}@example.org`, { 'X-Client-IP': ip }));
  148. }
  149. check('ipv6: 3 addresses of one /64 (written differently) pass', v6.slice(0, 3).every(x => x.status === 200), J(v6.map(x => x.status)));
  150. check('ipv6: a 4th address of the same /64 → 429', limited(v6[3]), v6[3].t);
  151. r = await code(ID, '[email protected]', { 'X-Client-IP': '2001:db8:aa:2::1' });
  152. check('ipv6: the next /64 is another bucket → 200', r.status === 200, r.t);
  153. r = await code(ID, '[email protected]', { 'X-Client-IP': '::ffff:203.0.113.7' });
  154. check('ipv4-mapped ipv6 ::ffff:203.0.113.7 = 203.0.113.7 → 429', limited(r), r.t);
  155. // ---- the per-address limit still applies (3 per address, across IPs) --------------------
  156. const per = [];
  157. for (const n of [1, 2, 3, 4]) per.push(await code(ID, '[email protected]', { 'X-Client-IP': `198.18.0.${n}` }));
  158. check('per address: 3 codes to one address from 3 IPs pass', per.slice(0, 3).every(x => x.status === 200), J(per.map(x => x.status)));
  159. check('per address: the 4th from a 4th IP → 429 "sent to this address", mailed 3 times', per[3].status === 429 && /too many codes were sent to this address/.test(per[3].j.error) && mails(SINK, '[email protected]').length === 3, per[3].t);
  160. // ---- the route itself ---------------------------------------------------------------
  161. r = await fetch(ID + '/api/code');
  162. check('GET /api/code → 405', r.status === 405, String(r.status));
  163. r = await code(ID, null, { 'X-Client-IP': '198.19.0.1' }, '{"email":"[email protected]","ip":"1.2.3.4"}');
  164. check('strict body: an unknown field (ip) → 400 naming it', r.status === 400 && r.j.error === 'unknown field: ip', r.t);
  165. r = await code(ID, null, { 'X-Client-IP': '198.19.0.1' }, '{bad');
  166. check('invalid JSON → 400, no source path', r.status === 400 && /not valid JSON/.test(r.j.error) && !/\.hl/.test(r.t), r.t);
  167. r = await code(ID, 'not-an-address', { 'X-Client-IP': '198.19.0.1' });
  168. check('not an address → 400', r.status === 400 && r.j.error === 'that is not an email address', r.t);
  169. const fr = await fetch(ID + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ t: 'emit', i: 1, event: 'requestCode', payload: ['[email protected]'] }) });
  170. const fj = await fr.json();
  171. check('the old face requestCode is gone (no handler), nothing mailed', fj.ok === false && /no class/.test(fj.error || '') && mails(SINK, '[email protected]').length === 0, J(fj));
  172. // ---- the long window (day limit 5) and the short window's expiry (2 s) ------------------
  173. const s = [];
  174. for (const n of [1, 2, 3, 4]) s.push(await code(IDS, `s${n}@example.org`, { 'X-Client-IP': '192.0.2.50' }));
  175. check('short server: 3 pass, the 4th in the window → 429', s.slice(0, 3).every(x => x.status === 200) && limited(s[3]), J(s.map(x => x.status)));
  176. await sleep(2200);
  177. const s2 = [await code(IDS, '[email protected]', { 'X-Client-IP': '192.0.2.50' }), await code(IDS, '[email protected]', { 'X-Client-IP': '192.0.2.50' })];
  178. check('short server: after the 2 s window 2 more pass (5 in the long window)', s2.every(x => x.status === 200), J(s2.map(x => x.status)));
  179. await sleep(2200);
  180. r = await code(IDS, '[email protected]', { 'X-Client-IP': '192.0.2.50' });
  181. check('short server: the short window is free again, but the day limit (5) → 429, not mailed', limited(r) && mails(SINK_S, '[email protected]').length === 0, r.t);
  182. r = await code(IDS, '[email protected]', { 'X-Client-IP': '192.0.2.51' });
  183. check('short server: another IP is unaffected → 200', r.status === 200, r.t);
  184. // ---- real browsers: one IP each (nginx's header, set per browser) ----------------------
  185. A = await launchBrowser({ debugPortRange: (process.env.IPLIMIT_GATE_CHROME_A || '8720-8729').split('-').map(Number) });
  186. B = await launchBrowser({ debugPortRange: (process.env.IPLIMIT_GATE_CHROME_B || '8730-8739').split('-').map(Number) });
  187. a = live(await A.newPage());
  188. b = live(await B.newPage());
  189. for (const [pg, ip] of [[a, '100.64.0.1'], [b, '100.64.0.2']]) {
  190. await pg.send('Network.enable');
  191. await pg.send('Network.setExtraHTTPHeaders', { headers: { 'X-Client-IP': ip } });
  192. }
  193. await a.goto(ID + '/');
  194. for (const n of [1, 2, 3]) {
  195. await askCode(a, `ba${n}@example.org`);
  196. const ok = await a.evaluate('!!document.querySelector("#code")');
  197. check(`browser A (100.64.0.1): code ${n} → the code form, mailed`, ok && mails(SINK, `ba${n}@example.org`).length === 1, await a.text('#message'));
  198. await a.click('#back');
  199. await a.waitForSelector('#email');
  200. }
  201. await askCode(a, '[email protected]');
  202. const shown = await a.text('#message');
  203. check('browser A: the 4th → the refusal is VISIBLE on the page, still on the email form, not mailed', shown === IPMSG && await a.evaluate('!!document.querySelector("#emailform") && !document.querySelector("#code")') && mails(SINK, '[email protected]').length === 0, shown);
  204. await viewport(a, 390, 844); await shot(a, 'refused-390');
  205. check('layout: 390px refusal has no horizontal overflow', await noOverflow(a));
  206. await viewport(a, 1280, 900); await shot(a, 'refused-1280');
  207. check('layout: 1280px refusal has no horizontal overflow', await noOverflow(a));
  208. await b.goto(ID + '/');
  209. await askCode(b, '[email protected]');
  210. check('browser B (100.64.0.2): the same moment, another IP → the code form', await b.evaluate('!!document.querySelector("#code")'), await b.text('#message'));
  211. const bc = mails(SINK, '[email protected]').at(-1);
  212. await b.type('#code', bc, { clear: true });
  213. await b.click('#verify');
  214. // first login: the sign-in patch shows the identities list a moment BEFORE the welcome form (signedIn/manage arrive before
  215. // editing/welcome in the page's patch stream), so waiting for "#identityform || #identities" raced the welcome form — wait for the form itself
  216. await b.waitFor('!!document.querySelector("#welcome") && !!document.querySelector("#whoami")', { label: 'B signed in: the welcome form' });
  217. check('browser B: the code signs in (first login: the welcome form)', await b.evaluate('!!document.querySelector("#welcome")') && (await b.text('#whoami')) === '[email protected]', await b.text('#message'));
  218. await b.goto(ID + '/');
  219. await b.waitForSelector('#identities');
  220. check('browser B: reload keeps the session (identsid cookie over the pinned listener)', (await b.text('#whoami')) === '[email protected]');
  221. // the refused fetch is a 429: Chrome logs "Failed to load resource … 429" — expected
  222. const expected = /favicon|status of 429 .*\/api\/code$/;
  223. const problems = [...a.problems(), ...b.problems()].filter(m => !expected.test(m.text));
  224. check('browsers: no console errors or warnings (besides the expected 429 line)', problems.length === 0, J(problems.slice(0, 5)));
  225. } catch (e) {
  226. failures++;
  227. console.log('FAIL (aborted) ' + (e && e.stack || e));
  228. for (const [n, pg] of [['A', a], ['B', b]]) if (pg) console.log(`console ${n}: ` + J(pg.messages.slice(-8)));
  229. } finally {
  230. for (const br of [A, B]) { if (br) { try { await br.close(); } catch {} } }
  231. for (const { p } of procs) { try { p.kill('SIGTERM'); } catch {} }
  232. await sleep(500);
  233. for (const { p } of procs) { if (p.exitCode === null && p.signalCode === null) { try { p.kill('SIGKILL'); } catch {} } }
  234. await sleep(200);
  235. console.log(`\n${passes} passed, ${failures} failed`);
  236. process.exit(failures ? 1 : 0);
  237. }

Branches

Latest commits

  • a4887ea3ident#47: the selector's sign-in frame no longer has a Continue button; the identity row itself is the link (gate tests/signin.mjs fails on the old code)mre
  • d8ec703dident#45: /docs shows docs/IDENT.md (hl:markdown, vendored from ac1ed9da), one Docs entry in the main menu, README for developers only, gates tests/docs.mjs and tests/sessionwrites.mjs in deploy.shmre
  • ec6aad35Merge branch 'a28g-amp-callsites' into d45-docsmre
  • 6bfbd3f2ident#45: docs/IDENT.md, what ident is and how it works; CONCEPT.md marks one id per app as droppedmre
  • c0edca26ident#28 A28G: write & at every call that hands a session to an &-parameter; gate tests/sessionwrites.mjs pins that sign-in, pending address, embed sign-in and selector land in the session filesmre
  • 80965c08ident#28: README says the deploy goes through the standbymre
  • 2f41670cident#28: ident-standby service on port 45012 (no background round in the standby) and deploy.sh hands over through standby-swap.shmre
  • a544b261ident#28: README names the new vendored Hybrielmre
  • 716860b0ident#28: gates follow Hybriel ac1ed9da (lazy sessions, meta attribute order, JSON key order, default X-Frame-Options switched off for the embed page)mre
  • 889e00fbident#28: Hybriel master ac1ed9da (sessions reload a newer file, a replayed reconnect carries the server session); a startup fault exits 1 (on Error)mre
  • f5a55f8aident#11: apps can ask for nickname, firstname and lastname (fields list on /api/exchange, new POST /api/profile); empty fields come back null; gate checks, READMEmre
  • d8be66ebident: report and log line for the widget cache and frame height changemre
  • 2068f61aident#31: browsers revalidate the widget scripts on every load; the sign-in frame is exactly as tall as the current step (the frame page reports its height, selector.js accepts it from ident only)mre
  • a22d2daaident#31: the sign-in frame is no taller than the tallest step needs (plain CSS height per width), gate check for itmre
  • a77d1b22ident#31: the welcome form keeps editId a plain value (browser gate), README, wider rows in the framemre
  • 5c481bfdident#31: sign in to ident inside the selector's panel (email, code, identity in an iframe; a new address goes to ident in the same tab and comes back)mre
  • 061abfe2ident: the apps gate waits until the test app's login button stops moving before it clicks (the page grows after load and the click missed about every second run)mre
  • 45f7e4daident: the user menu's Sign out waits for the server before it reloads (the apps gate failed because the session could still be signed in)mre
  • f07658c7ident: home page shows the account once (account bar removed, the user menu carries email, Sign out, Sign out everywhere); wildcard origins https://*.domain for apps on many subdomains; gates follow (WIP: gates not re-run after the last edits)mre
  • f2c43bbbtheme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre