diff --git a/src/web/routes/system-routes.ts b/src/web/routes/system-routes.ts index 3b9b2ca8..a8dc9e7e 100644 --- a/src/web/routes/system-routes.ts +++ b/src/web/routes/system-routes.ts @@ -17,7 +17,7 @@ import { ApiErrorCode, createErrorResponse, getErrorMessage, type NiceConfig } f import { isUnauthenticatedNetworkAcknowledged } from '../network-auth-policy.js'; import { isMultiUserMode } from '../../config/multiuser.js'; import { findUser, canUsernameRunPrivilegedCommands } from '../../user-store.js'; -import { getAuthUser, requireAdmin, canAccessOwned } from '../route-helpers.js'; +import { getAuthUser, isAdmin, requireAdmin, canAccessOwned } from '../route-helpers.js'; import { ConfigUpdateSchema, SettingsUpdateSchema, @@ -144,6 +144,28 @@ export function resolveSpanUrl(hostHeader: string | undefined, fallbackPort = '3 return `http://localhost:${port}`; } +/** + * What GET /api/settings answers a NON-ADMIN in multi-user mode: settings.json minus what + * belongs to the server's admin rather than to the reader. `voiceSettings.apiKey` is the + * Deepgram key an admin saved, a credential (the reader's browser seeded it into its own + * voice config and dictated on the admin's account); `caseOrder` and `lastUsedCase` name the + * admin's cases. Everything else stays readable, because the page reads the synced feature + * switches from it. Writes are admin-only there (PUT /api/settings). Exported for unit testing. + */ +export function settingsForNonAdmin(settings: unknown): unknown { + if (!settings || typeof settings !== 'object' || Array.isArray(settings)) return settings; + const out: Record = { ...(settings as Record) }; + delete out.caseOrder; + delete out.lastUsedCase; + const voice = out.voiceSettings; + if (voice && typeof voice === 'object' && !Array.isArray(voice) && 'apiKey' in voice) { + const voiceOut: Record = { ...(voice as Record) }; + delete voiceOut.apiKey; + out.voiceSettings = voiceOut; + } + return out; +} + export function registerSystemRoutes( app: FastifyInstance, ctx: SessionPort & EventPort & ConfigPort & InfraPort & AuthPort & TabLayoutPort @@ -941,7 +963,7 @@ export function registerSystemRoutes( // ========== Settings ========== - app.get('/api/settings', async () => { + app.get('/api/settings', async (req) => { // A plain read. This route must NEVER write settings.json: readJsonConfig() // answers `{}` for ANY read failure (a parse error, EACCES, EMFILE, a read // that lands inside PUT's non-atomic write), not only for a missing file, @@ -953,7 +975,11 @@ export function registerSystemRoutes( // `workspaceHooksEnabled` means ON, and the client resolves its own display // default through planUsageChipEnabled(). Pinned by // test/routes/system-routes-settings-get-plan-usage-default.test.ts. - return readJsonConfig(SETTINGS_PATH, 'settings', {}); + const settings = await readJsonConfig(SETTINGS_PATH, 'settings', {}); + // Readable by every signed-in user, but a non-admin in multi-user mode gets it without + // the admin's credential and case names (settingsForNonAdmin). isAdmin is always true in + // single-user mode, so that answer is the file as it is. + return isAdmin(req) ? settings : settingsForNonAdmin(settings); }); app.put('/api/settings', async (req, reply) => { diff --git a/test/routes/system-routes-settings-admin-only.test.ts b/test/routes/system-routes-settings-admin-only.test.ts index 44505cd3..49ea02cf 100644 --- a/test/routes/system-routes-settings-admin-only.test.ts +++ b/test/routes/system-routes-settings-admin-only.test.ts @@ -10,14 +10,16 @@ * tunnel, the tmux history limit); * - the same gate on the other server-wide writes: PUT /api/execution/model-config, * PUT /api/config and PUT /api/cases/order; - * - an admin, and single-user mode, write as before; GET /api/settings stays readable. + * - an admin, and single-user mode, write as before; GET /api/settings stays readable, + * but a non-admin reads it without the admin's Deepgram key and case names + * (settingsForNonAdmin). * * Uses app.inject(), so no real HTTP port is needed. Port: N/A. */ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js'; -import { registerSystemRoutes } from '../../src/web/routes/system-routes.js'; +import { registerSystemRoutes, settingsForNonAdmin } from '../../src/web/routes/system-routes.js'; import { registerCaseRoutes } from '../../src/web/routes/case-routes.js'; const { STORED, subagentWatcher, imageWatcher, workflowRunWatcher } = vi.hoisted(() => { @@ -66,6 +68,7 @@ vi.mock('../../src/workflow-run-watcher.js', () => ({ workflowRunWatcher })); import fs from 'node:fs/promises'; const writeFile = vi.mocked(fs.writeFile); +const readFile = vi.mocked(fs.readFile); const NON_ADMIN = { username: 'bob', role: 'user' } as const; const ADMIN = { username: 'root', role: 'admin' } as const; @@ -174,6 +177,54 @@ describe('server-wide settings writes are admin-only in multi-user mode', () => } }); + describe("GET /api/settings: what is the admin's stays the admin's", () => { + // An admin's App Settings save stores the Deepgram key (voiceSettings.apiKey) here, and + // the admin's own cases are named in caseOrder / lastUsedCase. + const WITH_SECRETS = { + autoNameSessions: true, + runMode: 'shell', + caseOrder: ['rootcase', 'secret-project'], + lastUsedCase: 'secret-project', + voiceSettings: { provider: 'deepgram', apiKey: 'dg-SECRET-probe-123', language: 'en' }, + }; + + it('gives a non-admin the settings without the Deepgram key and the case names', async () => { + const { app } = await as(NON_ADMIN); + readFile.mockResolvedValueOnce(JSON.stringify(WITH_SECRETS)); + const res = await app.inject({ method: 'GET', url: '/api/settings' }); + expect(res.statusCode).toBe(200); + expect(res.body).not.toContain('dg-SECRET-probe-123'); + expect(res.body).not.toContain('secret-project'); + expect(JSON.parse(res.body)).toEqual({ + autoNameSessions: true, + runMode: 'shell', + voiceSettings: { provider: 'deepgram', language: 'en' }, + }); + }); + + for (const [label, user] of [ + ['an admin in multi-user mode', ADMIN], + ['single-user mode', null], + ] as const) { + it(`gives ${label} the file as it is`, async () => { + const { app } = await as(user); + readFile.mockResolvedValueOnce(JSON.stringify(WITH_SECRETS)); + const res = await app.inject({ method: 'GET', url: '/api/settings' }); + expect(res.statusCode).toBe(200); + expect(JSON.parse(res.body)).toEqual(WITH_SECRETS); + }); + } + + it('settingsForNonAdmin leaves its input alone and passes a non-object through', () => { + const input = structuredClone(WITH_SECRETS); + settingsForNonAdmin(input); + expect(input).toEqual(WITH_SECRETS); + expect(settingsForNonAdmin([1, 2])).toEqual([1, 2]); + expect(settingsForNonAdmin(null)).toBe(null); + expect(settingsForNonAdmin({ voiceSettings: { language: 'de' } })).toEqual({ voiceSettings: { language: 'de' } }); + }); + }); + describe('PUT /api/execution/model-config', () => { const config = { defaultModel: 'opus', agentTypeOverrides: { explore: 'sonnet' } }; diff --git a/test/settings-admin-only-multiuser.test.ts b/test/settings-admin-only-multiuser.test.ts index fcfebae8..8e700bf4 100644 --- a/test/settings-admin-only-multiuser.test.ts +++ b/test/settings-admin-only-multiuser.test.ts @@ -7,7 +7,8 @@ * real file back, so "settings.json is unchanged" is asserted on bytes: * - PUT /api/settings, PUT /api/execution/model-config and PUT /api/cases/order are * 403 FORBIDDEN for a non-admin, and the file is byte-identical afterwards; - * - GET /api/settings stays readable by the non-admin; + * - GET /api/settings stays readable by the non-admin, without the admin's Deepgram + * key and case names (an admin still reads the file as it is); * - a non-admin's quick-start does not record its case as `lastUsedCase` (a key every * user can read through GET /api/settings), while an admin's still does; * - an admin's PUT /api/settings still writes. @@ -37,6 +38,7 @@ const INITIAL = { lastUsedCase: 'rootcase', caseOrder: ['rootcase'], modelConfig: { defaultModel: 'sonnet' }, + voiceSettings: { provider: 'deepgram', apiKey: 'dg-SECRET-live-456', language: 'en' }, }; const readSettingsBytes = () => fs.readFile(SETTINGS_PATH, 'utf-8'); @@ -101,10 +103,18 @@ describe('a non-admin and the server-wide settings.json', () => { expect(await readSettingsBytes()).toBe(before); }); - it('can still read it', async () => { + it("can still read it, without the admin's Deepgram key and case names", async () => { const res = await send('GET', '/api/settings', bob); expect(res.status).toBe(200); expect(res.body.data.autoNameSessions).toBe(false); + expect(JSON.stringify(res.body)).not.toContain('dg-SECRET-live-456'); + expect(res.body.data.voiceSettings).toEqual({ provider: 'deepgram', language: 'en' }); + expect('caseOrder' in res.body.data).toBe(false); + expect('lastUsedCase' in res.body.data).toBe(false); + + const admin = await send('GET', '/api/settings', root); + expect(admin.body.data.voiceSettings.apiKey).toBe('dg-SECRET-live-456'); + expect(admin.body.data.caseOrder).toEqual(['rootcase']); }); it("does not get its quick-start case recorded as everyone's lastUsedCase; an admin's still is", async () => {