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
- 8342cd28Merge branch 'notes9-no-poll' into mainAtlas
- 1f0457a5|||PR make provisional rejected-draft setup deterministicAtlas
- 996768bf|||PR WIP sequence note creation before provisional-id adoptionAtlas
- c49ce093|||PR WIP remove notes polling and use framework reachabilityAtlas
- c028ac61Merge branch 'notes-pr7-kunibert' into mainAtlas
- 9cc92bdfKeep conflict and history fixes while awaiting queued save supportAtlas
- a5c27cb6Allow real edits back to earlier text and honor configured identAtlas
- 15c46ced|||PR Preserve note edits, conflict bases and visible historyAtlas
- 4c6e0bf6Merge branch 'notes13-day61' into mainAtlas
- eb51864f|||PR Back/Forward via navigate, server drafts, Hybriel day61Atlas
- 3537cf7eMerge branch 'vendor-day59' into mainAtlas
- c13d188b|||PR Vendor Hybriel day59Atlas
- 24c95433Merge branch 'notes17-ghost-note' into mainAtlas
- ae1075b2Preserve rejected drafts during note ID adoptionAtlas
- 383cce23|||PR Prevent saved local edits from restoring deleted notesAtlas
- 99ca1cf6Merge branch 'vendor-day56' into mainAtlas
- 649cef37|||PR Vendor Hybriel day56Atlas
- aadd0abcMerge branch 'hl-standard-2' into mainAtlas
- 52ffac9f|||PR Keyboard and reload checks for the notes gate (HL-STANDARD F21, F5)Atlas
- 617ee8c0Merge branch 'hl-standard' into mainAtlas