forked from deepset-ai/haystack-tutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolicy-testing.ts
More file actions
287 lines (240 loc) · 8.55 KB
/
Copy pathpolicy-testing.ts
File metadata and controls
287 lines (240 loc) · 8.55 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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
/**
* Policy Testing Example
*
* This example demonstrates how to test and validate TealEngine policies
* before deploying them to production.
*/
import { TealEngine } from 'tealtiger';
async function main() {
console.log('=== TealEngine Policy Testing Example ===\n');
// Example 1: Testing a custom policy
console.log('1. Testing Custom Policy');
console.log('------------------------');
const customPolicy = {
tools: {
'chat': { allowed: true },
'file_read': { allowed: true },
'file_write': { allowed: false },
'database_write': { allowed: false }
},
identity: {
agentId: 'test-agent-001',
role: 'assistant',
permissions: ['read', 'chat'],
forbidden: ['write', 'delete']
},
codeExecution: {
allowedLanguages: [],
blockedPatterns: ['eval', 'exec', 'system'],
sandboxRequired: true
},
behavioral: {
costLimit: {
daily: 5.00,
hourly: 1.00
},
rateLimit: {
requests: 50,
window: '1h'
}
}
};
const engine = new TealEngine(customPolicy);
// Test case 1: Allowed action
console.log('\nTest Case 1: Allowed chat action');
const test1 = engine.test({
agentId: 'test-agent-001',
action: 'chat.create',
tool: 'chat',
content: 'Hello, how can I help?'
});
console.log('Result:', test1.allowed ? '✅ PASS' : '❌ FAIL');
console.log('Reason:', test1.reason);
// Test case 2: Blocked action
console.log('\nTest Case 2: Blocked file write');
const test2 = engine.test({
agentId: 'test-agent-001',
action: 'file.write',
tool: 'file_write',
content: 'Write to file'
});
console.log('Result:', !test2.allowed ? '✅ PASS' : '❌ FAIL');
console.log('Reason:', test2.reason);
// Test case 3: Code execution blocked
console.log('\nTest Case 3: Code execution blocked');
const test3 = engine.test({
agentId: 'test-agent-001',
action: 'code.execute',
tool: 'code_execution',
content: 'eval("malicious code")'
});
console.log('Result:', !test3.allowed ? '✅ PASS' : '❌ FAIL');
console.log('Reason:', test3.reason);
console.log('\n---\n');
// Example 2: Policy validation
console.log('2. Policy Validation');
console.log('--------------------');
const validationResult = engine.validate();
console.log('Policy valid:', validationResult.valid ? '✅ YES' : '❌ NO');
if (!validationResult.valid) {
console.log('Errors:', validationResult.errors);
}
console.log('\n---\n');
// Example 3: Testing policy templates
console.log('3. Testing Policy Templates');
console.log('---------------------------');
const templates = [
{ name: 'Customer Support', template: TealEngine.Templates.customerSupport() },
{ name: 'Data Analysis', template: TealEngine.Templates.dataAnalysis() },
{ name: 'Code Generation', template: TealEngine.Templates.codeGeneration() },
{ name: 'Strict Security', template: TealEngine.Templates.strictSecurity() }
];
for (const { name, template } of templates) {
console.log(`\nTemplate: ${name}`);
const templateEngine = new TealEngine(template);
const validation = templateEngine.validate();
console.log('Valid:', validation.valid ? '✅ YES' : '❌ NO');
// Test a common action
const testResult = templateEngine.test({
agentId: 'template-test',
action: 'chat.create',
tool: 'chat',
content: 'Test message'
});
console.log('Chat allowed:', testResult.allowed ? '✅ YES' : '❌ NO');
}
console.log('\n---\n');
// Example 4: Coverage testing
console.log('4. Policy Coverage Testing');
console.log('--------------------------');
const coverageEngine = new TealEngine(customPolicy);
const testScenarios = [
{ name: 'Chat', tool: 'chat', action: 'chat.create' },
{ name: 'File Read', tool: 'file_read', action: 'file.read' },
{ name: 'File Write', tool: 'file_write', action: 'file.write' },
{ name: 'Database Write', tool: 'database_write', action: 'database.write' },
{ name: 'Code Execution', tool: 'code_execution', action: 'code.execute' }
];
console.log('\nTesting coverage for all scenarios:');
const results = testScenarios.map(scenario => {
const result = coverageEngine.test({
agentId: 'test-agent-001',
action: scenario.action,
tool: scenario.tool,
content: `Test ${scenario.name}`
});
return {
scenario: scenario.name,
allowed: result.allowed,
reason: result.reason
};
});
console.log('\nCoverage Report:');
results.forEach(result => {
const status = result.allowed ? '✅ ALLOW' : '❌ BLOCK';
console.log(` ${status} - ${result.scenario}: ${result.reason}`);
});
const coverage = {
total: results.length,
allowed: results.filter(r => r.allowed).length,
blocked: results.filter(r => !r.allowed).length
};
console.log(`\nCoverage: ${coverage.allowed}/${coverage.total} allowed, ${coverage.blocked}/${coverage.total} blocked`);
console.log('\n---\n');
// Example 5: Performance testing
console.log('5. Performance Testing');
console.log('----------------------');
const perfEngine = new TealEngine(customPolicy);
const iterations = 1000;
console.log(`\nRunning ${iterations} policy evaluations...`);
const startTime = Date.now();
for (let i = 0; i < iterations; i++) {
perfEngine.test({
agentId: 'test-agent-001',
action: 'chat.create',
tool: 'chat',
content: `Test message ${i}`
});
}
const endTime = Date.now();
const totalTime = endTime - startTime;
const avgTime = totalTime / iterations;
console.log(`Total time: ${totalTime}ms`);
console.log(`Average time per evaluation: ${avgTime.toFixed(3)}ms`);
console.log(`Throughput: ${(iterations / (totalTime / 1000)).toFixed(0)} evaluations/second`);
// Check if performance meets target (<5ms per evaluation)
const meetsTarget = avgTime < 5;
console.log(`Performance target (<5ms): ${meetsTarget ? '✅ PASS' : '❌ FAIL'}`);
console.log('\n---\n');
// Example 6: Edge case testing
console.log('6. Edge Case Testing');
console.log('--------------------');
const edgeCases = [
{
name: 'Empty content',
test: { agentId: 'test-agent-001', action: 'chat.create', tool: 'chat', content: '' }
},
{
name: 'Very long content',
test: { agentId: 'test-agent-001', action: 'chat.create', tool: 'chat', content: 'x'.repeat(10000) }
},
{
name: 'Special characters',
test: { agentId: 'test-agent-001', action: 'chat.create', tool: 'chat', content: '!@#$%^&*()_+{}[]|\\:";\'<>?,./' }
},
{
name: 'Unicode characters',
test: { agentId: 'test-agent-001', action: 'chat.create', tool: 'chat', content: '你好世界 🌍 مرحبا' }
},
{
name: 'Unknown tool',
test: { agentId: 'test-agent-001', action: 'unknown.action', tool: 'unknown_tool', content: 'test' }
}
];
console.log('\nTesting edge cases:');
edgeCases.forEach(({ name, test }) => {
try {
const result = engine.test(test);
console.log(` ✅ ${name}: ${result.allowed ? 'ALLOW' : 'BLOCK'}`);
} catch (error: any) {
console.log(` ❌ ${name}: ERROR - ${error.message}`);
}
});
console.log('\n---\n');
// Example 7: Policy comparison
console.log('7. Policy Comparison');
console.log('--------------------');
const strictPolicy = TealEngine.Templates.strictSecurity();
const lenientPolicy = TealEngine.Templates.development();
const strictEngine = new TealEngine(strictPolicy);
const lenientEngine = new TealEngine(lenientPolicy);
const comparisonTests = [
{ tool: 'chat', action: 'chat.create' },
{ tool: 'file_write', action: 'file.write' },
{ tool: 'code_execution', action: 'code.execute' },
{ tool: 'database_write', action: 'database.write' }
];
console.log('\nComparing Strict vs Lenient policies:');
console.log('Tool | Strict | Lenient');
console.log('---------------------|--------|--------');
comparisonTests.forEach(({ tool, action }) => {
const strictResult = strictEngine.test({
agentId: 'test',
action,
tool,
content: 'test'
});
const lenientResult = lenientEngine.test({
agentId: 'test',
action,
tool,
content: 'test'
});
const strictStatus = strictResult.allowed ? '✅' : '❌';
const lenientStatus = lenientResult.allowed ? '✅' : '❌';
console.log(`${tool.padEnd(20)} | ${strictStatus} | ${lenientStatus}`);
});
console.log('\n=== Policy Testing Complete ===');
}
// Run the example
main().catch(console.error);