-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhooks-implementation.ts
More file actions
165 lines (148 loc) · 5.95 KB
/
Copy pathhooks-implementation.ts
File metadata and controls
165 lines (148 loc) · 5.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
/**
* Implementación de referencia del hook `before_action` (issue #583).
*
* Este archivo NO se compila ni se ejecuta: documenta cómo consumir una
* `security-policy.json` generada por el Creator. Ver `security-policy-guide.md`.
* El logger original era `src/logger.ts` (pino); aquí se reemplaza por un stub
* para que el archivo se lea de forma autocontenida.
*/
import fs from 'fs';
import path from 'path';
const logger = {
info: (..._args: unknown[]): void => {},
warn: (..._args: unknown[]): void => {},
error: (..._args: unknown[]): void => {},
};
// --- Types ---
interface AllowedCommand {
binary: string;
allowed_args: string[];
}
interface SecurityPolicy {
version: string;
mode: 'allowlist' | 'denylist';
allowed_tools: string[];
allowed_commands: { entries: AllowedCommand[] };
blocked_tool_patterns: string[];
blocked_args_substrings: Record<string, string[]>;
}
// --- Policy Loading (fail-closed) ---
function loadPolicy(): SecurityPolicy {
const policyPath = process.env.SECURITY_POLICY_PATH || path.resolve('./artemisa/security-policy.json');
try {
const raw = JSON.parse(fs.readFileSync(policyPath, 'utf8'));
if (!raw.version || !raw.allowed_commands?.entries) {
throw new Error('Invalid policy schema');
}
return raw as SecurityPolicy;
} catch (err) {
logger.error({ err, policyPath }, '[SECURITY] Error loading security policy');
return {
version: '0.0.0',
mode: 'allowlist',
allowed_tools: [],
allowed_commands: { entries: [] },
blocked_tool_patterns: [''],
blocked_args_substrings: {},
};
}
}
const policy = loadPolicy();
// --- Command Parsing & Validation ---
// Shell metacharacters that indicate injection attempts
const SHELL_METACHAR_PATTERN = /[\$`\(\)<>\n\r\x00\\]/;
function parseCommand(cmd: string): { binary: string; fullCmd: string }[] {
// Split on pipe, semicolon, ampersand (command chaining)
return cmd
.split(/\s*[|;&]\s*/)
.map((s) => s.trim())
.filter(Boolean)
.map((seg) => {
const parts = seg.split(/\s+/);
return { binary: parts[0] ?? '', fullCmd: seg };
});
}
export function validateCommand(command: string): { allowed: boolean; reason?: string } {
const segments = parseCommand(command);
if (segments.length === 0) return { allowed: false, reason: 'Empty command' };
// Block shell metacharacters in the entire command (prevents subshells, backticks, etc.)
if (SHELL_METACHAR_PATTERN.test(command)) {
return { allowed: false, reason: 'Command contains shell metacharacters (possible injection)' };
}
for (const { binary, fullCmd } of segments) {
const entry = policy.allowed_commands.entries.find((e) => e.binary === binary);
if (!entry) return { allowed: false, reason: `Binary "${binary}" not in allowlist` };
if (entry.allowed_args.length > 0) {
const argsStr = fullCmd.slice(binary.length).trim();
if (argsStr.length > 0) {
// Exact match: args must exactly match one of the allowed patterns,
// OR match as a complete prefix followed by a space (word boundary)
const isAllowed = entry.allowed_args.some((p) => argsStr === p || argsStr.startsWith(p + ' '));
if (!isAllowed) {
return {
allowed: false,
reason: `Arguments "${argsStr}" not allowed for "${binary}". Permitted: ${entry.allowed_args.join(', ')}`,
};
}
}
}
}
return { allowed: true };
}
// --- Defense-in-Depth: Denylist ---
function denylistCheck(toolName: string, args: Record<string, unknown>): { blocked: boolean; reason?: string } {
const toolNameLower = toolName.toLowerCase();
for (const pattern of policy.blocked_tool_patterns) {
if (pattern && toolNameLower.includes(pattern.toLowerCase())) {
return { blocked: true, reason: `Tool name matches blocked pattern: "${pattern}"` };
}
}
const serialized = JSON.stringify(args).toLowerCase();
const allBlocked = [
...(policy.blocked_args_substrings['*'] || []),
...(policy.blocked_args_substrings[toolName] || []),
];
for (const substr of allBlocked) {
if (serialized.includes(substr.toLowerCase())) {
return { blocked: true, reason: `Arguments contain blocked pattern: "${substr}"` };
}
}
return { blocked: false };
}
// --- Main Hook ---
export const agentHooks = {
before_action: (toolName: string, args: Record<string, unknown>): boolean => {
if ('bypass_secret' in args) {
logger.warn('[SECURITY] Model attempted to inject bypass_secret — stripped');
delete args.bypass_secret;
}
// Note: admin bypass is now request-scoped and checked by the route handler
// before calling hooks. before_action always enforces policy.
const denyResult = denylistCheck(toolName, args);
if (denyResult.blocked) {
logger.error(`[HOOK BLOCKED] ${denyResult.reason}`);
throw new Error(`HOOK TRIGGERED: Action blocked by security policy — ${denyResult.reason}`);
}
if (policy.allowed_tools.length > 0) {
if (!policy.allowed_tools.includes(toolName)) {
const shellTools = ['execute_bash', 'run_command', 'shell', 'exec'];
if (shellTools.includes(toolName.toLowerCase())) {
const command = (args.command || args.cmd || args.script || '') as string;
const result = validateCommand(command);
if (!result.allowed) {
logger.error(`[HOOK BLOCKED] Command rejected: ${result.reason}`);
throw new Error(
`HOOK TRIGGERED: Command blocked — ${result.reason}. Only allowlisted operations are permitted.`,
);
}
logger.info(`[HOOK OK] Command validated: ${command.slice(0, 80)}`);
return true;
}
logger.error(`[HOOK BLOCKED] Tool "${toolName}" not in allowlist — fail-closed`);
throw new Error(`HOOK TRIGGERED: Tool "${toolName}" not in allowlist. Undeclared actions fail closed.`);
}
}
logger.info(`[HOOK OK] Action authorized: ${toolName}`);
return true;
},
};