fix: permissions parsing

This commit is contained in:
Nate 2025-07-27 19:47:11 -07:00
parent 08e5fc23bf
commit 43e86f3e24
4 changed files with 341 additions and 14 deletions

View file

@ -176,6 +176,119 @@ describe("Permission Checker", () => {
};
expect(matchesArguments(args, differentButEqualObjectPatterns)).toBe(false);
});
describe("glob pattern matching", () => {
it("should match glob patterns with asterisk wildcards", () => {
const args = { command: "cd ../projects && ls", file_path: "/src/file.ts" };
// Test command patterns
expect(matchesArguments(args, { command: "cd*" })).toBe(true);
expect(matchesArguments(args, { command: "*ls" })).toBe(true);
expect(matchesArguments(args, { command: "*&&*" })).toBe(true);
expect(matchesArguments(args, { command: "pwd*" })).toBe(false);
// Test file path patterns
expect(matchesArguments(args, { file_path: "*.ts" })).toBe(true);
expect(matchesArguments(args, { file_path: "/src/*" })).toBe(true);
expect(matchesArguments(args, { file_path: "**/file.ts" })).toBe(true);
expect(matchesArguments(args, { file_path: "*.js" })).toBe(false);
});
it("should match glob patterns with question mark wildcards", () => {
const args = { command: "git add", file: "test1.js" };
expect(matchesArguments(args, { command: "git a?d" })).toBe(true);
expect(matchesArguments(args, { command: "git a??d" })).toBe(false);
expect(matchesArguments(args, { file: "test?.js" })).toBe(true);
expect(matchesArguments(args, { file: "test??.js" })).toBe(false);
});
it("should match complex glob patterns", () => {
const args = {
command: "npm run test:unit",
path: "/home/user/projects/myapp/src/utils/helper.ts"
};
expect(matchesArguments(args, { command: "npm * test:*" })).toBe(true);
expect(matchesArguments(args, { command: "npm run *:unit" })).toBe(true);
expect(matchesArguments(args, { path: "**/src/**/*.ts" })).toBe(true);
expect(matchesArguments(args, { path: "/home/*/projects/*/src/**" })).toBe(true);
expect(matchesArguments(args, { command: "yarn *" })).toBe(false);
});
it("should escape special regex characters in glob patterns", () => {
const args = {
command: "echo 'test.pattern'",
regex: "test[0-9]+",
special: "file(1).txt"
};
// Literal dots, brackets, parentheses should match exactly
expect(matchesArguments(args, { command: "*'test.pattern'*" })).toBe(true);
expect(matchesArguments(args, { regex: "test[0-9]+" })).toBe(true);
expect(matchesArguments(args, { special: "file(1).txt" })).toBe(true);
expect(matchesArguments(args, { special: "file(*).txt" })).toBe(true);
// These should not match due to regex escaping
expect(matchesArguments(args, { command: "*test_pattern*" })).toBe(false);
expect(matchesArguments(args, { regex: "test*" })).toBe(true); // * is wildcard, + is literal
});
it("should handle mixed exact and glob patterns", () => {
const args = {
tool: "bash",
command: "cd projects && npm install",
flag: "--verbose"
};
// Mix of exact and glob matching
expect(matchesArguments(args, {
tool: "bash", // exact match
command: "cd*install", // glob match
flag: "--verbose" // exact match
})).toBe(true);
expect(matchesArguments(args, {
tool: "bash", // exact match
command: "cd*test", // glob no match
flag: "--verbose" // exact match
})).toBe(false);
});
it("should convert non-string values to strings for pattern matching", () => {
const args = {
port: 3000,
enabled: true,
count: null,
items: [1, 2, 3]
};
expect(matchesArguments(args, { port: "30*" })).toBe(true);
expect(matchesArguments(args, { enabled: "tr*" })).toBe(true);
expect(matchesArguments(args, { count: "*" })).toBe(true); // null -> ""
expect(matchesArguments(args, { items: "*,*,*" })).toBe(true); // array toString
expect(matchesArguments(args, { port: "40*" })).toBe(false);
expect(matchesArguments(args, { enabled: "fa*" })).toBe(false);
});
it("should handle empty and undefined argument values", () => {
const args = {
empty: "",
undef: undefined,
zero: 0,
false_val: false
};
expect(matchesArguments(args, { empty: "*" })).toBe(true);
expect(matchesArguments(args, { undef: "*" })).toBe(true); // undefined -> ""
expect(matchesArguments(args, { zero: "*" })).toBe(true); // 0 -> "0"
expect(matchesArguments(args, { false_val: "*" })).toBe(true); // false -> "false"
expect(matchesArguments(args, { empty: "nonempty*" })).toBe(false);
expect(matchesArguments(args, { zero: "1*" })).toBe(false);
});
});
});
describe("checkToolPermission", () => {
@ -334,6 +447,51 @@ describe("Permission Checker", () => {
expect(npmResult.permission).toBe("ask");
expect(npmResult.matchedPolicy?.tool).toBe("run_terminal_command");
});
it("should match argument patterns with glob patterns", () => {
const permissions: ToolPermissions = {
policies: [
{
tool: "run_terminal_command",
permission: "exclude",
argumentMatches: { command: "rm*" }
},
{
tool: "write_file",
permission: "ask",
argumentMatches: { file_path: "**/*.ts" }
},
{
tool: "write_file",
permission: "allow"
}
],
};
// Should exclude dangerous rm commands
const rmResult = checkToolPermission(
{ name: "run_terminal_command", arguments: { command: "rm -rf /" } },
permissions
);
expect(rmResult.permission).toBe("exclude");
expect(rmResult.matchedPolicy?.argumentMatches?.command).toBe("rm*");
// Should ask for TypeScript files
const tsResult = checkToolPermission(
{ name: "write_file", arguments: { file_path: "/src/components/Button.ts" } },
permissions
);
expect(tsResult.permission).toBe("ask");
expect(tsResult.matchedPolicy?.argumentMatches?.file_path).toBe("**/*.ts");
// Should allow other file writes
const jsResult = checkToolPermission(
{ name: "write_file", arguments: { file_path: "/src/utils/helper.js" } },
permissions
);
expect(jsResult.permission).toBe("allow");
expect(jsResult.matchedPolicy?.argumentMatches).toBeUndefined();
});
});
describe("filterExcludedTools", () => {

View file

@ -61,6 +61,7 @@ export function matchesToolPattern(
/**
* Checks if tool call arguments match the specified patterns.
* Supports glob patterns with * and ? wildcards.
*/
export function matchesArguments(
args: Record<string, any>,
@ -73,9 +74,25 @@ export function matchesArguments(
if (pattern === "*") continue; // Wildcard matches anything
// Exact match
if (argValue !== pattern) {
return false;
// Handle glob patterns with wildcards (only for string patterns)
if (typeof pattern === "string" && (pattern.includes("*") || pattern.includes("?"))) {
// Convert argValue to string for pattern matching
const stringValue = String(argValue || "");
// Escape all regex metacharacters except * and ?
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&");
// Convert * and ? to their regex equivalents
const regexPattern = escaped.replace(/\*/g, ".*").replace(/\?/g, ".");
const regex = new RegExp(`^${regexPattern}$`);
if (!regex.test(stringValue)) {
return false;
}
} else {
// Exact match for non-glob patterns (preserve original behavior)
if (argValue !== pattern) {
return false;
}
}
}

View file

@ -1,4 +1,4 @@
import { yamlConfigToPolicies } from "./permissionsYamlLoader.js";
import { yamlConfigToPolicies, parseToolPattern } from "./permissionsYamlLoader.js";
describe("permissionsYamlLoader", () => {
describe("yamlConfigToPolicies", () => {
@ -85,4 +85,114 @@ describe("permissionsYamlLoader", () => {
]);
});
});
describe("parseToolPattern", () => {
it("should parse tool name without arguments", () => {
const policy = parseToolPattern("Write", "allow");
expect(policy).toEqual({
tool: "write_file",
permission: "allow"
});
});
it("should parse tool name with file path pattern", () => {
const policy = parseToolPattern("Write(**/*.ts)", "exclude");
expect(policy).toEqual({
tool: "write_file",
permission: "exclude",
argumentMatches: {
file_path: "**/*.ts"
}
});
});
it("should parse bash command with argument", () => {
const policy = parseToolPattern("Bash(npm install)", "ask");
expect(policy).toEqual({
tool: "run_terminal_command",
permission: "ask",
argumentMatches: {
command: "npm install"
}
});
});
it("should handle various tool types with arguments", () => {
const testCases = [
{
pattern: "Read(src/**/*.js)",
expected: { tool: "read_file", permission: "allow", argumentMatches: { file_path: "src/**/*.js" } }
},
{
pattern: "List(/home/user)",
expected: { tool: "list_files", permission: "allow", argumentMatches: { path: "/home/user" } }
},
{
pattern: "Search(TODO)",
expected: { tool: "search_code", permission: "allow", argumentMatches: { query: "TODO" } }
},
{
pattern: "Fetch(https://api.example.com)",
expected: { tool: "fetch", permission: "allow", argumentMatches: { url: "https://api.example.com" } }
}
];
testCases.forEach(({ pattern, expected }) => {
const policy = parseToolPattern(pattern, "allow");
expect(policy).toEqual(expected);
});
});
it("should handle empty arguments", () => {
const policy = parseToolPattern("Write()", "allow");
expect(policy).toEqual({
tool: "write_file",
permission: "allow"
});
});
it("should handle whitespace in arguments", () => {
const policy = parseToolPattern("Bash( npm run test )", "ask");
expect(policy).toEqual({
tool: "run_terminal_command",
permission: "ask",
argumentMatches: {
command: "npm run test"
}
});
});
it("should handle unknown tools with default argument key", () => {
const policy = parseToolPattern("CustomTool(some-pattern)", "allow");
expect(policy).toEqual({
tool: "CustomTool",
permission: "allow",
argumentMatches: {
pattern: "some-pattern"
}
});
});
it("should throw error for invalid pattern", () => {
expect(() => parseToolPattern("Write(unclosed", "allow")).toThrow("Invalid tool pattern: Write(unclosed");
});
it("should normalize tool names in patterns", () => {
const policy = parseToolPattern("write(**/*.ts)", "allow");
expect(policy).toEqual({
tool: "write_file",
permission: "allow",
argumentMatches: {
file_path: "**/*.ts"
}
});
});
});
});

View file

@ -4,7 +4,7 @@ import * as path from "path";
import * as yaml from "yaml";
import logger from "../util/logger.js";
import { normalizeToolName } from "./toolNameMapping.js";
import { ToolPermissionPolicy } from "./types.js";
import { ToolPermissionPolicy, PermissionPolicy } from "./types.js";
export const PERMISSIONS_YAML_PATH = path.join(
os.homedir(),
@ -67,6 +67,51 @@ export function loadPermissionsYaml(): PermissionsYamlConfig | null {
}
}
/**
* Parses a pattern string into a ToolPermissionPolicy
* Supports formats like:
* - "Write" -> { tool: "write_file", permission }
* - "Write(pattern)" -> { tool: "write_file", permission, argumentMatches: { file_path: "pattern" } }
* - "Bash(npm install)" -> { tool: "run_terminal_command", permission, argumentMatches: { command: "npm install" } }
*/
export function parseToolPattern(pattern: string, permission: PermissionPolicy): ToolPermissionPolicy {
const match = pattern.match(/^([^(]+)(?:\(([^)]*)\))?$/);
if (!match) {
throw new Error(`Invalid tool pattern: ${pattern}`);
}
const [, toolName, args] = match;
const normalizedName = normalizeToolName(toolName.trim());
const policy: ToolPermissionPolicy = {
tool: normalizedName,
permission,
};
if (args) {
const trimmedArgs = args.trim();
if (trimmedArgs) {
// Map tool names to their primary argument parameter
const toolArgMappings: Record<string, string> = {
"write_file": "file_path",
"read_file": "file_path",
"list_files": "path",
"search_code": "query",
"run_terminal_command": "command",
"fetch": "url",
"view_diff": "file_path",
};
const argKey = toolArgMappings[normalizedName] || "pattern";
policy.argumentMatches = {
[argKey]: trimmedArgs
};
}
}
return policy;
}
/**
* Converts permissions YAML config to ToolPermissionPolicy array
*/
@ -77,23 +122,20 @@ export function yamlConfigToPolicies(
// Order matters: more restrictive policies first
if (config.exclude) {
for (const tool of config.exclude) {
const normalizedName = normalizeToolName(tool);
policies.push({ tool: normalizedName, permission: "exclude" });
for (const pattern of config.exclude) {
policies.push(parseToolPattern(pattern, "exclude"));
}
}
if (config.ask) {
for (const tool of config.ask) {
const normalizedName = normalizeToolName(tool);
policies.push({ tool: normalizedName, permission: "ask" });
for (const pattern of config.ask) {
policies.push(parseToolPattern(pattern, "ask"));
}
}
if (config.allow) {
for (const tool of config.allow) {
const normalizedName = normalizeToolName(tool);
policies.push({ tool: normalizedName, permission: "allow" });
for (const pattern of config.allow) {
policies.push(parseToolPattern(pattern, "allow"));
}
}