rust-kgdb 0.3.11 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,469 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * HyperMind Secure Agent Sandbox Demo
4
+ *
5
+ * This demonstrates the WASM sandbox security model for enterprise agent deployment.
6
+ * Each agent runs in isolated memory with capability-based access control.
7
+ *
8
+ * SECURITY FEATURES:
9
+ * 1. Memory isolation (64MB default limit per agent)
10
+ * 2. CPU time limits (10s default, fuel metering)
11
+ * 3. Capability-based access control
12
+ * 4. Proxied scope for safe KG operations
13
+ * 5. Full execution trace for audit compliance
14
+ *
15
+ * ENTERPRISE USE CASES:
16
+ * - Fraud detection agents with restricted write access
17
+ * - Compliance agents with read-only KG access
18
+ * - Multi-tenant environments with isolated execution
19
+ */
20
+
21
+ const http = require('http')
22
+
23
+ const KGDB_ENDPOINT = process.env.KGDB_ENDPOINT || 'http://localhost:30080'
24
+
25
+ // =====================================================================
26
+ // CAPABILITY MODEL - Mirrors Rust sandbox.rs
27
+ // =====================================================================
28
+
29
+ /**
30
+ * Capability enum matching rust-kgdb sandbox
31
+ * @see crates/hypermind-runtime/src/sandbox.rs
32
+ */
33
+ const Capability = {
34
+ ReadKG: 'ReadKG', // SPARQL SELECT/CONSTRUCT
35
+ WriteKG: 'WriteKG', // SPARQL INSERT/DELETE
36
+ ExecuteTool: 'ExecuteTool', // Execute morphism tools
37
+ SpawnAgent: 'SpawnAgent', // Spawn sub-agents
38
+ HttpAccess: 'HttpAccess', // External HTTP APIs
39
+ FileRead: 'FileRead', // Filesystem read (restricted)
40
+ FileWrite: 'FileWrite', // Filesystem write (restricted)
41
+ }
42
+
43
+ /**
44
+ * Sandbox configuration
45
+ */
46
+ function createSandboxConfig(overrides = {}) {
47
+ return {
48
+ maxMemoryBytes: 64 * 1024 * 1024, // 64MB default
49
+ maxExecutionTime: 10000, // 10s in ms
50
+ capabilities: new Set([
51
+ Capability.ReadKG,
52
+ Capability.ExecuteTool
53
+ ]),
54
+ fuelLimit: 10_000_000, // ~10M operations
55
+ ...overrides
56
+ }
57
+ }
58
+
59
+ // =====================================================================
60
+ // AGENT PROFILES - Enterprise Security Templates
61
+ // =====================================================================
62
+
63
+ /**
64
+ * Fraud Detection Agent - Read KG, Execute Tools, NO Write
65
+ * Use case: Analyze transactions for circular patterns without modifying data
66
+ */
67
+ const FRAUD_DETECTOR_PROFILE = {
68
+ name: 'fraud-detector',
69
+ description: 'Analyzes knowledge graph for fraud patterns',
70
+ config: createSandboxConfig({
71
+ capabilities: new Set([
72
+ Capability.ReadKG,
73
+ Capability.ExecuteTool
74
+ ]),
75
+ maxMemoryBytes: 128 * 1024 * 1024, // 128MB for complex queries
76
+ maxExecutionTime: 30000 // 30s for deep analysis
77
+ }),
78
+ allowedQueries: [
79
+ 'SPARQL SELECT',
80
+ 'SPARQL CONSTRUCT'
81
+ ],
82
+ blockedOperations: [
83
+ 'INSERT',
84
+ 'DELETE',
85
+ 'DROP',
86
+ 'CLEAR'
87
+ ]
88
+ }
89
+
90
+ /**
91
+ * Compliance Agent - Read-only, External HTTP for reporting
92
+ */
93
+ const COMPLIANCE_AGENT_PROFILE = {
94
+ name: 'compliance-checker',
95
+ description: 'Validates regulatory compliance without modifications',
96
+ config: createSandboxConfig({
97
+ capabilities: new Set([
98
+ Capability.ReadKG,
99
+ Capability.HttpAccess // For sending reports
100
+ ]),
101
+ maxMemoryBytes: 64 * 1024 * 1024,
102
+ maxExecutionTime: 60000 // 60s for comprehensive checks
103
+ })
104
+ }
105
+
106
+ /**
107
+ * Admin Agent - Full access (use with caution)
108
+ */
109
+ const ADMIN_AGENT_PROFILE = {
110
+ name: 'admin-agent',
111
+ description: 'Full administrative access - requires explicit authorization',
112
+ config: createSandboxConfig({
113
+ capabilities: new Set([
114
+ Capability.ReadKG,
115
+ Capability.WriteKG,
116
+ Capability.ExecuteTool,
117
+ Capability.SpawnAgent,
118
+ Capability.HttpAccess
119
+ ]),
120
+ maxMemoryBytes: 256 * 1024 * 1024,
121
+ fuelLimit: 100_000_000 // 100M operations
122
+ })
123
+ }
124
+
125
+ // =====================================================================
126
+ // SANDBOX EXECUTION SIMULATION
127
+ // =====================================================================
128
+
129
+ /**
130
+ * Simulated sandbox execution with capability checking
131
+ */
132
+ class SecureAgentSandbox {
133
+ constructor(profile) {
134
+ this.profile = profile
135
+ this.config = profile.config
136
+ this.trace = []
137
+ this.fuelConsumed = 0
138
+ this.memoryUsed = 0
139
+ }
140
+
141
+ /**
142
+ * Check if capability is granted
143
+ */
144
+ hasCapability(cap) {
145
+ return this.config.capabilities.has(cap)
146
+ }
147
+
148
+ /**
149
+ * Execute SPARQL query with capability check
150
+ */
151
+ async kgQuery(sparql) {
152
+ // Check capability
153
+ if (!this.hasCapability(Capability.ReadKG)) {
154
+ const error = `CAPABILITY_DENIED: ${this.profile.name} lacks ReadKG capability`
155
+ this.trace.push({ type: 'error', message: error })
156
+ throw new Error(error)
157
+ }
158
+
159
+ // Check for blocked operations
160
+ if (this.profile.blockedOperations) {
161
+ for (const blocked of this.profile.blockedOperations) {
162
+ if (sparql.toUpperCase().includes(blocked)) {
163
+ const error = `OPERATION_BLOCKED: ${blocked} not allowed for ${this.profile.name}`
164
+ this.trace.push({ type: 'error', message: error })
165
+ throw new Error(error)
166
+ }
167
+ }
168
+ }
169
+
170
+ // Simulate fuel consumption
171
+ this.fuelConsumed += sparql.length * 100 // ~100 fuel per char
172
+ if (this.config.fuelLimit && this.fuelConsumed > this.config.fuelLimit) {
173
+ throw new Error('FUEL_EXHAUSTED: Execution limit exceeded')
174
+ }
175
+
176
+ // Record trace
177
+ this.trace.push({
178
+ type: 'kg_query',
179
+ timestamp: new Date().toISOString(),
180
+ query: sparql.substring(0, 100) + (sparql.length > 100 ? '...' : ''),
181
+ fuelUsed: sparql.length * 100
182
+ })
183
+
184
+ // Execute actual query
185
+ return executeSparql(sparql)
186
+ }
187
+
188
+ /**
189
+ * Execute SPARQL update with capability check
190
+ */
191
+ async kgInsert(updateSparql) {
192
+ if (!this.hasCapability(Capability.WriteKG)) {
193
+ const error = `CAPABILITY_DENIED: ${this.profile.name} lacks WriteKG capability`
194
+ this.trace.push({ type: 'error', message: error })
195
+ throw new Error(error)
196
+ }
197
+
198
+ this.trace.push({
199
+ type: 'kg_insert',
200
+ timestamp: new Date().toISOString(),
201
+ update: updateSparql.substring(0, 100) + '...'
202
+ })
203
+
204
+ // Would execute actual insert in production
205
+ return { success: true, triplesInserted: 0 }
206
+ }
207
+
208
+ /**
209
+ * Get execution trace for audit
210
+ */
211
+ getTrace() {
212
+ return {
213
+ agent: this.profile.name,
214
+ capabilities: Array.from(this.config.capabilities),
215
+ fuelConsumed: this.fuelConsumed,
216
+ fuelLimit: this.config.fuelLimit,
217
+ memoryUsed: this.memoryUsed,
218
+ entries: this.trace
219
+ }
220
+ }
221
+ }
222
+
223
+ // =====================================================================
224
+ // HTTP UTILITIES
225
+ // =====================================================================
226
+
227
+ function executeSparql(query) {
228
+ return new Promise((resolve, reject) => {
229
+ const url = new URL(KGDB_ENDPOINT)
230
+ const options = {
231
+ hostname: url.hostname,
232
+ port: url.port || 80,
233
+ path: '/dataset/query',
234
+ method: 'POST',
235
+ headers: {
236
+ 'Content-Type': 'application/sparql-query',
237
+ 'Accept': 'application/json'
238
+ }
239
+ }
240
+
241
+ const req = http.request(options, (res) => {
242
+ let data = ''
243
+ res.on('data', chunk => data += chunk)
244
+ res.on('end', () => {
245
+ try {
246
+ if (res.statusCode >= 400) {
247
+ reject(new Error(`HTTP ${res.statusCode}: ${data}`))
248
+ } else {
249
+ resolve(JSON.parse(data))
250
+ }
251
+ } catch (e) {
252
+ resolve({ raw: data })
253
+ }
254
+ })
255
+ })
256
+
257
+ req.on('error', reject)
258
+ req.write(query)
259
+ req.end()
260
+ })
261
+ }
262
+
263
+ // =====================================================================
264
+ // DEMO SCENARIOS
265
+ // =====================================================================
266
+
267
+ async function demoFraudDetectorAgent() {
268
+ console.log('\n' + '='.repeat(70))
269
+ console.log('DEMO 1: Fraud Detection Agent (Read-Only)')
270
+ console.log('='.repeat(70))
271
+
272
+ const sandbox = new SecureAgentSandbox(FRAUD_DETECTOR_PROFILE)
273
+
274
+ console.log('\nAgent Profile:')
275
+ console.log(` Name: ${sandbox.profile.name}`)
276
+ console.log(` Capabilities: ${Array.from(sandbox.config.capabilities).join(', ')}`)
277
+ console.log(` Memory Limit: ${sandbox.config.maxMemoryBytes / 1024 / 1024}MB`)
278
+ console.log(` Fuel Limit: ${sandbox.config.fuelLimit.toLocaleString()} operations`)
279
+
280
+ // Test 1: Allowed read query
281
+ console.log('\n[TEST 1] Execute allowed SELECT query:')
282
+ try {
283
+ const result = await sandbox.kgQuery(`
284
+ SELECT ?prof ?course WHERE {
285
+ ?prof <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://swat.cse.lehigh.edu/onto/univ-bench.owl#Professor> .
286
+ ?prof <http://swat.cse.lehigh.edu/onto/univ-bench.owl#teacherOf> ?course .
287
+ } LIMIT 5
288
+ `)
289
+ console.log(' SUCCESS: Query executed')
290
+ console.log(` Results: ${result.results?.bindings?.length || 0} rows`)
291
+ } catch (e) {
292
+ console.log(` ERROR: ${e.message}`)
293
+ }
294
+
295
+ // Test 2: Blocked INSERT attempt
296
+ console.log('\n[TEST 2] Attempt blocked INSERT operation:')
297
+ try {
298
+ await sandbox.kgQuery(`
299
+ INSERT DATA { <http://example.org/test> <http://example.org/p> "malicious" }
300
+ `)
301
+ console.log(' ERROR: Should have been blocked!')
302
+ } catch (e) {
303
+ console.log(` BLOCKED: ${e.message}`)
304
+ }
305
+
306
+ // Test 3: Attempt write capability
307
+ console.log('\n[TEST 3] Attempt kgInsert without WriteKG capability:')
308
+ try {
309
+ await sandbox.kgInsert('INSERT DATA { <http://test> <http://p> "value" }')
310
+ console.log(' ERROR: Should have been denied!')
311
+ } catch (e) {
312
+ console.log(` DENIED: ${e.message}`)
313
+ }
314
+
315
+ // Print audit trace
316
+ console.log('\n[AUDIT TRACE]')
317
+ const trace = sandbox.getTrace()
318
+ console.log(JSON.stringify(trace, null, 2))
319
+
320
+ return trace
321
+ }
322
+
323
+ async function demoCapabilityEscalation() {
324
+ console.log('\n' + '='.repeat(70))
325
+ console.log('DEMO 2: Capability Escalation Prevention')
326
+ console.log('='.repeat(70))
327
+
328
+ const sandbox = new SecureAgentSandbox(COMPLIANCE_AGENT_PROFILE)
329
+
330
+ console.log('\nAgent Profile:')
331
+ console.log(` Name: ${sandbox.profile.name}`)
332
+ console.log(` Capabilities: ${Array.from(sandbox.config.capabilities).join(', ')}`)
333
+
334
+ // Test: Try to spawn sub-agent without capability
335
+ console.log('\n[TEST] Attempt to use SpawnAgent capability:')
336
+ if (!sandbox.hasCapability(Capability.SpawnAgent)) {
337
+ console.log(' DENIED: Agent cannot spawn sub-agents')
338
+ }
339
+
340
+ // Test: Try to execute tool without capability
341
+ console.log('\n[TEST] Attempt to use ExecuteTool capability:')
342
+ if (!sandbox.hasCapability(Capability.ExecuteTool)) {
343
+ console.log(' DENIED: Agent cannot execute morphism tools')
344
+ }
345
+ }
346
+
347
+ async function demoResourceLimits() {
348
+ console.log('\n' + '='.repeat(70))
349
+ console.log('DEMO 3: Resource Limit Enforcement')
350
+ console.log('='.repeat(70))
351
+
352
+ // Create sandbox with very low fuel limit
353
+ const restrictedProfile = {
354
+ name: 'restricted-agent',
355
+ description: 'Agent with very low resource limits',
356
+ config: createSandboxConfig({
357
+ fuelLimit: 1000, // Very low limit
358
+ capabilities: new Set([Capability.ReadKG])
359
+ })
360
+ }
361
+
362
+ const sandbox = new SecureAgentSandbox(restrictedProfile)
363
+
364
+ console.log('\nAgent Profile:')
365
+ console.log(` Fuel Limit: ${sandbox.config.fuelLimit} operations (very low)`)
366
+
367
+ // Execute queries until fuel exhausted
368
+ console.log('\n[TEST] Execute queries until fuel exhausted:')
369
+ let queryCount = 0
370
+ while (sandbox.fuelConsumed < sandbox.config.fuelLimit + 5000) {
371
+ queryCount++
372
+ try {
373
+ await sandbox.kgQuery(`SELECT * WHERE { ?s ?p ?o } LIMIT 1`)
374
+ console.log(` Query ${queryCount}: OK (fuel: ${sandbox.fuelConsumed})`)
375
+ } catch (e) {
376
+ if (e.message.includes('FUEL_EXHAUSTED')) {
377
+ console.log(` Query ${queryCount}: FUEL_EXHAUSTED after ${sandbox.fuelConsumed} operations`)
378
+ break
379
+ }
380
+ // Network errors are OK for demo
381
+ queryCount++
382
+ }
383
+ if (queryCount > 5) break // Safety limit for demo
384
+ }
385
+ }
386
+
387
+ async function demoSecurityComparison() {
388
+ console.log('\n' + '='.repeat(70))
389
+ console.log('SECURITY MODEL COMPARISON')
390
+ console.log('='.repeat(70))
391
+
392
+ console.log(`
393
+ | Feature | HyperMind WASM | LangChain | AutoGPT |
394
+ |----------------------------|-------------------|-------------|-------------|
395
+ | Memory Isolation | YES (wasmtime) | NO | NO |
396
+ | CPU Time Limits | YES (fuel meter) | NO | NO |
397
+ | Capability-Based Access | YES (7 caps) | NO | NO |
398
+ | Execution Trace/Audit | YES (full) | Partial | NO |
399
+ | Multi-tenant Safe | YES | NO | NO |
400
+ | Secure by Default | YES | NO | NO |
401
+
402
+ HyperMind Security Model (crates/hypermind-runtime/src/sandbox.rs):
403
+
404
+ Capabilities:
405
+ - ReadKG: SPARQL SELECT/CONSTRUCT only
406
+ - WriteKG: SPARQL INSERT/DELETE (requires explicit grant)
407
+ - ExecuteTool: Run morphism tools (validated type contracts)
408
+ - SpawnAgent: Create sub-agents (controlled hierarchy)
409
+ - HttpAccess: External API calls (audit logged)
410
+ - FileRead: Restricted filesystem read
411
+ - FileWrite: Restricted filesystem write
412
+
413
+ Limits (configurable per agent):
414
+ - Memory: 64MB default (wasmtime linear memory)
415
+ - CPU: 10s default (fuel metering ~10M operations)
416
+ - Operations: All proxied through host imports
417
+
418
+ Host Imports (WASM can only call these):
419
+ - kg_query(ptr, len) -> i32
420
+ - kg_insert(ptr, len) -> i32
421
+ - tool_call(tool_ptr, tool_len, input_ptr, input_len) -> i32
422
+ - log(ptr, len)
423
+ `)
424
+ }
425
+
426
+ // =====================================================================
427
+ // MAIN
428
+ // =====================================================================
429
+
430
+ async function main() {
431
+ console.log('='.repeat(70))
432
+ console.log('HyperMind WASM Sandbox Security Demo')
433
+ console.log('Enterprise-Grade Agent Isolation')
434
+ console.log('='.repeat(70))
435
+ console.log(`\nKGDB Endpoint: ${KGDB_ENDPOINT}`)
436
+
437
+ await demoSecurityComparison()
438
+
439
+ try {
440
+ await demoFraudDetectorAgent()
441
+ } catch (e) {
442
+ console.log(`\nNote: KGDB connection failed (expected if cluster not running)`)
443
+ console.log(`Error: ${e.message}`)
444
+ }
445
+
446
+ await demoCapabilityEscalation()
447
+ await demoResourceLimits()
448
+
449
+ console.log('\n' + '='.repeat(70))
450
+ console.log('CONCLUSION: HyperMind WASM Sandbox')
451
+ console.log('='.repeat(70))
452
+ console.log(`
453
+ Enterprise Security Benefits:
454
+
455
+ 1. COMPLIANCE: Full audit trail of all agent operations
456
+ 2. ISOLATION: Each agent runs in isolated WASM memory
457
+ 3. CONTROL: Fine-grained capability-based access control
458
+ 4. LIMITS: Configurable memory and CPU constraints
459
+ 5. SAFETY: Secure-by-default with opt-in permissions
460
+
461
+ This is the ONLY agent framework with mathematical security guarantees
462
+ backed by WebAssembly runtime isolation.
463
+
464
+ Implementation: crates/hypermind-runtime/src/sandbox.rs
465
+ Build: cargo build -p hypermind-runtime --features wasm-sandbox
466
+ `)
467
+ }
468
+
469
+ main().catch(console.error)