notes
All repositories: gitoria
12.0 KB
// tests/ident-access-notes.mjs — GATE: notes' API accepts an ident access key (`Authorization: Bearer idt_…`, ident#27, app side).// A LOCAL ident (tests/identkit.mjs, NOTES_GATE_IDENT_DIR) with an app 'notes' and identities that were given keys through ident's own API;// a LOCAL notes started with that ident's key and secret. Checked: a write key reads /api/me (the identity's user), saves, reads back, lists// and deletes a note; the same note is there for the SAME identity's browser session and not for another identity; a read key lists and// reads but save is 403; revoked, unknown, wrong-shape and other-app keys are 401; ident down is 503 and nothing is saved; the cookie session// still works as before (and still refuses another Origin).// node tests/ident-access-notes.mjs (NOTES_IDA_PORT 8760, NOTES_IDA_IDENT_PORT 8761; every PID it starts is killed at the end)import { spawn } from 'node:child_process';import { rmSync, mkdirSync, existsSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import { startIdent } from './identkit.mjs';const APP = resolve(dirname(fileURLToPath(import.meta.url)), '..');const BIN = join(APP, 'bin/hybriel');const PORT = Number(process.env.NOTES_IDA_PORT || 8760), IPORT = Number(process.env.NOTES_IDA_IDENT_PORT || 8761);const BASE = `http://127.0.0.1:${PORT}`;const IDENT_DIR = process.env.NOTES_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/WorldAPI/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));const WORK = process.env.NOTES_IDA_DIR || join(APP, '.scratch/ident-access-gate');const COLD_MS = Number(process.env.NOTES_COLD_MS || 120000);const J = JSON.stringify;const sleep = (ms) => new Promise(r => setTimeout(r, ms));let passes = 0, failures = 0;const check = (label, ok, detail = '') => { console.log(`${ok ? ' ok ' : ' FAIL'} ${label}${ok ? '' : ' — ' + String(detail).slice(0, 400)}`); if (ok) passes++; else failures++; };rmSync(WORK, { recursive: true, force: true });mkdirSync(join(WORK, 'mpackdb'), { recursive: true }); mkdirSync(join(WORK, 'sessions'), { recursive: true });let ident = null, server = null, log = '';const stopAll = async () => { try { server && server.kill(); } catch {} try { ident && await ident.stop(); } catch {} };process.on('exit', () => { try { server && server.kill(); } catch {} try { ident && ident.proc.kill(); } catch {} });try {ident = await startIdent({ identDir: IDENT_DIR, workDir: join(WORK, 'ident'), port: IPORT });const alice = await ident.signIn('[email protected]');const mkApp = async (name, origins) => { const a = await ident.registerApp(alice, name, origins); a.id = a.raw.app.id; return a; };const nt = await mkApp('notes', [BASE]), other = await mkApp('otherapp', ['http://127.0.0.1:1']);const give = async (name, apps, level, identity) => {const r = await ident.emit('accGiveAccess', [identity ? { identity, apps, level, label: name } : { newName: name, apps, level, label: name }], alice.cookie);if (!r.value || !r.value.key) throw new Error('give failed: ' + r.raw);return r.value;};// the writer's key belongs to alice's OWN first identity: the one her browser login signs in asconst aliceId = (alice.identities[0] || {}).id;if (!aliceId) throw new Error('alice has no identity: ' + J(alice.identities));const writer = await give('Hermes', [nt.id], 'write', aliceId);const reader = await give('Reader', [nt.id], 'read');const stranger = await give('Stranger', [other.id], 'write');const victim = await give('Victim', [nt.id], 'write');server = spawn(BIN, ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, NOTES_PORT: String(PORT),NOTES_STORAGE: join(WORK, 'mpackdb'), NOTES_SESSIONS: join(WORK, 'sessions'), NOTES_WATCH: '0', NOTES_PUBLIC_URL: BASE, HL_HOST: '127.0.0.1',IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base, IDENT_API_KEY: nt.key, IDENT_API_SECRET: nt.secret } });server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);for (const end = Date.now() + COLD_MS; Date.now() < end;) { try { await fetch(BASE + '/api/me'); break; } catch { await sleep(300); } }const call = async (method, path, token, body, extra = {}) => {const h = { ...extra }; if (token) h.authorization = 'Bearer ' + token;if (body !== undefined) h['content-type'] = 'application/json';const r = await fetch(BASE + path, { method, headers: h, body: body === undefined ? undefined : J(body) });const t = await r.text(); let j = null; try { j = JSON.parse(t); } catch {}return { status: r.status, j, t };};const save = (key, id, text, base = 0, extra) => call('POST', '/api/notes', key, { op: 'save', id, local: id, text, base, at: Date.now() }, extra);console.log('# an idt_ write key');let r = await call('GET', '/api/me', writer.key);const meUser = r.j && r.j.user;check('/api/me with a write key gives a user id', r.status === 200 && typeof meUser === 'string' && meUser !== '', r.status + ' ' + r.t);r = await call('GET', '/api/me', writer.key);check('a second call gives the same user (none made twice)', r.j && r.j.user === meUser, r.t);r = await save(writer.key, 'keynote1', '# Made by a key\nno browser login');check('a write key saves a note (200)', r.status === 200 && r.j && r.j.text && r.j.text.startsWith('# Made by a key'), r.status + ' ' + r.t);const nid = r.j && r.j.id;r = await call('GET', '/api/notes?id=' + nid, writer.key);check('…and reads it back', r.status === 200 && r.j.text === '# Made by a key\nno browser login', r.status + ' ' + r.t);r = await call('GET', '/api/notes', writer.key);check('…and lists it', r.status === 200 && r.j.notes.some(n => n.id === nid && !n.gone), r.status + ' ' + r.t);console.log('# the same identity in a browser session sees it; another identity does not');const scode = await ident.selectorCode(alice, nt, BASE);const cb = await fetch(BASE + '/login/callback?ident_code=' + scode, { redirect: 'manual' });const ck = (cb.headers.get('set-cookie') || '').split(';')[0];const lj = await (await fetch(BASE + '/api/notes', { headers: { cookie: ck } })).json();check('the browser session of the key’s identity lists the key’s note', !!ck && !!lj.notes && lj.notes.some(n => n.id === nid), J(lj).slice(0, 200));const bobKey = (await give('Bobkey', [nt.id], 'write')).key;r = await call('GET', '/api/notes', bobKey);const meBob = (await call('GET', '/api/me', bobKey)).j.user;check('a second identity’s key is a different user', meBob && meBob !== meUser, meBob + ' ' + meUser);check('a key never sees another identity’s notes', r.status === 200 && !r.j.notes.some(n => n.id === nid), r.t);r = await call('GET', '/api/notes?id=' + nid, bobKey);check('…nor reads one by id (404)', r.status === 404, r.status + ' ' + r.t);console.log('# an idt_ read key');const rme = await call('GET', '/api/me', reader.key);check('a read key: /api/me 200', rme.status === 200 && rme.j.user, rme.status + ' ' + rme.t);r = await call('GET', '/api/notes', reader.key);check('a read key: list 200', r.status === 200, r.status + ' ' + r.t);const rn = await call('GET', '/api/notes?id=' + nid, reader.key);r = await save(reader.key, 'readernote', 'nope');check('a read key may not save: 403', r.status === 403, r.status + ' ' + r.t);r = await call('POST', '/api/notes', reader.key, { op: 'delete', id: nid, base: 0 });check('a read key may not delete: 403', r.status === 403, r.status + ' ' + r.t);r = await call('GET', '/api/notes?id=' + nid, writer.key);check('the note is untouched by the read key', r.status === 200 && r.j.text.startsWith('# Made by a key'), r.t);const wl = (await call('GET', '/api/notes', writer.key)).j.notes;check('nothing was saved by the read key', !wl.some(n => n.id === 'readernote' || n.id === 'readernote'), J(wl));console.log('# refused keys');const countNow = async () => (await call('GET', '/api/notes', writer.key)).j.notes.length;const n0 = await countNow();r = await save(stranger.key, 'foreign1', 'foreign');check('a key for another app: 401', r.status === 401, r.status + ' ' + r.t);r = await save('idt_' + '0'.repeat(48), 'unknown1', 'unknown');check('an unknown well-formed key: 401', r.status === 401, r.status + ' ' + r.t);r = await save('idt_abc', 'short1', 'short');check('a malformed idt_ key: 401', r.status === 401, r.status + ' ' + r.t);r = await call('GET', '/api/me', 'idt_' + '0'.repeat(48));check('/api/me with an unknown key: 401', r.status === 401, r.status + ' ' + r.t);r = await save(victim.key, 'victim1', 'before revoke');check('before the revoke the victim key writes (200)', r.status === 200, r.status + ' ' + r.t);await ident.emit('accRevokeCell', [victim.identity, nt.id], alice.cookie);r = await save(victim.key, 'victim2', 'after revoke');check('revoked: 401 at the very next call', r.status === 401, r.status + ' ' + r.t);check('no refusal carries the key back', !r.t.includes(victim.key));check('refused keys wrote nothing for the writer or for bob', (await countNow()) === n0 && (await call('GET', '/api/notes', bobKey)).j.notes.length === 0, '');console.log('# delete by key, then the old ways');r = await call('POST', '/api/notes', writer.key, { op: 'delete', id: nid, base: (await call('GET', '/api/notes?id=' + nid, writer.key)).j.edited });check('a write key deletes its note', r.status === 200 && r.j.ok, r.status + ' ' + r.t);r = await call('GET', '/api/notes?id=' + nid, writer.key);check('…and it is gone (404)', r.status === 404, r.status + ' ' + r.t);r = await call('GET', '/api/notes', null);check('no header: still 401', r.status === 401, r.status + ' ' + r.t);r = await call('POST', '/api/notes', null, { op: 'save', id: 'x', local: 'x', text: 'x', base: 0, at: 1 });check('no header, POST: still 401', r.status === 401, r.status + ' ' + r.t);r = await call('GET', '/api/notes', 'tkt_' + '0'.repeat(48));check('another Bearer scheme: still 401 (session path)', r.status === 401, r.status + ' ' + r.t);if (ck) {const pr = await fetch(BASE + '/api/notes', { method: 'POST', headers: { cookie: ck, 'content-type': 'application/json' }, body: J({ op: 'save', id: 'sess1', local: 'sess1', text: 'by session', base: 0, at: Date.now() }) });check('a browser session still saves', pr.status === 200, '' + pr.status);const pr2 = await fetch(BASE + '/api/notes', { method: 'POST', headers: { cookie: ck, origin: 'https://evil.example', 'content-type': 'application/json' }, body: J({ op: 'save', id: 'sess2', local: 'sess2', text: 'csrf', base: 0, at: Date.now() }) });check('a session with another Origin is still refused (403)', pr2.status === 403, '' + pr2.status);const mr = await (await fetch(BASE + '/api/me', { headers: { cookie: ck } })).json();check('/api/me by session gives the same user as the key', mr.user === meUser, J(mr));} else check('a browser session still saves', false, 'no session');console.log('# ident down');await ident.stop();const c1 = await countNow().catch(() => -1);r = await save(writer.key, 'down1', 'while ident is down');check('ident down: a valid write key is refused with 503', r.status === 503 && !r.t.includes(writer.key) && !r.t.includes(nt.secret), r.status + ' ' + r.t);r = await call('GET', '/api/notes', reader.key);check('ident down: a read key is refused with 503 too', r.status === 503, r.status + ' ' + r.t);r = await call('GET', '/api/notes', null);check('ident down: no header is a plain 401', r.status === 401, r.status + ' ' + r.t);if (ck) {const lr = await fetch(BASE + '/api/notes', { headers: { cookie: ck } });const lj = await lr.json();check('ident down: the session still lists, and nothing was saved by the 503', lr.status === 200 && !lj.notes.some(n => n.id === 'down1'), lr.status + ' ' + J(lj).slice(0, 200));}} catch (e) {failures++; console.log('FAIL gate error: ' + (e.stack || e) + '\n' + log.slice(-1500));} finally {await stopAll();}console.log(`\n${passes} passed, ${failures} failed`);process.exit(failures ? 1 : 0);
Branches
Latest commits
- e4e7402fnotes#11: plain declarations instead of let for variables never reassigned (components/notes.hl 3, lib/jsoncheck.hl 5, lib/util.hl 2, tools/migrate-short-ids.hl 8)mre
- 27b6a09enotes#8: Style blocks in the nested form (note-list, note-editor, .ask with their children nested, :empty as a nested pseudo-class); the same CSS rules, the pages look the samemre
- 71a9538bnotes: B27W report, log linemre
- 78ba0073notes: an ident access key (Authorization: Bearer idt_…) reads and writes its identity's notes through /api/me and /api/notes; gate tests/ident-access-notes.mjs (ident#27)mre
- 3de46dacnotes: the sign-in callback keeps the session it finds and signs it in (same cookie, nothing signed out; ident#28); security gate 73+5 failing → 78 passedmre
- 5909d458notes: MdEditor from components 59704ce (text on the clipboard always pastes, a file manager copy still attaches; pipe rows without a delimiter row; tickets#49, notes#5)mre
- 98bd6a98N5b: pipe rows without a delimiter row are a table (MdEditor ad4e929, plain copy); gate tests/dashboard-table.mjs; reportmre
- dbf93319N5 report: components gate rerun 613 passed, 0 failedmre
- 3a8bc0d2N5: empty Table-button table is written as a real pipe table (MdEditor 4bd1112, plain copy); gate tests/table-button.mjs; reportmre
- c16bd443N5: step 1 report (tables pass locally; his DASHBOARD note has no delimiter row)mre
- 6091320anotes: MdEditor 7437e32 (surface drawn at once when the page is claimed); gate measures claim-to-text on 5 note loads at 1280 and 390mre
- 0aa9277enotes: move each component's styles into its own Style block (shell and header selector in main.hl, list, editor frame and delete question in notes.hl); styles.hl keeps the theme inherit, the accent and the message colour; .gitignore ignores a bin symlink too; tests/shots.mjs for the pixel comparemre
- 9ba01de3notes: write the standby service out in full so the boot gate can read the main servicemre
- 98cab40anotes: standby service on its port plus 10 and a deploy that hands over through it without a gapmre
- 1fadb473notes gate: the editor table now has 1 px cell lines from the notes thememre
- 8762115cnotes: take the components e54f83a (paste as Markdown, text typed before the editor is built is kept, Table button); table lines come from the notes thememre
- ac23e194ident#31: the selector's sign-in returns to the page the user started on (return attribute = the login callback with next), gate checkmre
- 2804f0d3Merge branch 'iw-ident-widget'mre
- 52d8d242notes: e2e script checks Log out and the selector in the header instead of the user menumre
- e5abf7b7notes header: the selector alone top right plus Log out as before the theme missions; the user icon is gonemre