From 85122dd2bc4f674bae52417bea2cd1d2c2ded544 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Tue, 10 Nov 2026 14:49:31 -0600 Subject: [PATCH] feat(webui): separate account sessions from root authority (#1873) --- packages/webui/src/cli.mjs | 3 +- packages/webui/src/console-restart-http.mjs | 4 +- packages/webui/src/dev-owner.mjs | 4 +- packages/webui/src/serve.mjs | 23 +++-- packages/webui/src/sso.mjs | 50 +++++++---- packages/webui/tests/accounts-sso.test.mjs | 85 +++++++++++++++++++ packages/webui/tests/chat-instances.test.mjs | 2 +- packages/webui/tests/decide-sso.test.mjs | 3 +- packages/webui/tests/granted-user.test.mjs | 3 +- .../webui/tests/helpers/owner-accounts.mjs | 5 ++ packages/webui/tests/helpers/sso-session.mjs | 2 + .../tests/helpers/w15-project-remote-real.mjs | 2 +- .../tests/project-remote-transport.test.mjs | 3 +- packages/webui/tests/request-http.test.mjs | 3 +- packages/webui/tests/sso.test.mjs | 10 ++- .../webui/tests/user-option-swap.test.mjs | 3 +- 16 files changed, 163 insertions(+), 42 deletions(-) create mode 100644 packages/webui/tests/accounts-sso.test.mjs create mode 100644 packages/webui/tests/helpers/owner-accounts.mjs diff --git a/packages/webui/src/cli.mjs b/packages/webui/src/cli.mjs index 8dfb2f95e..714947a9d 100644 --- a/packages/webui/src/cli.mjs +++ b/packages/webui/src/cli.mjs @@ -21,6 +21,7 @@ import { loadRootAgents } from '../../organization/src/agent-levels.mjs'; import { consoleReads, redactor } from './reads.mjs'; import { createDevOwner } from './dev-owner.mjs'; import { devOwnerInstance, devLanOptions } from '../../cli/src/dev-local-owner.mjs'; +import { loadAccounts } from '../../organization/src/accounts.mjs'; import { createSso, readSlot } from './sso.mjs'; import { readFileSync, statSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; @@ -151,7 +152,7 @@ try { load: () => loadAccess(accessFilePath(configDir()), accessContextFor(system, process.env)), business: busBusiness({ dataRoot: system.dataRoot, business: options.business ?? null }), }); - sso = await createSso(system.console.sso, { secrets, users }); + sso = await createSso(system.console.sso, { secrets, users, accounts: { load: () => loadAccounts(join(configDir(), 'accounts.json'), { providers: system.console.sso.providers }) } }); // Each request of a granted user's session gets the bus options over that user's own // user-cli transport. The human transport above serves only the chat's `plugins` read (C6). userOptions = userOptionsFor({ owner: ownerCall, send: sendOn, transport: user => userCaller({ dataRoot: system.dataRoot, socket: socketPath(system.dataRoot), business: options.business ?? null, user }) }); diff --git a/packages/webui/src/console-restart-http.mjs b/packages/webui/src/console-restart-http.mjs index 7c1a719f2..c776f2eaf 100644 --- a/packages/webui/src/console-restart-http.mjs +++ b/packages/webui/src/console-restart-http.mjs @@ -22,9 +22,9 @@ async function emptyBody(req) { return value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length === 0 ? null : 'the body is {}'; } -export async function consoleRestartHTTP(req, res, { session = null, owner = false, send = false, restart = null, trail = null, boot, log = () => {} }) { +export async function consoleRestartHTTP(req, res, { session = null, operator = false, send = false, restart = null, trail = null, boot, log = () => {} }) { if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' }); - if (!owner || !session) return json(res, 403, { error: 'owner-only', message: 'restarting the Console is the owner\'s' }); + if (!operator || !session) return json(res, 403, { error: 'owner-only', message: 'restarting the Console requires an instance operator' }); if (!send) return json(res, 403, { error: 'read-only', message: 'start the Console with --send to make changes' }); const invalid = await emptyBody(req); if (invalid) return json(res, invalid === 'JSON body required' ? 415 : 400, { error: 'invalid-request', message: invalid }); diff --git a/packages/webui/src/dev-owner.mjs b/packages/webui/src/dev-owner.mjs index d62bddf02..ce5dddacf 100644 --- a/packages/webui/src/dev-owner.mjs +++ b/packages/webui/src/dev-owner.mjs @@ -1,8 +1,8 @@ import { DEV_OWNER } from '../../cli/src/dev-local-owner.mjs'; -const session = Object.freeze({ ...DEV_OWNER, name: 'Local operator' }); +const session = Object.freeze({ ...DEV_OWNER, name: 'Local operator', rootOwner: true, instanceRole: 'operator' }); export function createDevOwner() { - return Object.freeze({ devOwner: true, session: () => session, formTargets: () => [], + return Object.freeze({ devOwner: true, mode: 'dev', session: () => session, formTargets: () => [], handle: (_req, res) => { res.writeHead(404); res.end(); }, summary: () => [], health: () => ({}), close: () => {} }); } diff --git a/packages/webui/src/serve.mjs b/packages/webui/src/serve.mjs index 1e111ca83..c3228ecf6 100644 --- a/packages/webui/src/serve.mjs +++ b/packages/webui/src/serve.mjs @@ -790,6 +790,7 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF // names (without a port) a remote browser may use; only the dev owner takes them, and only with // them may it bind a non-loopback IPv4 address. SSO, preview and tester listeners stay loopback. if (!Array.isArray(devAllowHosts) || !devAllowHosts.every(devHostName)) throw new Error('dev allowed hosts must be host names or IPv4 addresses without a port'); + if ((sso?.mode === 'accounts') && (sso?.devOwner || devAllowHosts.length)) throw new Error('accounts mode refuses the dev LAN same-origin path'); if (devAllowHosts.length && !sso?.devOwner) throw new Error('dev allowed hosts need the dev local owner'); const devLan = Boolean(sso?.devOwner) && devAllowHosts.length > 0; if (sso?.devOwner && host !== '127.0.0.1' && !(devLan && isIP(host) === 4)) throw new Error(devLan ? 'dev local owner binds an IPv4 address' : 'dev local owner must bind 127.0.0.1'); @@ -935,10 +936,15 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF } if (session) signer = { sso: true, user: session.name, host: sso.publicHost, origin: localOrigin ?? sso.publicOrigin }; // Row 252: only the owner's session answers a decision. A granted user stops at userRoute below. - if (session && session.user === undefined) ssoSession = session; + if (session?.rootOwner === true) ssoSession = session; // FED R6 (#1800): a granted user. The Console's gate first; behind it no human-transport // object is left, so a route past the gate reaches the broker only as this user. - if (session?.user !== undefined) { + const instanceAction = originalPath === '/api/console/restart'; + if (session && !session.rootOwner && session.user === undefined && orgId === null && !orgList && !hook?.publicRead && !instanceAction && path !== '/api/config' && path !== '/healthz' && !files.has(path)) return json(res, 404, { error: 'not-found' }); + if (session && !session.rootOwner && session.user === undefined) { + bus = reads = send = settingsWrite = projectFiles = projectFile = projectSave = libraryStatus = libraryRevert = chat = nameWrite = assistantStop = instancesWrite = routesWrite = agentWrite = proxyCall = processing = decisionWrite = requestRead = requestWrite = upstream = null; + } + if (session?.user !== undefined && !session.rootOwner && !instanceAction) { if (!organizations && !userRoute(path, req.method)) return json(res, 403, { error: 'owner-only', message: 'this part of the Console is the business owner\'s' }); if (!organizations && userOptions === null) return json(res, 503, { error: 'not-configured', message: 'the Console has no user transport' }); if (!organizations) ({ bus, send, settingsWrite, projectFiles, projectFile, projectSave, chat, nameWrite, assistantStop, instancesWrite, routesWrite, agentWrite, processing } = userOptions(session)); @@ -982,11 +988,12 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF return json(res, 403, { error: 'unavailable', sent: false }); } if (hook) { - if (!hook.publicRead && (!currentSession || !named || (granted && req.method !== 'GET'))) return json(res, 403, { error: 'owner-only' }); + const instanceAction = originalPath === '/api/console/restart'; + if (!hook.publicRead && (!currentSession || !named || (granted && req.method !== 'GET' && !instanceAction))) return json(res, 403, { error: 'owner-only' }); const origin = localOrigin ?? sso?.publicOrigin; if (req.method !== 'GET' && one(req, 'origin') !== origin) return json(res, 403, { error: 'cross-origin request refused' }); if (req.method !== 'GET' && one(req, 'sec-fetch-site') !== 'same-origin') return json(res, 403, { error: 'cross-site request refused' }); - return hook.handler(req, res, { path: originalPath, search, session: ssoSession, orgId, origin, owner: !tester && !granted && named && sso !== null, send: owner.send !== null }); + return hook.handler(req, res, { path: originalPath, search, session: currentSession, orgId, origin, owner: !tester && !granted && named && currentSession?.rootOwner === true, operator: !tester && named && currentSession?.instanceRole === 'operator', send: owner.send !== null }); } const writer = tester ? { tester: true, user: 'tester', origin: TESTER_ORIGIN } : signer; // F3: the owner's routing and agent changes go to the action trail too (who, when, what). @@ -1012,7 +1019,7 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF if (decisionPath) { if (tester) return decisionRefuse(res, 'not-found'); const decide = decisionWrite && send && named && sso ? { call: decisionWrite, origin: localOrigin ?? sso.publicOrigin } : null; - return decisionHTTP(req, res, { path, decide, session: ssoSession, live: () => sso.session(req), confirmations, log }); + return decisionHTTP(req, res, { path, decide, session: ssoSession, live: () => { const live = sso.session(req); return live?.rootOwner === true ? live : null; }, confirmations, log }); } // #797 / #1839 Task 3: the owner's request intake controls. The tester listener never has them, and a // granted user stopped at userRoute above. Reads need the read transport; the writes also --send. @@ -1023,12 +1030,12 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF if (!(named && sso !== null)) return requestHTTP(req, res, { path, requestRead: null, requestWrite: null, session: null, live: () => null, origin: null, log }); return requestHTTP(req, res, { path, requestRead, requestWrite: send ? requestWrite : null, - session: ssoSession, live: () => sso.session(req), origin: localOrigin ?? sso.publicOrigin, log }); + session: ssoSession, live: () => { const live = sso.session(req); return live?.rootOwner === true ? live : null; }, origin: localOrigin ?? sso.publicOrigin, log }); } if (remotePath) { if (tester || granted || !named || sso === null) return json(res, 403, { error: 'owner-only' }); return projectRemoteHTTP(req, res, { path, read: requestRead, write: send ? requestWrite : null, - session: ssoSession, live: () => sso.session(req), origin: localOrigin ?? sso.publicOrigin }); + session: ssoSession, live: () => { const live = sso.session(req); return live?.rootOwner === true ? live : null; }, origin: localOrigin ?? sso.publicOrigin }); } // Phase P2 (#1873): the owner's System types read and writes on the selected organization. if (systemTypesPath) { @@ -1185,7 +1192,7 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF // `send`: the page shows the composer only where a send can pass (the public name, --send on). // `edit`: the editor shows Save only where a save can pass, the same test as the route's. // `user` and `federation` (FED R6) only when there is one, so the owner's config is unchanged. - if (path === '/api/config') return json(res, 200, { board: upstream, ...(organizations && preselect ? { preselect } : {}), ...(tester ? { tester: true } : {}), ...(sso ? { sso: true } : {}), ...(sso?.devOwner ? { devOwner: true } : {}), ...(granted ? { user: true, chatGrants } : {}), ...(!tester && !granted && named && sso !== null && requestRead ? { requests: true, requestWrites: Boolean(send && requestWrite), workspaceFiles: true, projectRemotes: true, projectRemoteWrites: Boolean(send && requestWrite) } : {}), ...(hub ? { federation: hub } : {}), ...(organizations ? { orgSetup: !tester && !granted && named && sso !== null && owner.send !== null } : {}), send: !organizations && !tester && Boolean(send) && named, ...(organizations && orgId ? { chatSend: !tester && Boolean(send) && named && orgBusHealthy, settingsSend: !tester && !granted && Boolean(send) && named && orgBusHealthy } : {}), boot, consoleRestart: !tester && !granted && named && sso !== null && owner.send !== null && restart !== null && trail !== null, decide: (!organizations || (orgId !== null && orgBusHealthy)) && !tester && !granted && Boolean(send) && Boolean(decisionWrite) && named && sso !== null, edit: !organizations && !tester && !granted && Boolean(send) && Boolean(projectSave) && named, northStarApprove: (!organizations || (orgId !== null && orgBusHealthy)) && !tester && !granted && Boolean(send) && Boolean(projectSave) && Boolean(projectFile) && named }); + if (path === '/api/config') return json(res, 200, { board: upstream, ...(organizations && preselect ? { preselect } : {}), ...(tester ? { tester: true } : {}), ...(sso ? { sso: true } : {}), ...(sso?.devOwner ? { devOwner: true } : {}), ...(granted ? { user: true, chatGrants } : {}), ...(!tester && !granted && named && sso !== null && requestRead ? { requests: true, requestWrites: Boolean(send && requestWrite), workspaceFiles: true, projectRemotes: true, projectRemoteWrites: Boolean(send && requestWrite) } : {}), ...(hub ? { federation: hub } : {}), ...(organizations ? { orgSetup: !tester && !granted && named && sso !== null && owner.send !== null } : {}), send: !organizations && !tester && Boolean(send) && named, ...(organizations && orgId ? { chatSend: !tester && Boolean(send) && named && orgBusHealthy, settingsSend: !tester && !granted && Boolean(send) && named && orgBusHealthy } : {}), boot, consoleRestart: !tester && named && currentSession?.instanceRole === 'operator' && owner.send !== null && restart !== null && trail !== null, decide: (!organizations || (orgId !== null && orgBusHealthy)) && !tester && !granted && Boolean(send) && Boolean(decisionWrite) && named && sso !== null, edit: !organizations && !tester && !granted && Boolean(send) && Boolean(projectSave) && named, northStarApprove: (!organizations || (orgId !== null && orgBusHealthy)) && !tester && !granted && Boolean(send) && Boolean(projectSave) && Boolean(projectFile) && named }); if (path === '/healthz') return json(res, 200, { ok: true, ...(sso ? { sso: sso.health() } : {}) }); if (path === '/favicon.ico') { res.writeHead(204); return res.end(); } const file = files.get(path); diff --git a/packages/webui/src/sso.mjs b/packages/webui/src/sso.mjs index 32f4037fe..e6b5d7bac 100644 --- a/packages/webui/src/sso.mjs +++ b/packages/webui/src/sso.mjs @@ -19,10 +19,10 @@ export const LOGIN_COOKIE = '__Host-mosaic_login'; const ATTRS = 'Path=/; Secure; HttpOnly; SameSite=Lax'; const LOGIN_MAX_AGE = 600; const SESSION_ABSOLUTE = 8 * 3600 * 1000, SESSION_IDLE = 3600 * 1000; -const MAX_SESSIONS = 64, MAX_LOGINS = 32; +const MAX_SESSIONS = 512, MAX_LOGINS = 128, MAX_ACCOUNT_SESSIONS = 8; const FETCH_TIMEOUT = 10000; const RETRY_CAP = 300000; -const CODES = new Set(['login-record-missing', 'state-mismatch', 'auth-error-response', 'grant-failed', 'id-token-invalid', 'signature-invalid', 'alg-refused', 'issuer-mismatch', 'subject-unknown', 'user-revoked', 'discovery-failed', 'jwks-failed']); +const CODES = new Set(['login-record-missing', 'state-mismatch', 'auth-error-response', 'grant-failed', 'id-token-invalid', 'signature-invalid', 'alg-refused', 'issuer-mismatch', 'subject-unknown', 'user-revoked', 'account-revoked', 'discovery-failed', 'jwks-failed']); const sha256 = value => createHash('sha256').update(value).digest('hex'); const escape = text => String(text).replace(/[&<>"']/g, c => `&#${c.charCodeAt(0)};`); @@ -125,7 +125,7 @@ async function discover(p, fetchOptions) { // `retryFirst` is for tests too; production waits 5 s, doubling, capped at 5 minutes. // `users` (FED R6, #1800) is consoleAccess() from access.mjs, or null: a subject that is not the // owner's signs in as the access-file user with a live grant, and each request checks it again. -export async function createSso(config, { secrets, fetch: customFetch = null, log = line => console.log(line), retryFirst = 5000, users = null } = {}) { +export async function createSso(config, { secrets, fetch: customFetch = null, log = line => console.log(line), retryFirst = 5000, users = null, accounts = null } = {}) { checkConsole({ sso: config }); oauth ??= await import('oauth4webapi'); const publicOrigin = config.publicOrigin; @@ -280,18 +280,25 @@ export async function createSso(config, { secrets, fetch: customFetch = null, lo try { header = JSON.parse(Buffer.from(result.id_token.split('.')[0], 'base64url').toString('utf8')); } catch { header = null; } if (!header || !entry.config.algs.includes(header.alg)) { refuse('alg-refused', pid); return failed(res, clear); } if (claims.iss !== entry.config.issuer) { refuse('issuer-mismatch', pid); return failed(res, clear); } - let name = typeof claims.sub === 'string' ? entry.subjects.get(claims.sub) : undefined; - // FED R6: console.sso subjects and access-file subjects are disjoint (R1), so the owner's - // list is asked first and a user is asked only on a miss. - const user = name === undefined && typeof claims.sub === 'string' ? users?.find({ provider: pid, sub: claims.sub }) ?? null : null; - if (user !== null) name = user; - if (name === undefined) { + // Account authority and the legacy root grant are independent. A configured + // owner subject alone is never an account and cannot bypass a refused store. + let account = null; + try { account = accounts?.load().users.find(u => u.state === 'active' && u.subjects.some(s => s.provider === pid && s.sub === claims.sub)) ?? null; } catch { /* fail closed for accounts */ } + const user = typeof claims.sub === 'string' ? users?.find({ provider: pid, sub: claims.sub }) ?? null : null; + const rootOwner = account?.instanceRole === 'operator' && entry.subjects.has(claims.sub); + if (!account && user === null) { refuse('subject-unknown', pid, ` iss=${JSON.stringify(String(claims.iss).slice(0, 255))} sub=${JSON.stringify(String(claims.sub).slice(0, 255))}`); return failed(res, clear); } - // Step 7: the session, then the return path. + const name = account?.name ?? user; const id = randomBytes(32).toString('base64url'), now = Date.now(); - remember(sessions, sha256(id), { provider: pid, iss: claims.iss, sub: claims.sub, name, ...(user !== null ? { user } : {}), idToken: result.id_token, created: now, seen: now }, MAX_SESSIONS); + if (account) { + const own = [...sessions].filter(([, s]) => s.account === account.id); + while (own.length >= MAX_ACCOUNT_SESSIONS) sessions.delete(own.shift()[0]); + } + remember(sessions, sha256(id), { provider: pid, iss: claims.iss, sub: claims.sub, name, + ...(account ? { account: account.id, instanceRole: account.instanceRole, authGen: account.authGen } : {}), + rootOwner, ...(user !== null ? { user } : {}), idToken: result.id_token, created: now, seen: now }, MAX_SESSIONS); return redirect(res, returnURL(record.ret), [...clear, `${SESSION_COOKIE}=${id}; ${ATTRS}`]); } @@ -304,13 +311,20 @@ export async function createSso(config, { secrets, fetch: customFetch = null, lo if (!s) return null; const now = Date.now(); if (now - s.created >= SESSION_ABSOLUTE || now - s.seen >= SESSION_IDLE) { sessions.delete(key); return null; } - // FED R6 (design 3.1 D5): a user's grant is read again on every request, so a user revoked, - // removed or expired since sign-in has no session from the next request on. - if (s.user !== undefined && !users?.check(s)) { - sessions.delete(key); - refuse('user-revoked', s.provider, ` user=${JSON.stringify(s.user)}`); - return null; + if (s.account !== undefined) { + let account; + try { account = accounts?.load().users.find(u => u.id === s.account); } catch { /* refuse */ } + if (!account || account.state !== 'active' || account.authGen !== s.authGen || account.instanceRole !== s.instanceRole || !account.subjects.some(x => x.provider === s.provider && x.sub === s.sub)) { + refuse('account-revoked', s.provider); + // Never reacquire account authority on this cookie, even after re-enable. + delete s.account; delete s.instanceRole; delete s.authGen; s.rootOwner = false; + } } + if (s.user !== undefined && !users?.check(s)) { + refuse('user-revoked', s.provider, ` user=${JSON.stringify(s.user)}`); + delete s.user; + } + if (s.account === undefined && s.user === undefined) { sessions.delete(key); return null; } if (touch) s.seen = now; return s; } @@ -351,7 +365,7 @@ export async function createSso(config, { secrets, fetch: customFetch = null, lo } return { - publicOrigin, publicHost, sessions, logins, handle, session, returnURL, + mode: 'accounts', publicOrigin, publicHost, sessions, logins, handle, session, returnURL, chatGrants: session => users?.chatGrants?.(session) ?? [], health: () => Object.fromEntries([...providers].map(([id, e]) => [id, e.state])), formTargets: () => [...new Set([...providers.values()].filter(e => e.as?.end_session_endpoint).map(e => new URL(e.as.end_session_endpoint).origin))], diff --git a/packages/webui/tests/accounts-sso.test.mjs b/packages/webui/tests/accounts-sso.test.mjs new file mode 100644 index 000000000..4f168b409 --- /dev/null +++ b/packages/webui/tests/accounts-sso.test.mjs @@ -0,0 +1,85 @@ +// M3: real accounts store, real OIDC code flow, isolated port-zero providers. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { request } from 'node:http'; +import { mkdtempSync, rmSync, writeFileSync, chmodSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { loadAccounts, withAccounts } from '../../organization/src/accounts.mjs'; +import { createSso, SESSION_COOKIE } from '../src/sso.mjs'; +import { startServer } from '../src/serve.mjs'; +import { consoleAccess } from '../src/access.mjs'; +import { fakeOidc } from './helpers/fake-oidc.mjs'; +import { close } from './fixture.mjs'; +const HOST = 'accounts.example.test', ORIGIN = `https://${HOST}`; +function call(port, path, { cookie, method = 'GET', body } = {}) { + return new Promise((resolve, reject) => { + const req = request({ host: '127.0.0.1', port, path, method, headers: { host: HOST, ...(cookie ? { cookie } : {}), ...(body ? { origin: ORIGIN, 'sec-fetch-site': 'same-origin', 'content-type': 'application/json' } : {}) } }, res => { + let text = ''; res.on('data', c => text += c); res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, text })); + }); req.on('error', reject); req.end(body); + }); +} +async function setup(t, { legacy = false } = {}) { + const dir = mkdtempSync(join(tmpdir(), 'as-')); chmodSync(dir, 0o700); t.after(() => rmSync(dir, { recursive: true, force: true })); + const op = await fakeOidc(); t.after(() => op.close()); const iss = op.issuer('a'); + const config = { publicOrigin: ORIGIN, providers: [{ id: 'a', issuer: iss.issuer, clientId: iss.clientId, clientSecret: { slot: 'a' }, algs: ['RS256'], subjects: [{ sub: 'owner', name: 'Owner' }, { sub: 'drift', name: 'Drift' }] }] }; + const ctx = { configDir: dir, providers: config.providers }, file = join(dir, 'accounts.json'); + const row = (id, sub, instanceRole) => ({ id, subjects: [{ provider: 'a', sub }], name: sub, instanceRole, state: 'active', authGen: 1, created: '2026-11-10T00:00:00Z' }); + await withAccounts(ctx, { init: true, revision: 0, verb: 'init' }, d => { d.users.push(row('u-000000000001', 'owner', 'operator'), row('u-000000000002', 'pat', 'user'), row('u-000000000003', 'op', 'operator')); }); + let access = { users: [{ id: 'legacy', subjects: [{ provider: 'a', sub: 'pat' }] }], grants: legacy ? [{ user: 'legacy', business: 'demo', projects: ['*'], instances: ['*'], level: 'collaborator' }] : [] }; + const lines = [], sso = await createSso(config, { secrets: new Map([['a', iss.clientSecret]]), fetch: op.fetch, log: l => lines.push(l), accounts: { load: () => loadAccounts(file, ctx) }, users: consoleAccess({ load: () => access, business: () => 'demo' }) }); + t.after(() => sso.close()); let restarts = 0; + const web = await startServer({ port: 0, board: 'http://127.0.0.1:9', sso, bus: { inbox: async () => [] }, send: async () => ({}), restart: () => restarts++, trail: () => {}, userOptions: () => ({ bus: { inbox: async () => [] }, chat: { projects: async () => [] } }), log: () => {} }); t.after(() => close(web)); const port = web.address().port; + async function login(sub = 'pat') { + const begin = await call(port, '/auth/login'); const loc = begin.headers.location; const grant = op.grant(iss, loc, { sub }); + const r = await call(port, `/auth/callback?${new URLSearchParams({ code: grant.code, state: new URL(loc).searchParams.get('state') })}`, { cookie: begin.headers['set-cookie'][0].split(';')[0] }); + const cookie = r.headers['set-cookie']?.find(c => c.startsWith(SESSION_COOKIE + '=') && !c.includes('Max-Age=0'))?.split(';')[0]; return { ...r, cookie }; + } + const read = () => loadAccounts(file, ctx); + const change = (fn, verb = 'user.update') => withAccounts(ctx, { revision: read().revision, verb }, fn); + return { login, sso, lines, file, port, read, change, revoke: () => { access.grants = []; }, restarts: () => restarts }; +} +test('account sign-in records separate authority; unknown and drifted owner subjects refuse', async t => { + const s = await setup(t); const p = await s.login(); assert.equal(p.status, 303); + const session = s.sso.session({ headers: { cookie: p.cookie } }); assert.equal(session.account, 'u-000000000002'); assert.equal(session.authGen, 1); assert.equal(session.instanceRole, 'user'); assert.equal(session.rootOwner, false); assert.equal(session.user, undefined); + for (const sub of ['unknown', 'drift']) { const r = await s.login(sub); assert.equal(r.status, 403); assert.equal(r.cookie, undefined); assert.match(s.lines.at(-1), /subject-unknown/); } + const owner = await s.login('owner'); assert.equal(s.sso.session({ headers: { cookie: owner.cookie } }).rootOwner, true); +}); +test('disabled, removed, signout, changed subject and role generations invalidate without resurrection', async t => { + for (const mutation of ['disable', 'disable-enable', 'role-roundtrip', 'signout', 'subject', 'remove', 'missing', 'invalid']) await t.test(mutation, async t => { + const s = await setup(t), r = await s.login(); assert.ok(r.cookie, 'account sign-in required before revocation'); + if (mutation.startsWith('disable')) { await s.change(d => d.users[1].state = 'disabled'); if (mutation.endsWith('enable')) await s.change(d => d.users[1].state = 'active'); } + if (mutation === 'role-roundtrip') { await s.change(d => d.users[1].instanceRole = 'operator'); await s.change(d => d.users[1].instanceRole = 'user'); } + if (mutation === 'signout') await s.change(d => d.users[1].authGen++, 'user.signout'); + if (mutation === 'subject') await s.change(d => d.users[1].subjects[0].sub = 'changed'); + if (mutation === 'remove') await s.change(d => d.users.splice(1, 1), 'user.remove'); + if (mutation === 'missing') rmSync(s.file); if (mutation === 'invalid') writeFileSync(s.file, '{}'); + assert.equal(s.sso.session({ headers: { cookie: r.cookie } }), null); + assert.equal((await call(s.port, '/api/bus/inbox', { cookie: r.cookie })).status, 401); + }); +}); +test('the ninth account session evicts only that account oldest; global caps are 512/128', async t => { + const s = await setup(t), other = await s.login('owner'), cookies = []; + for (let i = 0; i < 9; i++) cookies.push((await s.login()).cookie); + assert.equal(s.sso.session({ headers: { cookie: cookies[0] } }), null); + for (const cookie of [...cookies.slice(1), other.cookie]) assert.ok(s.sso.session({ headers: { cookie } })); + for (let i = 0; i < 129; i++) await call(s.port, '/auth/login'); assert.equal(s.sso.logins.size, 128); +}); +test('root routes refuse account-only sessions and restart checks operator independently of root ownership', async t => { + const s = await setup(t), pat = await s.login(), op = await s.login('op'); + for (const path of ['/api/bus/inbox', '/api/settings', '/api/chat/projects', '/board']) assert.equal((await call(s.port, path, { cookie: pat.cookie })).status, 404, path); + assert.equal((await call(s.port, '/api/console/restart', { cookie: pat.cookie, method: 'POST', body: '{}' })).status, 403); + assert.equal(s.restarts(), 0); + assert.equal((await call(s.port, '/api/console/restart', { cookie: op.cookie, method: 'POST', body: '{}' })).status, 202); + assert.equal(s.restarts(), 1); +}); +test('legacy root grant and account authority revoke independently and never return on an old cookie', async t => { + const s = await setup(t, { legacy: true }), r = await s.login(); + let session = s.sso.session({ headers: { cookie: r.cookie } }); assert.equal(session.user, 'legacy'); assert.equal(session.account, 'u-000000000002'); + await s.change(d => d.users[1].state = 'disabled'); + session = s.sso.session({ headers: { cookie: r.cookie } }); assert.ok(session); assert.equal(session.user, 'legacy'); assert.equal(session.account, undefined); assert.equal(session.instanceRole, undefined); + await s.change(d => d.users[1].state = 'active'); assert.equal(s.sso.session({ headers: { cookie: r.cookie } }).account, undefined); + s.revoke(); assert.equal(s.sso.session({ headers: { cookie: r.cookie } }), null); + const fresh = await s.login(); assert.ok(fresh.cookie); assert.equal(s.sso.session({ headers: { cookie: fresh.cookie } }).user, undefined); + assert.equal((await call(s.port, '/api/chat/projects', { cookie: fresh.cookie })).status, 404); +}); diff --git a/packages/webui/tests/chat-instances.test.mjs b/packages/webui/tests/chat-instances.test.mjs index 893c38f80..3bb1fd5c2 100644 --- a/packages/webui/tests/chat-instances.test.mjs +++ b/packages/webui/tests/chat-instances.test.mjs @@ -80,7 +80,7 @@ test('C2-09a metadata stays behind the SSO session check and a GET never refresh const headers = { host: sso.publicHost }; assert.equal((await get(server, { headers })).status, 401); assert.equal(reads, 0); - session = { name: 'jason' }; + session = { name: 'jason', rootOwner: true }; assert.equal((await get(server, { headers })).status, 200); assert.equal(reads, 1); assert.deepEqual(touches, [false, false]); diff --git a/packages/webui/tests/decide-sso.test.mjs b/packages/webui/tests/decide-sso.test.mjs index f4c94b167..a9918809d 100644 --- a/packages/webui/tests/decide-sso.test.mjs +++ b/packages/webui/tests/decide-sso.test.mjs @@ -1,3 +1,4 @@ +import { ownerAccounts } from './helpers/owner-accounts.mjs'; // Row 252 (#1753, design sections 4 and 5): the Console decision routes on the human listener, signed // in through the fake OP in helpers/fake-oidc.mjs on loopback. The bus transport is a recording stub, // so this covers the listener's gates and the session it passes; decision-http.test.mjs covers the @@ -53,7 +54,7 @@ async function setup(t, server = {}, access = null) { const config = { publicOrigin: ORIGIN, providers: [{ id: 'a', issuer: iss.issuer, clientId: iss.clientId, clientSecret: { slot: 'a' }, algs: ['RS256'], subjects: [{ sub: 'user-a', name: 'person-a' }] }] }; const lines = []; const users = access && { users: consoleAccess({ load: () => access, business: () => 'demo' }) }; - const sso = await createSso(config, { secrets: new Map([['a', iss.clientSecret]]), fetch: op.fetch, log: l => lines.push(l), ...users }); + const sso = await createSso(config, { accounts: ownerAccounts(config), secrets: new Map([['a', iss.clientSecret]]), fetch: op.fetch, log: l => lines.push(l), ...users }); t.after(() => sso.close()); const calls = []; const decisionWrite = async (verb, args, ctx) => { diff --git a/packages/webui/tests/granted-user.test.mjs b/packages/webui/tests/granted-user.test.mjs index 75ac7a1b3..e345ede3a 100644 --- a/packages/webui/tests/granted-user.test.mjs +++ b/packages/webui/tests/granted-user.test.mjs @@ -1,3 +1,4 @@ +import { ownerAccounts } from './helpers/owner-accounts.mjs'; // 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 @@ -92,7 +93,7 @@ async function setup(t, { users = [ALICE], grants = [grant()] } = {}) { 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' }) }); + const sso = await createSso(config, { accounts: ownerAccounts(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)])); diff --git a/packages/webui/tests/helpers/owner-accounts.mjs b/packages/webui/tests/helpers/owner-accounts.mjs new file mode 100644 index 000000000..25b49eb15 --- /dev/null +++ b/packages/webui/tests/helpers/owner-accounts.mjs @@ -0,0 +1,5 @@ +// Existing OIDC regression fixtures explicitly initialize their configured owners. +// Production never infers account authority from console.sso alone. +export const ownerAccounts = config => ({ load: () => ({ users: config.providers.flatMap((p, i) => p.subjects.map((s, j) => ({ + id: `u-${(i * 64 + j + 1).toString(16).padStart(12, '0')}`, subjects: [{ provider: p.id, sub: s.sub }], name: s.name, state: 'active', instanceRole: 'operator', authGen: 1, +}))) }) }); diff --git a/packages/webui/tests/helpers/sso-session.mjs b/packages/webui/tests/helpers/sso-session.mjs index 36162bfc4..b64eac239 100644 --- a/packages/webui/tests/helpers/sso-session.mjs +++ b/packages/webui/tests/helpers/sso-session.mjs @@ -1,3 +1,4 @@ +import { ownerAccounts } from './owner-accounts.mjs'; // Q284 / #385: real OIDC sessions for writer-route tests. The provider is the existing // in-process fake and is shared only within one test-file process; each test gets its own // createSso instance and completes the real login, code and callback flow. @@ -58,6 +59,7 @@ export async function createSsoSession(t, { subjects: configuredSubjects, }], }, { + accounts: ownerAccounts({ providers: [{ id: issuer.name, subjects: configuredSubjects }] }), secrets: new Map([[issuer.name, issuer.clientSecret]]), fetch: op.fetch, log, diff --git a/packages/webui/tests/helpers/w15-project-remote-real.mjs b/packages/webui/tests/helpers/w15-project-remote-real.mjs index 7afeb31e6..78e66f948 100644 --- a/packages/webui/tests/helpers/w15-project-remote-real.mjs +++ b/packages/webui/tests/helpers/w15-project-remote-real.mjs @@ -34,7 +34,7 @@ export async function realRemoteFixture(t, mutate = () => {}) { }; await attach(); const subject = { provider: 'fixture', iss: 'https://issuer.example', sub: 'owner' }; - const session = { ...subject, name: 'jason' }; + const session = { rootOwner: true, instanceRole: 'operator', ...subject, name: 'jason' }; let active = true; const sso = { publicOrigin: '', publicHost: '', formTargets: () => [], session: () => active ? session : null, handle: () => {}, health: () => ({}) }; const transport = (verb, args, ctx) => new Client({ path, console: { subject: ctx.subject } }).call(verb, args); diff --git a/packages/webui/tests/project-remote-transport.test.mjs b/packages/webui/tests/project-remote-transport.test.mjs index e56ee07cf..bcdb0493e 100644 --- a/packages/webui/tests/project-remote-transport.test.mjs +++ b/packages/webui/tests/project-remote-transport.test.mjs @@ -1,3 +1,4 @@ +import { ownerAccounts } from './helpers/owner-accounts.mjs'; import test from 'node:test'; import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; @@ -82,7 +83,7 @@ test('real SSO refuses viewer and collaborator and sign-out prevents the saved w { id: 'g-2', user: 'bob', business: 'demo', projects: ['*'], instances: ['assistant'], level: 'collaborator' }, ] }; const config = { publicOrigin: origin, providers: [{ id: 'a', issuer: issuer.issuer, clientId: issuer.clientId, clientSecret: { slot: 'a' }, algs: ['RS256'], subjects: [{ sub: 'owner-sub', name: 'jason' }] }] }; - const sso = await createSso(config, { secrets: new Map([['a', issuer.clientSecret]]), fetch: op.fetch, users: consoleAccess({ load: () => access, business: () => 'demo' }), log: () => {} }); + const sso = await createSso(config, { accounts: ownerAccounts(config), secrets: new Map([['a', issuer.clientSecret]]), fetch: op.fetch, users: consoleAccess({ load: () => access, business: () => 'demo' }), log: () => {} }); t.after(() => sso.close()); const f = await realRemoteFixture(t), original = readFileSync(f.file); let writes = 0; diff --git a/packages/webui/tests/request-http.test.mjs b/packages/webui/tests/request-http.test.mjs index fd2dd88f2..a6af35e07 100644 --- a/packages/webui/tests/request-http.test.mjs +++ b/packages/webui/tests/request-http.test.mjs @@ -1,3 +1,4 @@ +import { ownerAccounts } from './helpers/owner-accounts.mjs'; // #797 / #1839 Task 3: the Console's request intake routes. The first half drives requestHTTP with a // fake request, response and bus transport. The second half signs in through the fake OP on loopback // and checks the listener's gates, as decide-sso.test.mjs does for decisions. The bus side is @@ -253,7 +254,7 @@ async function listener(t, server = {}, access = null) { const config = { publicOrigin: LISTEN, providers: [{ id: 'a', issuer: iss.issuer, clientId: iss.clientId, clientSecret: { slot: 'a' }, algs: ['RS256'], subjects: [{ sub: 'user-a', name: 'person-a' }] }] }; const lines = []; const users = access && { users: consoleAccess({ load: () => access, business: () => 'demo' }) }; - const sso = await createSso(config, { secrets: new Map([['a', iss.clientSecret]]), fetch: op.fetch, log: l => lines.push(l), ...users }); + const sso = await createSso(config, { accounts: ownerAccounts(config), secrets: new Map([['a', iss.clientSecret]]), fetch: op.fetch, log: l => lines.push(l), ...users }); t.after(() => sso.close()); const reads = [], writes = []; const requestRead = async (verb, args, ctx) => { reads.push({ verb, args, ctx }); return { ...STATE, request: args.request }; }; diff --git a/packages/webui/tests/sso.test.mjs b/packages/webui/tests/sso.test.mjs index a5b0b0551..5a96629bc 100644 --- a/packages/webui/tests/sso.test.mjs +++ b/packages/webui/tests/sso.test.mjs @@ -1,3 +1,4 @@ +import { ownerAccounts } from './helpers/owner-accounts.mjs'; // Q175 phase 1 (#1690, design agents/sage/work/q175-sso/DESIGN.md section 9): the Console as an // OIDC relying party (--sso). 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 or slot file. The public name @@ -56,7 +57,7 @@ async function setup(t, { issuers = [{ name: 'a' }], provider = {}, before = nul const config = { publicOrigin: ORIGIN, providers: iss.map(i => providerFor(i, provider[i.name] ?? {})) }; const lines = []; const log = line => { lines.push(line); ALL_LINES.push(line); }; - const sso = await createSso(config, { secrets: new Map(iss.map(i => [i.name, i.clientSecret])), fetch: op.fetch, log, retryFirst }); + const sso = await createSso(config, { accounts: ownerAccounts(config), secrets: new Map(iss.map(i => [i.name, i.clientSecret])), fetch: op.fetch, log, retryFirst }); t.after(() => sso.close()); const sends = []; const bus = Object.fromEntries(['inbox', 'tasks', 'agents', 'trail', 'decisions'].map(v => [v, async () => [{ verb: v }]])); @@ -365,6 +366,7 @@ test('11: the CLI refuses --sso with the old flags and without console.sso, then assert.equal(wide.status, 2); assert.match(wide.stderr, /^refused: console\.sso provider a client secret slot must have no group or other permission bits$/m); chmodSync(join(root, 'cfg', 'secrets', 'mosaic-stack', 'a'), 0o600); + writeFileSync(join(root, 'cfg', 'accounts.json'), JSON.stringify({ accountsVersion: 1, revision: 1, users: ownerAccounts({ providers: [providerFor(a)] }).load().users.map(u => ({ ...u, created: '2026-11-10T00:00:00Z' })), memberships: [], invites: [] }), { mode: 0o600 }); // The child trusts the fake OP's certificate through NODE_EXTRA_CA_CERTS; the code under test has no flag for it. const child = spawn(process.execPath, [CLI, 'serve', '--port', '0', '--sso', '--send'], { env: { ...env, NODE_EXTRA_CA_CERTS: join(root, 'ca.pem') } }); t.after(() => child.kill('SIGKILL')); @@ -522,11 +524,11 @@ test('16: a provider with RS256 and ES256 takes either, and refuses PS256 with a refused(env, (await signIn(env, { opts: { key: ps } })).r, 'id-token-invalid'); }); -test('17: 33 started logins leave 32 records, and the first one\'s callback finds none', async t => { +test('17: 129 started logins leave 128 records, and the first one\'s callback finds none', async t => { const env = await setup(t); const first = await begin(env); - for (let i = 0; i < 32; i++) await begin(env); - assert.equal(env.sso.logins.size, 32); + for (let i = 0; i < 128; i++) await begin(env); + assert.equal(env.sso.logins.size, 128); refused(env, await callback(env, first, { code: grant(env, first, env.iss[0]).code }), 'login-record-missing'); }); diff --git a/packages/webui/tests/user-option-swap.test.mjs b/packages/webui/tests/user-option-swap.test.mjs index 2d447601c..a50da6ee1 100644 --- a/packages/webui/tests/user-option-swap.test.mjs +++ b/packages/webui/tests/user-option-swap.test.mjs @@ -1,3 +1,4 @@ +import { ownerAccounts } from './helpers/owner-accounts.mjs'; // R6-N1 (#1807, row 294 N1): the user-session option swap in serve.mjs, driven through HTTP. // granted-user.test.mjs G4 stops every owner route at the userRoute gate, so it never reaches the // swap behind it. Here serve.mjs loads with that gate stubbed open (a load hook keyed on one query @@ -87,7 +88,7 @@ async function setup(t) { const userOptions = userOptionsFor({ owner: ownerCall, send: true, transport: name => { opened.push(name); return userTransport(name); } }); const lines = []; 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: l => lines.push(l), users: consoleAccess({ load, business: () => 'demo' }) }); + const sso = await createSso(config, { accounts: ownerAccounts(config), secrets: new Map([['a', iss.clientSecret]]), fetch: op.fetch, log: l => lines.push(l), users: consoleAccess({ load, business: () => 'demo' }) }); t.after(() => sso.close()); // Every owner option is a stub that records its own name. const stub = name => async () => { owner.push(['option', name]); return name === 'send' ? { id: 'msg-0001' } : [{ verb: name }]; };