Skip to content

Commit f59392f

Browse files
authored
fix(channels): redact logs and reject unknown filters (#125939)
* fix(channels): redact and validate log filters * fix(logging): preserve filtered redacted channel tails * fix(channels): match log filters on exact boundaries * fix(logging): honor redaction off mode
1 parent 1d36dac commit f59392f

10 files changed

Lines changed: 348 additions & 222 deletions

File tree

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ const listRawChannelPluginCatalogEntriesMock = vi.hoisted(() =>
1717
vi.fn<() => ChannelPluginCatalogEntry[]>(() => []),
1818
);
1919
const channelsAddCommandMock = vi.hoisted(() => vi.fn(async () => undefined));
20+
const channelsLogsCommandMock = vi.hoisted(() =>
21+
vi.fn(async (_options: { channel?: string }, _runtime: unknown) => undefined),
22+
);
2023
const channelsResolveCommandMock = vi.hoisted(() => vi.fn(async () => undefined));
2124
const runtimeMock = vi.hoisted(() => ({
2225
log: vi.fn(),
@@ -34,6 +37,7 @@ vi.mock("../channels/plugins/catalog.js", () => ({
3437

3538
vi.mock("../commands/channels.js", () => ({
3639
channelsAddCommand: channelsAddCommandMock,
40+
channelsLogsCommand: channelsLogsCommandMock,
3741
channelsResolveCommand: channelsResolveCommandMock,
3842
}));
3943

@@ -91,6 +95,19 @@ describe("registerChannelsCli", () => {
9195
expect(getChannelSubcommandNames(program, "dead-letters")).toEqual(["list", "resubmit"]);
9296
});
9397

98+
it.each([
99+
["omitted", ["channels", "logs"], undefined],
100+
["explicit all", ["channels", "logs", "--channel", "all"], "all"],
101+
])("distinguishes an %s channels logs filter", async (_label, args, expectedChannel) => {
102+
const program = new Command().name("openclaw").exitOverride();
103+
104+
await registerChannelsCli(program, ["node", "openclaw", ...args]);
105+
await program.parseAsync(args, { from: "user" });
106+
107+
const [options] = channelsLogsCommandMock.mock.calls[0] ?? [];
108+
expect(options?.channel).toBe(expectedChannel);
109+
});
110+
94111
it.each(["auto", "user", "group", "channel"])(
95112
"forwards the supported %s resolve target kind",
96113
async (kind) => {

‎src/cli/channels-cli.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ export async function registerChannelsCli(
257257
channels
258258
.command("logs")
259259
.description("Show recent channel logs from the gateway log file")
260-
.option("--channel <name>", `Channel (${formatCliChannelOptions(["all"])})`, "all")
260+
.option("--channel <name>", `Channel (${formatCliChannelOptions(["all"])}; default: all)`)
261261
.option("--lines <n>", "Number of lines (default: 200)", "200")
262262
.option("--json", "Output JSON", false)
263263
.action(async (opts) => {

‎src/commands/channels.logs.test.ts‎

Lines changed: 160 additions & 112 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,20 @@ import os from "node:os";
44
import path from "node:path";
55
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
66
import { setLoggerOverride } from "../logging.js";
7+
import { registerSecretValueForRedaction } from "../logging/secret-redaction-registry.js";
8+
import { resetSecretRedactionRegistryForTest } from "../logging/secret-redaction-registry.test-support.js";
79
import { createTestRuntime } from "./test-runtime-config-helpers.js";
810

9-
const pluginRegistryMocks = vi.hoisted(() => ({
10-
loadPluginRegistrySnapshot: vi.fn(() => ({ plugins: [] })),
11-
listPluginContributionIds: vi.fn(() => ["external-chat"]),
12-
}));
11+
const pluginRegistryMocks = vi.hoisted(() => {
12+
const plugins = [{ id: "vendor-external-chat", channels: ["external-chat"] }];
13+
return {
14+
loadPluginManifestRegistryForPluginRegistry: vi.fn(() => ({ diagnostics: [], plugins })),
15+
};
16+
});
1317

1418
vi.mock("../plugins/plugin-registry.js", () => ({
15-
loadPluginManifestRegistryForPluginRegistry: () => ({ diagnostics: [], plugins: [] }),
16-
loadPluginRegistrySnapshot: pluginRegistryMocks.loadPluginRegistrySnapshot,
17-
listPluginContributionIds: pluginRegistryMocks.listPluginContributionIds,
19+
loadPluginManifestRegistryForPluginRegistry:
20+
pluginRegistryMocks.loadPluginManifestRegistryForPluginRegistry,
1821
}));
1922

2023
vi.mock("../channels/plugins/index.js", () => ({
@@ -26,20 +29,22 @@ vi.mock("../channels/plugins/index.js", () => ({
2629
import { channelsLogsCommand } from "./channels/logs.js";
2730

2831
const runtime = createTestRuntime();
29-
type PositionalRead = (
30-
buffer: Buffer,
31-
offset: number,
32-
length: number,
33-
position: number | null,
34-
) => Promise<{ bytesRead: number; buffer: Buffer }>;
35-
36-
function logLine(params: { module: string; message: string }) {
32+
function logLine(params: {
33+
subsystem?: string;
34+
module?: string;
35+
plugin?: string;
36+
message: string;
37+
}) {
3738
return JSON.stringify({
3839
time: "2026-04-25T12:00:00.000Z",
3940
0: params.message,
4041
_meta: {
4142
logLevelName: "INFO",
42-
name: JSON.stringify({ module: params.module }),
43+
name: JSON.stringify({
44+
...(params.subsystem ? { subsystem: params.subsystem } : {}),
45+
...(params.module ? { module: params.module } : {}),
46+
...(params.plugin ? { plugin: params.plugin } : {}),
47+
}),
4348
},
4449
});
4550
}
@@ -48,7 +53,7 @@ function readJsonPayload() {
4853
return JSON.parse(String(runtime.log.mock.calls[0]?.[0])) as {
4954
file: string;
5055
channel: string;
51-
lines: Array<{ message: string }>;
56+
lines: Array<{ message: string; raw: string }>;
5257
};
5358
}
5459

@@ -63,12 +68,12 @@ describe("channelsLogsCommand", () => {
6368
runtime.log.mockClear();
6469
runtime.error.mockClear();
6570
runtime.exit.mockClear();
66-
pluginRegistryMocks.loadPluginRegistrySnapshot.mockClear();
67-
pluginRegistryMocks.listPluginContributionIds.mockClear();
71+
pluginRegistryMocks.loadPluginManifestRegistryForPluginRegistry.mockClear();
6872
});
6973

7074
afterEach(async () => {
7175
vi.restoreAllMocks();
76+
resetSecretRedactionRegistryForTest();
7277
setLoggerOverride(null);
7378
await fs.rm(tempDir, { recursive: true, force: true });
7479
});
@@ -77,24 +82,153 @@ describe("channelsLogsCommand", () => {
7782
await fs.writeFile(
7883
logPath,
7984
[
80-
logLine({ module: "gateway/channels/external-chat/send", message: "external sent" }),
85+
logLine({ plugin: "vendor-external-chat", message: "external sent" }),
86+
logLine({ plugin: "vendor-external-chat-shadow", message: "shadow sent" }),
8187
logLine({ module: "gateway/channels/slack/send", message: "slack sent" }),
8288
].join("\n"),
8389
);
8490

8591
await channelsLogsCommand({ channel: "external-chat", json: true }, runtime);
8692

87-
expect(pluginRegistryMocks.loadPluginRegistrySnapshot).toHaveBeenCalledOnce();
88-
expect(pluginRegistryMocks.listPluginContributionIds).toHaveBeenCalledOnce();
89-
const [contributionOptions] = pluginRegistryMocks.listPluginContributionIds.mock
90-
.calls[0] as unknown as [{ contribution?: string; includeDisabled?: boolean }];
91-
expect(contributionOptions?.contribution).toBe("channels");
92-
expect(contributionOptions?.includeDisabled).toBe(true);
93+
expect(pluginRegistryMocks.loadPluginManifestRegistryForPluginRegistry).toHaveBeenCalledWith({
94+
includeDisabled: true,
95+
env: process.env,
96+
});
9397
const payload = readJsonPayload();
9498
expect(payload.channel).toBe("external-chat");
9599
expect(payload.lines.map((line) => line.message)).toEqual(["external sent"]);
96100
});
97101

102+
it.each([
103+
{
104+
label: "subsystem",
105+
channel: "slack",
106+
shadow: { subsystem: "gateway/channels/slack-archive" },
107+
match: { subsystem: "gateway/channels/slack/send" },
108+
},
109+
{
110+
label: "module",
111+
channel: "external-chat",
112+
shadow: { module: "external-chat-shadow" },
113+
match: { module: "external-chat" },
114+
},
115+
])("excludes a shadow $label while preserving an exact channel match", async (fixture) => {
116+
await fs.writeFile(
117+
logPath,
118+
[
119+
logLine({ ...fixture.shadow, message: "shadow" }),
120+
logLine({ ...fixture.match, message: "match" }),
121+
].join("\n"),
122+
);
123+
124+
await channelsLogsCommand({ channel: fixture.channel, json: true }, runtime);
125+
126+
expect(readJsonPayload().lines.map((line) => line.message)).toEqual(["match"]);
127+
});
128+
129+
it.each([false, true])(
130+
"rejects an unknown explicit channel without widening output (json=%s)",
131+
async (json) => {
132+
await fs.writeFile(
133+
logPath,
134+
logLine({ module: "gateway/channels/slack/send", message: "unrelated message" }),
135+
);
136+
137+
const error = await channelsLogsCommand({ channel: "slakc", json }, runtime).catch(
138+
(cause: unknown) => cause,
139+
);
140+
expect(error).toBeInstanceOf(Error);
141+
expect((error as Error).message).toContain('Unknown channel "slakc". Valid channels: all,');
142+
expect((error as Error).message).toContain("external-chat");
143+
expect((error as Error).message).toContain("slack");
144+
expect(runtime.log).not.toHaveBeenCalled();
145+
},
146+
);
147+
148+
it("redacts credential-bearing channel lines in text output", async () => {
149+
const fixtureCredential = "opaque-registry-value-1234567890";
150+
registerSecretValueForRedaction(fixtureCredential);
151+
await fs.writeFile(
152+
logPath,
153+
logLine({
154+
module: "gateway/channels/slack/send",
155+
message: `opaque=${fixtureCredential}`,
156+
}),
157+
);
158+
159+
await channelsLogsCommand({ channel: "slack" }, runtime);
160+
161+
const output = runtime.log.mock.calls.flat().join("\n");
162+
expect(output).toContain("2026-04-25T12:00:00.000Z info");
163+
expect(output).toContain("opaque=opaque…7890");
164+
expect(output).not.toContain(fixtureCredential);
165+
});
166+
167+
it("redacts credential-bearing channel lines in JSON output", async () => {
168+
const fixtureCredential = "opaque-registry-value-1234567890";
169+
registerSecretValueForRedaction(fixtureCredential);
170+
await fs.writeFile(
171+
logPath,
172+
logLine({
173+
module: "gateway/channels/slack/send",
174+
message: `opaque=${fixtureCredential}`,
175+
}),
176+
);
177+
178+
await channelsLogsCommand({ channel: "slack", json: true }, runtime);
179+
180+
const payload = readJsonPayload();
181+
expect(payload.lines[0]?.message).toBe("opaque=opaque…7890");
182+
expect(JSON.stringify(payload)).not.toContain(fixtureCredential);
183+
});
184+
185+
it("preserves ordering and line limits for an explicit all filter", async () => {
186+
await fs.writeFile(
187+
logPath,
188+
[
189+
logLine({ module: "gateway/channels/slack/send", message: "first" }),
190+
logLine({ module: "gateway/channels/external-chat/send", message: "second" }),
191+
logLine({ module: "gateway/channels/slack/send", message: "third" }),
192+
].join("\n"),
193+
);
194+
195+
await channelsLogsCommand({ channel: "all", lines: 2, json: true }, runtime);
196+
197+
const payload = readJsonPayload();
198+
expect(payload.channel).toBe("all");
199+
expect(payload.lines.map((line) => line.message)).toEqual(["second", "third"]);
200+
});
201+
202+
it("finds sparse channel records beyond the shared 5000-line cap", async () => {
203+
const filler = logLine({ module: "gateway/health", message: "ok" });
204+
const lines = [
205+
logLine({ module: "gateway/channels/slack/send", message: "first match" }),
206+
...Array.from({ length: 5000 }, () => filler),
207+
logLine({ module: "gateway/channels/slack/send", message: "second match" }),
208+
];
209+
await fs.writeFile(logPath, lines.join("\n"));
210+
211+
await channelsLogsCommand({ channel: "slack", lines: 2000, json: true }, runtime);
212+
213+
expect(readJsonPayload().lines.map((line) => line.message)).toEqual([
214+
"first match",
215+
"second match",
216+
]);
217+
});
218+
219+
it("treats an omitted channel filter as all", async () => {
220+
await fs.writeFile(
221+
logPath,
222+
logLine({ module: "gateway/channels/slack/send", message: "omitted filter" }),
223+
);
224+
225+
await channelsLogsCommand({ json: true }, runtime);
226+
227+
const payload = readJsonPayload();
228+
expect(payload.channel).toBe("all");
229+
expect(payload.lines.map((line) => line.message)).toEqual(["omitted filter"]);
230+
});
231+
98232
it("falls back to the latest rolling log when the configured rolling file is missing", async () => {
99233
const configuredFile = path.join(tempDir, "openclaw-2026-04-26.log");
100234
const fallbackFile = path.join(tempDir, "openclaw-2026-04-25.log");
@@ -149,92 +283,6 @@ describe("channelsLogsCommand", () => {
149283
expect(payload.lines.map((line) => line.message)).toEqual(["current sent"]);
150284
});
151285

152-
it("fills short positional reads before parsing channel log lines", async () => {
153-
const realOpen = fs.open.bind(fs);
154-
const readLengths: number[] = [];
155-
vi.spyOn(fs, "open").mockImplementation(async (...args) => {
156-
const handle = await realOpen(...args);
157-
const realRead = handle.read.bind(handle) as PositionalRead;
158-
const shortRead = vi.fn<PositionalRead>((buffer, offset, length, position) => {
159-
readLengths.push(length);
160-
return realRead(buffer, offset, Math.min(length, 4), position);
161-
});
162-
Object.defineProperty(handle, "read", { configurable: true, value: shortRead });
163-
return handle;
164-
});
165-
await fs.writeFile(
166-
logPath,
167-
[
168-
logLine({ module: "gateway/channels/slack/send", message: "first" }),
169-
logLine({ module: "gateway/channels/slack/send", message: "second" }),
170-
].join("\n"),
171-
);
172-
173-
await channelsLogsCommand({ channel: "slack", json: true }, runtime);
174-
175-
expect(readJsonPayload().lines.map((line) => line.message)).toEqual(["first", "second"]);
176-
expect(readLengths.length).toBeGreaterThan(1);
177-
});
178-
179-
it("returns the first line of the tail window when start aligns with a line boundary", async () => {
180-
// MAX_BYTES in readTailLines is 1_000_000. We build a file of 2_000_000 bytes
181-
// made of 10_000 lines each exactly 200 bytes (199 payload + "\n"), so the
182-
// read window starts at byte offset 1_000_000 which is exactly on a line
183-
// boundary (byte 999_999 is the trailing "\n" of the previous line).
184-
// Without checking the byte before the window, readTailLines drops line 5000 silently.
185-
const LINE_SIZE = 200;
186-
const TOTAL_LINES = 10_000;
187-
const FIRST_INDEX = 5000; // first line of the tail window after alignment
188-
189-
const buildLine = (message: string) => {
190-
const base = logLine({
191-
module: "gateway/channels/slack/send",
192-
message,
193-
});
194-
const payloadLen = LINE_SIZE - 1; // reserve 1 byte for newline
195-
// Re-emit with a padded message so total byte length is constant.
196-
const padNeeded = payloadLen - Buffer.byteLength(base);
197-
if (padNeeded < 0) {
198-
throw new Error(`base log line too long: ${Buffer.byteLength(base)} > ${payloadLen}`);
199-
}
200-
const padded = logLine({
201-
module: "gateway/channels/slack/send",
202-
message: message + " ".repeat(padNeeded),
203-
});
204-
if (Buffer.byteLength(padded) !== payloadLen) {
205-
throw new Error(`padded line wrong size: ${Buffer.byteLength(padded)} vs ${payloadLen}`);
206-
}
207-
return padded + "\n";
208-
};
209-
210-
const handle = await fs.open(logPath, "w");
211-
try {
212-
for (let i = 0; i < TOTAL_LINES; i++) {
213-
let message: string;
214-
if (i === FIRST_INDEX) {
215-
message = "first-line-in-window";
216-
} else if (i === TOTAL_LINES - 1) {
217-
message = "last-line";
218-
} else {
219-
message = "filler";
220-
}
221-
await handle.write(buildLine(message));
222-
}
223-
} finally {
224-
await handle.close();
225-
}
226-
227-
await channelsLogsCommand(
228-
{ channel: "slack", json: true, lines: String(TOTAL_LINES) },
229-
runtime,
230-
);
231-
232-
const payload = readJsonPayload();
233-
const messages = payload.lines.map((line) => line.message.trimEnd());
234-
expect(messages[0]).toBe("first-line-in-window");
235-
expect(messages[messages.length - 1]).toBe("last-line");
236-
});
237-
238286
it("does not fall back to rolling logs for a missing custom log file", async () => {
239287
const configuredFile = path.join(tempDir, "custom-channel.log");
240288
const fallbackFile = path.join(tempDir, "openclaw-2026-04-25.log");

0 commit comments

Comments
 (0)