Files
stack/packages/webui/tests/granted-user.test.mjs

415 lines
27 KiB
JavaScript

// FED R6 (#1800, federation design 3.1 D3-D5, 3.4 and 3.7): a granted user signs in to the
// Console. Every provider is the fake OP in helpers/fake-oidc.mjs on loopback; no test reaches a
// real provider, the live Console or a real config, slot or access file. The broker is an
// in-process Broker with an access function (bus/tests/user-principal.test.mjs), reached through a
// per-session user transport that binds the user on every call, as user-cli.mjs does. The real
// user-cli spawn is checked on its own in G8 against a recording socket.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { request, createServer as createHttpServer } from 'node:http';
import { createServer as createNetServer } from 'node:net';
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { Store } from '../../bus/src/store.mjs';
import { Broker } from '../../bus/src/broker.mjs';
import { HUMAN_CLI } from '../../cli/src/transport.mjs';
import { startServer, userRoute } from '../src/serve.mjs';
import { createSso, SESSION_COOKIE } from '../src/sso.mjs';
import { consoleAccess } from '../src/access.mjs';
import { consoleBus, userOptionsFor } from '../src/console-bus.mjs';
import { BusReadError, USER_CLI, userCall } from '../src/bus.mjs';
import { close, fixture } from './fixture.mjs';
import { browser } from './browser.mjs';
import { fakeOidc } from './helpers/fake-oidc.mjs';
const HOST = 'console.example.test', ORIGIN = `https://${HOST}`;
const PUBLIC = new URL('../src/public/', import.meta.url);
const NOTICE = "The business owner sees your thread's agent's decisions, inbox entries, claims, tasks and project files, but not your messages.";
const OWNER_MARKER = 'owner-plugins-marker-7f3a';
const FEDERATION = { self: 'hub', peers: [{ id: 'factory', origin: 'https://factory.example.test', label: 'Software factory' }] };
function call(port, { method = 'GET', path = '/', headers = {}, body, host = HOST } = {}) {
return new Promise((resolve, reject) => {
const length = body === undefined ? {} : { 'content-length': Buffer.byteLength(body) };
const req = request({ host: '127.0.0.1', port, method, path, headers: { host, ...length, ...headers } }, res => {
let text = '';
res.on('data', c => (text += c));
res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, body: text && (res.headers['content-type'] ?? '').startsWith('application/json') ? JSON.parse(text) : text }));
});
req.on('error', reject);
req.end(body);
});
}
const setCookies = r => [r.headers['set-cookie'] ?? []].flat();
const sessionOf = r => setCookies(r).find(c => c.startsWith(`${SESSION_COOKIE}=`) && !c.includes('Max-Age=0'))?.split(';')[0] ?? null;
const writeHeaders = cookie => ({ cookie, origin: ORIGIN, 'sec-fetch-site': 'same-origin', 'content-type': 'application/json' });
const grant = (over = {}) => ({ id: 'g-1', user: 'alice', business: 'demo', projects: ['*'], instances: ['assistant'], level: 'collaborator', ...over });
const ALICE = { id: 'alice', home: 'local', subjects: [{ provider: 'a', sub: 'alice-sub' }] };
// The fake OP, an in-process broker for business `demo`, createSso with the access hook, and the
// human listener. The owner's options are counting stubs; each user session's options are
// consoleBus over that user's transport. `counts` records every owner stub and user transport call.
async function setup(t, { users = [ALICE], grants = [grant()] } = {}) {
const op = await fakeOidc();
t.after(() => op.close());
const iss = op.issuer('a');
const root = mkdtempSync(join(tmpdir(), 'webui-granted-user-'));
const store = new Store(root);
t.after(() => { store.close(); rmSync(root, { recursive: true, force: true }); });
const access = { doc: { accessVersion: 1, revision: 1, users, grants }, fail: false };
const load = () => { if (access.fail) throw new Error('access file refused'); return access.doc; };
const broker = new Broker({
store,
businesses: {
demo: {
id: 'demo', human: 'jason', arbiters: { technical: 'chief', delivery: 'chief' }, vars: {},
roles: {
chief: { definition: 'chief-of-staff', authority: { withinRole: ['message.send'], crossRole: [] } },
assistant: { definition: 'assistant', authority: { withinRole: ['message.send'], crossRole: [] } },
},
definitions: { 'chief-of-staff': {}, assistant: { messaging: JSON.parse(readFileSync(new URL('../../../roles/assistant.json', import.meta.url), 'utf8')).messaging } },
},
},
access: load,
});
const human = broker.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true });
const counts = { owner: 0, user: 0 };
// As user-cli.mjs: a fresh bind per call, and the broker's refusal code as the transport's.
// `userVerbs` and `ownerVerbs` record what each transport carried for a user session.
const userVerbs = [], ownerVerbs = [];
const userTransport = user => async (verb, args = {}) => {
counts.user++; userVerbs.push(verb);
try { return broker.request(broker.bindUser({ business: 'demo', user }), { verb, args }); }
catch (e) { throw new BusReadError(e.code ?? 'invalid-response'); }
};
// The owner's transport as cli.mjs passes it (ownerCall). Its answer carries a marker that must
// never reach a user's response.
const ownerCall = async (verb, args) => { ownerVerbs.push([verb, args]); return { plugins: { channel: ['webui'] }, marker: OWNER_MARKER }; };
const opened = [];
const userOptions = userOptionsFor({ owner: ownerCall, send: true, transport: user => { opened.push(user); return userTransport(user); } });
const lines = [];
const log = line => lines.push(line);
const config = { publicOrigin: ORIGIN, providers: [{ id: 'a', issuer: iss.issuer, clientId: iss.clientId, clientSecret: { slot: 'a' }, algs: ['RS256'], subjects: [{ sub: 'owner-sub', name: 'jason' }] }] };
const sso = await createSso(config, { secrets: new Map([['a', iss.clientSecret]]), fetch: op.fetch, log, users: consoleAccess({ load, business: () => 'demo' }) });
t.after(() => sso.close());
const stub = name => async () => { counts.owner++; return name === 'send' ? { id: 'msg-0001' } : [{ verb: name }]; };
const ownerBus = Object.fromEntries(['inbox', 'tasks', 'agents', 'trail', 'decisions', 'names', 'instances', 'routes', 'thread.claims'].map(v => [v, stub(v)]));
const owner = {
bus: ownerBus, send: stub('send'), settingsWrite: stub('settings'), projectFiles: stub('files'), projectFile: stub('file'), projectSave: stub('save'),
nameWrite: stub('name'), assistantStop: stub('stop'), instancesWrite: stub('instances'), routesWrite: stub('routes'), agentWrite: stub('agent'),
processing: { read: stub('processing'), halt: stub('halt'), resume: stub('resume') },
reads: Object.fromEntries(['settings', 'business', 'busStatus', 'queue', 'row'].map(v => [v, stub(v)])),
chat: Object.fromEntries(['projects', 'threads', 'messages', 'send', 'open', 'createProject', 'createThread'].map(v => [v, stub(v)])),
};
const web = await startServer({ port: 0, board: 'http://127.0.0.1:9', sso, log, ...owner, userOptions, federation: FEDERATION });
t.after(() => close(web));
const p1 = broker.request(human, { verb: 'project.create', args: { name: 'shared' } }).id;
const p2 = broker.request(human, { verb: 'project.create', args: { name: 'private' } }).id;
return { op, iss, broker, human, store, access, counts, opened, lines, port: web.address().port, p1, p2, userTransport, ownerCall, userVerbs, ownerVerbs };
}
// A whole sign-in with `sub`: start, a code at the OP, the callback.
async function signIn(env, sub) {
const start = await call(env.port, { path: '/auth/login' });
assert.equal(start.status, 303);
const cookie = setCookies(start)[0].split(';')[0];
const location = start.headers.location;
const g = env.op.grant(env.iss, location, { sub });
const q = new URLSearchParams({ code: g.code, state: new URL(location).searchParams.get('state') });
const r = await call(env.port, { path: `/auth/callback?${q}`, headers: { cookie } });
return { r, session: sessionOf(r) };
}
const events = env => env.store.get('SELECT count(*) n FROM events').n;
// Every table's row count but events', for a "nothing else written" pin.
const tables = env => Object.fromEntries(env.store.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT IN ('events', 'sqlite_sequence') ORDER BY name")
.map(({ name }) => [name, env.store.get(`SELECT count(*) n FROM "${name}"`).n]));
test('R6 G1 a granted user signs in, gets the user page and reaches the broker as itself', async t => {
const env = await setup(t);
env.access.doc.grants = [grant({ projects: [env.p1] })];
const { r, session } = await signIn(env, 'alice-sub');
assert.equal(r.status, 303, JSON.stringify(r.body));
assert.ok(session, 'a session cookie was set');
const config = await call(env.port, { path: '/api/config', headers: { cookie: session } });
assert.equal(config.status, 200);
assert.equal(config.body.user, true);
assert.equal(config.body.edit, false);
assert.deepEqual(config.body.federation, FEDERATION);
const page = await call(env.port, { path: '/', headers: { cookie: session } });
assert.equal(page.status, 200);
assert.match(page.body, /<script src="\/user\.js" defer><\/script>/);
assert.doesNotMatch(page.body, /app\.js|bus\.js|agents\.js|processing\.js|editor\.js/);
// Only the granted project shows: the broker answered as alice, not as the owner.
const projects = await call(env.port, { path: '/api/chat/projects', headers: { cookie: session } });
assert.equal(projects.status, 200, JSON.stringify(projects.body));
assert.deepEqual(projects.body.rows.map(p => p.id), [env.p1]);
const made = await call(env.port, { method: 'POST', path: '/api/chat/threads', headers: writeHeaders(session), body: JSON.stringify({ project: env.p1, name: 'alice work' }) });
assert.equal(made.status, 200, JSON.stringify(made.body));
const threads = await call(env.port, { path: '/api/chat/threads', headers: { cookie: session } });
assert.deepEqual(threads.body.rows.map(x => x.id), [made.body.id]);
assert.equal(env.counts.owner, 0, 'an owner object ran for a user session');
assert.ok(env.opened.length > 0 && env.opened.every(u => u === 'alice'));
assert.ok(env.lines.some(l => / chat action=createThread user="alice" id=/.test(l)));
// The owner signs in as before and gets the owner page and config.
const ownerSession = (await signIn(env, 'owner-sub')).session;
const ownerConfig = await call(env.port, { path: '/api/config', headers: { cookie: ownerSession } });
assert.equal(Object.hasOwn(ownerConfig.body, 'user'), false);
assert.deepEqual(ownerConfig.body.federation, FEDERATION);
assert.match((await call(env.port, { path: '/', headers: { cookie: ownerSession } })).body, /<script src="\/app\.js" defer><\/script>/);
});
test('R6 G2 a subject with no live grant in this business is refused subject-unknown', async t => {
const past = new Date(Date.now() - 60000).toISOString();
for (const [why, users, grants, sub] of [
['a listed user with no grant', [ALICE], [], 'alice-sub'],
['a grant in another business', [ALICE], [grant({ business: 'other' })], 'alice-sub'],
['an expired grant', [ALICE], [grant({ expires: past })], 'alice-sub'],
["another user's grant", [ALICE, { id: 'bob', home: 'local', subjects: [{ provider: 'a', sub: 'bob-sub' }] }], [grant({ user: 'bob' })], 'alice-sub'],
['a sub in no file', [ALICE], [grant()], 'stranger-sub'],
]) {
await t.test(why, async t => {
const env = await setup(t, { users, grants });
const { r, session } = await signIn(env, sub);
assert.equal(r.status, 403, why);
assert.equal(session, null, `${why}: a session cookie was set`);
assert.match(env.lines.at(-1), / sso refused code=subject-unknown provider=a /);
assert.deepEqual(env.opened, []);
assert.equal(env.counts.user + env.counts.owner, 0);
});
}
await t.test('a file the loader refuses', async t => {
const env = await setup(t);
env.access.fail = true;
const { r, session } = await signIn(env, 'alice-sub');
assert.equal(r.status, 403);
assert.equal(session, null);
});
});
test('R6 G3 a revoke counts on the next request: 401 and the session is gone', async t => {
for (const [why, revoke] of [
['grant removed', env => { env.access.doc.grants = []; }],
['subject removed', env => { env.access.doc.users = [{ ...ALICE, subjects: [] }]; }],
['grant expired', env => { env.access.doc.grants = [grant({ expires: new Date(Date.now() - 1000).toISOString() })]; }],
['file now refused', env => { env.access.fail = true; }],
]) {
await t.test(why, async t => {
const env = await setup(t);
const { session } = await signIn(env, 'alice-sub');
assert.equal((await call(env.port, { path: '/api/chat/projects', headers: { cookie: session } })).status, 200);
revoke(env);
const before = env.counts.user;
const r = await call(env.port, { path: '/api/chat/projects', headers: { cookie: session } });
assert.equal(r.status, 401, `${why}: ${JSON.stringify(r.body)}`);
assert.equal(r.body.error, 'sign-in required');
assert.match(env.lines.at(-1), / sso refused code=user-revoked provider=a user="alice"$/);
assert.equal(env.counts.user, before, 'the transport ran after the revoke');
// Restoring the grant does not bring the session back: it was deleted.
env.access.fail = false; env.access.doc.users = [ALICE]; env.access.doc.grants = [grant()];
assert.equal((await call(env.port, { path: '/api/chat/projects', headers: { cookie: session } })).status, 401);
const page = await call(env.port, { path: '/', headers: { cookie: session } });
assert.equal(page.status, 303);
assert.match(page.headers.location, /^\/auth\/login\?return=/);
});
}
});
// Every owner route a user session might try; none is a chat route.
const OWNER_ROUTES = [
['GET', '/api/bus/inbox'], ['GET', '/api/bus/tasks'], ['GET', '/api/bus/names'], ['GET', '/api/bus/thread.claims'],
['POST', '/api/bus/message', { to: 'coder', body: 'hi' }],
['GET', '/api/settings'], ['POST', '/api/settings', { revision: 'x' }],
['POST', '/api/name', { role: 'assistant', name: 'x' }], ['POST', '/api/assistant/stop', {}],
['POST', '/api/instances', { instance: 'x' }], ['POST', '/api/routes', { routes: [] }],
['POST', '/api/agent/launch', { instance: 'x' }], ['GET', '/api/agent/request?id=x'],
['GET', '/api/processing'], ['POST', '/api/processing/halt', {}],
['GET', '/api/project-files?project=p'], ['GET', '/api/project-file?project=p&path=a'], ['POST', '/api/project-file', { project: 'p' }],
['GET', '/api/board'], ['GET', '/api/conversations'], ['POST', '/api/seen', {}], ['POST', '/api/reply', {}],
['GET', '/api/queue'], ['GET', '/api/queue/1'], ['GET', '/api/business'], ['GET', '/api/bus-status'], ['GET', '/api/task-fields'],
['GET', '/app.js'], ['GET', '/bus.js'], ['GET', '/agents.js'], ['GET', '/editor.js'], ['GET', '/shared/app.css'], ['GET', '/index.html'],
];
test('R6 G4 every owner route answers 403 owner-only before any bus call', async t => {
const env = await setup(t);
const { session } = await signIn(env, 'alice-sub');
const before = events(env);
for (const [method, path, value] of OWNER_ROUTES) {
const r = await call(env.port, { method, path, headers: value === undefined ? { cookie: session } : writeHeaders(session), body: value === undefined ? undefined : JSON.stringify(value) });
assert.equal(r.status, 403, `${method} ${path}: ${r.status} ${JSON.stringify(r.body)}`);
assert.equal(r.body.error, 'owner-only', `${method} ${path}`);
assert.equal(userRoute(new URL(path, 'http://x').pathname, method), false, `${method} ${path}`);
}
assert.deepEqual(env.counts, { owner: 0, user: 0 });
assert.deepEqual(env.opened, [], 'a user transport was built for an owner route');
assert.equal(events(env), before, 'something was written');
});
test('R6 G5 the bus refuses every owner verb over the user transport on its own', async t => {
const env = await setup(t);
const o = consoleBus(env.userTransport('alice'), { send: true, owner: env.ownerCall });
const before = env.store.get('SELECT coalesce(max(seq), 0) n FROM events').n, rest = tables(env);
const refusals = [
['inbox', () => o.bus.inbox()], ['tasks', () => o.bus.tasks()], ['agents', () => o.bus.agents()], ['trail', () => o.bus.trail()],
['decisions', () => o.bus.decisions()], ['instances', () => o.bus.instances()], ['routes', () => o.bus.routes()], ['thread.claims', () => o.bus['thread.claims']()],
['message.send', () => o.send({ to: 'chief', body: 'as the owner' })], ['limits.set', () => o.settingsWrite({ revision: 'x' })],
['project.files', () => o.projectFiles({ project: env.p1 })], ['project.file', () => o.projectFile({ project: env.p1, path: 'a' })],
['project.file.save', () => o.projectSave({ project: env.p1 })], ['name.set', () => o.nameWrite({ role: 'assistant', name: 'x' })],
['assistant.stop', () => o.assistantStop({})], ['instances.set', () => o.instancesWrite({})], ['routes.set', () => o.routesWrite({})],
['instance.launch', () => o.agentWrite('instance.launch', {})], ['processing.status', () => o.processing.read()],
['processing.halt', () => o.processing.halt({})], ['library.status', () => o.libraryStatus({})],
['project.create', () => o.chat.createProject({ name: 'mine' })],
];
for (const [why, run] of refusals) await assert.rejects(Promise.resolve().then(run), e => e.code === 'access-refused', why);
// The broker records each refusal (row 37): one action.refused per verb, its body the code
// alone (#refused names no verb). No other table gains or loses a row.
const added = env.store.all('SELECT kind, body FROM events WHERE seq > ? ORDER BY seq', before);
assert.equal(added.length, refusals.length, 'one event per refused verb');
for (const e of added) {
assert.equal(e.kind, 'action.refused');
assert.deepEqual(JSON.parse(e.body), { code: 'access-refused' });
}
assert.deepEqual(tables(env), rest, 'a refused verb wrote');
});
// sage-3153 (C6): in a user's chat the owner transport carries `plugins` with {} and nothing else,
// every chat verb goes over the user transport, and the owner's answer never reaches the user.
test('R6 G9 a user chat sends only the plugins read over the owner transport', async t => {
const env = await setup(t);
const { session } = await signIn(env, 'alice-sub');
const bodies = [];
const go = async (method, path, value) => {
const r = await call(env.port, { method, path, headers: value === undefined ? { cookie: session } : writeHeaders(session), body: value === undefined ? undefined : JSON.stringify(value) });
assert.equal(r.status, 200, `${method} ${path}: ${JSON.stringify(r.body)}`);
bodies.push(JSON.stringify(r.body));
return r.body;
};
await go('GET', '/api/chat/projects');
const thread = (await go('POST', '/api/chat/threads', { project: env.p1, name: 'alice work' })).id;
await go('GET', `/api/chat/threads?project=${env.p1}`);
await go('POST', `/api/chat/threads/${thread}/open`, {});
await go('POST', `/api/chat/threads/${thread}/messages`, { body: 'hello' });
await go('GET', `/api/chat/threads/${thread}/messages`);
assert.ok(env.ownerVerbs.length > 0, 'the chat never read plugins');
// Exactly the verb `plugins` and exactly {}: no value from the session or a request reaches it.
for (const entry of env.ownerVerbs) assert.deepEqual(entry, ['plugins', {}]);
const sent = JSON.stringify(env.ownerVerbs);
for (const value of ['alice', 'alice-sub', 'alice work', 'hello', env.p1, thread]) assert.equal(sent.includes(value), false, `${value} reached the owner transport`);
for (const verb of ['project.list', 'thread.create', 'thread.list', 'thread.open', 'thread.send', 'thread.messages']) assert.ok(env.userVerbs.includes(verb), `${verb} did not go over the user transport`);
assert.equal(env.userVerbs.includes('plugins'), false);
for (const body of bodies) assert.doesNotMatch(body, new RegExp(OWNER_MARKER));
assert.equal(env.counts.owner, 0);
});
test('R6 G6 the user page holds the notice word for word', async t => {
const html = readFileSync(new URL('user.html', PUBLIC), 'utf8');
const notice = /<p id="user-notice"[^>]*>([^<]*)<\/p>/.exec(html);
assert.ok(notice, 'no #user-notice paragraph');
assert.equal(notice[1], NOTICE);
const env = await setup(t);
const { session } = await signIn(env, 'alice-sub');
assert.ok((await call(env.port, { path: '/', headers: { cookie: session } })).body.includes(NOTICE));
});
// The user page outside a session: a small static server over the public files, /api/config stubbed.
async function userPage(t, config) {
const types = { html: 'text/html', js: 'text/javascript', css: 'text/css', svg: 'image/svg+xml' };
const server = createHttpServer((req, res) => {
const path = new URL(req.url, 'http://x').pathname;
if (path === '/api/config') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(config)); }
if (path.startsWith('/api/chat/')) { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ rows: [], at: new Date().toISOString() })); }
const name = path === '/' ? 'user.html' : path.slice(1);
if (!/^[a-z.]+$/.test(name)) { res.writeHead(404); return res.end(); }
try { const body = readFileSync(new URL(name, PUBLIC)); res.writeHead(200, { 'content-type': types[name.split('.').pop()] ?? 'text/plain' }); res.end(body); }
catch { res.writeHead(404); res.end(); }
});
await new Promise(r => server.listen(0, '127.0.0.1', r));
t.after(() => close(server));
return server.address().port;
}
test('a granted user opening an archived organization route has no enabled lifecycle controls', async t => {
const b = await browser(); t.after(() => b.close());
const port = await userPage(t, { user: true, send: true });
await b.navigate(`http://127.0.0.1:${port}/#/orgs/beta/settings/organizations?org=beta`);
assert.equal(await b.evaluate(`!!document.querySelector('#org-restore:not(:disabled), #org-delete-open:not(:disabled), #org-delete-final:not(:disabled)')`), false);
});
test('R6 G7 the hub label and plain peer links render from config on both pages', async t => {
const links = 'JSON.stringify({label:document.querySelector("#hub-label")?.textContent,hidden:document.querySelector("#federation").hidden,peers:[...document.querySelectorAll("#federation a")].map(a=>[a.getAttribute("href"),a.textContent,a.attributes.length])})';
const expected = { label: 'This Console: hub', hidden: false, peers: [['https://factory.example.test', 'Software factory', 2]] };
const wait = (b, expression) => b.evaluate(`(async()=>{for(let i=0;i<100;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30));}throw new Error(${JSON.stringify(expression)});})()`);
const b = await browser(); t.after(() => b.close());
// The owner page, over the real server.
const f = await fixture(); t.after(() => f.close());
const owner = await startServer({ port: 0, board: f.boardURL, federation: FEDERATION }); t.after(() => close(owner));
await b.navigate(`http://127.0.0.1:${owner.address().port}/`);
await wait(b, '!document.querySelector("#federation").hidden');
assert.deepEqual(JSON.parse(await b.evaluate(links)), expected);
// The user page, with a hostile label kept as text.
const hostile = { self: 'hub', peers: [...FEDERATION.peers, { id: 'x', origin: 'https://x.example.test', label: '<img src=x onerror="window.injected=1">' }, { id: 'y', origin: 'javascript:alert(1)', label: 'bad' }] };
await b.navigate(`http://127.0.0.1:${await userPage(t, { user: true, send: true, federation: hostile })}/`);
await wait(b, '!document.querySelector("#federation").hidden');
const user = JSON.parse(await b.evaluate(links));
assert.equal(user.label, 'This Console: hub');
assert.deepEqual(user.peers, [...expected.peers, ['https://x.example.test', '<img src=x onerror="window.injected=1">', 2]]);
assert.equal(await b.evaluate('window.injected'), undefined);
assert.equal(await b.evaluate('document.querySelector("#user-notice").textContent'), NOTICE);
// No federation in config: nothing is shown.
await b.navigate(`http://127.0.0.1:${await userPage(t, { user: true, send: true })}/`);
await wait(b, 'document.querySelector(".chat-area")');
assert.equal(await b.evaluate('document.querySelector("#federation").hidden'), true);
});
test('R6 G8 userCall spawns user-cli directly with the user nonce, no human nonce, and the user request', async t => {
const dir = mkdtempSync(join(tmpdir(), 'webui-user-call-'));
t.after(() => rmSync(dir, { recursive: true, force: true }));
const socket = join(dir, 'bus.sock');
const seen = [];
const server = createNetServer(conn => {
let input = '';
conn.on('data', chunk => {
input += chunk;
if (!input.includes('\n')) return;
const message = JSON.parse(input);
const pid = message.user?.pid;
// Read the child while it waits on this answer.
const proc = name => readFileSync(`/proc/${pid}/${name}`, 'utf8');
seen.push({ message, argv: proc('cmdline').split('\0'), env: proc('environ').split('\0').map(e => e.split('=')[0]), ppid: Number(proc('stat').replace(/^.*\) /s, '').split(' ')[1]) });
conn.end(JSON.stringify({ ok: true, result: { answered: true } }) + '\n');
});
});
await new Promise(r => server.listen(socket, r));
t.after(() => server.close());
const result = await userCall({ socket, business: 'demo', user: 'alice', env: { ...process.env, MOSAIC_BUS_CLI_NONCE: 'f'.repeat(64) } })('thread.list', { project: 'p' });
assert.deepEqual(result, { answered: true });
assert.equal(seen.length, 1);
const [{ message, argv, env, ppid }] = seen;
assert.equal(argv[1], USER_CLI);
assert.notEqual(argv[1], HUMAN_CLI);
assert.equal(argv[2], socket);
assert.equal(ppid, process.pid, 'user-cli re-executed: the Console is not its parent');
assert.ok(env.includes('MOSAIC_BUS_USER_NONCE'));
assert.equal(env.includes('MOSAIC_BUS_CLI_NONCE'), false);
assert.deepEqual(Object.keys(message).sort(), ['args', 'user', 'verb']);
assert.equal(message.verb, 'thread.list');
assert.deepEqual(message.args, { project: 'p' });
assert.equal(message.user.business, 'demo');
assert.equal(message.user.user, 'alice');
assert.match(message.user.nonce, /^[0-9a-f]{64}$/);
assert.equal(USER_CLI, fileURLToPath(new URL('../../bus/src/user-cli.mjs', import.meta.url)));
});
test('project assets are owner-only while granted-user chat remains available', async t => {
const env = await setup(t);
const { session: owner } = await signIn(env, 'owner-sub');
const { session: user } = await signIn(env, 'alice-sub');
for (const path of ['/projects.js', '/projects.css']) {
assert.equal((await call(env.port, { path, headers: { cookie: owner } })).status, 200, `owner ${path}`);
assert.equal((await call(env.port, { path, headers: { cookie: user } })).status, 403, `user ${path}`);
}
assert.equal((await call(env.port, { path: '/chat.js', headers: { cookie: user } })).status, 200);
assert.equal((await call(env.port, { path: '/api/chat/projects', headers: { cookie: user } })).status, 200);
});