Skip to content

Commit 39bcf69

Browse files
committed
fix(cron): reject unsafe custom session targets earlier
1 parent 00337cd commit 39bcf69

9 files changed

Lines changed: 183 additions & 15 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,7 @@ Docs: https://docs.openclaw.ai
188188
- Browser/profiles: reject remote browser profile `cdpUrl` values that violate strict SSRF policy before saving config, with clearer validation errors for blocked endpoints. (#60477) Thanks @eleqtrizit.
189189
- Browser/screenshots: stop sending `fromSurface: false` on CDP screenshots so managed Chrome 146+ browsers can capture images again. (#60682) Thanks @mvanhorn.
190190
- Mattermost/slash commands: harden native slash-command callback token validation to use constant-time secret comparison, matching the existing interaction-token path.
191+
- Cron/security: reject unsafe custom `sessionTarget: "session:..."` IDs earlier during cron add, update, and execution so malformed custom session keys fail closed with clear errors.
191192

192193
## 2026.4.1
193194

‎src/cron/normalize.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -593,6 +593,23 @@ describe("normalizeCronJobCreate", () => {
593593

594594
expect(normalized.sessionTarget).toBe("session:MySessionID");
595595
});
596+
597+
it("rejects custom session ids with path separators", () => {
598+
expect(() =>
599+
normalizeCronJobCreate({
600+
name: "bad-custom-session",
601+
schedule: { kind: "cron", expr: "* * * * *" },
602+
sessionTarget: "session:../../outside",
603+
payload: { kind: "agentTurn", message: "hello" },
604+
}),
605+
).toThrow("invalid cron sessionTarget session id");
606+
607+
expect(() =>
608+
normalizeCronJobPatch({
609+
sessionTarget: "session:..\\outside",
610+
}),
611+
).toThrow("invalid cron sessionTarget session id");
612+
});
596613
});
597614

598615
describe("normalizeCronJobPatch", () => {

‎src/cron/normalize.ts‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
} from "./delivery-field-schemas.js";
99
import { parseAbsoluteTimeMs } from "./parse.js";
1010
import { inferLegacyName } from "./service/normalize.js";
11+
import { assertSafeCronSessionTargetId } from "./session-target.js";
1112
import { normalizeCronStaggerMs, resolveDefaultCronStaggerMs } from "./stagger.js";
1213
import type { CronJobCreate, CronJobPatch } from "./types.js";
1314

@@ -321,10 +322,7 @@ function normalizeSessionTarget(raw: unknown) {
321322
}
322323
// Support custom session IDs with "session:" prefix
323324
if (lower.startsWith("session:")) {
324-
const sessionId = trimmed.slice(8).trim();
325-
if (sessionId) {
326-
return `session:${sessionId}`;
327-
}
325+
return `session:${assertSafeCronSessionTargetId(trimmed.slice(8))}`;
328326
}
329327
return undefined;
330328
}
@@ -539,7 +537,7 @@ export function normalizeCronJobInput(
539537
const sessionKey = options.sessionContext.sessionKey.trim();
540538
if (sessionKey) {
541539
// Store as session:customId format for persistence
542-
next.sessionTarget = `session:${sessionKey}`;
540+
next.sessionTarget = `session:${assertSafeCronSessionTargetId(sessionKey)}`;
543541
}
544542
}
545543
// If "current" wasn't resolved, fall back to "isolated" behavior
@@ -551,7 +549,7 @@ export function normalizeCronJobInput(
551549
if (next.sessionTarget === "current") {
552550
const sessionKey = options.sessionContext?.sessionKey?.trim();
553551
if (sessionKey) {
554-
next.sessionTarget = `session:${sessionKey}`;
552+
next.sessionTarget = `session:${assertSafeCronSessionTargetId(sessionKey)}`;
555553
} else {
556554
next.sessionTarget = "isolated";
557555
}

‎src/cron/service.jobs.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -475,6 +475,20 @@ describe("createJob rejects sessionTarget main for non-default agents", () => {
475475
).not.toThrow();
476476
});
477477

478+
it("rejects custom session targets with path separators", () => {
479+
const state = createMockState(now, { defaultAgentId: "main" });
480+
expect(() =>
481+
createJob(state, {
482+
name: "bad-custom-session",
483+
enabled: true,
484+
schedule: { kind: "every", everyMs: 60_000 },
485+
sessionTarget: "session:../../outside",
486+
wakeMode: "now",
487+
payload: { kind: "agentTurn", message: "hello" },
488+
}),
489+
).toThrow("invalid cron sessionTarget session id");
490+
});
491+
478492
it("rejects failureDestination on main jobs without webhook delivery mode", () => {
479493
const state = createMockState(now, { defaultAgentId: "main" });
480494
expect(() =>
@@ -526,6 +540,20 @@ describe("applyJobPatch rejects sessionTarget main for non-default agents", () =
526540
}
527541
expect(() => applyJobPatch(job, patch, { defaultAgentId: "main" })).not.toThrow();
528542
});
543+
544+
it("rejects patching to a custom session target with path separators", () => {
545+
const job = createMainJob();
546+
expect(() =>
547+
applyJobPatch(
548+
job,
549+
{
550+
sessionTarget: "session:..\\outside",
551+
payload: { kind: "agentTurn", message: "hello" },
552+
},
553+
{ defaultAgentId: "main" },
554+
),
555+
).toThrow("invalid cron sessionTarget session id");
556+
});
529557
});
530558

531559
describe("cron stagger defaults", () => {

‎src/cron/service/jobs.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
computeNextRunAtMs,
77
computePreviousRunAtMs,
88
} from "../schedule.js";
9+
import { assertSafeCronSessionTargetId } from "../session-target.js";
910
import {
1011
normalizeCronStaggerMs,
1112
resolveCronStaggerMs,
@@ -136,6 +137,9 @@ export function assertSupportedJobSpec(job: Pick<CronJob, "sessionTarget" | "pay
136137
job.sessionTarget === "isolated" ||
137138
job.sessionTarget === "current" ||
138139
job.sessionTarget.startsWith("session:");
140+
if (job.sessionTarget.startsWith("session:")) {
141+
assertSafeCronSessionTargetId(job.sessionTarget.slice(8));
142+
}
139143
if (job.sessionTarget === "main" && job.payload.kind !== "systemEvent") {
140144
throw new Error('main cron jobs require payload.kind="systemEvent"');
141145
}

‎src/cron/session-target.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
const INVALID_CRON_SESSION_TARGET_ID_ERROR = "invalid cron sessionTarget session id";
2+
3+
export function assertSafeCronSessionTargetId(sessionId: string): string {
4+
const trimmed = sessionId.trim();
5+
if (!trimmed) {
6+
throw new Error(INVALID_CRON_SESSION_TARGET_ID_ERROR);
7+
}
8+
if (trimmed.includes("/") || trimmed.includes("\\") || trimmed.includes("\0")) {
9+
throw new Error(INVALID_CRON_SESSION_TARGET_ID_ERROR);
10+
}
11+
return trimmed;
12+
}

‎src/gateway/server-cron.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
resolveCronRunLogPruneOptions,
1919
} from "../cron/run-log.js";
2020
import { CronService } from "../cron/service.js";
21+
import { assertSafeCronSessionTargetId } from "../cron/session-target.js";
2122
import { resolveCronStorePath } from "../cron/store.js";
2223
import { normalizeHttpWebhookUrl } from "../cron/webhook-url.js";
2324
import { formatErrorMessage } from "../infra/errors.js";
@@ -287,10 +288,7 @@ export function buildGatewayCronService(params: {
287288
const { agentId, cfg: runtimeConfig } = resolveCronAgent(job.agentId);
288289
let sessionKey = `cron:${job.id}`;
289290
if (job.sessionTarget.startsWith("session:")) {
290-
const customSessionId = job.sessionTarget.slice(8).trim();
291-
if (customSessionId) {
292-
sessionKey = customSessionId;
293-
}
291+
sessionKey = assertSafeCronSessionTargetId(job.sessionTarget.slice(8));
294292
}
295293
try {
296294
return await runCronIsolatedAgentTurn({

‎src/gateway/server-methods/cron.ts‎

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -93,10 +93,23 @@ export const cronHandlers: GatewayRequestHandlers = {
9393
typeof (params as { sessionKey?: unknown } | null)?.sessionKey === "string"
9494
? (params as { sessionKey: string }).sessionKey
9595
: undefined;
96-
const normalized =
97-
normalizeCronJobCreate(params, {
98-
sessionContext: { sessionKey },
99-
}) ?? params;
96+
let normalized: unknown;
97+
try {
98+
normalized =
99+
normalizeCronJobCreate(params, {
100+
sessionContext: { sessionKey },
101+
}) ?? params;
102+
} catch (err) {
103+
respond(
104+
false,
105+
undefined,
106+
errorShape(
107+
ErrorCodes.INVALID_REQUEST,
108+
`invalid cron.add params: ${err instanceof Error ? err.message : String(err)}`,
109+
),
110+
);
111+
return;
112+
}
100113
if (!validateCronAddParams(normalized)) {
101114
respond(
102115
false,
@@ -123,7 +136,20 @@ export const cronHandlers: GatewayRequestHandlers = {
123136
respond(true, job, undefined);
124137
},
125138
"cron.update": async ({ params, respond, context }) => {
126-
const normalizedPatch = normalizeCronJobPatch((params as { patch?: unknown } | null)?.patch);
139+
let normalizedPatch: ReturnType<typeof normalizeCronJobPatch>;
140+
try {
141+
normalizedPatch = normalizeCronJobPatch((params as { patch?: unknown } | null)?.patch);
142+
} catch (err) {
143+
respond(
144+
false,
145+
undefined,
146+
errorShape(
147+
ErrorCodes.INVALID_REQUEST,
148+
`invalid cron.update params: ${err instanceof Error ? err.message : String(err)}`,
149+
),
150+
);
151+
return;
152+
}
127153
const candidate =
128154
normalizedPatch && typeof params === "object" && params !== null
129155
? { ...params, patch: normalizedPatch }

‎src/gateway/server.cron.test.ts‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -462,6 +462,52 @@ describe("gateway server cron", () => {
462462
}
463463
});
464464

465+
test("rejects unsafe custom session ids on add and update", async () => {
466+
const { prevSkipCron } = await setupCronTestRun({
467+
tempPrefix: "openclaw-gw-cron-bad-session-target-",
468+
cronEnabled: false,
469+
});
470+
471+
const { server, ws } = await startServerWithClient();
472+
await connectOk(ws);
473+
474+
try {
475+
const addRes = await rpcReq(ws, "cron.add", {
476+
name: "bad custom session",
477+
enabled: true,
478+
schedule: { kind: "every", everyMs: 60_000 },
479+
sessionTarget: "session:../../outside",
480+
wakeMode: "now",
481+
payload: { kind: "agentTurn", message: "hello" },
482+
});
483+
expect(addRes.ok).toBe(false);
484+
expect(addRes.error?.message).toContain("invalid cron sessionTarget session id");
485+
486+
const validRes = await rpcReq(ws, "cron.add", {
487+
name: "good custom session",
488+
enabled: true,
489+
schedule: { kind: "every", everyMs: 60_000 },
490+
sessionTarget: "session:project-alpha:ops",
491+
wakeMode: "now",
492+
payload: { kind: "agentTurn", message: "hello" },
493+
});
494+
expect(validRes.ok).toBe(true);
495+
const jobId = (validRes.payload as { id?: unknown } | null)?.id;
496+
expect(typeof jobId).toBe("string");
497+
498+
const updateRes = await rpcReq(ws, "cron.update", {
499+
id: jobId,
500+
patch: {
501+
sessionTarget: "session:..\\outside",
502+
},
503+
});
504+
expect(updateRes.ok).toBe(false);
505+
expect(updateRes.error?.message).toContain("invalid cron sessionTarget session id");
506+
} finally {
507+
await cleanupCronTestRun({ ws, server, prevSkipCron });
508+
}
509+
});
510+
465511
test("writes cron run history and auto-runs due jobs", async () => {
466512
const { prevSkipCron } = await setupCronTestRun({
467513
tempPrefix: "openclaw-gw-cron-log-",
@@ -559,6 +605,44 @@ describe("gateway server cron", () => {
559605
}
560606
}, 45_000);
561607

608+
test("fails closed for persisted unsafe custom session ids", async () => {
609+
const now = Date.now();
610+
const { prevSkipCron } = await setupCronTestRun({
611+
tempPrefix: "openclaw-gw-cron-persisted-bad-session-target-",
612+
cronEnabled: false,
613+
jobs: [
614+
{
615+
id: "bad-custom-session-job",
616+
name: "bad custom session job",
617+
enabled: true,
618+
createdAtMs: now,
619+
updatedAtMs: now,
620+
schedule: { kind: "every", everyMs: 60_000 },
621+
sessionTarget: "session:../../outside",
622+
wakeMode: "now",
623+
payload: { kind: "agentTurn", message: "hello" },
624+
state: {},
625+
},
626+
],
627+
});
628+
629+
cronIsolatedRun.mockClear();
630+
const { server, ws } = await startServerWithClient();
631+
await connectOk(ws);
632+
633+
try {
634+
const runRes = await rpcReq(ws, "cron.run", {
635+
id: "bad-custom-session-job",
636+
mode: "force",
637+
});
638+
expect(runRes.ok).toBe(false);
639+
expect(runRes.error?.message).toContain("invalid cron sessionTarget session id");
640+
expect(cronIsolatedRun).not.toHaveBeenCalled();
641+
} finally {
642+
await cleanupCronTestRun({ ws, server, prevSkipCron });
643+
}
644+
});
645+
562646
test("returns from cron.run immediately while isolated work continues in background", async () => {
563647
const { prevSkipCron } = await setupCronTestRun({
564648
tempPrefix: "openclaw-gw-cron-run-detached-",

0 commit comments

Comments
 (0)