Skip to content

Commit 3af3493

Browse files
authored
feat(config): journal every config change with source labels and manual-edit detection (#111147)
* feat(config): journal every config change with source labels and manual-edit detection * fix(config): narrow journal exports and align plugin-write test expectations * refactor(config): split journal snapshot store out of io.audit * chore(config): keep journal snapshot context helpers module-local
1 parent c684b13 commit 3af3493

31 files changed

Lines changed: 1782 additions & 63 deletions

‎src/cli/config-cli.test.ts‎

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,11 @@ const mockReadConfigFileSnapshot = vi.fn<() => Promise<ConfigFileSnapshot>>();
2020
const mockWriteConfigFile = vi.fn<
2121
(
2222
cfg: OpenClawConfig,
23-
options?: { unsetPaths?: string[][]; explicitSetPaths?: string[][] },
23+
options?: {
24+
auditOrigin?: "cli";
25+
unsetPaths?: string[][];
26+
explicitSetPaths?: string[][];
27+
},
2428
) => Promise<void>
2529
>(async () => {});
2630
const mockResolveSecretRefValue = vi.fn();
@@ -33,11 +37,19 @@ vi.mock("../config/config.js", () => ({
3337
readConfigFileSnapshot: () => mockReadConfigFileSnapshot(),
3438
writeConfigFile: (
3539
cfg: OpenClawConfig,
36-
options?: { unsetPaths?: string[][]; explicitSetPaths?: string[][] },
40+
options?: {
41+
auditOrigin?: "cli";
42+
unsetPaths?: string[][];
43+
explicitSetPaths?: string[][];
44+
},
3745
) => mockWriteConfigFile(cfg, options),
3846
replaceConfigFile: (params: {
3947
nextConfig: OpenClawConfig;
40-
writeOptions?: { unsetPaths?: string[][]; explicitSetPaths?: string[][] };
48+
writeOptions?: {
49+
auditOrigin?: "cli";
50+
unsetPaths?: string[][];
51+
explicitSetPaths?: string[][];
52+
};
4153
}) => mockWriteConfigFile(params.nextConfig, params.writeOptions),
4254
}));
4355

@@ -380,12 +392,16 @@ function firstWrittenConfig(): OpenClawConfig {
380392
}
381393

382394
function firstWriteConfigOptions():
383-
| { unsetPaths?: string[][]; explicitSetPaths?: string[][] }
395+
| { auditOrigin?: "cli"; unsetPaths?: string[][]; explicitSetPaths?: string[][] }
384396
| undefined {
385397
return mockWriteConfigFile.mock.calls[0]?.[1];
386398
}
387399

388-
function requireWriteOptions(): { unsetPaths?: string[][]; explicitSetPaths?: string[][] } {
400+
function requireWriteOptions(): {
401+
auditOrigin?: "cli";
402+
unsetPaths?: string[][];
403+
explicitSetPaths?: string[][];
404+
} {
389405
const options = firstWriteConfigOptions();
390406
if (!options) {
391407
throw new Error("expected write options");
@@ -508,6 +524,7 @@ describe("config cli", () => {
508524
expect(written.tools).toEqual(resolved.tools);
509525
expect(written.logging).toEqual(resolved.logging);
510526
expect(written.agents).not.toHaveProperty("defaults");
527+
expect(requireWriteOptions().auditOrigin).toBe("cli");
511528
});
512529

513530
it("marks set paths explicit so default-equal writes persist", async () => {
@@ -3373,6 +3390,7 @@ describe("config cli", () => {
33733390
expect(written.tools?.profile).toBe("coding");
33743391
expect(written.logging).toEqual(resolved.logging);
33753392
expect(firstWriteConfigOptions()).toEqual({
3393+
auditOrigin: "cli",
33763394
unsetPaths: [["tools", "alsoAllow"]],
33773395
});
33783396
});
@@ -3393,7 +3411,7 @@ describe("config cli", () => {
33933411
expect(mockWriteConfigFile).toHaveBeenCalledTimes(1);
33943412
const written = firstWrittenConfig();
33953413
expect(written.agents?.list).toEqual([{ id: "agent-a" }, { id: "agent-c" }]);
3396-
expect(firstWriteConfigOptions()).toBeUndefined();
3414+
expect(firstWriteConfigOptions()).toEqual({ auditOrigin: "cli" });
33973415
});
33983416

33993417
it("preserves write-level unset handling for numeric object keys", async () => {
@@ -3419,6 +3437,7 @@ describe("config cli", () => {
34193437
"456": { channels: ["alerts"] },
34203438
});
34213439
expect(firstWriteConfigOptions()).toEqual({
3440+
auditOrigin: "cli",
34223441
unsetPaths: [["channels", "discord", "guilds", "123"]],
34233442
});
34243443
});

‎src/cli/config-cli.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2331,13 +2331,14 @@ async function runConfigOperations(params: {
23312331
...(unsetPaths.length > 0 || explicitSetPaths.length > 0
23322332
? {
23332333
writeOptions: {
2334+
auditOrigin: "cli",
23342335
...(unsetPaths.length > 0 ? { unsetPaths } : {}),
23352336
...(normalizedExplicitSetPaths.length > 0
23362337
? { explicitSetPaths: normalizedExplicitSetPaths }
23372338
: {}),
23382339
},
23392340
}
2340-
: {}),
2341+
: { writeOptions: { auditOrigin: "cli" } }),
23412342
});
23422343
if (removedGatewayAuthPaths.length > 0) {
23432344
runtime.log(
@@ -2577,8 +2578,8 @@ export async function runConfigUnset(opts: {
25772578
nextConfig: next,
25782579
...(snapshot.hash !== undefined ? { baseHash: snapshot.hash } : {}),
25792580
...(unsetResult.leafContainer === "array"
2580-
? {}
2581-
: { writeOptions: { unsetPaths: [parsedPath] } }),
2581+
? { writeOptions: { auditOrigin: "cli" } }
2582+
: { writeOptions: { auditOrigin: "cli", unsetPaths: [parsedPath] } }),
25822583
});
25832584
const hint = configApplyHintForOperations(
25842585
[buildUnsetOperation(parsedPath)],

‎src/cli/plugins-cli.uninstall.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,7 @@ describe("plugins cli uninstall", () => {
194194
},
195195
writeOptions: {
196196
allowConfigSizeDrop: true,
197+
auditOrigin: "plugin-install",
197198
afterWrite: { mode: "restart", reason: "plugin source changed" },
198199
unsetPaths: [["plugins", "installs"]],
199200
},

‎src/cli/plugins-install-config.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ vi.mock("./plugins-location-bridges.js", () => ({
6363
const DISCORD_REPO_INSTALL_SPEC = repoInstallSpec("discord");
6464
const installWriteOptions = {
6565
assertConfigPathForWrite: assertConfigPathForWriteMock,
66+
// Central install persistence stamps the journal origin onto every write.
67+
auditOrigin: "plugin-install",
6668
expectedConfigPath: "/tmp/config.json5",
6769
ownedConfigPathForWrite: "/tmp/config.json5",
6870
includeFileHashesForWrite: { "/tmp/plugins.json5": "include-1" },

‎src/cli/plugins-uninstall-command.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,7 @@ export async function runPluginUninstallCommand(
185185
...(snapshot.hash !== undefined ? { baseHash: snapshot.hash } : {}),
186186
writeOptions: {
187187
allowConfigSizeDrop: true,
188+
auditOrigin: "plugin-install",
188189
afterWrite: { mode: "restart", reason: "plugin source changed" },
189190
},
190191
}),

‎src/commands/doctor-gateway-services.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -789,6 +789,7 @@ export async function maybeRepairGatewayServiceConfig(
789789
nextConfig: nextCfg,
790790
afterWrite: { mode: "auto" },
791791
writeOptions: {
792+
auditOrigin: "doctor",
792793
allowConfigSizeDrop: options.allowConfigSizeDrop === true || updateRepairMode,
793794
skipPluginValidation: options.skipPluginValidation === true || updateRepairMode,
794795
preservedLegacyRootKeys: options.preservedLegacyRootKeys,

‎src/commands/doctor/legacy-config-repair.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ export async function repairLegacyConfigForUpdateChannel(params: {
4141
nextConfig: validated.config,
4242
baseHash: params.configSnapshot.hash,
4343
writeOptions: {
44+
auditOrigin: "doctor",
4445
allowConfigSizeDrop: true,
4546
skipOutputLogs: params.jsonMode,
4647
},
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
// Covers config journal snapshot fingerprints, slot ownership, and restoration.
2+
import fs from "node:fs";
3+
import { promises as fsPromises } from "node:fs";
4+
import path from "node:path";
5+
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
6+
import { resetPluginStateStoreForTests } from "../plugin-state/plugin-state-store.js";
7+
import { createSuiteTempRootTracker } from "../test-helpers/temp-dir.js";
8+
import {
9+
fingerprintConfigSnapshotAuthoredConfig,
10+
readConfigSnapshotAuditRecord,
11+
readLatestConfigSnapshotAuditRecord,
12+
restoreConfigSnapshotAuditRecord,
13+
upsertConfigSnapshotAuditRecord,
14+
} from "./config-journal-snapshot.js";
15+
16+
describe("config journal snapshots", () => {
17+
const suiteRootTracker = createSuiteTempRootTracker({
18+
prefix: "openclaw-config-journal-snapshot-",
19+
});
20+
21+
beforeAll(async () => {
22+
await suiteRootTracker.setup();
23+
});
24+
25+
it("fingerprints every snapshot leaf with a per-install key", async () => {
26+
const home = await suiteRootTracker.make("fingerprint-home");
27+
const stateDir = path.join(home, ".openclaw");
28+
const fingerprinted = fingerprintConfigSnapshotAuthoredConfig(
29+
{
30+
gateway: { auth: { token: "test-token" }, port: 18789 },
31+
},
32+
{
33+
env: { OPENCLAW_STATE_DIR: stateDir } as NodeJS.ProcessEnv,
34+
homedir: () => home,
35+
},
36+
);
37+
38+
expect(fingerprinted).toMatchObject({
39+
gateway: {
40+
auth: { token: expect.stringMatching(/^fp:[0-9a-f]{12}$/) },
41+
port: expect.stringMatching(/^fp:[0-9a-f]{12}$/),
42+
},
43+
});
44+
expect(JSON.stringify(fingerprinted)).not.toContain("test-token");
45+
expect(fs.statSync(path.join(stateDir, "config-journal-fingerprint.key")).mode & 0o777).toBe(
46+
0o600,
47+
);
48+
49+
// Type-only edits must change the fingerprint: "1" vs 1 vs true vs "true".
50+
const context = {
51+
env: { OPENCLAW_STATE_DIR: stateDir } as NodeJS.ProcessEnv,
52+
homedir: () => home,
53+
};
54+
const fingerprintOf = (value: unknown) =>
55+
(fingerprintConfigSnapshotAuthoredConfig({ leaf: value }, context) as { leaf: string }).leaf;
56+
const variants = [
57+
fingerprintOf("1"),
58+
fingerprintOf(1),
59+
fingerprintOf(true),
60+
fingerprintOf("true"),
61+
];
62+
expect(new Set(variants).size).toBe(variants.length);
63+
expect(fingerprintOf("1")).toBe(fingerprintOf("1"));
64+
});
65+
66+
it("hands the snapshot slot to another config path via the unfiltered CAS token", async () => {
67+
const home = await suiteRootTracker.make("snapshot-path-transfer");
68+
const env = { OPENCLAW_STATE_DIR: path.join(home, ".openclaw") } as NodeJS.ProcessEnv;
69+
const context = { env, homedir: () => home };
70+
const pathA = path.join(home, ".openclaw", "config-a.json");
71+
const pathB = path.join(home, ".openclaw", "config-b.json");
72+
upsertConfigSnapshotAuditRecord({
73+
...context,
74+
configPath: pathA,
75+
rawHash: "path-a-hash",
76+
authoredConfig: { gateway: { port: 1 } },
77+
});
78+
// Path-filtered read for B sees nothing, but the unfiltered slot is the
79+
// CAS token that lets B take the slot over from A.
80+
expect(readConfigSnapshotAuditRecord({ ...context, configPath: pathB })).toBeNull();
81+
const foreign = readLatestConfigSnapshotAuditRecord(context);
82+
expect(foreign?.configPath).toBe(path.resolve(pathA));
83+
const taken = upsertConfigSnapshotAuditRecord({
84+
...context,
85+
configPath: pathB,
86+
rawHash: "path-b-hash",
87+
authoredConfig: { gateway: { port: 2 } },
88+
expectedSnapshot: foreign,
89+
});
90+
expect(taken?.configPath).toBe(path.resolve(pathB));
91+
expect(readConfigSnapshotAuditRecord({ ...context, configPath: pathB })?.rawHash).toBe(
92+
"path-b-hash",
93+
);
94+
});
95+
96+
it("does not restore a snapshot slot after another writer replaces it", async () => {
97+
const home = await suiteRootTracker.make("snapshot-compare-and-set");
98+
const configPath = path.join(home, ".openclaw", "openclaw.json");
99+
const env = { OPENCLAW_STATE_DIR: path.join(home, ".openclaw") } as NodeJS.ProcessEnv;
100+
const context = { env, homedir: () => home };
101+
const prior = upsertConfigSnapshotAuditRecord({
102+
...context,
103+
configPath,
104+
rawHash: "prior",
105+
authoredConfig: { gateway: { port: 18789 } },
106+
});
107+
const written = upsertConfigSnapshotAuditRecord({
108+
...context,
109+
configPath,
110+
rawHash: "written",
111+
authoredConfig: { gateway: { port: 18790 } },
112+
});
113+
upsertConfigSnapshotAuditRecord({
114+
...context,
115+
configPath,
116+
rawHash: "newer-process",
117+
authoredConfig: { gateway: { port: 18791 } },
118+
});
119+
120+
restoreConfigSnapshotAuditRecord({
121+
...context,
122+
snapshot: prior,
123+
expectedSnapshot: written,
124+
});
125+
126+
expect(readConfigSnapshotAuditRecord({ ...context, configPath })).toMatchObject({
127+
rawHash: "newer-process",
128+
});
129+
});
130+
131+
it("falls back to a redaction marker when the fingerprint key cannot be stored", async () => {
132+
const home = await suiteRootTracker.make("fingerprint-fallback");
133+
const statePath = path.join(home, "state-file");
134+
await fsPromises.writeFile(statePath, "not a directory", "utf-8");
135+
136+
expect(
137+
fingerprintConfigSnapshotAuthoredConfig(
138+
{ gateway: { auth: { token: "test-token" } } },
139+
{ env: { OPENCLAW_STATE_DIR: statePath } as NodeJS.ProcessEnv, homedir: () => home },
140+
),
141+
).toEqual({ gateway: { auth: { token: "***" } } });
142+
});
143+
144+
afterAll(async () => {
145+
await suiteRootTracker.cleanup();
146+
});
147+
148+
afterEach(() => {
149+
resetPluginStateStoreForTests();
150+
});
151+
});

0 commit comments

Comments
 (0)