Skip to content

Commit 3f26a0c

Browse files
committed
fix(cron): harden preHook against shell injection and log leakage
Replace shell `command` string with direct `file` + `args[]` execFile (CWE-78): metacharacters in config are now literal text, not parsed by /bin/sh or cmd.exe. Schemas, normalization, and tool surfaces are updated to match; legacy `{command}` payloads are rejected at the normalizer. Stop logging raw hook stdout/stderr at info level (CWE-532). On success, log only metadata (outcome, exitCode). On skip/error, log truncated and redacted output at debug via summarizePreHookOutput, keeping secrets printed by hook scripts out of routine info logs. Addresses Aisle Security Analysis findings on PR #62195.
1 parent 40c03f8 commit 3f26a0c

16 files changed

Lines changed: 205 additions & 88 deletions
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
f0421335bfd388b7ebe1b8d478036ece4bf5eb8fd7b1de81b8cdc4ec6522ce20 config-baseline.json
2-
bf00f7910d8f0d8e12592e8a1c6bd0397f8e62fef2c11eb0cbd3b3a3e2a78ffe config-baseline.core.json
1+
c1b0272dea9d803b4c0461f8f2c4b458693a6da0165c17e96d5978f1d673460e config-baseline.json
2+
7038cb496fae832a29e6f84d882047a768919d3e346ca4ddb34d9eff27690d39 config-baseline.core.json
33
22d7cd6d8279146b2d79c9531a55b80b52a2c99c81338c508104729154fdd02d config-baseline.channel.json
4-
c6f99aed28b98e5914585956ec303b615a8ef975abf5cec186a61781c20b9106 config-baseline.plugin.json
4+
322929b91b6ac7eabd3a3fbbdb18ad7dd611626f2f33430711968d03b4364bb6 config-baseline.plugin.json

‎docs/automation/cron-jobs.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -355,14 +355,15 @@ Model override note:
355355

356356
## Pre-run hooks
357357

358-
An optional `preHook` runs a shell command before agent execution. Use it to gate runs on preconditions like disk space, network reachability, or API availability.
358+
An optional `preHook` runs a fixed executable before agent execution. Use it to gate runs on preconditions like disk space, network reachability, or API availability. The hook is spawned directly — no shell — so metacharacters in `file` or `args` are passed as literal text.
359359

360360
```json5
361361
{
362362
schedule: "cron 0 8 * * 1-5",
363363
payload: { kind: "agentTurn", message: "check PRs" },
364364
preHook: {
365-
command: "ping -c1 -W2 api.openai.com > /dev/null 2>&1",
365+
file: "/usr/local/bin/check-api-reachable",
366+
args: ["api.openai.com"],
366367
timeoutSeconds: 10,
367368
},
368369
}
@@ -377,8 +378,8 @@ The hook runs with the same permissions as the cron trigger. Exit codes control
377378
| Any other | Error (increments `consecutiveErrors`, triggers backoff and alerts) |
378379

379380
- **Timeout**: default 30 seconds, maximum 300 seconds. The process is killed when the timeout is reached.
380-
- **Output**: stdout and stderr are captured (up to 64 KB) and included in structured logs.
381-
- **Platform**: `/bin/sh -c` on Unix, `cmd.exe /c` on Windows.
381+
- **Output**: stdout and stderr are captured (up to 64 KB), truncated and redacted before being written to structured logs. Keep secrets out of hook output; do not rely on raw output appearing in logs.
382+
- **Shell**: not used. If you need shell features (pipes, globs, redirection), wrap them in a script file and set `file` to that script.
382383

383384
## Configuration
384385

‎docs/gateway/heartbeat.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -425,7 +425,7 @@ Use `--mode next-heartbeat` to wait for the next scheduled tick.
425425

426426
## Pre-run hooks (optional)
427427

428-
An optional `preHook` runs a shell command before each heartbeat turn. The hook runs after preflight checks (enabled, active hours, queue empty) but before the agent turn.
428+
An optional `preHook` runs a fixed executable before each heartbeat turn. The hook runs after preflight checks (enabled, active hours, queue empty) but before the agent turn. It is spawned directly — no shell — so metacharacters in `file` or `args` are passed as literal text.
429429

430430
```json5
431431
{
@@ -434,7 +434,8 @@ An optional `preHook` runs a shell command before each heartbeat turn. The hook
434434
heartbeat: {
435435
every: "30m",
436436
preHook: {
437-
command: "/usr/local/bin/check-should-run.sh",
437+
file: "/usr/local/bin/check-should-run.sh",
438+
args: ["--quiet"],
438439
timeoutSeconds: 30,
439440
},
440441
},
@@ -449,7 +450,7 @@ An optional `preHook` runs a shell command before each heartbeat turn. The hook
449450
| 10 | Skip (not a failure) |
450451
| Any other | Fail (logged as heartbeat error) |
451452

452-
Default timeout is 30 seconds (max 300). stdout and stderr are captured in logs.
453+
Default timeout is 30 seconds (max 300). stdout and stderr are captured, truncated and redacted before being written to logs — keep secrets out of hook output. If you need shell features (pipes, globs, redirection), wrap them in a script file and set `file` to that script.
453454

454455
## Reasoning delivery (optional)
455456

‎src/agents/tools/cron-tool.schema.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ describe("CronToolSchema", () => {
135135
});
136136

137137
it("patch.preHook uses plain object type for OpenAPI 3.0 compat", () => {
138-
const root = (CronToolSchema as Record<string, unknown>).properties as
138+
const root = (CronToolSchema as unknown as Record<string, unknown>).properties as
139139
| Record<string, { properties?: Record<string, unknown> }>
140140
| undefined;
141141
const patchProps = root?.patch?.properties as

‎src/agents/tools/cron-tool.ts‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -206,10 +206,16 @@ const CronJobObjectSchema = Type.Optional(
206206
preHook: Type.Optional(
207207
Type.Object(
208208
{
209-
command: Type.String({
209+
file: Type.String({
210210
description:
211-
"Shell command to run before execution. Exit 0 = proceed, 10 = skip, other = error.",
211+
"Absolute path of the executable to run before execution. No shell interpretation. Exit 0 = proceed, 10 = skip, other = error.",
212212
}),
213+
args: Type.Optional(
214+
Type.Array(Type.String(), {
215+
description:
216+
"Literal string arguments passed to the executable. Not parsed by a shell.",
217+
}),
218+
),
213219
timeoutSeconds: Type.Optional(
214220
Type.Number({ description: "Timeout in seconds (default 30, max 300)" }),
215221
),
@@ -223,13 +229,18 @@ const CronJobObjectSchema = Type.Optional(
223229
);
224230

225231
const CronPatchPreHookSchema = Type.Optional(
226-
Type.Unsafe<{ command: string; timeoutSeconds?: number } | false>({
232+
Type.Unsafe<{ file: string; args?: string[]; timeoutSeconds?: number } | false>({
227233
type: "object",
228234
properties: {
229-
command: Type.String({
235+
file: Type.String({
230236
description:
231-
"Shell command to run before execution. Exit 0 = proceed, 10 = skip, other = error.",
237+
"Absolute path of the executable to run before execution. No shell interpretation. Exit 0 = proceed, 10 = skip, other = error.",
232238
}),
239+
args: Type.Optional(
240+
Type.Array(Type.String(), {
241+
description: "Literal string arguments passed to the executable. Not parsed by a shell.",
242+
}),
243+
),
233244
timeoutSeconds: Type.Optional(
234245
Type.Number({ description: "Timeout in seconds (default 30, max 300)" }),
235246
),

‎src/config/schema.base.generated.ts‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5136,17 +5136,23 @@ export const GENERATED_BASE_CONFIG_SCHEMA: BaseConfigSchemaResponse = {
51365136
preHook: {
51375137
type: "object",
51385138
properties: {
5139-
command: {
5139+
file: {
51405140
type: "string",
51415141
minLength: 1,
51425142
},
5143+
args: {
5144+
type: "array",
5145+
items: {
5146+
type: "string",
5147+
},
5148+
},
51435149
timeoutSeconds: {
51445150
type: "integer",
51455151
minimum: 1,
51465152
maximum: 300,
51475153
},
51485154
},
5149-
required: ["command"],
5155+
required: ["file"],
51505156
additionalProperties: false,
51515157
},
51525158
},
@@ -6476,17 +6482,23 @@ export const GENERATED_BASE_CONFIG_SCHEMA: BaseConfigSchemaResponse = {
64766482
preHook: {
64776483
type: "object",
64786484
properties: {
6479-
command: {
6485+
file: {
64806486
type: "string",
64816487
minLength: 1,
64826488
},
6489+
args: {
6490+
type: "array",
6491+
items: {
6492+
type: "string",
6493+
},
6494+
},
64836495
timeoutSeconds: {
64846496
type: "integer",
64856497
minimum: 1,
64866498
maximum: 300,
64876499
},
64886500
},
6489-
required: ["command"],
6501+
required: ["file"],
64906502
additionalProperties: false,
64916503
},
64926504
},

‎src/config/types.agent-defaults.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -383,7 +383,7 @@ export type AgentDefaultsConfig = {
383383
*/
384384
includeReasoning?: boolean;
385385
/** Optional pre-run script gate. Exit 0 = proceed, exit 10 = skip, other = error. */
386-
preHook?: { command: string; timeoutSeconds?: number };
386+
preHook?: { file: string; args?: string[]; timeoutSeconds?: number };
387387
};
388388
/** Max concurrent agent runs across all conversations. Default: 1 (sequential). */
389389
maxConcurrent?: number;

‎src/config/zod-schema.agent-runtime.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,8 @@ export const HeartbeatSchema = z
4343
isolatedSession: z.boolean().optional(),
4444
preHook: z
4545
.object({
46-
command: z.string().trim().min(1),
46+
file: z.string().trim().min(1),
47+
args: z.array(z.string()).optional(),
4748
timeoutSeconds: z.number().int().min(1).max(300).optional(),
4849
})
4950
.strict()

‎src/cron/normalize.test.ts‎

Lines changed: 39 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -888,49 +888,69 @@ describe("preHook normalization", () => {
888888
return normalizeCronJobPatch({ preHook }) as Record<string, unknown> | null;
889889
}
890890

891-
it("passes through valid preHook with command", () => {
892-
const result = createWithPreHook({ command: "check-disk.sh" });
893-
expect(result?.preHook).toEqual({ command: "check-disk.sh" });
891+
it("passes through valid preHook with file", () => {
892+
const result = createWithPreHook({ file: "/usr/local/bin/check-disk.sh" });
893+
expect(result?.preHook).toEqual({ file: "/usr/local/bin/check-disk.sh" });
894894
});
895895

896-
it("trims command whitespace", () => {
897-
const result = createWithPreHook({ command: " ping host " });
898-
expect((result?.preHook as { command: string }).command).toBe("ping host");
896+
it("includes args array when valid", () => {
897+
const result = createWithPreHook({ file: "/bin/ping", args: ["-c1", "api.example.com"] });
898+
expect(result?.preHook).toEqual({
899+
file: "/bin/ping",
900+
args: ["-c1", "api.example.com"],
901+
});
902+
});
903+
904+
it("trims file whitespace", () => {
905+
const result = createWithPreHook({ file: " /usr/bin/true " });
906+
expect((result?.preHook as { file: string }).file).toBe("/usr/bin/true");
899907
});
900908

901909
it("includes timeoutSeconds when valid", () => {
902-
const result = createWithPreHook({ command: "check", timeoutSeconds: 60 });
903-
expect(result?.preHook).toEqual({ command: "check", timeoutSeconds: 60 });
910+
const result = createWithPreHook({ file: "/bin/true", timeoutSeconds: 60 });
911+
expect(result?.preHook).toEqual({ file: "/bin/true", timeoutSeconds: 60 });
904912
});
905913

906914
it("clamps timeoutSeconds to 1-300 range", () => {
907-
const high = createWithPreHook({ command: "check", timeoutSeconds: 999 });
915+
const high = createWithPreHook({ file: "/bin/true", timeoutSeconds: 999 });
908916
expect((high?.preHook as { timeoutSeconds: number }).timeoutSeconds).toBe(300);
909917

910-
const low = createWithPreHook({ command: "check", timeoutSeconds: 0.5 });
918+
const low = createWithPreHook({ file: "/bin/true", timeoutSeconds: 0.5 });
911919
expect((low?.preHook as { timeoutSeconds: number }).timeoutSeconds).toBe(1);
912920
});
913921

914-
it("strips preHook when command is empty string (create)", () => {
915-
const result = createWithPreHook({ command: " " });
922+
it("strips preHook when file is empty string (create)", () => {
923+
const result = createWithPreHook({ file: " " });
916924
expect(result?.preHook).toBeUndefined();
917925
});
918926

919-
it("drops preHook with empty command in patch instead of clearing", () => {
920-
const result = patchWithPreHook({ command: " " });
927+
it("drops preHook with empty file in patch instead of clearing", () => {
928+
const result = patchWithPreHook({ file: " " });
921929
expect(result).not.toHaveProperty("preHook");
922930
});
923931

924-
it("strips preHook when command is not a string", () => {
925-
const result = createWithPreHook({ command: 123 });
932+
it("strips preHook when file is not a string", () => {
933+
const result = createWithPreHook({ file: 123 });
934+
expect(result?.preHook).toBeUndefined();
935+
});
936+
937+
it("rejects legacy `command` shell-string payload", () => {
938+
// Legacy {command: string} must be rejected — using a shell command string
939+
// is a shell-injection vector (CWE-78) and is no longer supported.
940+
const result = createWithPreHook({ command: "ping host" });
926941
expect(result?.preHook).toBeUndefined();
927942
});
928943

929944
it("rejects bare string preHook", () => {
930-
const result = createWithPreHook("ping host");
945+
const result = createWithPreHook("/bin/true");
931946
expect(result?.preHook).toBeUndefined();
932947
});
933948

949+
it("drops non-string args entries", () => {
950+
const result = createWithPreHook({ file: "/bin/echo", args: ["ok", 42] });
951+
expect(result?.preHook).toEqual({ file: "/bin/echo" });
952+
});
953+
934954
it("allows null preHook in patch to clear", () => {
935955
const result = patchWithPreHook(null);
936956
expect(result?.preHook).toBeNull();
@@ -942,7 +962,7 @@ describe("preHook normalization", () => {
942962
});
943963

944964
it("drops non-numeric timeoutSeconds", () => {
945-
const result = createWithPreHook({ command: "check", timeoutSeconds: "fast" });
946-
expect(result?.preHook).toEqual({ command: "check" });
965+
const result = createWithPreHook({ file: "/bin/true", timeoutSeconds: "fast" });
966+
expect(result?.preHook).toEqual({ file: "/bin/true" });
947967
});
948968
});

‎src/cron/normalize.ts‎

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -496,27 +496,31 @@ export function normalizeCronJobInput(
496496
delete next.isolation;
497497
}
498498

499-
// Normalize preHook: valid object with non-empty command passes through;
500-
// null clears (patch); primitives and malformed objects are rejected.
499+
// Normalize preHook: valid object with non-empty file path passes through;
500+
// null clears (patch); primitives, malformed objects, and shell strings are rejected.
501501
if ("preHook" in base) {
502502
if (isRecord(base.preHook)) {
503-
const rawCmd = base.preHook.command;
504-
if (typeof rawCmd === "string") {
505-
const command = rawCmd.trim();
506-
if (command) {
507-
const hook: { command: string; timeoutSeconds?: number } = { command };
503+
const rawFile = base.preHook.file;
504+
if (typeof rawFile === "string") {
505+
const file = rawFile.trim();
506+
if (file) {
507+
const hook: { file: string; args?: string[]; timeoutSeconds?: number } = { file };
508+
const rawArgs = base.preHook.args;
509+
if (Array.isArray(rawArgs) && rawArgs.every((a) => typeof a === "string")) {
510+
hook.args = [...rawArgs];
511+
}
508512
const rawTimeout = base.preHook.timeoutSeconds;
509513
if (typeof rawTimeout === "number" && Number.isFinite(rawTimeout) && rawTimeout > 0) {
510514
hook.timeoutSeconds = Math.min(300, Math.max(1, Math.floor(rawTimeout)));
511515
}
512516
next.preHook = hook;
513517
} else {
514-
// Empty command string is malformed — reject silently.
518+
// Empty file string is malformed — reject silently.
515519
// Clearing requires explicit null/false in a patch.
516520
delete next.preHook;
517521
}
518522
} else {
519-
// Object without valid command string — reject
523+
// Object without valid file string — reject (also rejects legacy `command`).
520524
delete next.preHook;
521525
}
522526
} else if (!options.applyDefaults && (base.preHook === null || base.preHook === false)) {

0 commit comments

Comments
 (0)