components
All repositories: gitoria
10.6 KB
// tests/ident-access.mjs — THE GATE of components/ident-access/: an app checks an ident access key (ident#27, app side).// It starts a LOCAL ident (IDENT_APP, default ../ident-checkout) with its own storage, registers an app, gives identities keys through// ident's own API, then starts tests/ident-access/project.hl (the component wired as its README says) and asks it over HTTP.// Red before the component exists (the gate app cannot compile), green after. Ports: IA_IDENT_PORT (8788), IA_APP_PORT (8789).// Run: IDENT_APP=/path/to/ident node tests/ident-access.mjs (exit 0 = all passed; every PID it starts is killed at the end)import { spawn } from 'node:child_process';import { readFileSync, writeFileSync, rmSync, mkdirSync } from 'node:fs';import { dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';const HERE = join(dirname(fileURLToPath(import.meta.url)), '..');const IDENT = process.env.IDENT_APP;if (!IDENT) { console.log('set IDENT_APP to an ident checkout (with bin/hybriel)'); process.exit(2); }const G = process.env.IA_GATE_DIR || join(HERE, '.scratch/ident-access-gate');const PI = Number(process.env.IA_IDENT_PORT || 8788), PA = Number(process.env.IA_APP_PORT || 8789);const ID = 'http://127.0.0.1:' + PI, APP = 'http://127.0.0.1:' + PA;const sleep = (ms) => new Promise(r => setTimeout(r, ms));let passed = 0, failed = 0;const check = (name, ok, detail = '') => { if (ok) { passed++; console.log(' ok ' + name); } else { failed++; console.log(' FAIL ' + name + (detail ? ' — ' + detail : '')); } };const J = JSON.stringify;rmSync(G, { recursive: true, force: true }); mkdirSync(G, { recursive: true });const procs = [];let logs = '';function start(name, cwd, bin, args, env) {const p = spawn(bin, args, { cwd, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ...env } });p.stdout.on('data', d => { logs += `[${name}] ` + d; }); p.stderr.on('data', d => { logs += `[${name}] ` + d; });procs.push(p); writeFileSync(join(G, name + '.pid'), String(p.pid));return p;}const stopAll = () => { for (const p of procs) { try { p.kill(); } catch {} } };process.on('exit', stopAll);async function up(url, p, what) {for (const end = Date.now() + 150000; Date.now() < end;) {if (p.exitCode !== null) throw new Error(what + ' exited with ' + p.exitCode + '\n' + logs.slice(-2500));try { await fetch(url, { redirect: 'manual' }); return; } catch {} await sleep(300);}throw new Error(what + ' did not come up\n' + logs.slice(-2500));}// ---- the local ident --------------------------------------------------------------------const identProc = start('ident', IDENT, join(IDENT, 'bin/hybriel'), ['project.hl'], { SMTP_HOST: '', SMTP_USER: '', SMTP_PASSWORD: '', IDENT_PORT: String(PI), IDENT_STORAGE: join(G, 'ident'), IDENT_SESSIONS: join(G, 'sess') + '/', IDENT_MAIL_SINK: join(G, 'mail.txt'), IDENT_IP_LIMIT: '1000', IDENT_IP_DAY_LIMIT: '1000', IDENT_WATCH: '0' });await up(ID + '/', identProc, 'ident');let emitI = 0;async function emit(event, payload, cookie) {const r = await fetch(ID + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) }, body: J({ t: 'emit', i: ++emitI, event, payload }) });const t = await r.text(); let j = null; try { j = JSON.parse(t); } catch {}return { cookie: (r.headers.get('set-cookie') || '').split(';')[0], value: j && j.value, raw: t };}const email = '[email protected]';await fetch(ID + '/api/code', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ email }) });const lines = readFileSync(join(G, 'mail.txt'), 'utf8').trim().split('\n').filter(l => l.startsWith(email + ' '));const login = await emit('verifyCode', [email, lines[lines.length - 1].split(' ')[1], 'UTC']);if (!login.cookie) throw new Error('ident login failed: ' + login.raw);const mkApp = async (name) => {let r;for (let i = 0; i < 6; i++) { r = await emit('appCreate', [{ name, origins: ['http://127.0.0.1:1'] }], login.cookie); if (r.value && r.value.app) break; await sleep(1000); }if (!r.value || !r.value.app) throw new Error('appCreate failed: ' + r.raw);return { id: r.value.app.id, key: r.value.app.apiKey, secret: r.value.secret };};const give = async (name, apps, level) => {const r = await emit('accGiveAccess', [{ newName: name, apps, level, label: name }], login.cookie);if (!r.value || !r.value.key) throw new Error('give failed: ' + r.raw);return r.value;};const tickets = await mkApp('tickets'), other = await mkApp('otherapp');const writer = await give('Hermes', [tickets.id], 'write');const reader = await give('Reader', [tickets.id], 'read');const stranger = await give('Stranger', [other.id], 'write');const victim = await give('Victim', [tickets.id], 'write');// ---- the gate app: the component wired as its README says ---------------------------------const appEnv = { GATE_APP_PORT: String(PA), IDENT_URL: ID, IDENT_APP_KEY: tickets.key, IDENT_APP_SECRET: tickets.secret };const appProc = start('gateapp', join(HERE, 'tests/ident-access'), join(HERE, 'bin/hybriel'), ['project.hl'], appEnv);await up(APP + '/whoami', appProc, 'gate app');const ask = async (path, headers = {}, method = 'GET') => {const r = await fetch(APP + path, { method, headers, body: method === 'POST' ? '{}' : undefined });const t = await r.text(); let j = null; try { j = JSON.parse(t); } catch {}return { status: r.status, j, t, www: r.headers.get('www-authenticate') };};const bearer = (k) => ({ authorization: 'Bearer ' + k });const basic = (u, p) => ({ authorization: 'Basic ' + Buffer.from(u + ':' + p).toString('base64') });console.log('# ident-access');let r = await ask('/whoami', bearer(writer.key));check('a valid write key: 200, identity, name, access write', r.status === 200 && r.j && /^[2-9a-hj-km-np-z]{5}$/.test(r.j.identity) && r.j.name === 'Hermes' && r.j.access === 'write', r.status + ' ' + r.t);const hermesId = r.j && r.j.identity;r = await ask('/write', bearer(writer.key), 'POST');check('a write key may write', r.status === 200 && r.j && r.j.wrote === true, r.status + ' ' + r.t);r = await ask('/whoami', basic('git', writer.key));check('HTTP Basic with the key as the password (git) works, any user name', r.status === 200 && r.j && r.j.identity === hermesId, r.status + ' ' + r.t);r = await ask('/whoami', bearer(reader.key));check('a read key: whoami 200 with access read', r.status === 200 && r.j && r.j.access === 'read' && r.j.name === 'Reader', r.status + ' ' + r.t);r = await ask('/write', bearer(reader.key), 'POST');check('a read key may not write: 403, nothing written', r.status === 403 && !(r.j && r.j.wrote), r.status + ' ' + r.t);r = await ask('/whoami', bearer(stranger.key));check('a key given for another app only: 401', r.status === 401 && !(r.j && r.j.identity), r.status + ' ' + r.t);check('a refused answer never carries the key back', !r.t.includes(stranger.key));// revoked: valid, revoke, the very next call refused (no cache that outlives it)r = await ask('/whoami', bearer(victim.key));check('before the revoke the victim key is valid', r.status === 200, r.status + ' ' + r.t);const rv = await emit('accRevokeCell', [victim.identity, tickets.id], login.cookie);r = await ask('/whoami', bearer(victim.key));check('revoked: refused at the very next call', r.status === 401, r.status + ' ' + r.t + ' ' + rv.raw);// wrong shapes and missing headersfor (const [name, h] of [['no header at all', {}],['an empty Authorization header', { authorization: '' }],['a Bearer without a token', { authorization: 'Bearer ' }],['a token of another kind (tkt_…)', bearer('tkt_abc123')],['idt_ with too few digits', bearer('idt_' + 'a'.repeat(47))],['idt_ with too many digits', bearer('idt_' + 'a'.repeat(49))],['idt_ with upper-case hex', bearer('idt_' + 'A'.repeat(48))],['idt_ with non-hex letters', bearer('idt_' + 'z'.repeat(48))],['a scheme that is neither Bearer nor Basic', { authorization: 'Digest ' + writer.key }],['the key bare, without a scheme', { authorization: writer.key }],['Basic that is not base64', { authorization: 'Basic %%%%' }],['Basic with no colon', { authorization: 'Basic ' + Buffer.from(writer.key).toString('base64') }],['Basic with bytes that are not UTF-8', { authorization: 'Basic ' + Buffer.from([0x67, 0x3a, 0xff, 0xfe, 0xc3, 0x28]).toString('base64') }],['an unknown but well-formed key', bearer('idt_' + '0'.repeat(48))],]) {r = await ask('/whoami', h);check(name + ': refused with 401, not allowed, not a crash', r.status === 401 && !(r.j && r.j.identity), r.status + ' ' + r.t);}r = await ask('/whoami', {});check('a missing header: the answer asks for credentials (WWW-Authenticate: Basic, so git prompts)', /^Basic /i.test(r.www || ''), String(r.www));r = await ask('/write', {}, 'POST');check('a missing header on a write: 401', r.status === 401 && !(r.j && r.j.wrote), r.status + ' ' + r.t);// the app's settings wrong (secret): ident says 401 to the APP — the user must be refused, not allowed (503: our fault, not theirs)const badApp = start('badapp', join(HERE, 'tests/ident-access'), join(HERE, 'bin/hybriel'), ['project.hl'], { ...appEnv, GATE_APP_PORT: String(PA + 1), IDENT_APP_SECRET: 'sk_wrong' });await up('http://127.0.0.1:' + (PA + 1) + '/whoami', badApp, 'gate app with a wrong secret');const rb = await fetch('http://127.0.0.1:' + (PA + 1) + '/whoami', { headers: bearer(writer.key) });check('wrong app secret in the settings: the valid key is refused (503), not allowed', rb.status === 503, String(rb.status));const rbt = await rb.text();check('…and the answer does not leak the secret', !rbt.includes('sk_'));// ident downidentProc.kill();for (const end = Date.now() + 10000; identProc.exitCode === null && Date.now() < end;) await sleep(100);// hl:fetch has no catch for a refused connection (the Hybriel gap in the README): the framework answers 500, which is a refusal too.// What matters: never 200, no identity, and nothing secret in the text.const refused = (x) => x.status >= 500 && x.status < 600 && !(x.j && (x.j.identity || x.j.wrote)) && !x.t.includes(appEnv.IDENT_APP_SECRET) && !x.t.includes(writer.key);r = await ask('/whoami', bearer(writer.key));check('ident down: a valid key is refused (5xx), never allowed', refused(r), r.status + ' ' + r.t);r = await ask('/write', bearer(writer.key), 'POST');check('ident down: a write is refused too', refused(r), r.status + ' ' + r.t);r = await ask('/whoami', bearer(writer.key));check('ident down: still refused on the second call (nothing was remembered)', refused(r), r.status + ' ' + r.t);r = await ask('/whoami', {});check('ident down: a missing header is still a plain 401', r.status === 401, r.status + ' ' + r.t);console.log(`\n${passed} passed, ${failed} failed`);stopAll();process.exit(failed ? 1 : 0);
Branches
- b27b
- mainmain branch
- vl27-resetkey
Latest commits
- 3d43c187ident-access: server-side check of an ident access key (Bearer or Basic password), asks ident on every call, README, gate tests/ident-access.mjs (ident#27 app side)mre
- 59704ce1Merge branch 'n5b-pipes'mre
- 23b9164aMdEditor: a clipboard whose text is only the names or file:// paths of its files (a file manager copy) is about the files, as before; any other text wins (tickets#49); gate casesmre
- b0f1ec28MdEditor: a clipboard with text always pastes the text, also when a picture is on it too (a spreadsheet or office app), files on or off; a picture alone still goes to the files; real Ctrl+V gate tests/md-paste-files.mjs (tickets#49)mre
- ad4e929bMdEditor: pipe rows without a delimiter row are a table (first row = header, short rows padded, written back without an invented | --- | line) (notes#5)mre
- 4bd11128MdEditor: the Table button's empty table is written as a real pipe table (empty cells), so it survives the source switch, a save and a reload (notes#7)mre
- 7437e32bMdEditor draws its surface at once when claimed from server HTML: 1 ms mount animation, the first editor mounts all editors of the pagemre
- 5de0264cRe-vendor onto Hybriel master acaceaf3 (set-day27b): binary, lib and plugins; exit 1 on a startup fault; .gitignore binmre
- 79c77e7dMerge sb3-standby: components deploys through its standbymre
- c5442043components: no jobs switch needed in the standbymre
- 8d2fb24ccomponents: a standby container (port 45016, profile standby); deploy hands over through standby-swap.sh without a gapmre
- c2834dd3Merge mr-fixes: media player state after a queue pick, Range handling, cover-less audio, accessibility labelsmre
- 354fe3c6Media player: audio without a cover starts and shows its time (the mount tick sits on the seek bar, which every item has); the speed button names the current speed, the seek slider says its time in words; a gate page for the first render on cover-less audio and a fourth demo queue item without a covermre
- ee4aee1eMedia player: a new queue item shows its own speed, mute, play state and time and starts when asked, also for two videos in a row; the media route reads suffix ranges and ignores range lists and garbage instead of answering 500; stronger gate checks (the 10 percent drag, the played bar, the queue tap)mre
- 9a4f9b31Merge mp-player: media served from the committed filesmre
- ab96e686Media route: serve the demo's media from the committed files in components/media-player (storage/ is not in git, the deploy gate found no files)mre
- b2980734Merge mp-player: the media player (components/media-player), its demo and the media iconsmre
- 1c41293eMediaPlayer: back / forward 10 s as replay / forward 10 icons (circular arrow with a 10), the play button keeps its surface background on audio and video, the media route's range end is a letmre
- 9e1ab228MP: report, LOG line, STATUS entrymre
- dd003e5dMediaPlayer: audio and video in one phone-first player (components/media-player), its demo /media-player with a queue, the media icons in components/icons, the demo's media files served with ranges (lib/media.hl), 35 gate checksmre