Skip to content

Commit eb9df27

Browse files
authored
fix(server): check commands named through a variable the line sets (#5973)
OpenCode v2 asks about each command of a shell line on its own and drops bare assignments, so `x=printf; $x ...` reached the agent permissions plugin as `$x ...` and was only asked about, even where `printf *` is blocked. The plugin now keeps each shell call's whole line by call id, and the parser checks a variable-named program with every literal value the line gives it (`x=rm`, `export x=rm`, `x=rm $x`, `for x in rm`, `${x:-rm}`). Programs named through variables the line doesn't set, substitutions or patterns are still asked about. Signed-off-by: Jalil <reachjalil@gmail.com>
1 parent 500d73e commit eb9df27

4 files changed

Lines changed: 117 additions & 10 deletions

File tree

‎apps/server/src/agent-permission-engine.ts‎

Lines changed: 73 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -117,17 +117,22 @@ export function agentPermissionEngineV2Rules(rules: readonly AgentPermissionRule
117117
/**
118118
* The decision a v2 permission evaluation ends with: the engine's, made at
119119
* least as strict as the organization's, with the rule that blocks a call
120-
* named in its message.
120+
* named in its message. The engine asks about each command of a line on its
121+
* own and leaves out bare assignments, so `commandLine`, the whole line of the
122+
* shell call when known, supplies the values that may name a command's
123+
* program (`x=rm; $x -rf dir`). It is used only when it holds every resource.
121124
*/
122125
export function agentPermissionEngineV2Decision(
123126
rules: readonly AgentPermissionRule[],
124127
action: string,
125128
resources: readonly string[],
126129
engineEffect: "allow" | "ask" | "deny",
130+
commandLine?: string,
127131
): { effect: "allow" | "ask" | "deny"; message?: string } {
128132
const ourAction = v2Action(action);
129133
if (!ourAction) return { effect: engineEffect };
130-
const parsed = ourAction === "shell" ? resources.map(parseShellCommands) : [];
134+
const assigned = commandLine !== undefined && resources.every((resource) => commandLine.includes(resource)) ? assignedValues(commandLine) : undefined;
135+
const parsed = ourAction === "shell" ? resources.map((resource) => parseShellCommands(resource, assigned)) : [];
131136
const commands = ourAction === "shell" ? parsed.flatMap((entry) => entry.commands) : resources;
132137
const ours = decideAgentPermission(rules, ourAction, commands);
133138
if (ours.effect === "deny" && ours.rule) return { effect: "deny", message: agentPermissionDenialMessage(ours.rule, ours.resource) };
@@ -286,6 +291,60 @@ function namesProgramDynamically(command: string): boolean {
286291
return program !== "[" && program !== "[[" && /[$`*?[{]/.test(program);
287292
}
288293

294+
/** `NAME=value` where the value is literal text, possibly quoted, not something the shell computes. */
295+
const LITERAL_ASSIGNMENT = /(?<![^\s;&|(){}`'"])([A-Za-z_][A-Za-z0-9_]*)=((?:[^\s;&|()<>'"`$\\]|'[^']*'|"[^"$`\\]*")+)(?![^\s;&|()<>'"`])/g;
296+
297+
/** `for NAME in words`, up to the end of the line or the next `;`. */
298+
const FOR_LOOP = /\bfor\s+([A-Za-z_][A-Za-z0-9_]*)\s+in\s+([^;\n]*)/g;
299+
300+
/** The literal values a command line gives each of its variables (see assignedValues). */
301+
export type AssignedValues = ReadonlyMap<string, ReadonlySet<string>>;
302+
303+
/**
304+
* The literal values a command line gives each variable anywhere in it,
305+
* including in scripts it hands to other shells: `x=rm`, `export x='rm'`,
306+
* `x=rm $x` and `for x in ls rm`. A value the shell computes (`x=$(…)`) is left out.
307+
*/
308+
function assignedValues(text: string): AssignedValues {
309+
const values = new Map<string, Set<string>>();
310+
const assign = (name: string, value: string) => {
311+
if (!value || /[$`]/.test(value)) return;
312+
const known = values.get(name) ?? new Set<string>();
313+
values.set(name, known.add(value));
314+
};
315+
const scanned = text.slice(0, SHELL_PARSE_BUDGET);
316+
for (const [, name, value] of scanned.matchAll(LITERAL_ASSIGNMENT)) assign(name!, shellWords(value!).join(" "));
317+
for (const [, name, list] of scanned.matchAll(FOR_LOOP)) {
318+
const words = shellWords(list!);
319+
const end = words.indexOf("do");
320+
for (const word of end === -1 ? words : words.slice(0, end)) assign(name!, word);
321+
}
322+
return values;
323+
}
324+
325+
/** `$x` and `${x}`, and `${x:-word}`, `${x:=word}` and `${x:+word}`, whose word may be what they expand to. */
326+
const VARIABLE_REFERENCE = /\$(?:\{([A-Za-z_][A-Za-z0-9_]*)(?::?[-=+]([^}]*))?\}|([A-Za-z_][A-Za-z0-9_]*))/g;
327+
328+
/** Most commands one variable-named program resolves to; further combinations of values are not tried. */
329+
const RESOLVED_COMMANDS_LIMIT = 32;
330+
331+
/**
332+
* The command with each variable in its program name replaced by every value
333+
* the line gives it, or the word a `${x:-word}` names: after `x=rm`, `$x -rf dir`
334+
* may run `rm -rf dir`. Variables nothing on the line sets stay as they are.
335+
*/
336+
function resolvedCommands(command: string, values: AssignedValues): string[] {
337+
const program = /^\S*/.exec(command)?.[0] ?? "";
338+
let resolved = [command];
339+
for (const [reference, braced, word, plain] of program.matchAll(VARIABLE_REFERENCE)) {
340+
const options = new Set(values.get((braced ?? plain)!));
341+
if (word && !/[$`]/.test(word)) options.add(word);
342+
if (options.size === 0) continue;
343+
resolved = resolved.flatMap((entry) => [...options].map((value) => entry.replaceAll(reference, value))).slice(0, RESOLVED_COMMANDS_LIMIT);
344+
}
345+
return resolved.filter((entry) => entry !== command);
346+
}
347+
289348
/**
290349
* The scripts a command hands to another shell (`bash -c '…'`,
291350
* `bash --noprofile -o pipefail -c '…'`, `sudo -u x sh -lc '…'`,
@@ -333,12 +392,17 @@ function wrappedCommands(command: string, spend: Spend): string[] {
333392
* a wrapper such as `sudo` runs, searched again in turn. A rough split only
334393
* adds candidates, so a pattern can block more than the line runs, never less.
335394
*
395+
* A program named through a variable is also searched with each value
396+
* `assigned` gives it: by default the line's own assignments, or those of the
397+
* whole line the command belongs to.
398+
*
336399
* `unchecked` says the line runs something no pattern can be checked against:
337-
* a program named through an expansion (`x=rm; $x -rf dir`), scripts nested
338-
* deeper than are searched, or more text than one parse reads. A script that
339-
* only exists when the line runs (`curl … | sh`) is checked as written.
400+
* a program named through an expansion (`$x -rf dir`), even one resolved
401+
* from the line, since its variable may hold something else when it runs,
402+
* scripts nested deeper than are searched, or more text than one parse reads.
403+
* A script that only exists when the line runs (`curl … | sh`) is checked as written.
340404
*/
341-
export function parseShellCommands(command: string): { commands: string[]; unchecked: boolean } {
405+
export function parseShellCommands(command: string, assigned: AssignedValues = assignedValues(command)): { commands: string[]; unchecked: boolean } {
342406
const found = new Set<string>();
343407
let unchecked = false;
344408
let budget = SHELL_PARSE_BUDGET;
@@ -359,7 +423,9 @@ export function parseShellCommands(command: string): { commands: string[]; unche
359423
const command = withoutShellKeywords(candidate);
360424
const stripped = withoutAssignments(command);
361425
for (const entry of [candidate, withoutAssignments(candidate), command, stripped, byProgramName(stripped)]) found.add(entry);
362-
if (namesProgramDynamically(stripped)) unchecked = true;
426+
if (!namesProgramDynamically(stripped)) return;
427+
unchecked = true;
428+
for (const resolved of resolvedCommands(stripped, assigned)) visit(resolved, depth + 1);
363429
};
364430
add(line);
365431
// Quotes do not change what runs: `"rm" -rf x` runs rm.

‎apps/server/src/opencode-plugins/openwork-agent-permissions-v2.ts‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,12 @@ type Registration = { dispose(): Promise<void> };
99
type PermissionEvent = {
1010
readonly action: string;
1111
readonly resources: readonly string[];
12+
readonly source?: { readonly type?: string; readonly id?: string };
1213
effect: "allow" | "ask" | "deny";
1314
message?: string;
1415
};
1516
type ToolError = { error?: { _tag?: unknown; permission?: unknown; resources?: unknown; reason?: string } };
17+
type ExecuteBefore = { readonly tool: string; readonly id: string; readonly input: unknown };
1618
type ExecuteAfter = { readonly status: string; readonly error?: ToolError };
1719
type McpEditor = {
1820
list(): Iterable<readonly [string, unknown]>;
@@ -22,9 +24,15 @@ type Context = {
2224
options: { rules?: unknown; organizationMcp?: unknown };
2325
mcp: { transform(callback: (editor: McpEditor) => void): Promise<Registration> };
2426
permission: { hook(name: "evaluate", callback: (event: PermissionEvent) => void): Promise<Registration> };
25-
tool: { hook(name: "execute.after", callback: (event: ExecuteAfter) => void): Promise<Registration> };
27+
tool: {
28+
hook(name: "execute.before", callback: (event: ExecuteBefore) => void): Promise<Registration>;
29+
hook(name: "execute.after", callback: (event: ExecuteAfter) => void): Promise<Registration>;
30+
};
2631
};
2732

33+
/** How many recent shell calls' command lines are kept for their permission evaluation. */
34+
const COMMAND_LINES_KEPT = 100;
35+
2836
function strings(value: unknown): string[] {
2937
return Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === "string") : [];
3038
}
@@ -39,10 +47,22 @@ export default {
3947
async setup(context: Context) {
4048
const rules = parseAgentPermissionRules(context.options.rules);
4149
const organizationMcp = parseOrganizationMcpServers(context.options.organizationMcp);
50+
// The engine asks about each command of a shell call's line on its own,
51+
// without the assignments that may name a program (`x=rm; $x -rf dir`), so
52+
// keep the whole line of recent calls by call id for their evaluation.
53+
const commandLines = new Map<string, string>();
54+
const lines = await context.tool.hook("execute.before", (event) => {
55+
const command = typeof event.input === "object" && event.input !== null ? (event.input as { command?: unknown }).command : undefined;
56+
if (event.tool !== "shell" || typeof command !== "string") return;
57+
commandLines.set(event.id, command);
58+
// A failed call never reaches execute.after through OpenWork's wrapped tools, so only the latest are kept.
59+
if (commandLines.size > COMMAND_LINES_KEPT) commandLines.delete(commandLines.keys().next().value!);
60+
});
4261
// Called whenever the engine's own rules did not deny, which is every
4362
// agent permission but a blocked local skill.
4463
const permission = await context.permission.hook("evaluate", (event) => {
45-
const decision = agentPermissionEngineV2Decision(rules, event.action, event.resources, event.effect);
64+
const line = event.source?.type === "tool" && event.source.id ? commandLines.get(event.source.id) : undefined;
65+
const decision = agentPermissionEngineV2Decision(rules, event.action, event.resources, event.effect, line);
4666
event.effect = decision.effect;
4767
if (decision.message) event.message = decision.message;
4868
});
@@ -68,6 +88,7 @@ export default {
6888
await servers?.dispose();
6989
await explain.dispose();
7090
await permission.dispose();
91+
await lines.dispose();
7192
};
7293
},
7394
};

‎evals/core/agent-permissions.e2e.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ test("a contractor's agent asks before commands, runs the ones the team allows,
3232
const shell = (command: string): MockAgentToolStep => ({ tool: world.shellTool, arguments: { command, description: "Run a command" } });
3333
const blockedCommand = "printf '%s' 'saved by the agent' > 'note.txt'";
3434
const wrappedCommand = `bash -c "printf '%s' 'saved through bash' > 'wrapped-note.txt'"`;
35+
const variableCommand = "x=printf; $x '%s' 'saved through a variable' > 'variable-note.txt'";
3536
const allowedCommand = "echo 'checked in'";
3637
const askedCommand = "pwd";
3738

@@ -89,6 +90,25 @@ test("a contractor's agent asks before commands, runs the ones the team allows,
8990
expect(told).toContain('"printf *" is blocked for Contractors');
9091
});
9192

93+
await step("before: the agent names printf through a shell variable it sets on the same line", async () => {
94+
await turn("Save the note through a variable.", [shell(variableCommand)]);
95+
const call = await settled(world.shellTool, (input) => input.command === variableCommand);
96+
await user.notSee(approval);
97+
evidence.recordAssertionEvidence("the agent's variable-named printf call", `${call?.status ?? "none"}, no approval asked: ${variableCommand}`, call?.status === "error");
98+
expect(call?.status).toBe("error");
99+
await user.screenshot();
100+
});
101+
102+
await step("after: the variable-named printf never ran, and the agent was told the Contractors rule instead of Riley being asked to approve it", async () => {
103+
const call = await world.toolCall(world.shellTool, (input) => input.command === variableCommand);
104+
const wrote = await world.wrote("variable-note.txt");
105+
const told = reason(call);
106+
evidence.recordAssertionEvidence("variable-named command blocked before it ran", `note written: ${wrote}; the agent was told: ${told || "(nothing)"}`,
107+
!wrote && told.includes('"printf *" is blocked for Contractors'));
108+
expect(wrote).toBe(false);
109+
expect(told).toContain('"printf *" is blocked for Contractors');
110+
});
111+
92112
await step("an echo command, which Contractors always allow, runs without asking Riley", async () => {
93113
await turn("Say that you checked in.", [shell(allowedCommand)]);
94114
const call = await settled(world.shellTool, (input) => input.command === allowedCommand);

‎packages/docs/cloud/share-with-your-team/agent-permissions.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ In the built-in browser, a blocked website doesn't load and the browser shows th
6363

6464
## Known limits
6565

66-
- **Commands named through a variable.** Command rules match the command as it is written. A command whose program name comes from a shell variable, substitution or pattern, such as `x=rm; $x -rf build`, can't be matched to a rule. Where commands are blocked it is blocked; where a command rule only blocks some commands, such as `rm *`, it is asked about, and the member can approve it.
66+
- **Commands named through a variable.** Command rules match the command as it is written. When a command line sets the variable that names a program, as in `x=rm; $x -rf build`, `export x=rm`, `for x in rm` or `${x:-rm}`, the program is checked with each value the line gives it, so `rm *` blocks it. A program named through a variable the line doesn't set, such as `$EDITOR`, a substitution such as `$(which rm)` or a pattern such as `/bin/r?` can't be matched to a rule. Where commands are blocked it is blocked; where a command rule only blocks some commands, such as `rm *`, it is asked about, and the member can approve it.
6767
- **Command lines OpenWork can't fully read.** A line nested or long enough that OpenWork stops reading it is handled the same way. A script that only exists when the command runs, such as `curl … | sh`, is checked as written.
6868
- **Text that looks like a command.** Each line of a command is checked, including the text in a heredoc (`cat <<EOF` … `EOF`). A line there that matches a blocked pattern blocks the whole command, even though it is only written to a file.
6969
- **Ask first for file edits.** It applies to the agent's file editing. When commands are allowed, a command that writes a file, such as `echo … > notes.txt`, isn't asked about; set **Run commands** to **Ask first** as well to cover those.

0 commit comments

Comments
 (0)