From 4b12be745aac329452832601b063efdee16b55b8 Mon Sep 17 00:00:00 2001 From: Tiberiu Socaci Date: Sat, 5 Dec 2026 16:49:43 +0200 Subject: [PATCH] fix: audit default conversation template changes Signed-off-by: Tiberiu Socaci --- CHANGELOG.md | 5 ++ FEATURES.md | 5 ++ TEST-PLAN.md | 10 +++ src/web/routes/settings.js | 24 +++++- test/settings-template-audit.test.js | 116 +++++++++++++++++++++++++++ 5 files changed, 159 insertions(+), 1 deletion(-) create mode 100644 test/settings-template-audit.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index a81b627c..ffb05ce6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## 0.7.1 — in development +- Audit: saving a changed new-channel, user DM or admin DM default under Conversations → + Templates now records the template, changed field names and signed-in administrator. Restores + are recorded too; unchanged or refused saves do not create a change event. Template values and + credentials are never included in these events. + - Voice calls: Gemini 4 Live (`gemini-4-live`) is the new default voice model. It costs the same as Gemini 3.8 Live and answers faster. An install that had saved 3.8 Live under Settings → Voice calls keeps it until an admin selects Gemini 4 Live; 3.8 Live remains available. diff --git a/FEATURES.md b/FEATURES.md index cf09e20c..9a35e04c 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -10248,6 +10248,11 @@ are retired, bullet by bullet; everything else stands. - **Conversations → Templates** edits new-channel, user DM and admin DM defaults with a separate Save for each. **Skills → Organization** manages shared skills and connectors, **Skills → Templates** manages skill templates, and **Variables** manages deployment-wide variables. + A successful effective template change records `conversation_template_changed` with the + `channel`, `user` or `admin` template, changed field names and verified admin account (the + shared `admin-ui` principal for local-open or legacy sessions), never template values. + Restores count as changes; no-op, invalid and stale saves do not. The event precedes downstream + reconnect/sync work so a failure there does not conceal an already-persisted change. - A reusable **new-channel template** is copied into a channel's metadata only when the bot first registers it. It defaults to Autonomous mode with approved-domain network egress; edits affect future joins without silently changing existing channels. diff --git a/TEST-PLAN.md b/TEST-PLAN.md index c138dc03..6028d23b 100644 --- a/TEST-PLAN.md +++ b/TEST-PLAN.md @@ -16887,6 +16887,16 @@ none` for its cases and live gates. Kept as history. across DMs; a per-DM custom config overrides. - [ ] The new-channel template defaults to Autonomous + approved-domain network, persists with the global Settings save, is copied on first registration, and never overwrites an existing channel. +- [x] Template audit route regression (`test/settings-template-audit.test.js`): successful saves + and restores emit one `conversation_template_changed` per changed channel/user/admin + template, naming only changed fields and the verified session actor; forged body identities + and values never appear. No-op, unrelated, invalid or stale saves emit no template mutation. + A later reconnect failure still leaves the committed change audited. Local-open saves use + the shared `admin-ui` actor. +- [ ] Live `MODE-BASE-OPTIONS-01`, Claude and Codex: save and reopen the default template through + Conversations → Templates, restore it exactly, and verify both effective changes in Audit + with the correct template, changed field names and signed-in account; include desktop and + narrow-screen evidence. Unit coverage does not replace this live acceptance gate. - [ ] Setting an admin password gates the UI (login required); "Remove password" reopens it; `/api/health` stays reachable without a session. diff --git a/src/web/routes/settings.js b/src/web/routes/settings.js index 2c65afdd..8c15c7bd 100644 --- a/src/web/routes/settings.js +++ b/src/web/routes/settings.js @@ -20,6 +20,7 @@ import { syncWorkspaceSkillsOrThrow } from "../../gateway/skills/workspace-sync. import { realpathSync, statSync } from "node:fs"; import os from "node:os"; import path from "node:path"; +import { isDeepStrictEqual } from "node:util"; import { forbiddenWorkDirReason } from "../../gateway/workdir-boundary.js"; import { allowedFsRoot, allowedFsRoots, allowedRootFor, listSubfolderNames, resolveWithinRoots, resolveWithinRoot, pathWithin, hashPassword, verifyPassword } from "../security.js"; import { listAvailableSkills } from "../../gateway/folders.js"; @@ -874,13 +875,34 @@ export function createSettingsRouter({ if (patch.publicUrl !== undefined && normalizePublicUrl(patch.publicUrl) !== normalizePublicUrl(getSettings().publicUrl) && passkeysConfigured() && !requireRecentAdminAuth(req)) { return res.status(403).json({ error: "Verify your passkey before changing the gateway URL.", code: "reauth_required" }); } + const templateChanges = []; + const session = adminSession(req); + const actor = session?.accountId ? `admin:${session.accountId}` : ADMIN_UI_ACTOR; try { - saveSettings(patch, { expectVersion }); + saveSettings(() => { + // Compare effective templates under the settings write lock. The cleaner supplies the + // field allowlist: audit field names only, never template values or request-body keys. + const before = { channel: getChannelTemplate(), ...getDmTemplates() }; + const after = { channel: patch.channelTemplate, ...patch.dmTemplates }; + for (const [template, value] of Object.entries(after)) { + if (!value) continue; + const previous = cleanConversationTemplate(before[template]); + const next = cleanConversationTemplate(value); + const keys = Object.keys(next).filter((key) => !isDeepStrictEqual(previous[key], next[key])); + if (keys.length) templateChanges.push({ template, keys }); + } + return patch; + }, { expectVersion }); } catch (e) { if (e?.code !== "settings_version_conflict") throw e; // Hand back the CURRENT settings so the page can show what it now has instead of guessing. return res.status(409).json(staleSettingsResponse()); } + // The write has committed. Record it before reconnecting or syncing projections, which + // can fail independently of the already-persisted template change. + for (const change of templateChanges) { + await logEvent("conversation_template_changed", { ...change, actor, author: actor, source: "admin-ui" }); + } applySettingsToEnv(); if (patch.maxConcurrentRuns !== undefined || patch.reservedInteractiveRuns !== undefined) { const { refreshRunSlots } = await import("../../gateway/run.js"); diff --git a/test/settings-template-audit.test.js b/test/settings-template-audit.test.js new file mode 100644 index 00000000..8e1bf7ff --- /dev/null +++ b/test/settings-template-audit.test.js @@ -0,0 +1,116 @@ +import test, { after } from "node:test"; +import assert from "node:assert/strict"; +import express from "express"; +import { ensureTestEnv } from "./helpers.js"; + +ensureTestEnv(); +const settings = await import("../src/config/settings.js"); +const { createAdminRouter } = await import("../src/web/routes/admin.js"); +const { createAdminAccount } = await import("../src/config/admin-accounts.js"); +const { createAdminSession } = await import("../src/web/auth.js"); +const { readEvents } = await import("../src/util/logger.js"); + +const account = createAdminAccount("template-audit"); +let cookie; +createAdminSession({ headers: {} }, { setHeader: (_name, value) => { cookie = value.split(";")[0]; } }, account); +const slack = { + snapshot: () => ({ status: "disconnected", connected: false }), + connect: async () => { throw new Error("fixture reconnect failure"); }, +}; +const app = express(); +app.use(express.json()); +app.use(createAdminRouter({ slack })); +app.use((error, _req, res, _next) => res.status(500).json({ error: error.message })); +const server = await new Promise((resolve) => { + const instance = app.listen(0, "127.0.0.1", () => resolve(instance)); +}); +after(() => server.close()); +const base = `http://127.0.0.1:${server.address().port}`; +const events = () => readEvents({ limit: 1000 }).filter((row) => row.event === "conversation_template_changed"); +const put = async (body, sessionCookie = cookie) => { + const response = await fetch(`${base}/settings`, { + method: "PUT", + headers: { "content-type": "application/json", ...(sessionCookie ? { cookie: sessionCookie } : {}) }, + body: JSON.stringify({ connectSlack: false, ...body }), + }); + return { status: response.status, body: await response.json() }; +}; + +test("channel template saves and restores audit changed field names with the verified administrator", async () => { + const original = settings.getChannelTemplate(); + const changed = { ...original, allowNetwork: !original.allowNetwork, autoMode: !original.autoMode }; + const start = events().length; + for (const template of [changed, original]) { + const saved = await put({ + channelTemplate: { ...template, secretFixture: "never-audit-body-values" }, + actor: "forged-actor", accountId: "forged-account", + settingsVersion: settings.getSettingsVersion(), + }); + assert.equal(saved.status, 200); + assert.deepEqual(settings.getChannelTemplate(), template); + const { ts, ...event } = events()[0]; + assert.ok(Date.parse(ts)); + assert.deepEqual(event, { + event: "conversation_template_changed", template: "channel", keys: ["allowNetwork", "autoMode"], + actor: `admin:${account.id}`, author: `admin:${account.id}`, source: "admin-ui", + }); + } + assert.equal(events().length, start + 2, "one event for each committed mutation, including restoration"); +}); + +test("each changed DM role is identified and an untouched role emits nothing", async () => { + const original = settings.getDmTemplates(); + const user = { ...original.user, cleanMode: !original.user.cleanMode }; + const admin = { ...original.admin, autoMode: !original.admin.autoMode }; + const start = events().length; + assert.equal((await put({ dmTemplates: { user } })).status, 200); + assert.deepEqual(settings.getDmTemplates(), { user, admin: original.admin }); + assert.equal(events().length, start + 1); + assert.equal(events()[0].template, "user"); + assert.deepEqual(events()[0].keys, ["cleanMode"]); + assert.equal((await put({ dmTemplates: { user: original.user, admin } })).status, 200); + assert.equal(events().length, start + 3); + assert.deepEqual(events().slice(0, 2).map(({ template, keys }) => ({ template, keys })), [ + { template: "admin", keys: ["autoMode"] }, { template: "user", keys: ["cleanMode"] }, + ]); +}); + +test("no-op, unrelated, invalid and stale saves do not claim a template change", async () => { + const start = events().length; + const channelTemplate = settings.getChannelTemplate(); + assert.equal((await put({ channelTemplate, dmTemplates: settings.getDmTemplates() })).status, 200); + assert.equal((await put({ sessionKeepalive: "17m", actor: "forged" })).status, 200); + assert.equal((await put({ channelTemplate: { ...channelTemplate, effort: "invalid-fixture-effort" } })).status, 400); + assert.equal((await put({ + channelTemplate: { ...channelTemplate, allowNetwork: !channelTemplate.allowNetwork }, + settingsVersion: String(Number(settings.getSettingsVersion()) - 1), + })).status, 409); + assert.deepEqual(settings.getChannelTemplate(), channelTemplate); + assert.equal(events().length, start); +}); + +test("a template committed before a later reconnect failure remains audited without logging values", async () => { + const original = settings.getChannelTemplate(); + const channelTemplate = { ...original, cleanMode: !original.cleanMode }; + const start = events().length; + const saved = await put({ + channelTemplate, connectSlack: true, + slackBotToken: "xoxb-template-audit-fixture", slackAppToken: "xapp-template-audit-fixture", + slackSigningSecret: "template-audit-signing-fixture", + }); + assert.equal(saved.status, 500); + assert.match(saved.body.error, /fixture reconnect failure/); + assert.deepEqual(settings.getChannelTemplate(), channelTemplate); + assert.equal(events().length, start + 1); + assert.deepEqual(events()[0].keys, ["cleanMode"]); + assert.doesNotMatch(JSON.stringify(events()), /xoxb-|xapp-|never-audit-body-values|forged/); +}); + +test("local-open or legacy shared-admin saves use the established admin-ui principal", async () => { + const channelTemplate = settings.getChannelTemplate(); + const start = events().length; + assert.equal((await put({ channelTemplate: { ...channelTemplate, cleanMode: !channelTemplate.cleanMode } }, "")).status, 200); + assert.equal(events().length, start + 1); + assert.equal(events()[0].actor, "admin-ui"); + assert.equal(events()[0].author, "admin-ui"); +});