gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit47e516af47e516afident#33 ident#34: the identity form's avatar rules move into identityform.hl; the preview and Remove button are hidden with the hidden attribute instead of built class strings (avatarPreviewClass, avatarRemoveClass gone)mre47e516af/tests/migration.mjs

15.8 KB

  1. // tests/migration.mjs — THE MIGRATION GATE (mission 009, ticket ident #10 / old #39):
  2. // an OLD-FORMAT store (tests/oldstore-009.hl: `*id` tables, numeric public ids, sessions
  3. // holding `user: {id: <number>}`) → tools/migrate-009.hl on a COPY, twice (idempotent) →
  4. // the new code on the migrated store:
  5. // * a migrated session is still signed in (HTTP and a real Chrome);
  6. // * an app's STORED per-app ids come out of the exchange again with its UNCHANGED key +
  7. // secret (login button in Chrome through the test app → "welcome back"; selector);
  8. // * a code issued before the migration (grants) still exchanges; the per-app id of a
  9. // deleted identity stays; every appIdentity byte-identical.
  10. // Own servers: ident :8395, test app :8396 (env MIGRATION_GATE_PORT / MIGRATION_GATE_TESTAPP_PORT override; Bob's app origin :8397 = MIGRATION_GATE_BOBAPP_PORT) (the fixture app's origin); storage
  11. // .scratch/migration-gate (wiped at start); Chrome on 8710-8719. Screenshot .scratch/migration-*.png
  12. import { spawn, execFileSync } from 'node:child_process';
  13. import { readFileSync, writeFileSync, rmSync, mkdirSync, cpSync } from 'node:fs';
  14. import { createHash } from 'node:crypto';
  15. import { dirname, join } from 'node:path';
  16. import { fileURLToPath } from 'node:url';
  17. import { launchBrowser, sleep } from './cdp.mjs';
  18. // 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
  19. // page (the SSR HTML carries #hl-seed) therefore waits until the page is live (socket open) before the test touches it.
  20. function live(page) {
  21. const goto = page.goto.bind(page);
  22. page.goto = async (url, o) => {
  23. const r = await goto(url, o);
  24. await page.waitFor("!document.getElementById('hl-seed') || (!!window.__hl && !!window.__hl.socket && window.__hl.socket.readyState === 1)", { label: 'page hydrated ' + url });
  25. return r;
  26. };
  27. return page;
  28. }
  29. const APP = join(dirname(fileURLToPath(import.meta.url)), '..');
  30. const G = join(APP, '.scratch/migration-gate');
  31. const BIN = join(APP, 'bin/hybriel');
  32. const IPORT = process.env.MIGRATION_GATE_PORT || '8395', TPORT = process.env.MIGRATION_GATE_TESTAPP_PORT || '8396';
  33. const ID = 'http://127.0.0.1:' + IPORT, TA = 'http://127.0.0.1:' + TPORT;
  34. const BOB = 'http://127.0.0.1:' + (process.env.MIGRATION_GATE_BOBAPP_PORT || '8397'); // Bob's app origin (never listens; only matched as a return origin)
  35. const J = JSON.stringify;
  36. const x = (c, n) => c.repeat(n);
  37. const K1 = 'pk_' + x('1', 32), S1 = 'sk_' + x('2', 48), K2 = 'pk_' + x('3', 32), S2 = 'sk_' + x('4', 48);
  38. const AI = { def: x('a', 32), work: x('b', 32), gone: x('c', 32), bob: x('d', 32) };
  39. let passed = 0, failed = 0;
  40. const check = (name, ok, detail = '') => {
  41. if (ok) { passed++; console.log(' ok ' + name); }
  42. else { failed++; console.log(' FAIL ' + name + (detail ? ' — ' + detail : '')); }
  43. };
  44. const run = (script, env) => execFileSync(BIN, [script], { cwd: APP, env: { ...process.env, ...env }, encoding: 'utf8' });
  45. rmSync(G, { recursive: true, force: true });
  46. mkdirSync(join(G, 'old'), { recursive: true });
  47. mkdirSync(join(G, 'sess'), { recursive: true });
  48. // ---- 1. the old-format store and its sessions -------------------------------------------
  49. console.log('# old store');
  50. const made = run(join(APP, 'tests/oldstore-009.hl'), { OLD_PREFIX: join(G, 'old/ident'), OLD_TESTAPP: TA, OLD_BOBAPP: BOB });
  51. check('fixture: old store written', /accounts 2 identities 3 apps 2 connections 4 otp 1 sends 1 requests 1 grants 1/.test(made), made.trim());
  52. // hl:webex session files: the file name is sha256(sid), the content JSON (webex sessions.hl)
  53. const SID = { alice: x('1a', 16), bob: x('2b', 16), anon: x('3c', 16) };
  54. const sess = (sid, user) => writeFileSync(join(G, 'sess', createHash('sha256').update(sid).digest('hex')),
  55. J({ created: Date.now() - 5000, data: {}, id: sid, seen: Date.now() - 1000, user }), { mode: 0o600 });
  56. sess(SID.alice, { id: 1 }); sess(SID.bob, { id: 2 }); sess(SID.anon, null);
  57. // ---- 2. migrate a COPY, twice -------------------------------------------------------------
  58. console.log('# migrate');
  59. cpSync(join(G, 'old'), join(G, 'oldcopy'), { recursive: true }); // opening a table rewrites it (hybriel #40)
  60. const menv = { IDENT_OLD_STORAGE: join(G, 'oldcopy/ident'), IDENT_STORAGE: join(G, 'new'), IDENT_SESSIONS_MIGRATE: join(G, 'sess') };
  61. const r1 = run(join(APP, 'tools/migrate-009.hl'), menv);
  62. writeFileSync(join(G, 'migrate-run1.txt'), r1);
  63. check('run 1: accounts 2, identities 3, apps 2, connections 4 (one of a deleted identity), otp/sends/requests/grants 1 each',
  64. /accounts 2 new/.test(r1) && /identities 3 new/.test(r1) && /apps 2 new/.test(r1) && /connections 4 new/.test(r1) && /otp 1 new/.test(r1) && /sends 1 new/.test(r1) && /requests 1 new/.test(r1) && /grants 1 new/.test(r1), r1);
  65. check('run 1: sessions 2 migrated, 1 anonymous left alone; 0 failed', /sessions 2 new, 0 already there, 1 anonymous, 0 left alone/.test(r1) && /migrate: 0 failed/.test(r1), r1);
  66. const r2 = run(join(APP, 'tools/migrate-009.hl'), menv);
  67. writeFileSync(join(G, 'migrate-run2.txt'), r2);
  68. check('run 2 (idempotent): nothing new anywhere, 0 failed', !/ [1-9]\d* new/.test(r2) && /sessions 0 new, 2 already there/.test(r2) && /migrate: 0 failed/.test(r2), r2);
  69. const sAlice = JSON.parse(readFileSync(join(G, 'sess', createHash('sha256').update(SID.alice).digest('hex')), 'utf8'));
  70. check('alice\'s session now holds her account\'s UUID', /^[0-9a-z]{12}$/.test(sAlice.user.id) && sAlice.id === SID.alice, J(sAlice.user));
  71. // the migrated store, read on a COPY
  72. cpSync(join(G, 'new'), join(G, 'newcopy'), { recursive: true });
  73. const st = JSON.parse(run(join(APP, 'tools/dump-store.hl'), { IDENT_STORAGE: join(G, 'newcopy') }));
  74. check('every per-app id byte-identical (4 connections)', J(st.connections.map(c => c.appIdentity).sort()) === J(Object.values(AI).sort()), J(st.connections.map(c => c.appIdentity)));
  75. check('API keys and secret hashes byte-identical', J(st.apps.map(a => [a.apiKey, a.secretHash]).sort()) === J([[K1, createHash('sha256').update(S1).digest('hex')], [K2, createHash('sha256').update(S2).digest('hex')]].sort()));
  76. check('all keys are 12-char UUIDs, references rewritten', Object.values(st).flat().every(r => /^[0-9a-z]{12}$/.test(r.id))
  77. && st.identities.every(i => st.accounts.some(a => a.id === i.account)) && st.apps.every(a => st.accounts.some(c => c.id === a.owner)));
  78. const goneConn = st.connections.find(c => c.appIdentity === AI.gone);
  79. check('the deleted identity\'s connection is kept as gone:4', goneConn && goneConn.identity === 'gone:4', J(goneConn));
  80. // ---- 3. the new code on the migrated store -------------------------------------------------
  81. const procs = [];
  82. function start(cwd, env, log) {
  83. const p = spawn(BIN, ['project.hl'], { cwd, env: { ...process.env, SMTP_HOST: '', SMTP_USER: '', SMTP_PASSWORD: '', ...env }, stdio: ['ignore', 'pipe', 'pipe'] });
  84. let out = ''; p.stdout.on('data', d => { out += d; }); p.stderr.on('data', d => { out += d; });
  85. p.on('exit', () => writeFileSync(join(G, log), out));
  86. procs.push(p);
  87. }
  88. start(APP, { IDENT_PORT: IPORT, IDENT_STORAGE: join(G, 'new'), IDENT_SESSIONS: join(G, 'sess') + '/', IDENT_MAIL_SINK: join(G, 'mail.txt'), IDENT_IP_LIMIT: '1000', IDENT_IP_DAY_LIMIT: '1000' }, 'ident.log');
  89. for (const end = Date.now() + Number(process.env.IDENT_COLD_MS || 120000); Date.now() < end;) { try { await fetch(ID + "/", { redirect: "manual" }); break; } catch {} await sleep(250); }
  90. // ident#23: the identities got their short ids at boot; each app trades its stored per-app ids for them in one step
  91. const migrateIds = async (key, secret, finish) => { const r = await fetch(ID + '/api/migrate-ids', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J(finish ? { key, secret, finish } : { key, secret }) }); return { status: r.status, j: await r.json() }; };
  92. const m1 = await migrateIds(K1, S1), m2 = await migrateIds(K2, S2);
  93. const SHORT = /^[2-9a-hj-km-np-z]{5}$/;
  94. check('migrate-ids (app 1): Default and Work map to short ids; the deleted identity is left out',
  95. m1.status === 200 && J(Object.keys(m1.j.ids).sort()) === J([AI.def, AI.work].sort()) && Object.values(m1.j.ids).every(v => SHORT.test(v)) && m1.j.ids[AI.def] !== m1.j.ids[AI.work], J(m1));
  96. check('migrate-ids (app 2): Bob maps to a short id', m2.status === 200 && J(Object.keys(m2.j.ids)) === J([AI.bob]) && SHORT.test(m2.j.ids[AI.bob]), J(m2));
  97. const M = { ...m1.j.ids, ...m2.j.ids };
  98. const wrong = await migrateIds(K1, S2);
  99. check('migrate-ids with the wrong secret → 401', wrong.status === 401, J(wrong));
  100. writeFileSync(join(G, 'testapp.json'), J({ key: K1, secret: S1, users: { [M[AI.def]]: { n: 1 }, [M[AI.work]]: { n: 2 } }, count: 2, sessions: {} }));
  101. start(join(APP, 'testapp'), { TESTAPP_PORT: TPORT, TESTAPP_URL: TA, IDENT_URL: ID, TESTAPP_STORE: join(G, 'testapp.json') }, 'testapp.log');
  102. for (const end = Date.now() + Number(process.env.IDENT_COLD_MS || 120000); Date.now() < end;) { try { await fetch(TA + "/", { redirect: "manual" }); break; } catch {} await sleep(250); }
  103. let browser = null;
  104. try {
  105. console.log('# sessions');
  106. const home = async (sid) => (await fetch(ID + '/', { headers: { cookie: 'identsid=' + sid } })).text();
  107. let h = await home(SID.alice);
  108. check('alice\'s OLD cookie: still signed in, her identities (Default first = default, Work; the deleted one absent)',
  109. h.includes('[email protected]') && /Default[\s\S]*default[\s\S]*Work/.test(h) && !h.includes('>Old<'), h.slice(0, 200));
  110. h = await home(SID.bob);
  111. check('bob\'s OLD cookie: still signed in as bob', h.includes('[email protected]') && !h.includes('[email protected]'));
  112. h = await home(SID.anon);
  113. check('the anonymous session: signed out (sign-in form)', h.includes('id="emailform"') && !h.includes('id="whoami"'));
  114. const aliceIds = [...new Set([...(await home(SID.alice)).matchAll(/value="([0-9a-z]{12})"/g)].map(m => m[1]))];
  115. check('alice\'s identity ids are UUIDs (2)', aliceIds.length === 2, J(aliceIds));
  116. console.log('# exchange');
  117. const exchange = async (body) => { const r = await fetch(ID + '/api/exchange', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J(body) }); return { status: r.status, j: await r.json() }; };
  118. let e = await exchange({ key: K1, secret: S1, code: x('e', 48) });
  119. check('a code issued BEFORE the migration still exchanges → the Work identity\'s stored id', e.status === 200 && e.j.identity === M[AI.work], J(e));
  120. e = await exchange({ key: K1, secret: S1, code: x('e', 48) });
  121. check('…once', e.status === 400, J(e));
  122. const emit = async (event, payload, sid) => (await (await fetch(ID + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', cookie: 'identsid=' + sid }, body: J({ t: 'emit', i: 1, event, payload }) })).json()).value;
  123. const bobIds = [...new Set([...(await home(SID.bob)).matchAll(/value="([0-9a-z]{12})"/g)].map(m => m[1]))];
  124. const l = await fetch(ID + '/login?key=' + K2 + '&return=' + encodeURIComponent(BOB + '/cb'), { redirect: 'manual' });
  125. const v = await emit('chooseIdentity', [l.headers.get('location').split('/').pop(), bobIds[0]], SID.bob);
  126. e = await exchange({ key: K2, secret: S2, code: new URL(v.url).searchParams.get('ident_code') });
  127. check('bob (old cookie) → Bob app (unchanged key + secret) → his stored id', e.status === 200 && e.j.identity === M[AI.bob], J(e));
  128. const sel = await fetch(ID + '/api/selector/identities?key=' + K1, { headers: { origin: TA, cookie: 'identsid=' + SID.alice } });
  129. const sj = await sel.json();
  130. check('selector: signed in, Default and Work', sel.status === 200 && sj.signedIn && J(sj.identities.map(i => i.name)) === J(['Default', 'Work']), J(sj));
  131. const ch = await (await fetch(ID + '/api/selector/choose?key=' + K1, { method: 'POST', headers: { origin: TA, cookie: 'identsid=' + SID.alice, 'content-type': 'application/json' }, body: J({ identity: sj.identities[1].id }) })).json();
  132. e = await exchange({ key: K1, secret: S1, code: ch.code });
  133. check('selector choice Work → exchange → the stored Work id', e.status === 200 && e.j.identity === M[AI.work], J(e));
  134. console.log('# old ids until the app has migrated');
  135. const notify = async (key, secret, identity) => { const r = await fetch(ID + '/api/notify', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ key, secret, identity, name: 'New comment', text: 'hello' }) }); return r.status; };
  136. check('notify: the OLD per-app id still works before the app migrated', (await notify(K1, S1, AI.work)) === 200);
  137. check('notify: the short id works too', (await notify(K1, S1, M[AI.work])) === 200);
  138. check('notify: the old id of ANOTHER app\'s user → 404', (await notify(K1, S1, AI.bob)) === 404);
  139. const fin = await migrateIds(K1, S1, true);
  140. check('migrate-ids finish: same map, marked finished', fin.status === 200 && fin.j.finished === true && J(fin.j.ids) === J(m1.j.ids), J(fin));
  141. check('after finish: the old id is gone (404), the short id still works', (await notify(K1, S1, AI.work)) === 404 && (await notify(K1, S1, M[AI.work])) === 200);
  142. check('after finish: nothing left to map', J((await migrateIds(K1, S1)).j.ids) === '{}');
  143. check('app 2 was not finished: its old id still works', (await notify(K2, S2, AI.bob)) === 200);
  144. console.log('# browser');
  145. browser = await launchBrowser({ debugPortRange: (process.env.MIGRATION_GATE_CHROME || '8710-8719').split('-').map(Number) });
  146. const p = live(await browser.newPage());
  147. await p.send('Network.enable');
  148. await p.send('Network.setCookie', { name: 'identsid', value: SID.alice, url: ID, httpOnly: true, sameSite: 'Lax' });
  149. await p.goto(ID + '/');
  150. await p.waitFor('!!document.querySelector("#identities") && !!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'ident signed in' });
  151. check('Chrome with alice\'s old cookie: signed in, Default (default badge) and Work',
  152. (await p.evaluate('document.querySelector("#whoami").textContent')) === '[email protected]'
  153. && J(await p.evaluate('[...document.querySelectorAll("#identities li")].map(li => li.querySelector("identity-label, identityLabel").textContent + (li.querySelector("default-badge, defaultBadge") ? "*" : ""))')) === J(['Default*', 'Work']));
  154. const { data } = await p.send('Page.captureScreenshot', { format: 'png' });
  155. writeFileSync(join(APP, '.scratch/migration-signedin-1280.png'), Buffer.from(data, 'base64'));
  156. const viaButton = async (nth) => {
  157. await p.goto(TA + '/');
  158. await p.click('#login');
  159. await p.waitFor('location.pathname.startsWith("/signin/") && !!document.querySelector("#chooselist") && !!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'choice' });
  160. await p.click(`#chooselist li:nth-child(${nth}) .choose`);
  161. await p.waitFor(`location.href.startsWith(${J(TA + '/callback')}) && !!document.querySelector("#result")`, { label: 'back at the app' });
  162. return { identity: await p.evaluate('document.querySelector("#identity").textContent.trim()'), state: await p.evaluate('document.querySelector("#userstate").textContent') };
  163. };
  164. let b = await viaButton(1);
  165. check('Chrome: test app → login button → Default → the SAME stored id, "welcome back"', b.identity === M[AI.def] && b.state === 'welcome back', J(b));
  166. b = await viaButton(2);
  167. check('Chrome: test app → login button → Work → the SAME stored id, "welcome back"', b.identity === M[AI.work] && b.state === 'welcome back', J(b));
  168. const shot = await p.send('Page.captureScreenshot', { format: 'png' });
  169. writeFileSync(join(APP, '.scratch/migration-testapp-1280.png'), Buffer.from(shot.data, 'base64'));
  170. const ta = JSON.parse(readFileSync(join(G, 'testapp.json'), 'utf8'));
  171. check('the test app made no new users (count still 2)', ta.count === 2, J(ta.count));
  172. check('Chrome: no console errors', p.problems().length === 0, J(p.problems()));
  173. } catch (err) {
  174. failed++; console.log(' FAIL (aborted) ' + err.stack);
  175. } finally {
  176. if (browser) await browser.close();
  177. for (const p of procs) { try { p.kill(); } catch {} }
  178. await sleep(300);
  179. }
  180. console.log(`\n${passed} passed, ${failed} failed`);
  181. process.exit(failed ? 1 : 0);

Branches

Latest commits

  • 47e516afident#33 ident#34: the identity form's avatar rules move into identityform.hl; the preview and Remove button are hidden with the hidden attribute instead of built class strings (avatarPreviewClass, avatarRemoveClass gone)mre
  • 5cb5cf0eident#33: the code field's look moves into codestep.hl's Stylemre
  • f421cd60ident#33: the shell's own rules (user menu address, offline note, network probe) move into main.hl's Stylemre
  • c512fb96Merge branch 'f4-homesplit' into mainIdent
  • 07d1717c|||PR ident#40 home.hl is split into components, one per area: email step, identity form, identity list, app identity choice, time zone; each moves its faces with it, the email step is shared with embed.hl (#40.3, rest of #40.2)mre
  • 59e8fcc1ident#40.3: the app's identity choice is one component (components/chooseidentity.hl); its face chooseIdentity moves with itmre
  • e23efdfcident#40.3: the identity list is one component (components/identitylist.hl); its delete and face dropIdentity move with itmre
  • e24b59a6ident#40.3: the time zone is one component (components/timezone.hl); its face changeTimeZone moves with itmre
  • 8cbc5717ident#40.3: the email step is one component (components/emailstep.hl) placed by home.hl and embed.hlmre
  • 6fad3bd2Merge branch 'f3-codestep' into mainIdent
  • 51e387f2|||PR ident#40 the code step is one component (components/codestep.hl) placed by home.hl and embed.hl; its verify face, setCode, browserZone and verify call exist once (#40.2)mre
  • c28bddeeMerge branch 'f2-shell' into mainIdent
  • c3a40ff6|||PR ident#40 one shell for the app and /start (account part off on /start, #40.1); startshell.hl removed; unused signOut faces gone (#40.4)mre
  • 060f3870ident#40.4: use the shell sign-out faces in regression gatesmre
  • 9b94aa6aMerge branch 'f1b-cleanup' into mainIdent
  • edcfce3f|||PR ident#41 ident#43 ident#44 login error page as a component (same status codes and text, pixel-identical), declarations and route wiring cleaned upmre
  • 3ac85995ident#43 ident#44: plain declarations for never-reassigned lets, one envString helper, named route functions and audience rule out of project.hlmre
  • c7eef14aMerge branch 'nv1-navigate' into mainIdent
  • 644f9775|||PR ident#36 navigate() instead of window.location in the shell, start shell and homemre
  • 4ca2f921deploy.sh: tar --hard-dereference so backups hold no hard linksmre