Refactor PolicyEngine to Core Package (#12325)

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
This commit is contained in:
Allen Hutchison
2025-11-03 15:41:00 -08:00
committed by GitHub
parent 60d2c2cc90
commit ffc5e4d048
35 changed files with 1357 additions and 2156 deletions

View File

@@ -519,26 +519,8 @@ export async function loadCliConfig(
approvalMode,
);
// Debug: Log the merged policy configuration
// Only log when message bus integration is enabled (when policies are active)
const enableMessageBusIntegration =
settings.tools?.enableMessageBusIntegration ?? false;
if (enableMessageBusIntegration) {
debugLogger.debug('=== Policy Engine Configuration ===');
debugLogger.debug(
`Default decision: ${policyEngineConfig.defaultDecision}`,
);
debugLogger.debug(`Total rules: ${policyEngineConfig.rules?.length || 0}`);
if (policyEngineConfig.rules && policyEngineConfig.rules.length > 0) {
debugLogger.debug('Rules (sorted by priority):');
policyEngineConfig.rules.forEach((rule, index) => {
debugLogger.debug(
` [${index}] toolName: ${rule.toolName || '*'}, decision: ${rule.decision}, priority: ${rule.priority}, argsPattern: ${rule.argsPattern ? rule.argsPattern.source : 'none'}`,
);
});
}
debugLogger.debug('===================================');
}
const allowedTools = argv.allowedTools || settings.tools?.allowed || [];
const allowedToolsSet = new Set(allowedTools);

View File

@@ -1,982 +0,0 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { ApprovalMode, PolicyDecision } from '@google/gemini-cli-core';
import type { Dirent } from 'node:fs';
import nodePath from 'node:path';
describe('policy-toml-loader', () => {
beforeEach(() => {
vi.resetModules();
});
afterEach(() => {
vi.restoreAllMocks();
vi.doUnmock('node:fs/promises');
});
describe('loadPoliciesFromToml', () => {
it('should load and parse a simple policy file', async () => {
const actualFs =
await vi.importActual<typeof import('node:fs/promises')>(
'node:fs/promises',
);
const mockReaddir = vi.fn(
async (
path: string,
_options?: { withFileTypes: boolean },
): Promise<Dirent[]> => {
if (nodePath.normalize(path) === nodePath.normalize('/policies')) {
return [
{
name: 'test.toml',
isFile: () => true,
isDirectory: () => false,
} as Dirent,
];
}
return [];
},
);
const mockReadFile = vi.fn(async (path: string): Promise<string> => {
if (
nodePath.normalize(path) ===
nodePath.normalize(nodePath.join('/policies', 'test.toml'))
) {
return `
[[rule]]
toolName = "glob"
decision = "allow"
priority = 100
`;
}
throw new Error('File not found');
});
vi.doMock('node:fs/promises', () => ({
...actualFs,
default: { ...actualFs, readFile: mockReadFile, readdir: mockReaddir },
readFile: mockReadFile,
readdir: mockReaddir,
}));
const { loadPoliciesFromToml: load } = await import(
'./policy-toml-loader.js'
);
const getPolicyTier = (_dir: string) => 1;
const result = await load(
ApprovalMode.DEFAULT,
['/policies'],
getPolicyTier,
);
expect(result.rules).toHaveLength(1);
expect(result.rules[0]).toEqual({
toolName: 'glob',
decision: PolicyDecision.ALLOW,
priority: 1.1, // tier 1 + 100/1000
});
expect(result.errors).toHaveLength(0);
});
it('should expand commandPrefix array to multiple rules', async () => {
const actualFs =
await vi.importActual<typeof import('node:fs/promises')>(
'node:fs/promises',
);
const mockReaddir = vi.fn(
async (
path: string,
_options?: { withFileTypes: boolean },
): Promise<Dirent[]> => {
if (nodePath.normalize(path) === nodePath.normalize('/policies')) {
return [
{
name: 'shell.toml',
isFile: () => true,
isDirectory: () => false,
} as Dirent,
];
}
return [];
},
);
const mockReadFile = vi.fn(async (path: string): Promise<string> => {
if (
nodePath.normalize(path) ===
nodePath.normalize(nodePath.join('/policies', 'shell.toml'))
) {
return `
[[rule]]
toolName = "run_shell_command"
commandPrefix = ["git status", "git log"]
decision = "allow"
priority = 100
`;
}
throw new Error('File not found');
});
vi.doMock('node:fs/promises', () => ({
...actualFs,
default: { ...actualFs, readFile: mockReadFile, readdir: mockReaddir },
readFile: mockReadFile,
readdir: mockReaddir,
}));
const { loadPoliciesFromToml: load } = await import(
'./policy-toml-loader.js'
);
const getPolicyTier = (_dir: string) => 2;
const result = await load(
ApprovalMode.DEFAULT,
['/policies'],
getPolicyTier,
);
expect(result.rules).toHaveLength(2);
expect(result.rules[0].toolName).toBe('run_shell_command');
expect(result.rules[1].toolName).toBe('run_shell_command');
expect(
result.rules[0].argsPattern?.test('{"command":"git status"}'),
).toBe(true);
expect(result.rules[1].argsPattern?.test('{"command":"git log"}')).toBe(
true,
);
expect(result.errors).toHaveLength(0);
});
it('should transform commandRegex to argsPattern', async () => {
const actualFs =
await vi.importActual<typeof import('node:fs/promises')>(
'node:fs/promises',
);
const mockReaddir = vi.fn(
async (
path: string,
_options?: { withFileTypes: boolean },
): Promise<Dirent[]> => {
if (nodePath.normalize(path) === nodePath.normalize('/policies')) {
return [
{
name: 'shell.toml',
isFile: () => true,
isDirectory: () => false,
} as Dirent,
];
}
return [];
},
);
const mockReadFile = vi.fn(async (path: string): Promise<string> => {
if (
nodePath.normalize(path) ===
nodePath.normalize(nodePath.join('/policies', 'shell.toml'))
) {
return `
[[rule]]
toolName = "run_shell_command"
commandRegex = "git (status|log).*"
decision = "allow"
priority = 100
`;
}
throw new Error('File not found');
});
vi.doMock('node:fs/promises', () => ({
...actualFs,
default: { ...actualFs, readFile: mockReadFile, readdir: mockReaddir },
readFile: mockReadFile,
readdir: mockReaddir,
}));
const { loadPoliciesFromToml: load } = await import(
'./policy-toml-loader.js'
);
const getPolicyTier = (_dir: string) => 2;
const result = await load(
ApprovalMode.DEFAULT,
['/policies'],
getPolicyTier,
);
expect(result.rules).toHaveLength(1);
expect(
result.rules[0].argsPattern?.test('{"command":"git status"}'),
).toBe(true);
expect(
result.rules[0].argsPattern?.test('{"command":"git log --all"}'),
).toBe(true);
expect(
result.rules[0].argsPattern?.test('{"command":"git branch"}'),
).toBe(false);
expect(result.errors).toHaveLength(0);
});
it('should expand toolName array', async () => {
const actualFs =
await vi.importActual<typeof import('node:fs/promises')>(
'node:fs/promises',
);
const mockReaddir = vi.fn(
async (
path: string,
_options?: { withFileTypes: boolean },
): Promise<Dirent[]> => {
if (nodePath.normalize(path) === nodePath.normalize('/policies')) {
return [
{
name: 'tools.toml',
isFile: () => true,
isDirectory: () => false,
} as Dirent,
];
}
return [];
},
);
const mockReadFile = vi.fn(async (path: string): Promise<string> => {
if (
nodePath.normalize(path) ===
nodePath.normalize(nodePath.join('/policies', 'tools.toml'))
) {
return `
[[rule]]
toolName = ["glob", "grep", "read"]
decision = "allow"
priority = 100
`;
}
throw new Error('File not found');
});
vi.doMock('node:fs/promises', () => ({
...actualFs,
default: { ...actualFs, readFile: mockReadFile, readdir: mockReaddir },
readFile: mockReadFile,
readdir: mockReaddir,
}));
const { loadPoliciesFromToml: load } = await import(
'./policy-toml-loader.js'
);
const getPolicyTier = (_dir: string) => 1;
const result = await load(
ApprovalMode.DEFAULT,
['/policies'],
getPolicyTier,
);
expect(result.rules).toHaveLength(3);
expect(result.rules.map((r) => r.toolName)).toEqual([
'glob',
'grep',
'read',
]);
expect(result.errors).toHaveLength(0);
});
it('should transform mcpName to composite toolName', async () => {
const actualFs =
await vi.importActual<typeof import('node:fs/promises')>(
'node:fs/promises',
);
const mockReaddir = vi.fn(
async (
path: string,
_options?: { withFileTypes: boolean },
): Promise<Dirent[]> => {
if (nodePath.normalize(path) === nodePath.normalize('/policies')) {
return [
{
name: 'mcp.toml',
isFile: () => true,
isDirectory: () => false,
} as Dirent,
];
}
return [];
},
);
const mockReadFile = vi.fn(async (path: string): Promise<string> => {
if (
nodePath.normalize(path) ===
nodePath.normalize(nodePath.join('/policies', 'mcp.toml'))
) {
return `
[[rule]]
mcpName = "google-workspace"
toolName = ["calendar.list", "calendar.get"]
decision = "allow"
priority = 100
`;
}
throw new Error('File not found');
});
vi.doMock('node:fs/promises', () => ({
...actualFs,
default: { ...actualFs, readFile: mockReadFile, readdir: mockReaddir },
readFile: mockReadFile,
readdir: mockReaddir,
}));
const { loadPoliciesFromToml: load } = await import(
'./policy-toml-loader.js'
);
const getPolicyTier = (_dir: string) => 2;
const result = await load(
ApprovalMode.DEFAULT,
['/policies'],
getPolicyTier,
);
expect(result.rules).toHaveLength(2);
expect(result.rules[0].toolName).toBe('google-workspace__calendar.list');
expect(result.rules[1].toolName).toBe('google-workspace__calendar.get');
expect(result.errors).toHaveLength(0);
});
it('should filter rules by mode', async () => {
const actualFs =
await vi.importActual<typeof import('node:fs/promises')>(
'node:fs/promises',
);
const mockReaddir = vi.fn(
async (
path: string,
_options?: { withFileTypes: boolean },
): Promise<Dirent[]> => {
if (nodePath.normalize(path) === nodePath.normalize('/policies')) {
return [
{
name: 'modes.toml',
isFile: () => true,
isDirectory: () => false,
} as Dirent,
];
}
return [];
},
);
const mockReadFile = vi.fn(async (path: string): Promise<string> => {
if (
nodePath.normalize(path) ===
nodePath.normalize(nodePath.join('/policies', 'modes.toml'))
) {
return `
[[rule]]
toolName = "glob"
decision = "allow"
priority = 100
modes = ["default", "yolo"]
[[rule]]
toolName = "grep"
decision = "allow"
priority = 100
modes = ["yolo"]
`;
}
throw new Error('File not found');
});
vi.doMock('node:fs/promises', () => ({
...actualFs,
default: { ...actualFs, readFile: mockReadFile, readdir: mockReaddir },
readFile: mockReadFile,
readdir: mockReaddir,
}));
const { loadPoliciesFromToml: load } = await import(
'./policy-toml-loader.js'
);
const getPolicyTier = (_dir: string) => 1;
const result = await load(
ApprovalMode.DEFAULT,
['/policies'],
getPolicyTier,
);
// Only the first rule should be included (modes includes "default")
expect(result.rules).toHaveLength(1);
expect(result.rules[0].toolName).toBe('glob');
expect(result.errors).toHaveLength(0);
});
it('should handle TOML parse errors', async () => {
const actualFs =
await vi.importActual<typeof import('node:fs/promises')>(
'node:fs/promises',
);
const mockReaddir = vi.fn(
async (
path: string,
_options?: { withFileTypes: boolean },
): Promise<Dirent[]> => {
if (nodePath.normalize(path) === nodePath.normalize('/policies')) {
return [
{
name: 'invalid.toml',
isFile: () => true,
isDirectory: () => false,
} as Dirent,
];
}
return [];
},
);
const mockReadFile = vi.fn(async (path: string): Promise<string> => {
if (
nodePath.normalize(path) ===
nodePath.normalize(nodePath.join('/policies', 'invalid.toml'))
) {
return `
[[rule]
toolName = "glob"
decision = "allow"
priority = 100
`;
}
throw new Error('File not found');
});
vi.doMock('node:fs/promises', () => ({
...actualFs,
default: { ...actualFs, readFile: mockReadFile, readdir: mockReaddir },
readFile: mockReadFile,
readdir: mockReaddir,
}));
const { loadPoliciesFromToml: load } = await import(
'./policy-toml-loader.js'
);
const getPolicyTier = (_dir: string) => 1;
const result = await load(
ApprovalMode.DEFAULT,
['/policies'],
getPolicyTier,
);
expect(result.rules).toHaveLength(0);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].errorType).toBe('toml_parse');
expect(result.errors[0].fileName).toBe('invalid.toml');
});
it('should handle schema validation errors', async () => {
const actualFs =
await vi.importActual<typeof import('node:fs/promises')>(
'node:fs/promises',
);
const mockReaddir = vi.fn(
async (
path: string,
_options?: { withFileTypes: boolean },
): Promise<Dirent[]> => {
if (nodePath.normalize(path) === nodePath.normalize('/policies')) {
return [
{
name: 'invalid.toml',
isFile: () => true,
isDirectory: () => false,
} as Dirent,
];
}
return [];
},
);
const mockReadFile = vi.fn(async (path: string): Promise<string> => {
if (
nodePath.normalize(path) ===
nodePath.normalize(nodePath.join('/policies', 'invalid.toml'))
) {
return `
[[rule]]
toolName = "glob"
priority = 100
`;
}
throw new Error('File not found');
});
vi.doMock('node:fs/promises', () => ({
...actualFs,
default: { ...actualFs, readFile: mockReadFile, readdir: mockReaddir },
readFile: mockReadFile,
readdir: mockReaddir,
}));
const { loadPoliciesFromToml: load } = await import(
'./policy-toml-loader.js'
);
const getPolicyTier = (_dir: string) => 1;
const result = await load(
ApprovalMode.DEFAULT,
['/policies'],
getPolicyTier,
);
expect(result.rules).toHaveLength(0);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].errorType).toBe('schema_validation');
expect(result.errors[0].details).toContain('decision');
});
it('should reject commandPrefix without run_shell_command', async () => {
const actualFs =
await vi.importActual<typeof import('node:fs/promises')>(
'node:fs/promises',
);
const mockReaddir = vi.fn(
async (
path: string,
_options?: { withFileTypes: boolean },
): Promise<Dirent[]> => {
if (nodePath.normalize(path) === nodePath.normalize('/policies')) {
return [
{
name: 'invalid.toml',
isFile: () => true,
isDirectory: () => false,
} as Dirent,
];
}
return [];
},
);
const mockReadFile = vi.fn(async (path: string): Promise<string> => {
if (
nodePath.normalize(path) ===
nodePath.normalize(nodePath.join('/policies', 'invalid.toml'))
) {
return `
[[rule]]
toolName = "glob"
commandPrefix = "git status"
decision = "allow"
priority = 100
`;
}
throw new Error('File not found');
});
vi.doMock('node:fs/promises', () => ({
...actualFs,
default: { ...actualFs, readFile: mockReadFile, readdir: mockReaddir },
readFile: mockReadFile,
readdir: mockReaddir,
}));
const { loadPoliciesFromToml: load } = await import(
'./policy-toml-loader.js'
);
const getPolicyTier = (_dir: string) => 1;
const result = await load(
ApprovalMode.DEFAULT,
['/policies'],
getPolicyTier,
);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].errorType).toBe('rule_validation');
expect(result.errors[0].details).toContain('run_shell_command');
});
it('should reject commandPrefix + argsPattern combination', async () => {
const actualFs =
await vi.importActual<typeof import('node:fs/promises')>(
'node:fs/promises',
);
const mockReaddir = vi.fn(
async (
path: string,
_options?: { withFileTypes: boolean },
): Promise<Dirent[]> => {
if (nodePath.normalize(path) === nodePath.normalize('/policies')) {
return [
{
name: 'invalid.toml',
isFile: () => true,
isDirectory: () => false,
} as Dirent,
];
}
return [];
},
);
const mockReadFile = vi.fn(async (path: string): Promise<string> => {
if (
nodePath.normalize(path) ===
nodePath.normalize(nodePath.join('/policies', 'invalid.toml'))
) {
return `
[[rule]]
toolName = "run_shell_command"
commandPrefix = "git status"
argsPattern = "test"
decision = "allow"
priority = 100
`;
}
throw new Error('File not found');
});
vi.doMock('node:fs/promises', () => ({
...actualFs,
default: { ...actualFs, readFile: mockReadFile, readdir: mockReaddir },
readFile: mockReadFile,
readdir: mockReaddir,
}));
const { loadPoliciesFromToml: load } = await import(
'./policy-toml-loader.js'
);
const getPolicyTier = (_dir: string) => 1;
const result = await load(
ApprovalMode.DEFAULT,
['/policies'],
getPolicyTier,
);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].errorType).toBe('rule_validation');
expect(result.errors[0].details).toContain('mutually exclusive');
});
it('should handle invalid regex patterns', async () => {
const actualFs =
await vi.importActual<typeof import('node:fs/promises')>(
'node:fs/promises',
);
const mockReaddir = vi.fn(
async (
path: string,
_options?: { withFileTypes: boolean },
): Promise<Dirent[]> => {
if (nodePath.normalize(path) === nodePath.normalize('/policies')) {
return [
{
name: 'invalid.toml',
isFile: () => true,
isDirectory: () => false,
} as Dirent,
];
}
return [];
},
);
const mockReadFile = vi.fn(async (path: string): Promise<string> => {
if (
nodePath.normalize(path) ===
nodePath.normalize(nodePath.join('/policies', 'invalid.toml'))
) {
return `
[[rule]]
toolName = "run_shell_command"
commandRegex = "git (status|branch"
decision = "allow"
priority = 100
`;
}
throw new Error('File not found');
});
vi.doMock('node:fs/promises', () => ({
...actualFs,
default: { ...actualFs, readFile: mockReadFile, readdir: mockReaddir },
readFile: mockReadFile,
readdir: mockReaddir,
}));
const { loadPoliciesFromToml: load } = await import(
'./policy-toml-loader.js'
);
const getPolicyTier = (_dir: string) => 1;
const result = await load(
ApprovalMode.DEFAULT,
['/policies'],
getPolicyTier,
);
expect(result.rules).toHaveLength(0);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].errorType).toBe('regex_compilation');
expect(result.errors[0].details).toContain('git (status|branch');
});
it('should escape regex special characters in commandPrefix', async () => {
const actualFs =
await vi.importActual<typeof import('node:fs/promises')>(
'node:fs/promises',
);
const mockReaddir = vi.fn(
async (
path: string,
_options?: { withFileTypes: boolean },
): Promise<Dirent[]> => {
if (nodePath.normalize(path) === nodePath.normalize('/policies')) {
return [
{
name: 'shell.toml',
isFile: () => true,
isDirectory: () => false,
} as Dirent,
];
}
return [];
},
);
const mockReadFile = vi.fn(async (path: string): Promise<string> => {
if (
nodePath.normalize(path) ===
nodePath.normalize(nodePath.join('/policies', 'shell.toml'))
) {
return `
[[rule]]
toolName = "run_shell_command"
commandPrefix = "git log *.txt"
decision = "allow"
priority = 100
`;
}
throw new Error('File not found');
});
vi.doMock('node:fs/promises', () => ({
...actualFs,
default: { ...actualFs, readFile: mockReadFile, readdir: mockReaddir },
readFile: mockReadFile,
readdir: mockReaddir,
}));
const { loadPoliciesFromToml: load } = await import(
'./policy-toml-loader.js'
);
const getPolicyTier = (_dir: string) => 1;
const result = await load(
ApprovalMode.DEFAULT,
['/policies'],
getPolicyTier,
);
expect(result.rules).toHaveLength(1);
// Should match literal asterisk, not wildcard
expect(
result.rules[0].argsPattern?.test('{"command":"git log *.txt"}'),
).toBe(true);
expect(
result.rules[0].argsPattern?.test('{"command":"git log a.txt"}'),
).toBe(false);
expect(result.errors).toHaveLength(0);
});
it('should handle non-existent directory gracefully', async () => {
const actualFs =
await vi.importActual<typeof import('node:fs/promises')>(
'node:fs/promises',
);
const mockReaddir = vi.fn(async (_path: string): Promise<Dirent[]> => {
const error: NodeJS.ErrnoException = new Error('ENOENT');
error.code = 'ENOENT';
throw error;
});
vi.doMock('node:fs/promises', () => ({
...actualFs,
default: { ...actualFs, readdir: mockReaddir },
readdir: mockReaddir,
}));
const { loadPoliciesFromToml: load } = await import(
'./policy-toml-loader.js'
);
const getPolicyTier = (_dir: string) => 1;
const result = await load(
ApprovalMode.DEFAULT,
['/non-existent'],
getPolicyTier,
);
// Should not error for missing directories
expect(result.rules).toHaveLength(0);
expect(result.errors).toHaveLength(0);
});
it('should reject priority >= 1000 with helpful error message', async () => {
const actualFs =
await vi.importActual<typeof import('node:fs/promises')>(
'node:fs/promises',
);
const mockReaddir = vi.fn(
async (
path: string,
_options?: { withFileTypes: boolean },
): Promise<Dirent[]> => {
if (nodePath.normalize(path) === nodePath.normalize('/policies')) {
return [
{
name: 'invalid.toml',
isFile: () => true,
isDirectory: () => false,
} as Dirent,
];
}
return [];
},
);
const mockReadFile = vi.fn(async (path: string): Promise<string> => {
if (
nodePath.normalize(path) ===
nodePath.normalize(nodePath.join('/policies', 'invalid.toml'))
) {
return `
[[rule]]
toolName = "glob"
decision = "allow"
priority = 1000
`;
}
throw new Error('File not found');
});
vi.doMock('node:fs/promises', () => ({
...actualFs,
default: { ...actualFs, readFile: mockReadFile, readdir: mockReaddir },
readFile: mockReadFile,
readdir: mockReaddir,
}));
const { loadPoliciesFromToml: load } = await import(
'./policy-toml-loader.js'
);
const getPolicyTier = (_dir: string) => 1;
const result = await load(
ApprovalMode.DEFAULT,
['/policies'],
getPolicyTier,
);
expect(result.rules).toHaveLength(0);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].errorType).toBe('schema_validation');
expect(result.errors[0].details).toContain('priority');
expect(result.errors[0].details).toContain('tier overflow');
expect(result.errors[0].details).toContain(
'Priorities >= 1000 would jump to the next tier',
);
expect(result.errors[0].details).toContain('<= 999');
});
it('should reject negative priority with helpful error message', async () => {
const actualFs =
await vi.importActual<typeof import('node:fs/promises')>(
'node:fs/promises',
);
const mockReaddir = vi.fn(
async (
path: string,
_options?: { withFileTypes: boolean },
): Promise<Dirent[]> => {
if (nodePath.normalize(path) === nodePath.normalize('/policies')) {
return [
{
name: 'invalid.toml',
isFile: () => true,
isDirectory: () => false,
} as Dirent,
];
}
return [];
},
);
const mockReadFile = vi.fn(async (path: string): Promise<string> => {
if (
nodePath.normalize(path) ===
nodePath.normalize(nodePath.join('/policies', 'invalid.toml'))
) {
return `
[[rule]]
toolName = "glob"
decision = "allow"
priority = -1
`;
}
throw new Error('File not found');
});
vi.doMock('node:fs/promises', () => ({
...actualFs,
default: { ...actualFs, readFile: mockReadFile, readdir: mockReaddir },
readFile: mockReadFile,
readdir: mockReaddir,
}));
const { loadPoliciesFromToml: load } = await import(
'./policy-toml-loader.js'
);
const getPolicyTier = (_dir: string) => 1;
const result = await load(
ApprovalMode.DEFAULT,
['/policies'],
getPolicyTier,
);
expect(result.rules).toHaveLength(0);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].errorType).toBe('schema_validation');
expect(result.errors[0].details).toContain('priority');
expect(result.errors[0].details).toContain('>= 0');
expect(result.errors[0].details).toContain('must be >= 0');
});
});
});

View File

@@ -1,394 +0,0 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {
type PolicyRule,
PolicyDecision,
type ApprovalMode,
} from '@google/gemini-cli-core';
import fs from 'node:fs/promises';
import path from 'node:path';
import toml from '@iarna/toml';
import { z, type ZodError } from 'zod';
/**
* Schema for a single policy rule in the TOML file (before transformation).
*/
const PolicyRuleSchema = z.object({
toolName: z.union([z.string(), z.array(z.string())]).optional(),
mcpName: z.string().optional(),
argsPattern: z.string().optional(),
commandPrefix: z.union([z.string(), z.array(z.string())]).optional(),
commandRegex: z.string().optional(),
decision: z.nativeEnum(PolicyDecision),
// Priority must be in range [0, 999] to prevent tier overflow.
// With tier transformation (tier + priority/1000), this ensures:
// - Tier 1 (default): range [1.000, 1.999]
// - Tier 2 (user): range [2.000, 2.999]
// - Tier 3 (admin): range [3.000, 3.999]
priority: z
.number({
required_error: 'priority is required',
invalid_type_error: 'priority must be a number',
})
.int({ message: 'priority must be an integer' })
.min(0, { message: 'priority must be >= 0' })
.max(999, {
message:
'priority must be <= 999 to prevent tier overflow. Priorities >= 1000 would jump to the next tier.',
}),
modes: z.array(z.string()).optional(),
});
/**
* Schema for the entire policy TOML file.
*/
const PolicyFileSchema = z.object({
rule: z.array(PolicyRuleSchema),
});
/**
* Type for a raw policy rule from TOML (before transformation).
*/
type PolicyRuleToml = z.infer<typeof PolicyRuleSchema>;
/**
* Types of errors that can occur while loading policy files.
*/
export type PolicyFileErrorType =
| 'file_read'
| 'toml_parse'
| 'schema_validation'
| 'rule_validation'
| 'regex_compilation';
/**
* Detailed error information for policy file loading failures.
*/
export interface PolicyFileError {
filePath: string;
fileName: string;
tier: 'default' | 'user' | 'admin';
ruleIndex?: number;
errorType: PolicyFileErrorType;
message: string;
details?: string;
suggestion?: string;
}
/**
* Result of loading policies from TOML files.
*/
export interface PolicyLoadResult {
rules: PolicyRule[];
errors: PolicyFileError[];
}
/**
* Escapes special regex characters in a string for use in a regex pattern.
* This is used for commandPrefix to ensure literal string matching.
*
* @param str The string to escape
* @returns The escaped string safe for use in a regex
*/
function escapeRegex(str: string): string {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
/**
* Converts a tier number to a human-readable tier name.
*/
function getTierName(tier: number): 'default' | 'user' | 'admin' {
if (tier === 1) return 'default';
if (tier === 2) return 'user';
if (tier === 3) return 'admin';
return 'default';
}
/**
* Formats a Zod validation error into a readable error message.
*/
function formatSchemaError(error: ZodError, ruleIndex: number): string {
const issues = error.issues
.map((issue) => {
const path = issue.path.join('.');
return ` - Field "${path}": ${issue.message}`;
})
.join('\n');
return `Invalid policy rule (rule #${ruleIndex + 1}):\n${issues}`;
}
/**
* Validates shell command convenience syntax rules.
* Returns an error message if invalid, or null if valid.
*/
function validateShellCommandSyntax(
rule: PolicyRuleToml,
ruleIndex: number,
): string | null {
const hasCommandPrefix = rule.commandPrefix !== undefined;
const hasCommandRegex = rule.commandRegex !== undefined;
const hasArgsPattern = rule.argsPattern !== undefined;
if (hasCommandPrefix || hasCommandRegex) {
// Must have exactly toolName = "run_shell_command"
if (rule.toolName !== 'run_shell_command' || Array.isArray(rule.toolName)) {
return (
`Rule #${ruleIndex + 1}: commandPrefix and commandRegex can only be used with toolName = "run_shell_command"\n` +
` Found: toolName = ${JSON.stringify(rule.toolName)}\n` +
` Fix: Set toolName = "run_shell_command" (not an array)`
);
}
// Can't combine with argsPattern
if (hasArgsPattern) {
return (
`Rule #${ruleIndex + 1}: cannot use both commandPrefix/commandRegex and argsPattern\n` +
` These fields are mutually exclusive\n` +
` Fix: Use either commandPrefix/commandRegex OR argsPattern, not both`
);
}
// Can't use both commandPrefix and commandRegex
if (hasCommandPrefix && hasCommandRegex) {
return (
`Rule #${ruleIndex + 1}: cannot use both commandPrefix and commandRegex\n` +
` These fields are mutually exclusive\n` +
` Fix: Use either commandPrefix OR commandRegex, not both`
);
}
}
return null;
}
/**
* Transforms a priority number based on the policy tier.
* Formula: tier + priority/1000
*
* @param priority The priority value from the TOML file
* @param tier The tier (1=default, 2=user, 3=admin)
* @returns The transformed priority
*/
function transformPriority(priority: number, tier: number): number {
return tier + priority / 1000;
}
/**
* Loads and parses policies from TOML files in the specified directories.
*
* This function:
* 1. Scans directories for .toml files
* 2. Parses and validates each file
* 3. Transforms rules (commandPrefix, arrays, mcpName, priorities)
* 4. Filters rules by approval mode
* 5. Collects detailed error information for any failures
*
* @param approvalMode The current approval mode (for filtering rules by mode)
* @param policyDirs Array of directory paths to scan for policy files
* @param getPolicyTier Function to determine tier (1-3) for a directory
* @returns Object containing successfully parsed rules and any errors encountered
*/
export async function loadPoliciesFromToml(
approvalMode: ApprovalMode,
policyDirs: string[],
getPolicyTier: (dir: string) => number,
): Promise<PolicyLoadResult> {
const rules: PolicyRule[] = [];
const errors: PolicyFileError[] = [];
for (const dir of policyDirs) {
const tier = getPolicyTier(dir);
const tierName = getTierName(tier);
// Scan directory for all .toml files
let filesToLoad: string[];
try {
const dirEntries = await fs.readdir(dir, { withFileTypes: true });
filesToLoad = dirEntries
.filter((entry) => entry.isFile() && entry.name.endsWith('.toml'))
.map((entry) => entry.name);
} catch (e) {
const error = e as NodeJS.ErrnoException;
if (error.code === 'ENOENT') {
// Directory doesn't exist, skip it (not an error)
continue;
}
errors.push({
filePath: dir,
fileName: path.basename(dir),
tier: tierName,
errorType: 'file_read',
message: `Failed to read policy directory`,
details: error.message,
});
continue;
}
for (const file of filesToLoad) {
const filePath = path.join(dir, file);
try {
// Read file
const fileContent = await fs.readFile(filePath, 'utf-8');
// Parse TOML
let parsed: unknown;
try {
parsed = toml.parse(fileContent);
} catch (e) {
const error = e as Error;
errors.push({
filePath,
fileName: file,
tier: tierName,
errorType: 'toml_parse',
message: 'TOML parsing failed',
details: error.message,
suggestion:
'Check for syntax errors like missing quotes, brackets, or commas',
});
continue;
}
// Validate schema
const validationResult = PolicyFileSchema.safeParse(parsed);
if (!validationResult.success) {
errors.push({
filePath,
fileName: file,
tier: tierName,
errorType: 'schema_validation',
message: 'Schema validation failed',
details: formatSchemaError(validationResult.error, 0),
suggestion:
'Ensure all required fields (decision, priority) are present with correct types',
});
continue;
}
// Validate shell command convenience syntax
for (let i = 0; i < validationResult.data.rule.length; i++) {
const rule = validationResult.data.rule[i];
const validationError = validateShellCommandSyntax(rule, i);
if (validationError) {
errors.push({
filePath,
fileName: file,
tier: tierName,
ruleIndex: i,
errorType: 'rule_validation',
message: 'Invalid shell command syntax',
details: validationError,
});
// Continue to next rule, don't skip the entire file
}
}
// Transform rules
const parsedRules: PolicyRule[] = validationResult.data.rule
.filter((rule) => {
// Filter by mode
if (!rule.modes || rule.modes.length === 0) {
return true;
}
return rule.modes.includes(approvalMode);
})
.flatMap((rule) => {
// Transform commandPrefix/commandRegex to argsPattern
let effectiveArgsPattern = rule.argsPattern;
const commandPrefixes: string[] = [];
if (rule.commandPrefix) {
const prefixes = Array.isArray(rule.commandPrefix)
? rule.commandPrefix
: [rule.commandPrefix];
commandPrefixes.push(...prefixes);
} else if (rule.commandRegex) {
effectiveArgsPattern = `"command":"${rule.commandRegex}`;
}
// Expand command prefixes to multiple patterns
const argsPatterns: Array<string | undefined> =
commandPrefixes.length > 0
? commandPrefixes.map(
(prefix) => `"command":"${escapeRegex(prefix)}`,
)
: [effectiveArgsPattern];
// For each argsPattern, expand toolName arrays
return argsPatterns.flatMap((argsPattern) => {
const toolNames: Array<string | undefined> = rule.toolName
? Array.isArray(rule.toolName)
? rule.toolName
: [rule.toolName]
: [undefined];
// Create a policy rule for each tool name
return toolNames.map((toolName) => {
// Transform mcpName field to composite toolName format
let effectiveToolName: string | undefined;
if (rule.mcpName && toolName) {
effectiveToolName = `${rule.mcpName}__${toolName}`;
} else if (rule.mcpName) {
effectiveToolName = `${rule.mcpName}__*`;
} else {
effectiveToolName = toolName;
}
const policyRule: PolicyRule = {
toolName: effectiveToolName,
decision: rule.decision,
priority: transformPriority(rule.priority, tier),
};
// Compile regex pattern
if (argsPattern) {
try {
policyRule.argsPattern = new RegExp(argsPattern);
} catch (e) {
const error = e as Error;
errors.push({
filePath,
fileName: file,
tier: tierName,
errorType: 'regex_compilation',
message: 'Invalid regex pattern',
details: `Pattern: ${argsPattern}\nError: ${error.message}`,
suggestion:
'Check regex syntax for errors like unmatched brackets or invalid escape sequences',
});
// Skip this rule if regex compilation fails
return null;
}
}
return policyRule;
});
});
})
.filter((rule): rule is PolicyRule => rule !== null);
rules.push(...parsedRules);
} catch (e) {
const error = e as NodeJS.ErrnoException;
// Catch-all for unexpected errors
if (error.code !== 'ENOENT') {
errors.push({
filePath,
fileName: file,
tier: tierName,
errorType: 'file_read',
message: 'Failed to read policy file',
details: error.message,
});
}
}
}
}
return { rules, errors };
}

File diff suppressed because it is too large Load Diff

View File

@@ -6,237 +6,33 @@
import {
type PolicyEngineConfig,
PolicyDecision,
type PolicyRule,
type ApprovalMode,
type PolicyEngine,
type MessageBus,
MessageBusType,
type UpdatePolicy,
Storage,
type PolicySettings,
createPolicyEngineConfig as createCorePolicyEngineConfig,
createPolicyUpdater as createCorePolicyUpdater,
} from '@google/gemini-cli-core';
import { type Settings, getSystemSettingsPath } from './settings.js';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import {
loadPoliciesFromToml,
type PolicyFileError,
} from './policy-toml-loader.js';
// Get the directory name of the current module
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Store policy loading errors to be displayed after UI is ready
let storedPolicyErrors: string[] = [];
function getPolicyDirectories(): string[] {
const DEFAULT_POLICIES_DIR = path.resolve(__dirname, 'policies');
const USER_POLICIES_DIR = Storage.getUserPoliciesDir();
const systemSettingsPath = getSystemSettingsPath();
const ADMIN_POLICIES_DIR = path.join(
path.dirname(systemSettingsPath),
'policies',
);
return [
DEFAULT_POLICIES_DIR,
USER_POLICIES_DIR,
ADMIN_POLICIES_DIR,
].reverse();
}
/**
* Determines the policy tier (1=default, 2=user, 3=admin) for a given directory.
* This is used by the TOML loader to assign priority bands.
*/
function getPolicyTier(dir: string): number {
const DEFAULT_POLICIES_DIR = path.resolve(__dirname, 'policies');
const USER_POLICIES_DIR = Storage.getUserPoliciesDir();
const systemSettingsPath = getSystemSettingsPath();
const ADMIN_POLICIES_DIR = path.join(
path.dirname(systemSettingsPath),
'policies',
);
// Normalize paths for comparison
const normalizedDir = path.resolve(dir);
const normalizedDefault = path.resolve(DEFAULT_POLICIES_DIR);
const normalizedUser = path.resolve(USER_POLICIES_DIR);
const normalizedAdmin = path.resolve(ADMIN_POLICIES_DIR);
if (normalizedDir === normalizedDefault) return 1;
if (normalizedDir === normalizedUser) return 2;
if (normalizedDir === normalizedAdmin) return 3;
// Default to tier 1 if unknown
return 1;
}
/**
* Formats a policy file error for console logging.
*/
function formatPolicyError(error: PolicyFileError): string {
const tierLabel = error.tier.toUpperCase();
let message = `[${tierLabel}] Policy file error in ${error.fileName}:\n`;
message += ` ${error.message}`;
if (error.details) {
message += `\n${error.details}`;
}
if (error.suggestion) {
message += `\n Suggestion: ${error.suggestion}`;
}
return message;
}
import { type Settings } from './settings.js';
export async function createPolicyEngineConfig(
settings: Settings,
approvalMode: ApprovalMode,
): Promise<PolicyEngineConfig> {
const policyDirs = getPolicyDirectories();
// Load policies from TOML files
const { rules: tomlRules, errors } = await loadPoliciesFromToml(
approvalMode,
policyDirs,
getPolicyTier,
);
// Store any errors encountered during TOML loading
// These will be emitted by getPolicyErrorsForUI() after the UI is ready.
if (errors.length > 0) {
storedPolicyErrors = errors.map((error) => formatPolicyError(error));
}
const rules: PolicyRule[] = [...tomlRules];
// Priority system for policy rules:
// - Higher priority numbers win over lower priority numbers
// - When multiple rules match, the highest priority rule is applied
// - Rules are evaluated in order of priority (highest first)
//
// Priority bands (tiers):
// - Default policies (TOML): 1 + priority/1000 (e.g., priority 100 → 1.100)
// - User policies (TOML): 2 + priority/1000 (e.g., priority 100 → 2.100)
// - Admin policies (TOML): 3 + priority/1000 (e.g., priority 100 → 3.100)
//
// This ensures Admin > User > Default hierarchy is always preserved,
// while allowing user-specified priorities to work within each tier.
//
// Settings-based and dynamic rules (all in user tier 2.x):
// 2.95: Tools that the user has selected as "Always Allow" in the interactive UI
// 2.9: MCP servers excluded list (security: persistent server blocks)
// 2.4: Command line flag --exclude-tools (explicit temporary blocks)
// 2.3: Command line flag --allowed-tools (explicit temporary allows)
// 2.2: MCP servers with trust=true (persistent trusted servers)
// 2.1: MCP servers allowed list (persistent general server allows)
//
// TOML policy priorities (before transformation):
// 10: Write tools default to ASK_USER (becomes 1.010 in default tier)
// 15: Auto-edit tool override (becomes 1.015 in default tier)
// 50: Read-only tools (becomes 1.050 in default tier)
// 999: YOLO mode allow-all (becomes 1.999 in default tier)
// MCP servers that are explicitly excluded in settings.mcp.excluded
// Priority: 2.9 (highest in user tier for security - persistent server blocks)
if (settings.mcp?.excluded) {
for (const serverName of settings.mcp.excluded) {
rules.push({
toolName: `${serverName}__*`,
decision: PolicyDecision.DENY,
priority: 2.9,
});
}
}
// Tools that are explicitly excluded in the settings.
// Priority: 2.4 (user tier - explicit temporary blocks)
if (settings.tools?.exclude) {
for (const tool of settings.tools.exclude) {
rules.push({
toolName: tool,
decision: PolicyDecision.DENY,
priority: 2.4,
});
}
}
// Tools that are explicitly allowed in the settings.
// Priority: 2.3 (user tier - explicit temporary allows)
if (settings.tools?.allowed) {
for (const tool of settings.tools.allowed) {
rules.push({
toolName: tool,
decision: PolicyDecision.ALLOW,
priority: 2.3,
});
}
}
// MCP servers that are trusted in the settings.
// Priority: 2.2 (user tier - persistent trusted servers)
if (settings.mcpServers) {
for (const [serverName, serverConfig] of Object.entries(
settings.mcpServers,
)) {
if (serverConfig.trust) {
// Trust all tools from this MCP server
// Using pattern matching for MCP tool names which are formatted as "serverName__toolName"
rules.push({
toolName: `${serverName}__*`,
decision: PolicyDecision.ALLOW,
priority: 2.2,
});
}
}
}
// MCP servers that are explicitly allowed in settings.mcp.allowed
// Priority: 2.1 (user tier - persistent general server allows)
if (settings.mcp?.allowed) {
for (const serverName of settings.mcp.allowed) {
rules.push({
toolName: `${serverName}__*`,
decision: PolicyDecision.ALLOW,
priority: 2.1,
});
}
}
return {
rules,
defaultDecision: PolicyDecision.ASK_USER,
// Explicitly construct PolicySettings from Settings to ensure type safety
// and avoid accidental leakage of other settings properties.
const policySettings: PolicySettings = {
mcp: settings.mcp,
tools: settings.tools,
mcpServers: settings.mcpServers,
};
return createCorePolicyEngineConfig(policySettings, approvalMode);
}
export function createPolicyUpdater(
policyEngine: PolicyEngine,
messageBus: MessageBus,
) {
messageBus.subscribe(
MessageBusType.UPDATE_POLICY,
(message: UpdatePolicy) => {
const toolName = message.toolName;
policyEngine.addRule({
toolName,
decision: PolicyDecision.ALLOW,
// User tier (2) + high priority (950/1000) = 2.95
// This ensures user "always allow" selections are high priority
// but still lose to admin policies (3.xxx) and settings excludes (200)
priority: 2.95,
});
},
);
}
/**
* Gets and clears any policy errors that were stored during config loading.
* This should be called once the UI is ready to display errors.
*
* @returns Array of formatted error messages, or empty array if no errors
*/
export function getPolicyErrorsForUI(): string[] {
const errors = [...storedPolicyErrors];
storedPolicyErrors = []; // Clear after retrieving
return errors;
return createCorePolicyUpdater(policyEngine, messageBus);
}

View File

@@ -96,6 +96,7 @@ describe('BuiltinCommandLoader', () => {
mockConfig = {
getFolderTrust: vi.fn().mockReturnValue(true),
getUseModelRouter: () => false,
getEnableMessageBusIntegration: () => false,
} as unknown as Config;
restoreCommandMock.mockReturnValue({
@@ -187,6 +188,28 @@ describe('BuiltinCommandLoader', () => {
const modelCmd = commands.find((c) => c.name === 'model');
expect(modelCmd).toBeUndefined();
});
it('should include policies command when message bus integration is enabled', async () => {
const mockConfigWithMessageBus = {
...mockConfig,
getEnableMessageBusIntegration: () => true,
} as unknown as Config;
const loader = new BuiltinCommandLoader(mockConfigWithMessageBus);
const commands = await loader.loadCommands(new AbortController().signal);
const policiesCmd = commands.find((c) => c.name === 'policies');
expect(policiesCmd).toBeDefined();
});
it('should exclude policies command when message bus integration is disabled', async () => {
const mockConfigWithoutMessageBus = {
...mockConfig,
getEnableMessageBusIntegration: () => false,
} as unknown as Config;
const loader = new BuiltinCommandLoader(mockConfigWithoutMessageBus);
const commands = await loader.loadCommands(new AbortController().signal);
const policiesCmd = commands.find((c) => c.name === 'policies');
expect(policiesCmd).toBeUndefined();
});
});
describe('BuiltinCommandLoader profile', () => {
@@ -198,6 +221,7 @@ describe('BuiltinCommandLoader profile', () => {
getFolderTrust: vi.fn().mockReturnValue(false),
getUseModelRouter: () => false,
getCheckpointingEnabled: () => false,
getEnableMessageBusIntegration: () => false,
} as unknown as Config;
});

View File

@@ -28,6 +28,7 @@ import { memoryCommand } from '../ui/commands/memoryCommand.js';
import { modelCommand } from '../ui/commands/modelCommand.js';
import { permissionsCommand } from '../ui/commands/permissionsCommand.js';
import { privacyCommand } from '../ui/commands/privacyCommand.js';
import { policiesCommand } from '../ui/commands/policiesCommand.js';
import { profileCommand } from '../ui/commands/profileCommand.js';
import { quitCommand } from '../ui/commands/quitCommand.js';
import { restoreCommand } from '../ui/commands/restoreCommand.js';
@@ -75,6 +76,9 @@ export class BuiltinCommandLoader implements ICommandLoader {
...(this.config?.getUseModelRouter() ? [modelCommand] : []),
...(this.config?.getFolderTrust() ? [permissionsCommand] : []),
privacyCommand,
...(this.config?.getEnableMessageBusIntegration()
? [policiesCommand]
: []),
...(isDevelopment ? [profileCommand] : []),
quitCommand,
restoreCommand(this.config),

View File

@@ -52,7 +52,6 @@ import {
} from '@google/gemini-cli-core';
import { validateAuthMethod } from '../config/auth.js';
import { loadHierarchicalGeminiMemory } from '../config/config.js';
import { getPolicyErrorsForUI } from '../config/policy.js';
import process from 'node:process';
import { useHistory } from './hooks/useHistoryManager.js';
import { useMemoryMonitor } from './hooks/useMemoryMonitor.js';
@@ -937,18 +936,6 @@ Logging in with Google... Please restart Gemini CLI to continue.
};
appEvents.on(AppEvent.LogError, logErrorHandler);
// Emit any policy errors that were stored during config loading
// Only show these when message bus integration is enabled, as policies
// are only active when the message bus is being used.
if (config.getEnableMessageBusIntegration()) {
const policyErrors = getPolicyErrorsForUI();
if (policyErrors.length > 0) {
for (const error of policyErrors) {
appEvents.emit(AppEvent.LogError, error);
}
}
}
return () => {
appEvents.off(AppEvent.OpenDebugConsole, openDebugConsole);
appEvents.off(AppEvent.LogError, logErrorHandler);

View File

@@ -0,0 +1,108 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { policiesCommand } from './policiesCommand.js';
import { CommandKind } from './types.js';
import { MessageType } from '../types.js';
import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
import { type Config, PolicyDecision } from '@google/gemini-cli-core';
describe('policiesCommand', () => {
let mockContext: ReturnType<typeof createMockCommandContext>;
beforeEach(() => {
mockContext = createMockCommandContext();
});
it('should have correct command definition', () => {
expect(policiesCommand.name).toBe('policies');
expect(policiesCommand.description).toBe('Manage policies');
expect(policiesCommand.kind).toBe(CommandKind.BUILT_IN);
expect(policiesCommand.subCommands).toHaveLength(1);
expect(policiesCommand.subCommands![0].name).toBe('list');
});
describe('list subcommand', () => {
it('should show error if config is missing', async () => {
mockContext.services.config = null;
const listCommand = policiesCommand.subCommands![0];
await listCommand.action!(mockContext, '');
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
expect.objectContaining({
type: MessageType.ERROR,
text: 'Error: Config not available.',
}),
expect.any(Number),
);
});
it('should show message when no policies are active', async () => {
const mockPolicyEngine = {
getRules: vi.fn().mockReturnValue([]),
};
mockContext.services.config = {
getPolicyEngine: vi.fn().mockReturnValue(mockPolicyEngine),
} as unknown as Config;
const listCommand = policiesCommand.subCommands![0];
await listCommand.action!(mockContext, '');
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
expect.objectContaining({
type: MessageType.INFO,
text: 'No active policies.',
}),
expect.any(Number),
);
});
it('should list active policies in correct format', async () => {
const mockRules = [
{
decision: PolicyDecision.DENY,
toolName: 'dangerousTool',
priority: 10,
},
{
decision: PolicyDecision.ALLOW,
argsPattern: /safe/,
},
{
decision: PolicyDecision.ASK_USER,
},
];
const mockPolicyEngine = {
getRules: vi.fn().mockReturnValue(mockRules),
};
mockContext.services.config = {
getPolicyEngine: vi.fn().mockReturnValue(mockPolicyEngine),
} as unknown as Config;
const listCommand = policiesCommand.subCommands![0];
await listCommand.action!(mockContext, '');
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
expect.objectContaining({
type: MessageType.INFO,
text: expect.stringContaining('**Active Policies**'),
}),
expect.any(Number),
);
const call = vi.mocked(mockContext.ui.addItem).mock.calls[0];
const content = (call[0] as { text: string }).text;
expect(content).toContain(
'1. **DENY** tool: `dangerousTool` [Priority: 10]',
);
expect(content).toContain('2. **ALLOW** all tools (args match: `safe`)');
expect(content).toContain('3. **ASK_USER** all tools');
});
});
});

View File

@@ -0,0 +1,73 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { CommandKind, type SlashCommand } from './types.js';
import { MessageType } from '../types.js';
const listPoliciesCommand: SlashCommand = {
name: 'list',
description: 'List all active policies',
kind: CommandKind.BUILT_IN,
action: async (context) => {
const { config } = context.services;
if (!config) {
context.ui.addItem(
{
type: MessageType.ERROR,
text: 'Error: Config not available.',
},
Date.now(),
);
return;
}
const policyEngine = config.getPolicyEngine();
const rules = policyEngine.getRules();
if (rules.length === 0) {
context.ui.addItem(
{
type: MessageType.INFO,
text: 'No active policies.',
},
Date.now(),
);
return;
}
let content = '**Active Policies**\n\n';
rules.forEach((rule, index) => {
content += `${index + 1}. **${rule.decision.toUpperCase()}**`;
if (rule.toolName) {
content += ` tool: \`${rule.toolName}\``;
} else {
content += ` all tools`;
}
if (rule.argsPattern) {
content += ` (args match: \`${rule.argsPattern.source}\`)`;
}
if (rule.priority !== undefined) {
content += ` [Priority: ${rule.priority}]`;
}
content += '\n';
});
context.ui.addItem(
{
type: MessageType.INFO,
text: content,
},
Date.now(),
);
},
};
export const policiesCommand: SlashCommand = {
name: 'policies',
description: 'Manage policies',
kind: CommandKind.BUILT_IN,
subCommands: [listPoliciesCommand],
};