Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/core/src/hooks/hookEventHandler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import type { HookPlanner } from './hookPlanner.js';
import type { HookRunner } from './hookRunner.js';
import type { HookAggregator } from './hookAggregator.js';


// Mock debugLogger
const mockDebugLogger = vi.hoisted(() => ({
log: vi.fn(),
Expand Down Expand Up @@ -73,6 +74,9 @@ describe('HookEventHandler', () => {
.mockReturnValue('/test/project/.gemini/tmp/chats/session.json'),
}),
}),
getPolicyEngine: vi.fn().mockReturnValue({
checkHook: vi.fn().mockResolvedValue({ decision: 'allow' }),
}),
} as unknown as Config;

mockHookPlanner = {
Expand Down
96 changes: 91 additions & 5 deletions packages/core/src/hooks/hookEventHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type { Config } from '../config/config.js';
import type { HookPlanner, HookEventContext } from './hookPlanner.js';
import type { HookRunner } from './hookRunner.js';
import type { HookAggregator, AggregatedHookResult } from './hookAggregator.js';
import { HookEventName, HookType } from './types.js';
import { HookEventName, HookType, createHookOutput } from './types.js';
import type {
HookConfig,
HookInput,
Expand All @@ -29,8 +29,10 @@ import type {
PreCompressTrigger,
HookExecutionResult,
McpToolContext,
HookOutput,
} from './types.js';
import { defaultHookTranslator } from './hookTranslator.js';
import { PolicyDecision } from '../policy/types.js';
import type {
GenerateContentParameters,
GenerateContentResponse,
Expand Down Expand Up @@ -298,12 +300,93 @@ export class HookEventHandler {
};
}

// Filter hooks by policy
const policyEngine = this.config.getPolicyEngine();
const allowedConfigs: HookConfig[] = [];
const policyErrors: Error[] = [];
const policyOutputs: HookOutput[] = [];
const policyResults: HookExecutionResult[] = [];

for (let i = 0; i < plan.hookConfigs.length; i++) {
const config = plan.hookConfigs[i];
const { decision, rule } = await policyEngine.checkHook(
config,
eventName,
);
if (decision === PolicyDecision.DENY) {
const reason =
rule?.denyMessage ||
`Blocked by policy rule: ${rule?.source || 'unknown'}`;
debugLogger.warn(
`[HookEventHandler] Hook execution denied by policy: ${config.command}`,
);
const error = new Error(reason);
policyErrors.push(error);

const output = createHookOutput(eventName, {
decision: 'deny',
reason,
});
policyOutputs.push(output);

policyResults.push({
hookConfig: config,
eventName,
success: false,
error,
output,
duration: 0,
});

coreEvents.emitHookStart({
hookName: this.getHookName(config),
eventName,
hookIndex: i + 1,
totalHooks: plan.hookConfigs.length,
});
coreEvents.emitHookEnd({
hookName: this.getHookName(config),
eventName,
success: false,
});
} else {
allowedConfigs.push(config);
}
}

plan.hookConfigs = allowedConfigs;

if (plan.hookConfigs.length === 0) {
if (policyResults.length > 0) {
const aggregated = this.hookAggregator.aggregateResults(
policyResults,
eventName,
);
this.processCommonHookOutputFields(aggregated);
this.logHookExecution(
eventName,
input,
policyResults,
aggregated,
requestContext,
);
return aggregated;
}

return {
success: true,
allOutputs: [],
errors: [],
totalDuration: 0,
};
}

const onHookStart = (config: HookConfig, index: number) => {
coreEvents.emitHookStart({
hookName: this.getHookName(config),
eventName,
hookIndex: index + 1,
totalHooks: plan.hookConfigs.length,
hookIndex: index + 1 + policyResults.length, // Offset by denied hooks to preserve count
totalHooks: plan.hookConfigs.length + policyResults.length,
});
};

Expand Down Expand Up @@ -332,9 +415,12 @@ export class HookEventHandler {
onHookEnd,
);

// Combine policy results (denied hooks) with execution results
const combinedResults = [...policyResults, ...results];

// Aggregate results
const aggregated = this.hookAggregator.aggregateResults(
results,
combinedResults,
eventName,
);

Expand All @@ -345,7 +431,7 @@ export class HookEventHandler {
this.logHookExecution(
eventName,
input,
results,
combinedResults,
aggregated,
requestContext,
);
Expand Down
43 changes: 39 additions & 4 deletions packages/core/src/hooks/hookSystem.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,21 @@ describe('HookSystem Integration', () => {
});

// Provide getMessageBus mock for MessageBus integration tests
(config as unknown as { getMessageBus: () => unknown }).getMessageBus =
() => undefined;
// Provide getMessageBus mock for MessageBus integration tests
(
config as unknown as {
getMessageBus: () => unknown;
getPolicyEngine: () => unknown;
}
).getMessageBus = () => undefined;
(
config as unknown as {
getMessageBus: () => unknown;
getPolicyEngine: () => unknown;
}
).getPolicyEngine = () => ({
checkHook: vi.fn().mockResolvedValue({ decision: 'allow' }),
});

hookSystem = new HookSystem(config);

Expand Down Expand Up @@ -297,8 +310,19 @@ describe('HookSystem Integration', () => {
});

(
configWithDisabled as unknown as { getMessageBus: () => unknown }
configWithDisabled as unknown as {
getMessageBus: () => unknown;
getPolicyEngine: () => unknown;
}
).getMessageBus = () => undefined;
(
configWithDisabled as unknown as {
getMessageBus: () => unknown;
getPolicyEngine: () => unknown;
}
).getPolicyEngine = () => ({
checkHook: vi.fn().mockResolvedValue({ decision: 'allow' }),
});

const systemWithDisabled = new HookSystem(configWithDisabled);
await systemWithDisabled.initialize();
Expand Down Expand Up @@ -362,8 +386,19 @@ describe('HookSystem Integration', () => {
});

(
configForDisabling as unknown as { getMessageBus: () => unknown }
configForDisabling as unknown as {
getMessageBus: () => unknown;
getPolicyEngine: () => unknown;
}
).getMessageBus = () => undefined;
(
configForDisabling as unknown as {
getMessageBus: () => unknown;
getPolicyEngine: () => unknown;
}
).getPolicyEngine = () => ({
checkHook: vi.fn().mockResolvedValue({ decision: 'allow' }),
});

const systemForDisabling = new HookSystem(configForDisabling);
await systemForDisabling.initialize();
Expand Down
17 changes: 15 additions & 2 deletions packages/core/src/hooks/runtimeHooks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,21 @@ describe('Runtime Hooks', () => {
});

// Stub getMessageBus
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(config as any).getMessageBus = () => undefined;

(
config as unknown as {
getMessageBus: () => unknown;
getPolicyEngine: () => unknown;
}
).getMessageBus = () => undefined;
(
config as unknown as {
getMessageBus: () => unknown;
getPolicyEngine: () => unknown;
}
).getPolicyEngine = () => ({
checkHook: vi.fn().mockResolvedValue({ decision: 'allow' }),
});

hookSystem = new HookSystem(config);
});
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/policy/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ describe('createPolicyEngineConfig', () => {
const loadPoliciesSpy = vi.spyOn(tomlLoader, 'loadPoliciesFromToml');
loadPoliciesSpy.mockResolvedValue({
rules: [],
hookRules: [],
checkers: [],
errors: [],
});
Expand Down
4 changes: 4 additions & 0 deletions packages/core/src/policy/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
type PolicyEngineConfig,
PolicyDecision,
type PolicyRule,
type HookRule,
type ApprovalMode,
type PolicySettings,
} from './types.js';
Expand Down Expand Up @@ -197,6 +198,7 @@ export async function createPolicyEngineConfig(
// Load policies from TOML files
const {
rules: tomlRules,
hookRules: tomlHookRules,
checkers: tomlCheckers,
errors,
} = await loadPoliciesFromToml(securePolicyDirs, (p) => {
Expand Down Expand Up @@ -231,6 +233,7 @@ export async function createPolicyEngineConfig(
}

const rules: PolicyRule[] = [...tomlRules];
const hookRules: HookRule[] = [...tomlHookRules];
const checkers = [...tomlCheckers];

// Priority system for policy rules:
Expand Down Expand Up @@ -376,6 +379,7 @@ export async function createPolicyEngineConfig(

return {
rules,
hookRules,
checkers,
defaultDecision: PolicyDecision.ASK_USER,
approvalMode,
Expand Down
Loading