Skip to content

Commit 49e1ea2

Browse files
authored
fix(cli): redact machine-readable CLI error payloads (#124075)
1 parent f2c721b commit 49e1ea2

19 files changed

Lines changed: 189 additions & 64 deletions

‎src/cli/channels-cli.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { Option, type Command } from "commander";
33
import { formatDocsLink } from "../../packages/terminal-core/src/links.js";
44
import { theme } from "../../packages/terminal-core/src/theme.js";
55
import { danger } from "../globals.js";
6+
import { formatErrorMessage } from "../infra/errors.js";
67
import { defaultRuntime } from "../runtime.js";
78
import { createLazyImportLoader } from "../shared/lazy-promise.js";
89
import { resolveCliArgvInvocation } from "./argv-invocation.js";
@@ -70,7 +71,7 @@ function runChannelsCommand(action: () => Promise<void>) {
7071

7172
function runChannelsCommandWithDanger(action: () => Promise<void>, label: string) {
7273
return runCommandWithRuntime(defaultRuntime, action, (err) => {
73-
defaultRuntime.error(danger(`${label}: ${String(err)}`));
74+
defaultRuntime.error(danger(`${label}: ${formatErrorMessage(err)}`));
7475
defaultRuntime.exit(1);
7576
});
7677
}

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

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { diffConfigPaths } from "../gateway/config-diff.js";
1010
import { buildGatewayReloadPlan } from "../gateway/config-reload-plan.js";
1111
import { resolveGatewayReloadSettings } from "../gateway/config-reload-settings.js";
1212
import { danger, info } from "../globals.js";
13+
import { formatErrorMessage } from "../infra/errors.js";
1314
import type { RuntimeEnv } from "../runtime.js";
1415
import { writeRuntimeJson } from "../runtime.js";
1516
import { toDotPath } from "../shared/dot-path.js";
@@ -495,13 +496,13 @@ export function handleConfigMutationError(params: {
495496
runtime: RuntimeEnv;
496497
options: ConfigMutationOptions;
497498
}) {
499+
const message = formatErrorMessage(params.err);
498500
if (params.options.dryRun && params.options.json) {
499501
if (params.err instanceof ConfigSetDryRunValidationError) {
500502
writeRuntimeJson(params.runtime, params.err.result);
501503
params.runtime.exit(1);
502504
return;
503505
}
504-
const message = params.err instanceof Error ? params.err.message : String(params.err);
505506
const result: ConfigSetDryRunResult = {
506507
ok: false,
507508
operations: 0,
@@ -513,10 +514,10 @@ export function handleConfigMutationError(params: {
513514
errors: [{ kind: "schema", message }],
514515
};
515516
writeRuntimeJson(params.runtime, result);
516-
params.runtime.error(danger(String(params.err)));
517+
params.runtime.error(danger(message));
517518
params.runtime.exit(1);
518519
return;
519520
}
520-
params.runtime.error(danger(String(params.err)));
521+
params.runtime.error(danger(message));
521522
params.runtime.exit(1);
522523
}

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
type SecretRef,
1313
} from "../config/types.secrets.js";
1414
import { validateConfigObjectRawWithPlugins } from "../config/validation.js";
15+
import { formatErrorMessage } from "../infra/errors.js";
1516
import { loadPluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
1617
import { type RuntimeEnv, defaultRuntime, writeRuntimeJson } from "../runtime.js";
1718
import {
@@ -155,7 +156,7 @@ export async function collectDryRunResolvabilityErrors(params: {
155156
} catch (err) {
156157
failures.push({
157158
kind: "resolvability",
158-
message: String(err),
159+
message: formatErrorMessage(err),
159160
ref: `${ref.source}:${ref.provider}:${ref.id}`,
160161
});
161162
}

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

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3361,7 +3361,7 @@ describe("config cli", () => {
33613361
},
33623362
refsChecked: 0,
33633363
skippedExecRefs: 0,
3364-
errors: [{ kind: "schema", message }],
3364+
errors: [{ kind: "schema", message: expect.stringContaining(message) }],
33653365
});
33663366
expectErrorIncludes(message);
33673367
});
@@ -3398,7 +3398,10 @@ describe("config cli", () => {
33983398

33993399
it("aggregates schema and resolvability failures in --dry-run --json mode", async () => {
34003400
setGatewaySnapshot({ providers: { default: { source: "env" } } });
3401-
mockResolveSecretRefValue.mockRejectedValue(new Error("missing env var"));
3401+
const secret = "sk-abcdefghijklmnopqrstuv";
3402+
const error = new Error(`missing env var: Authorization: Bearer ${secret}`);
3403+
error.name = "SecretResolutionError";
3404+
mockResolveSecretRefValue.mockRejectedValue(error);
34023405

34033406
await expect(
34043407
runConfigCommand([
@@ -3421,6 +3424,8 @@ describe("config cli", () => {
34213424
expect(errorKinds).toContain("resolvability");
34223425
const errorRefs = (payload.errors ?? []).map((entry) => entry.ref ?? "");
34233426
expect(errorRefs).toContain("env:default:DISCORD_BOT_TOKEN");
3427+
expect(JSON.stringify(payload)).not.toContain(error.name);
3428+
expect(JSON.stringify(payload)).not.toContain(secret);
34243429
});
34253430

34263431
it("fails dry-run when provider updates make existing refs unresolvable", async () => {

‎src/cli/config-cli.ts‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { redactConfigObject } from "../config/redact-snapshot.js";
1010
import { readBestEffortRuntimeConfigSchema } from "../config/runtime-schema.js";
1111
import type { OpenClawConfig } from "../config/types.openclaw.js";
1212
import { danger, info, success, warn } from "../globals.js";
13+
import { formatErrorMessage } from "../infra/errors.js";
1314
import {
1415
ExitError,
1516
type RuntimeEnv,
@@ -182,11 +183,11 @@ export async function runConfigGet(opts: { path: string; json?: boolean; runtime
182183
throw err;
183184
}
184185
if (opts.json) {
185-
writeRuntimeJson(runtime, { error: String(err) });
186+
writeRuntimeJson(runtime, { error: formatErrorMessage(err) });
186187
runtime.exit(1);
187188
return;
188189
}
189-
runtime.error(danger(String(err)));
190+
runtime.error(danger(formatErrorMessage(err)));
190191
runtime.exit(1);
191192
}
192193
}
@@ -288,7 +289,7 @@ async function runConfigFile(opts: { json?: boolean; runtime?: RuntimeEnv }) {
288289
}
289290
writeRuntimeStdout(runtime, `${path}\n`);
290291
} catch (err) {
291-
runtime.error(danger(String(err)));
292+
runtime.error(danger(formatErrorMessage(err)));
292293
runtime.exit(1);
293294
}
294295
}
@@ -302,7 +303,7 @@ async function runConfigSchema(opts: { runtime?: RuntimeEnv } = {}) {
302303
schema.properties = { $schema: { type: "string" }, ...schema.properties };
303304
writeRuntimeJson(runtime, schema);
304305
} catch (err) {
305-
runtime.error(danger(`Config schema error: ${String(err)}`));
306+
runtime.error(danger(`Config schema error: ${formatErrorMessage(err)}`));
306307
runtime.exit(1);
307308
}
308309
}
@@ -368,9 +369,13 @@ async function runConfigValidate(opts: { json?: boolean; runtime?: RuntimeEnv }
368369
}
369370
} catch (err) {
370371
if (opts.json) {
371-
writeRuntimeJson(runtime, { valid: false, path: outputPath, error: String(err) }, 0);
372+
writeRuntimeJson(
373+
runtime,
374+
{ valid: false, path: outputPath, error: formatErrorMessage(err) },
375+
0,
376+
);
372377
} else {
373-
runtime.error(danger(`Config validation error: ${String(err)}`));
378+
runtime.error(danger(`Config validation error: ${formatErrorMessage(err)}`));
374379
}
375380
runtime.exit(1);
376381
}

‎src/cli/cron-cli/register.cron-edit.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import type { Command } from "commander";
88
import { THINKING_LEVELS_HELP } from "../../auto-reply/thinking.shared.js";
99
import type { CronJob } from "../../cron/types.js";
1010
import { danger } from "../../globals.js";
11+
import { formatErrorMessage } from "../../infra/errors.js";
1112
import { sanitizeAgentId } from "../../routing/session-key.js";
1213
import { defaultRuntime } from "../../runtime.js";
1314
import {
@@ -496,7 +497,7 @@ export function registerCronEditCommand(cron: Command) {
496497
defaultRuntime.writeJson(res);
497498
await warnIfCronSchedulerDisabled(opts);
498499
} catch (err) {
499-
defaultRuntime.error(danger(String(err)));
500+
defaultRuntime.error(danger(formatErrorMessage(err)));
500501
defaultRuntime.exit(1);
501502
}
502503
}),

‎src/cli/cron-cli/shared.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { parseAbsoluteTimeMs } from "../../cron/parse.js";
1212
import { resolveCronStaggerMs } from "../../cron/stagger.js";
1313
import type { CronDeliveryPreview, CronJob, CronSchedule } from "../../cron/types.js";
1414
import { danger } from "../../globals.js";
15+
import { formatErrorMessage } from "../../infra/errors.js";
1516
import { formatDurationHuman } from "../../infra/format-time/format-duration.ts";
1617
import {
1718
isOffsetlessIsoDateTime,
@@ -196,7 +197,7 @@ function formatCronStatusForDisplay(job: CronJob): string {
196197
}
197198

198199
export function handleCronCliError(err: unknown) {
199-
defaultRuntime.error(danger(String(err)));
200+
defaultRuntime.error(danger(formatErrorMessage(err)));
200201
defaultRuntime.exit(1);
201202
}
202203

‎src/cli/daemon-cli/status.test.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,10 @@ describe("runDaemonStatus", () => {
139139
});
140140

141141
it("renders service-inspection failures as JSON in JSON mode", async () => {
142-
gatherDaemonStatus.mockRejectedValueOnce(new Error("service manager unavailable"));
142+
const secret = "sk-abcdefghijklmnopqrstuv";
143+
const error = new Error(`service manager unavailable: Authorization: Bearer ${secret}`);
144+
error.name = "ServiceManagerError";
145+
gatherDaemonStatus.mockRejectedValueOnce(error);
143146

144147
await expect(
145148
runDaemonStatus({
@@ -153,8 +156,10 @@ describe("runDaemonStatus", () => {
153156
expect(printDaemonStatus).not.toHaveBeenCalled();
154157
expect(defaultRuntime.writeJson).toHaveBeenCalledWith({
155158
ok: false,
156-
error: "Gateway status failed: Error: service manager unavailable",
159+
error: expect.stringContaining("Gateway status failed: service manager unavailable"),
157160
});
161+
expect(JSON.stringify(defaultRuntime.writeJson.mock.calls)).not.toContain(error.name);
162+
expect(JSON.stringify(defaultRuntime.writeJson.mock.calls)).not.toContain(secret);
158163
expect(defaultRuntime.error).not.toHaveBeenCalled();
159164
expect(defaultRuntime.exit).toHaveBeenCalledTimes(1);
160165
});

‎src/cli/daemon-cli/status.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Gateway service status command entrypoint: gathers status, prints it, and handles probe failures.
22
import { colorize, isRich, theme } from "../../../packages/terminal-core/src/theme.js";
3+
import { formatErrorMessage } from "../../infra/errors.js";
34
import { defaultRuntime } from "../../runtime.js";
45
import { gatherDaemonStatus } from "./status.gather.js";
56
import { printDaemonStatus } from "./status.print.js";
@@ -34,7 +35,7 @@ export async function runDaemonStatus(opts: DaemonStatusOptions) {
3435
});
3536
printDaemonStatus(status, { json: opts.json, deep: opts.deep === true });
3637
} catch (err) {
37-
failDaemonStatus(opts, `Gateway status failed: ${String(err)}`);
38+
failDaemonStatus(opts, `Gateway status failed: ${formatErrorMessage(err)}`);
3839
return;
3940
}
4041

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

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -316,17 +316,17 @@ describe("registerDirectoryCli", () => {
316316
[
317317
"self",
318318
["directory", "self", "--channel", "demo-directory", "--json"],
319-
"Error: Channel demo-directory does not support directory self",
319+
"Channel demo-directory does not support directory self",
320320
],
321321
[
322322
"peers",
323323
["directory", "peers", "list", "--channel", "demo-directory", "--json"],
324-
"Error: Channel demo-directory does not support directory peers",
324+
"Channel demo-directory does not support directory peers",
325325
],
326326
[
327327
"groups",
328328
["directory", "groups", "list", "--channel", "demo-directory", "--json"],
329-
"Error: Channel demo-directory does not support directory groups",
329+
"Channel demo-directory does not support directory groups",
330330
],
331331
[
332332
"group members",
@@ -340,7 +340,7 @@ describe("registerDirectoryCli", () => {
340340
"group-1",
341341
"--json",
342342
],
343-
"Error: Channel demo-directory does not support group members listing",
343+
"Channel demo-directory does not support group members listing",
344344
],
345345
])("writes JSON errors for unsupported directory %s", async (_label, args, expectedError) => {
346346
mocks.resolveInstallableChannelPlugin.mockResolvedValue({
@@ -364,6 +364,41 @@ describe("registerDirectoryCli", () => {
364364
expect(runtimeState.defaultRuntime.exit).toHaveBeenCalledWith(1);
365365
});
366366

367+
it.each([
368+
{ mode: "human", args: ["directory", "self", "--channel", "demo-directory"] },
369+
{
370+
mode: "JSON",
371+
args: ["directory", "self", "--channel", "demo-directory", "--json"],
372+
},
373+
])("renders named errors without class names in $mode mode", async ({ mode, args }) => {
374+
const error = new Error("Multiple agents are configured, but this operation has no owner.");
375+
error.name = "AgentSelectionRequiredError";
376+
const self = vi.fn().mockRejectedValue(error);
377+
mocks.resolveInstallableChannelPlugin.mockResolvedValue({
378+
cfg: { channels: { "demo-directory": {} } },
379+
channelId: "demo-directory",
380+
plugin: { id: "demo-directory", directory: { self } },
381+
configChanged: false,
382+
});
383+
384+
const program = new Command().name("openclaw");
385+
registerDirectoryCli(program);
386+
387+
await expect(program.parseAsync(args, { from: "user" })).rejects.toThrow("exit:1");
388+
389+
if (mode === "JSON") {
390+
const payload = JSON.parse(runtimeState.runtimeLogs.at(-1) ?? "");
391+
expect(payload).toEqual({ error: error.message });
392+
expect(Object.keys(payload)).toEqual(["error"]);
393+
expect(runtimeState.defaultRuntime.error).not.toHaveBeenCalled();
394+
} else {
395+
expect(runtimeErrors()).toEqual([error.message]);
396+
expect(runtimeState.defaultRuntime.writeJson).not.toHaveBeenCalled();
397+
}
398+
expect([...runtimeState.runtimeLogs, ...runtimeErrors()].join("\n")).not.toContain(error.name);
399+
expect(runtimeState.defaultRuntime.exit).toHaveBeenCalledWith(1);
400+
});
401+
367402
it.each([
368403
["peers list", ["directory", "peers", "list", "--channel", "slack", "--limit", "5x"]],
369404
["groups list", ["directory", "groups", "list", "--channel", "slack", "--limit", "5x"]],

0 commit comments

Comments
 (0)