feat(policy): Introduce config-based policy engine with TOML configuration#11992
feat(policy): Introduce config-based policy engine with TOML configuration#11992allenhutchison merged 22 commits intomainfrom
Conversation
This commit replaces the programmatic policy system with a config-based system using TOML files. This change makes the policy engine more flexible and easier to configure without changing the code. The default policy rules are now defined in TOML files located in the `packages/cli/src/config/policies` directory. The `createPolicyEngineConfig` function has been updated to be asynchronous and now loads these policy files from the disk. The following changes were made: - Added a new `policies` directory in `packages/cli/src/config` to store the default TOML-based policy configurations. - Created `default.toml`, `read-only.toml`, `write.toml`, and `auto-edit.toml` to represent the different policy sets. - Refactored the `createPolicyEngineConfig` function to load, parse, and apply these new TOML configuration files. - Updated all call sites of `createPolicyEngineConfig` to be asynchronous. - Updated all relevant test files to reflect the changes.
Refactored policy directory resolution to use existing utilities instead of hard-coded paths and direct environment variable access. Core changes: - Added Storage.getUserPoliciesDir() method to return ~/.gemini/policies - Provides centralized configuration for user policy directory Policy module changes: - Import Storage from core and getSystemSettingsPath from settings.ts - Replace hard-coded '.gemini' path with Storage.getUserPoliciesDir() - Replace direct process.env access with getSystemSettingsPath() - Remove unnecessary homedir import - Simplify getPolicyDirectories() since getSystemSettingsPath() always returns a value with platform-specific defaults Test improvements: - Update admin policy test to use correct settings.json path format - All 19 policy tests pass Benefits: - Better code reuse and maintainability - Platform-aware path resolution - Single source of truth for policy directory paths
Added .toml extension to the list of file extensions copied during build. This ensures that policy TOML files in src/config/policies/ are included in the dist directory and can be loaded at runtime. Without this fix, the policy engine would fail to load default policy rules from TOML files, causing unexpected confirmation prompts for tools that should be auto-approved (like google_web_search). Fixes issue where google_web_search was asking for confirmation despite being configured as "allow" in read-only.toml.
…hing Added support for regex pattern matching on tool arguments in policy TOML files. This enables fine-grained control over tool approvals based on specific arguments. Changes: - Updated PolicyRuleSchema to accept optional argsPattern field (string) - Convert argsPattern strings to RegExp objects when loading policy files - Added comprehensive test for argsPattern matching with git commands - Proper TypeScript typing for rule conversion - Added debug logging to PolicyEngine.check() and config loading Example use case - allow specific git subcommands without confirmation: ```toml [[rule]] toolName = "ShellToolInvocation" argsPattern = "\"command\":\"git (status|diff|log|branch)" decision = "allow" priority = 100 ``` This allows users to auto-approve safe read-only git commands while still requiring confirmation for write operations like git commit or git push. The pattern matches against the JSON-stringified tool arguments, enabling powerful regex-based filtering. Known issues to address in follow-up PRs: 1. Policy loading only supports specific filenames (read-only.toml, write.toml, etc.) Should scan all .toml files in policies directory 2. Tool name inconsistency: ShellToolInvocation vs run_shell_command constant
Introduces a priority band (tier) system that ensures the policy hierarchy Admin > User > Default is always preserved, while allowing meaningful priorities within each tier. Priority transformation: - Default policies (TOML): 1 + priority/1000 (e.g., 100 → 1.100) - User policies (TOML): 2 + priority/1000 (e.g., 100 → 2.100) - Admin policies (TOML): 3 + priority/1000 (e.g., 100 → 3.100) This prevents high-priority default/user rules from overriding lower-priority admin rules, while maintaining predictable ordering within each tier. Changes: - Add getPolicyTier() to determine directory tier (1=default, 2=user, 3=admin) - Add transformPriority() to apply tier-based transformation - Update createPolicyUpdater() to use user tier priority (2.95) - Simplify policy files by removing unnecessary mode annotations - Reorganize policy files for clarity: - Rename default.toml → yolo.toml - Merge auto-edit.toml into write.toml - Remove redundant "default" mode annotations - Update all tests for transformed priorities - Add comprehensive test coverage for priority bands The modes field is now only used when restricting to specific modes, with rules without modes applying to all modes by default.
Previously, ShellToolInvocation, WriteTodosToolInvocation, and DiscoveredMCPToolInvocation did not pass tool names to BaseToolInvocation, causing the policy engine to see class names (e.g., "ShellToolInvocation") instead of the proper tool names from tool-names.ts constants (e.g., "run_shell_command"). Changes: - Fix ShellToolInvocation to pass _toolName and _toolDisplayName to super() - Fix WriteTodosToolInvocation to pass tool name parameters to super() - Fix DiscoveredMCPToolInvocation to pass composite tool name (serverName__toolName) and messageBus to super() - Add mcpName field to PolicyRuleSchema for TOML policies - Implement mcpName transformation logic: - mcpName only → "serverName__*" (server wildcard) - mcpName + toolName → "serverName__toolName" (specific tool) - toolName only → use as-is (built-in tools or short names) This enables flexible MCP tool configuration: - Server-level: mcpName = "google-workspace" (allows all tools) - Tool-specific: mcpName = "google-workspace", toolName = "gmail.send" - Composite format: toolName = "google-workspace__gmail.send" All tests pass.
Users can now specify multiple tools in a single rule using array syntax: [[rule]] toolName = ["tool1", "tool2", "tool3"] decision = "allow" priority = 100 This also works with mcpName for MCP tools: [[rule]] mcpName = "google-workspace" toolName = ["calendar.findFreeTime", "calendar.getEvent", "calendar.list"] decision = "allow" priority = 100 This is more concise than writing separate rules for each tool and ensures all tools in the array get the same decision and priority. Implementation: - Updated PolicyRuleSchema to accept string or array for toolName - Changed .map() to .flatMap() to expand array entries into multiple rules - Each tool in the array creates a separate PolicyRule with same decision/priority - Added comprehensive test coverage All tests pass (23/23 policy tests, 12/12 integration tests).
This commit fixes the integration between the message bus and MCP tools so that MCP tool invocations properly respect policy rules configured in TOML files. Fixes #7837 Key changes: - Added setMessageBus/getMessageBus methods to ToolRegistry - Set message bus on ToolRegistry before tool discovery (in createToolRegistry) - Updated discoverTools() to accept and pass messageBus parameter to MCP tools - Changed DiscoveredMCPToolInvocation to override getConfirmationDetails() instead of shouldConfirmExecute() to allow policy engine checks - Added debug logging to show when MCP tools are discovered with message bus (guarded by both debug mode and message bus integration being enabled) - Updated test mocks to include getMessageBus method The timing fix was critical: the message bus must be set on the registry BEFORE discoverAllTools() is called, otherwise MCP tools are created without access to the message bus and cannot check policies.
…mands This commit adds convenience syntax for defining shell command policies in TOML files, making it easier to write rules without manually crafting regex patterns. New TOML fields: - commandPrefix: String or array of command prefixes to match (e.g., "git status") - commandRegex: Regex pattern for more complex command matching Features: - commandPrefix automatically escapes regex special characters for literal matching - Array syntax expands to multiple rules (similar to toolName arrays) - Validation ensures these fields only work with toolName = "run_shell_command" - Mutually exclusive with argsPattern (use raw argsPattern for complex cases) Example usage: ```toml [[rule]] toolName = "run_shell_command" commandPrefix = ["git status", "git log", "git diff"] decision = "allow" priority = 100 [[rule]] toolName = "run_shell_command" commandRegex = "git (branch|status).*" decision = "allow" priority = 100 ``` Implementation: - Added escapeRegex() utility to escape regex special characters - Transforms commandPrefix/commandRegex to argsPattern during rule processing - Added validation to prevent misuse (e.g., with wrong toolName) - Added 4 comprehensive tests covering all use cases
This commit moves --allowed-tools and --exclude-tools command line flags from flat priorities (100, 200) to user tier priorities (2.100, 2.200) to align them with the three-tier priority system (Admin > User > Default). Changes: - settings.tools.allowed: 100 → 2.1 (user tier) - settings.tools.exclude: 200 → 2.2 (user tier) Priority hierarchy (highest to lowest): 1. MCP server settings (flat: 85-195) - highest for security 2. Admin TOML policies (3.0-3.999) 3. User TOML policies (2.0-2.999) 4. Command line flags (2.1, 2.2) - now in user tier 5. Default TOML policies (1.0-1.999) This means: - MCP server trust/allow settings override command line flags (by design) - Admin TOML policies override command line flags - Command line flags override default TOML policies - Command line flags have same tier as user TOML policies Updated tests to reflect new priority relationships.
…anced error handling Split sophisticated TOML policy file parsing logic into a separate module to improve code organization and maintainability. This change includes: - Created `policy-toml-loader.ts` with dedicated schemas, validation, and error handling - Comprehensive error types (file_read, toml_parse, schema_validation, rule_validation, regex_compilation) - Detailed error reporting with suggestions for common mistakes - 13 comprehensive unit tests covering all transformations and error scenarios - Refactored `policy.ts` to use the new loader, reducing complexity - Updated integration tests to reflect new user tier priority values (2.1, 2.2) The new loader provides structured error handling with detailed messages, making it easier for users to diagnose and fix policy file issues.
Summary of ChangesHello @allenhutchison, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request significantly enhances the tool execution policy system by introducing a robust, configuration-driven policy engine. It shifts from hardcoded rules to flexible TOML files, allowing users and administrators to define custom policies with a clear three-tier priority structure. This change provides greater control and transparency over how tools are approved, denied, or require confirmation, making the system more adaptable and secure without breaking existing functionality. Highlights
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
|
Size Change: +12.6 kB (+0.06%) Total Size: 20.2 MB
ℹ️ View Unchanged
|
There was a problem hiding this comment.
Code Review
This pull request introduces a powerful and flexible new policy engine based on TOML configuration, which is a significant improvement for managing tool execution policies. The implementation is thorough, covering file loading, parsing, validation, and integration with the existing system. However, there is a critical issue in the new priority system where old, untiered integer-based priorities for MCP settings coexist with the new tiered, float-based priorities. This inconsistency leads to confusing and incorrect precedence evaluation, which could result in unintended tool execution and potential security vulnerabilities. This core issue needs to be resolved by migrating all policy priorities to the new tiered system to ensure predictable and secure behavior.
Addresses review comments from Gemini Code Assist bot on PR #11992: 1. **Fix inconsistent priority system**: - Move ALL settings-based priorities to user tier (2.x) for consistency - New priority order (highest to lowest): * 2.9: MCP servers excluded (was 195) * 2.4: Command line --exclude-tools (was 2.2) * 2.3: Command line --allowed-tools (was 2.1) * 2.2: MCP servers with trust=true (was 90) * 2.1: MCP servers allowed (was 85) - This fixes the semantic bug where MCP server allow (85) would beat command-line tool exclude (2.2), which was insecure and wrong - Specific tool excludes now correctly beat server-wide allows 2. **Fix AUTO_EDIT mode for write_file**: - Add write_file to autoEdit mode rules in write.toml - AUTO_EDIT now approves both replace and write_file tools - Matches expected behavior from --approval-mode=auto_edit 3. **Update all tests**: - Fix integration test expectations for new priority system - Rename test to reflect correct precedence behavior - Update unit test assertions to use new tiered priorities - Fix test semantics: command line excludes now beat server trust
Fixes 22 failing policy tests on Windows CI by normalizing paths
for cross-platform compatibility.
**Changes:**
- Add nodePath import to both test files
- Replace hardcoded Unix-style paths with nodePath.normalize()
- Fix path comparisons:
- `path === '/policies'` → `nodePath.normalize(path) === nodePath.normalize('/policies')`
- `path.includes('.gemini/policies')` → `nodePath.normalize(path).includes(nodePath.normalize('.gemini/policies'))`
**Root Cause:**
Tests used hardcoded Unix-style paths (`/policies`, `.gemini/policies`)
in mocks, but on Windows the loader constructs paths with backslashes
using `path.join()`, causing mock comparisons to fail.
**Impact:**
- All 40 policy tests now pass on both Unix and Windows platforms
- policy-toml-loader.test.ts: 13 tests fixed
- policy.test.ts: 27 tests fixed
abhipatel12
left a comment
There was a problem hiding this comment.
This looks great! Had a few comment, let me know what you think!
Address PR review feedback to enhance policy configuration UX: - Add priority range validation (0-999) to prevent tier overflow with clear, actionable error messages explaining the tier system - Document priority system in all default TOML files to guide users on proper priority value selection - Implement deferred error reporting so policy validation errors are visible in UI after mount, only when message bus integration is enabled - Gate debug logs on message bus integration to reduce noise when policies are not active - Replace console.error with debugLogger in policy-engine for consistent logging to debug drawer This ensures users see helpful error messages when they misconfigure policies, preventing silent failures and tier boundary violations. Addresses feedback from abhipatel12 in PR #11992
abhipatel12
left a comment
There was a problem hiding this comment.
LGTM! had a comment on the logging but otherwise approved!
Config-Based Policy Engine
This PR introduces a flexible, extensible policy engine that allows users and administrators to define tool execution policies via TOML configuration files.
Overview
The new policy engine provides fine-grained control over tool execution with support for three-tier priority bands (default, user, admin) and sophisticated matching patterns. Users can now customize which tools auto-approve, which require confirmation, and which are blocked entirely.
Key Features
1. Three-Tier Priority System
2. TOML Configuration Files
Simple, readable policy definitions in
.tomlfiles:3. Flexible Matching Syntax
my-server__*)mcpName = "google-workspace"expands to all tools from that servercommandPrefixfor literal matching,commandRegexfor regex patternsargsPatternfor granular tool argument matchingtoolName = ["tool1", "tool2"]creates multiple rules4. Mode-Specific Rules
Apply different policies in different approval modes:
5. Enhanced Error Handling
Comprehensive validation with helpful error messages:
Technical Implementation
Architecture
packages/core/src/policy/policy-engine.ts): Core evaluation logicpackages/cli/src/config/policy-toml-loader.ts): Dedicated parsing module with error handlingpackages/cli/src/config/policy.ts): Combines TOML policies with settings-based rulesPolicy File Locations
<install-dir>/packages/cli/dist/src/config/policies/(shipped)~/.config/gemini/.gemini/policies/(user customizations)<system-settings-path>/policies/(admin overrides)Priority Bands
Example Policies
Auto-approve safe git commands:
Allow all Google Workspace tools:
Block dangerous operations:
Changes by Commit
toolNamearrays into multiple rulescommandPrefixandcommandRegexfieldsTesting
Breaking Changes
None. This is additive functionality that defaults to existing behavior when no policy files are present.
Fixes
Fixes #7837, #7838, #11299, #11300
Documentation
Policy files are auto-discovered from the three locations (default, user, admin) and merged with higher tiers winning. Users can create custom policies by adding
.tomlfiles to~/.config/gemini/.gemini/policies/.