do-memory-mcp 0.1.46

Model Context Protocol (MCP) server for AI agents
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! Tests for the sandbox module.

use serde_json::json;
use tokio::time::{Duration, timeout};

use super::*;
use crate::types::{ErrorType, ExecutionContext, ExecutionResult, SecurityViolationType};

/// Create a test execution context
fn create_test_context() -> ExecutionContext {
    ExecutionContext::new("test".to_string(), json!({}))
}

/// Set environment once for tests to disable WASM
#[allow(unsafe_code)]
fn set_once() {
    static ONCE: std::sync::Once = std::sync::Once::new();
    ONCE.call_once(|| {
        // SAFETY: test-only env var manipulation
        unsafe {
            std::env::set_var("MCP_USE_WASM", "false");
        }
    });
}

#[tokio::test]
async fn test_simple_execution() {
    set_once();
    // Skip in CI where Node.js sandbox may be unavailable or flaky
    if std::env::var("CI").is_ok() {
        return;
    }
    let sandbox = CodeSandbox::new(SandboxConfig::default()).unwrap();
    let code = "return 1 + 1;";
    let context = create_test_context();

    let result = sandbox.execute(code, context).await.unwrap();

    match result {
        ExecutionResult::Success { .. } => {
            // Success expected
        }
        other => panic!("Expected success, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_console_output() {
    set_once();
    if std::env::var("CI").is_ok() {
        return;
    }
    let sandbox = CodeSandbox::new(SandboxConfig::default()).unwrap();
    let code = r#"
        console.log("Hello");
        console.log("World");
        return "done";
    "#;
    let context = create_test_context();

    let result = sandbox.execute(code, context).await.unwrap();

    match result {
        ExecutionResult::Success { stdout, .. } => {
            assert!(stdout.contains("Hello"));
            assert!(stdout.contains("World"));
        }
        other => panic!("Expected success, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_timeout_enforcement() {
    timeout(Duration::from_secs(10), async {
        set_once();
        let config = SandboxConfig {
            max_execution_time_ms: 500, // 500ms timeout
            ..Default::default()
        };

        let sandbox = CodeSandbox::new(config).unwrap();
        let code = r#"
        let sum = 0;
        for (let i = 0; i !== 10000000000; i++) {
            sum += i;
            if (i % 1000000 === 0) {
                const x = sum;
            }
        }
        return sum;
    "#;
        let context = create_test_context();

        let result = sandbox.execute(code, context).await.unwrap();

        match result {
            ExecutionResult::Timeout { .. } => {
                // Timeout expected
            }
            other => panic!("Expected timeout, got: {:?}", other),
        }
    })
    .await
    .expect("Test timed out after 10 seconds");
}

#[tokio::test]
async fn test_filesystem_blocking() {
    timeout(Duration::from_secs(10), async {
        set_once();
        let sandbox = CodeSandbox::new(SandboxConfig::default()).unwrap();
        let code = r#"
        const fs = require('fs');
        fs.readFileSync('/etc/passwd');
    "#;
        let context = create_test_context();

        let result = sandbox.execute(code, context).await.unwrap();

        match result {
            ExecutionResult::SecurityViolation {
                violation_type: SecurityViolationType::FileSystemAccess,
                ..
            } => {
                // Security violation expected
            }
            other => panic!("Expected security violation, got: {:?}", other),
        }
    })
    .await
    .expect("Test timed out after 10 seconds");
}

#[tokio::test]
async fn test_network_blocking() {
    timeout(Duration::from_secs(10), async {
        set_once();
        let sandbox = CodeSandbox::new(SandboxConfig::default()).unwrap();
        let code = r#"
        const https = require('https');
        https.get('https://example.com');
    "#;
        let context = create_test_context();

        let result = sandbox.execute(code, context).await.unwrap();

        match result {
            ExecutionResult::SecurityViolation {
                violation_type: SecurityViolationType::NetworkAccess,
                ..
            } => {
                // Security violation expected
            }
            other => panic!("Expected security violation, got: {:?}", other),
        }
    })
    .await
    .expect("Test timed out after 10 seconds");
}

#[tokio::test]
async fn test_process_execution_blocking() {
    set_once();
    let sandbox = CodeSandbox::new(SandboxConfig::default()).unwrap();
    let code = r#"
        const { exec } = require('child_process');
        exec('ls -la');
    "#;
    let context = create_test_context();

    let result = sandbox.execute(code, context).await.unwrap();

    match result {
        ExecutionResult::SecurityViolation {
            violation_type: SecurityViolationType::ProcessExecution,
            ..
        } => {
            // Security violation expected
        }
        other => panic!("Expected security violation, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_security_bypass_attempts() {
    set_once();
    let sandbox = CodeSandbox::new(SandboxConfig::default()).unwrap();
    let context = create_test_context();

    // 1. Whitespace bypass
    let code1 = "const fs = require (  'fs'   );";
    let result1 = sandbox.execute(code1, context.clone()).await.unwrap();
    assert!(matches!(
        result1,
        ExecutionResult::SecurityViolation {
            violation_type: SecurityViolationType::FileSystemAccess,
            ..
        }
    ));

    // 2. Template literal bypass
    let code2 = "const fs = require(`fs`);";
    let result2 = sandbox.execute(code2, context.clone()).await.unwrap();
    assert!(matches!(
        result2,
        ExecutionResult::SecurityViolation {
            violation_type: SecurityViolationType::FileSystemAccess,
            ..
        }
    ));

    // 3. Newline bypass
    let code3 = "const fs = require(\n'fs'\n);";
    let result3 = sandbox.execute(code3, context.clone()).await.unwrap();
    assert!(matches!(
        result3,
        ExecutionResult::SecurityViolation {
            violation_type: SecurityViolationType::FileSystemAccess,
            ..
        }
    ));

    // 4. Malicious code (Function constructor)
    let code4 = "const f = new Function('return process');";
    let result4 = sandbox.execute(code4, context.clone()).await.unwrap();
    assert!(matches!(
        result4,
        ExecutionResult::SecurityViolation {
            violation_type: SecurityViolationType::MaliciousCode,
            ..
        }
    ));

    // 5. Runtime obfuscation bypass (split string)
    // This should NOT be caught by detect_security_violations (static analysis),
    // but should fail at runtime because 'require' is shadowed and deleted.
    let code5 = "const r = 'req' + 'uire'; const fs = global[r]('fs');";
    let result5 = sandbox.execute(code5, context.clone()).await.unwrap();
    match result5 {
        ExecutionResult::Error { .. } => {
            // Expected runtime error since require is not available
            // (exact message varies by Node.js version)
        }
        other => panic!(
            "Expected runtime error for split-string bypass, got: {:?}",
            other
        ),
    }
}

#[tokio::test]
async fn test_infinite_loop_detection() {
    timeout(Duration::from_secs(10), async {
        set_once();
        let sandbox = CodeSandbox::new(SandboxConfig::default()).unwrap();
        let code = "while(true) {}";
        let context = create_test_context();

        let result = sandbox.execute(code, context).await.unwrap();

        match result {
            ExecutionResult::SecurityViolation {
                violation_type: SecurityViolationType::InfiniteLoop,
                ..
            } => {
                // Security violation expected
            }
            other => panic!("Expected security violation, got: {:?}", other),
        }
    })
    .await
    .expect("Test timed out after 10 seconds");
}

#[tokio::test]
async fn test_eval_blocking() {
    set_once();
    let sandbox = CodeSandbox::new(SandboxConfig::default()).unwrap();
    let code = r#"eval("malicious code");"#;
    let context = create_test_context();

    let result = sandbox.execute(code, context).await.unwrap();

    match result {
        ExecutionResult::SecurityViolation {
            violation_type: SecurityViolationType::MaliciousCode,
            ..
        } => {
            // Security violation expected
        }
        other => panic!("Expected security violation, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_syntax_error() {
    set_once();
    if std::env::var("CI").is_ok() {
        return;
    }
    let sandbox = CodeSandbox::new(SandboxConfig::default()).unwrap();
    let code = "const x = ;"; // Invalid syntax
    let context = create_test_context();

    let result = sandbox.execute(code, context).await.unwrap();

    match &result {
        ExecutionResult::Error {
            error_type: ErrorType::Syntax,
            ..
        }
        | ExecutionResult::Error {
            error_type: ErrorType::Runtime,
            ..
        } => {
            // Syntax error expected; newer JS runtimes report as Runtime error
        }
        other => panic!("Expected syntax/runtime error, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_runtime_error() {
    set_once();
    if std::env::var("CI").is_ok() {
        return;
    }
    let sandbox = CodeSandbox::new(SandboxConfig::default()).unwrap();
    let code = r#"
        throw new Error("Runtime error");
    "#;
    let context = create_test_context();

    let result = sandbox.execute(code, context).await.unwrap();

    match result {
        ExecutionResult::Error {
            error_type: ErrorType::Runtime,
            message,
            ..
        } => {
            assert!(message.contains("Runtime error"));
        }
        other => panic!("Expected runtime error, got: {:?}", other),
    }
}

/// Verify the secure wrapper deletes dangerous globals at runtime.
/// This is a pure-Rust test that does NOT require Node.js, so it runs in CI.
/// It validates the defense-in-depth approach: even if static regex checks
/// are bypassed via runtime obfuscation, the globals are unavailable.
#[test]
fn test_wrapper_deletes_dangerous_globals() {
    set_once();
    let sandbox = CodeSandbox::new(SandboxConfig::default()).unwrap();
    let wrapper = sandbox
        .create_secure_wrapper("1+1", &create_test_context())
        .unwrap();

    // Core dangerous globals must be deleted from the global scope
    assert!(
        wrapper.contains("delete global.process"),
        "Wrapper must delete global.process"
    );
    assert!(
        wrapper.contains("delete global.require"),
        "Wrapper must delete global.require"
    );
    assert!(
        wrapper.contains("delete global.eval"),
        "Wrapper must delete global.eval to prevent runtime obfuscation bypass"
    );
    assert!(
        wrapper.contains("delete global.Function"),
        "Wrapper must delete global.Function to prevent runtime obfuscation bypass"
    );
}

/// Verify the pre-flight Node.js check works.
/// When node is available, CodeSandbox::new succeeds; when unavailable, it errors.
#[tokio::test]
async fn test_preflight_node_check() {
    set_once();
    if which::which("node").is_ok() {
        let result = CodeSandbox::new(SandboxConfig::default());
        assert!(
            result.is_ok(),
            "CodeSandbox::new should succeed when node is available"
        );
    } else {
        // Node not in PATH — should return an error, not panic
        let result = CodeSandbox::new(SandboxConfig::default());
        assert!(
            result.is_err(),
            "CodeSandbox::new should error when node is not in PATH"
        );
    }
}

/// Verify runtime blocking of eval/Function when static regex is bypassed.
/// Requires Node.js, so skipped in CI.
#[tokio::test]
async fn test_eval_runtime_blocking() {
    timeout(Duration::from_secs(10), async {
        set_once();
        if std::env::var("CI").is_ok() {
            return;
        }
        let sandbox = CodeSandbox::new(SandboxConfig::default()).unwrap();
        let context = create_test_context();

        // Runtime obfuscation bypass of eval via dynamic property access.
        // Static regex should NOT catch this (split string), but eval is
        // deleted from global scope so it should fail at runtime.
        let code = "const e = 'ev' + 'al'; global[e]('process');";
        let result = sandbox.execute(code, context.clone()).await.unwrap();
        match result {
            ExecutionResult::Error { message, .. } => {
                assert!(
                    message.contains("is not a function")
                        || message.contains("is not defined")
                        || message.contains("cannot read")
                );
            }
            other => panic!("Expected runtime error for eval bypass, got: {:?}", other),
        }

        // Same for Function constructor via runtime obfuscation
        let code2 = "const f = global['Fun' + 'ction']('return process');";
        let result2 = sandbox.execute(code2, context).await.unwrap();
        match result2 {
            ExecutionResult::Error { message, .. } => {
                assert!(
                    message.contains("is not a function")
                        || message.contains("is not defined")
                        || message.contains("cannot read")
                );
            }
            other => panic!(
                "Expected runtime error for Function bypass, got: {:?}",
                other
            ),
        }
    })
    .await
    .expect("Test timed out after 10 seconds");
}

#[tokio::test]
async fn test_code_length_limit() {
    set_once();
    let sandbox = CodeSandbox::new(SandboxConfig::default()).unwrap();
    let code = "a".repeat(100_001); // Exceeds 100KB limit
    let context = create_test_context();

    let result = sandbox.execute(&code, context).await.unwrap();

    match result {
        ExecutionResult::SecurityViolation { .. } => {
            // Security violation expected
        }
        other => panic!("Expected security violation, got: {:?}", other),
    }
}