Skip to content

Commit 3a17d59

Browse files
authored
fix: prevent $-pattern injection in prompt template and approval substitution (#123015)
* fix: prevent dollar-pattern injection in prompt template and approval substitution Three call sites used String.replace/replaceAll with a string replacement fed a runtime variable, causing dollar-amp/dollar-1/dollar-backtick sequences in user-supplied args or approval ids to corrupt the rendered text. Switch each to a function replacement so the value is treated literally: - prompt-template-arguments: dollar-ARGUMENTS and dollar-@ substitution corrupted slash-command args containing dollar signs - get-reply-inline-actions: bundle command template expansion had the same issue with normalizedArgs - approval-reaction-runtime: approval id placeholder rendering mangled ids containing dollar signs; the iMessage sibling (extensions/imessage/src/approval-text.ts) already escapes this * fix: rebase, drop unproven approval rewrite, add dollar regression Address review: the approval placeholder helper has no canonical /approve <id> producer in the plugin-SDK manual fallback path, so its rewrite is unproven - revert it. Keep the two reachable prompt-template fixes and add an owner-boundary regression covering literal dollar sequences in dollar-ARGUMENTS and dollar-@ substitution (fails on the old string replacement form, passes with the callback form). * test(auto-reply): cover literal dollar bundle command arguments * fix(agent-core): resolve prompt placeholders in a single substitution pass
1 parent bea8740 commit 3a17d59

4 files changed

Lines changed: 75 additions & 30 deletions

File tree

‎packages/agent-core/src/harness/prompt-template-arguments.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,15 @@ describe("prompt template arguments", () => {
88
expect(parseCommandArgs("first '' third")).toEqual(["first", "", "third"]);
99
expect(substituteArgs("$1|$2|$3", parseCommandArgs('first "" third'))).toBe("first||third");
1010
});
11+
12+
it("preserves literal dollar sequences in $ARGUMENTS and $@ substitution", () => {
13+
const args = parseCommandArgs("price $$ and $& here");
14+
expect(substituteArgs("Args: $ARGUMENTS", args)).toBe("Args: price $$ and $& here");
15+
expect(substituteArgs("Args: $@", args)).toBe("Args: price $$ and $& here");
16+
});
17+
18+
it("resolves every placeholder in one pass so inserted arguments are never re-expanded", () => {
19+
expect(substituteArgs("$1 $@", ["$ARGUMENTS", "safe"])).toBe("$ARGUMENTS $ARGUMENTS safe");
20+
expect(substituteArgs("$1 ${@:2:1}", ["$@", "$ARGUMENTS", "safe"])).toBe("$@ $ARGUMENTS");
21+
});
1122
});

‎packages/agent-core/src/harness/prompt-template-arguments.ts‎

Lines changed: 30 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -48,39 +48,40 @@ export function parseCommandArgs(argsString: string): string[] {
4848
* loading or invocation.
4949
*/
5050
export function substituteArgs(content: string, args: string[]): string {
51-
let result = content;
52-
result = result.replace(/\$(\d+)/g, (_, num: string) => {
53-
const parsed = parseStrictNonNegativeInteger(num);
54-
if (parsed === undefined || parsed <= 0) {
55-
return "";
56-
}
57-
return args[parsed - 1] ?? "";
58-
});
59-
result = result.replace(
60-
/\$\{@:(\d+)(?::(\d+))?\}/g,
61-
(_, startStr: string, lengthStr?: string) => {
62-
const parsedStart = parseStrictNonNegativeInteger(startStr);
63-
if (parsedStart === undefined) {
64-
return "";
65-
}
66-
// Keep shell-style `${@:0:...}` compatibility: start 0 includes `$0` in shell, but
67-
// prompt templates have no command name, so it maps to the first provided argument.
68-
let start = parsedStart - 1;
69-
if (start < 0) {
70-
start = 0;
51+
const allArgs = args.join(" ");
52+
// Single-pass substitution: an argument inserted for one placeholder must never
53+
// be re-interpreted by a later placeholder pass (e.g. `$1` inserting `$ARGUMENTS`).
54+
return content.replace(
55+
/\$(\d+)|\$\{@:(\d+)(?::(\d+))?\}|\$ARGUMENTS|\$@/g,
56+
(_match, num: string | undefined, startStr: string | undefined, lengthStr?: string) => {
57+
if (num !== undefined) {
58+
const parsed = parseStrictNonNegativeInteger(num);
59+
if (parsed === undefined || parsed <= 0) {
60+
return "";
61+
}
62+
return args[parsed - 1] ?? "";
7163
}
72-
if (lengthStr) {
73-
const length = parseStrictNonNegativeInteger(lengthStr);
74-
if (length === undefined) {
64+
if (startStr !== undefined) {
65+
const parsedStart = parseStrictNonNegativeInteger(startStr);
66+
if (parsedStart === undefined) {
7567
return "";
7668
}
77-
return args.slice(start, start + length).join(" ");
69+
// Keep shell-style `${@:0:...}` compatibility: start 0 includes `$0` in shell, but
70+
// prompt templates have no command name, so it maps to the first provided argument.
71+
let start = parsedStart - 1;
72+
if (start < 0) {
73+
start = 0;
74+
}
75+
if (lengthStr) {
76+
const length = parseStrictNonNegativeInteger(lengthStr);
77+
if (length === undefined) {
78+
return "";
79+
}
80+
return args.slice(start, start + length).join(" ");
81+
}
82+
return args.slice(start).join(" ");
7883
}
79-
return args.slice(start).join(" ");
84+
return allArgs;
8085
},
8186
);
82-
const allArgs = args.join(" ");
83-
result = result.replace(/\$ARGUMENTS/g, allArgs);
84-
result = result.replace(/\$@/g, allArgs);
85-
return result;
8687
}

‎src/auto-reply/reply/get-reply-inline-actions.skip-when-config-empty.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -762,6 +762,39 @@ describe("handleInlineActions", () => {
762762
);
763763
});
764764

765+
it("keeps literal $ patterns in bundle command arguments", async () => {
766+
const typing = createTypingController();
767+
handleCommandsMock.mockResolvedValue({ shouldContinue: false, reply: { text: "done" } });
768+
const ctx = buildTestCtx({
769+
Body: "/office_hours price $$ and $& here",
770+
CommandBody: "/office_hours price $$ and $& here",
771+
});
772+
const skillCommands = officeHoursSkillCommands();
773+
774+
const result = await runTestInlineActions({
775+
ctx,
776+
typing,
777+
cleanedBody: "/office_hours price $$ and $& here",
778+
command: {
779+
isAuthorizedSender: true,
780+
rawBodyNormalized: "/office_hours price $$ and $& here",
781+
commandBodyNormalized: "/office_hours price $$ and $& here",
782+
},
783+
overrides: {
784+
allowTextCommands: true,
785+
cfg: { commands: { text: true } },
786+
skillCommands,
787+
},
788+
});
789+
790+
expect(result).toEqual({ kind: "reply", reply: { text: "done" } });
791+
expect(ctx.Body).toBe("Act as an engineering advisor.\n\nFocus on:\nprice $$ and $& here");
792+
const commandArgs = mockObjectArg(handleCommandsMock, "handleCommands");
793+
expect(requireRecord(commandArgs.ctx, "handleCommands ctx").Body).toBe(
794+
"Act as an engineering advisor.\n\nFocus on:\nprice $$ and $& here",
795+
);
796+
});
797+
765798
it("loads workspace skills when /skill gets an empty preloaded command list", async () => {
766799
const typing = createTypingController();
767800
handleCommandsMock.mockResolvedValue({ shouldContinue: false, reply: { text: "done" } });

‎src/skills/discovery/chat-command-invocation.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ export function resolveSkillCommandInvocation(params: {
162162
export function expandBundleCommandPromptTemplate(template: string, args?: string): string {
163163
const normalizedArgs = args?.trim() ?? "";
164164
const rendered = template.includes("$ARGUMENTS")
165-
? template.replaceAll("$ARGUMENTS", normalizedArgs)
165+
? template.replaceAll("$ARGUMENTS", () => normalizedArgs)
166166
: template;
167167
if (!normalizedArgs || template.includes("$ARGUMENTS")) {
168168
return rendered.trim();

0 commit comments

Comments
 (0)