forge-sandbox 0.6.0

V8 sandbox for executing LLM-generated JavaScript via deno_core
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
//! deno_core op definitions for the Forge sandbox.
//!
//! The `#[op2]` macro generates additional public items (v8 function pointers,
//! metadata structs) that cannot carry doc comments. We suppress `missing_docs`
//! at the module level — all actual functions and types are documented below.
#![allow(missing_docs)]

use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;

use deno_core::op2;
use deno_core::OpState;
use deno_error::JsErrorBox;

use std::collections::HashSet;

use crate::stash::validate_key;
use crate::{ResourceDispatcher, StashDispatcher, ToolDispatcher};

/// Rate limiting state for tool calls within a single execution.
pub(crate) struct ToolCallLimits {
    /// Maximum number of tool calls allowed.
    pub(crate) max_calls: usize,
    /// Maximum size of serialized arguments per call.
    pub(crate) max_args_size: usize,
    /// Number of tool calls made so far.
    pub(crate) calls_made: usize,
}

/// Rate limiting state for stash operations within a single execution.
pub(crate) struct StashCallLimits {
    /// Maximum number of stash operations allowed (None = unlimited).
    pub(crate) max_calls: Option<usize>,
    /// Number of stash operations made so far.
    pub(crate) calls_made: usize,
}

impl StashCallLimits {
    /// Check if the limit has been reached. Returns an error message if so.
    pub(crate) fn check_limit(&mut self) -> Result<(), String> {
        if let Some(max) = self.max_calls {
            if self.calls_made >= max {
                return Err(format!(
                    "stash operation limit reached ({max} calls per execution)"
                ));
            }
        }
        self.calls_made += 1;
        Ok(())
    }
}

/// Log a message from sandbox code.
#[op2(fast)]
pub fn op_forge_log(#[string] msg: &str) {
    tracing::info!(target: "forge::sandbox::js", "{}", msg);
}

/// Store the execution result in OpState.
#[op2(fast)]
pub fn op_forge_set_result(state: &mut OpState, #[string] json: &str) {
    state.put(ExecutionResult(json.to_string()));
}

/// Call a tool on a downstream server via the ToolDispatcher.
///
/// Enforces per-execution rate limiting and argument size limits via
/// [`ToolCallLimits`] stored in OpState.
#[op2]
#[string]
pub async fn op_forge_call_tool(
    op_state: Rc<RefCell<OpState>>,
    #[string] server: String,
    #[string] tool: String,
    #[string] args_json: String,
) -> Result<String, JsErrorBox> {
    tracing::debug!(
        server = %server,
        tool = %tool,
        args_len = args_json.len(),
        "tool call dispatched"
    );

    // Check and increment tool call limits
    {
        let mut st = op_state.borrow_mut();
        let limits = st.borrow_mut::<ToolCallLimits>();
        if limits.calls_made >= limits.max_calls {
            return Err(JsErrorBox::generic(format!(
                "tool call limit exceeded (max {} calls per execution)",
                limits.max_calls
            )));
        }
        if args_json.len() > limits.max_args_size {
            return Err(JsErrorBox::generic(format!(
                "tool call args too large ({} bytes, max {} bytes)",
                args_json.len(),
                limits.max_args_size
            )));
        }
        limits.calls_made += 1;
    }

    let dispatcher = {
        let st = op_state.borrow();
        st.borrow::<Arc<dyn ToolDispatcher>>().clone()
    };

    let args: serde_json::Value = serde_json::from_str(&args_json)
        .map_err(|e| JsErrorBox::generic(format!("invalid JSON args: {e}")))?;

    let result = match dispatcher.call_tool(&server, &tool, args).await {
        Ok(val) => val,
        Err(e) => {
            let known = {
                let st = op_state.borrow();
                st.try_borrow::<KnownTools>()
                    .map(|kt| kt.0.clone())
                    .unwrap_or_default()
            };
            let pairs: Vec<(&str, &str)> = known
                .iter()
                .map(|(s, t)| (s.as_str(), t.as_str()))
                .collect();
            let mut structured = e.to_structured_error(Some(&pairs));
            crate::redact::redact_structured_error(&server, &tool, &mut structured);
            return serde_json::to_string(&structured)
                .map_err(|e| JsErrorBox::generic(format!("error serialization failed: {e}")));
        }
    };

    serde_json::to_string(&result)
        .map_err(|e| JsErrorBox::generic(format!("result serialization failed: {e}")))
}

/// Wrapper for execution results stored in OpState.
pub(crate) struct ExecutionResult(pub(crate) String);

/// Wrapper for the maximum resource content size, stored in OpState.
pub(crate) struct MaxResourceSize(pub(crate) usize);

/// Wrapper for the current server group, stored in OpState.
///
/// Used by stash ops to enforce group isolation. `None` means ungrouped.
pub(crate) struct CurrentGroup(pub(crate) Option<String>);

/// Set of known server names for SR-R6 validation.
///
/// Stored in OpState so `op_forge_read_resource` can reject unknown servers
/// before any dispatch machinery runs.
pub(crate) struct KnownServers(pub(crate) HashSet<String>);

/// Known (server, tool) pairs for structured error fuzzy matching.
///
/// Stored in OpState so tool/resource dispatch errors can produce
/// `{error:true, code:"TOOL_NOT_FOUND", suggested_fix:"Did you mean 'find_symbols'?"}`.
pub(crate) struct KnownTools(pub(crate) Vec<(String, String)>);

/// Validate a resource URI for security.
///
/// Rejects:
/// - URIs with path traversal (`..` as a path segment, including URL-encoded variants)
/// - URIs longer than 2048 bytes
/// - URIs containing null bytes
/// - URIs containing control characters (U+0000..U+001F, U+007F)
pub(crate) fn validate_resource_uri(uri: &str) -> Result<(), String> {
    if uri.len() > 2048 {
        return Err(format!(
            "resource URI too long ({} bytes, max 2048 bytes)",
            uri.len()
        ));
    }
    if uri.bytes().any(|b| b == 0) {
        return Err("resource URI must not contain null bytes".into());
    }
    if uri.chars().any(|c| c.is_control()) {
        return Err("resource URI must not contain control characters".into());
    }
    if has_path_traversal(uri) {
        return Err("resource URI must not contain path traversal".into());
    }
    if let Some(scheme) = extract_uri_scheme(uri) {
        if is_blocked_scheme(&scheme) {
            return Err(format!("URI scheme '{}' is not allowed", scheme));
        }
    }
    Ok(())
}

/// Blocked URI schemes that should never be passed to resource dispatchers.
const BLOCKED_SCHEMES: &[&str] = &[
    "data",
    "javascript",
    "ftp",
    "gopher",
    "telnet",
    "ldap",
    "dict",
];

/// Extract the scheme from a URI (text before `://` or `:`).
/// Returns `None` for schemeless URIs like `some-resource-id`.
fn extract_uri_scheme(uri: &str) -> Option<String> {
    // Check for `://` first (most common)
    if let Some(pos) = uri.find("://") {
        let candidate = &uri[..pos];
        // A valid scheme contains only alphanumeric, +, -, . and starts with a letter
        if !candidate.is_empty()
            && candidate.as_bytes()[0].is_ascii_alphabetic()
            && candidate
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || b == b'+' || b == b'-' || b == b'.')
        {
            return Some(candidate.to_ascii_lowercase());
        }
    }
    // Check for `:` without `//` (e.g., `data:text/plain,...`, `javascript:...`)
    if let Some(pos) = uri.find(':') {
        let candidate = &uri[..pos];
        if !candidate.is_empty()
            && candidate.as_bytes()[0].is_ascii_alphabetic()
            && candidate
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || b == b'+' || b == b'-' || b == b'.')
        {
            return Some(candidate.to_ascii_lowercase());
        }
    }
    None
}

/// Check if a scheme is in the blocklist (case-insensitive, scheme already lowercased).
fn is_blocked_scheme(scheme: &str) -> bool {
    BLOCKED_SCHEMES.contains(&scheme)
}

/// Check if a URI contains path traversal (`..`) as a path segment.
///
/// Checks the raw URI, then percent-decodes and checks again (to catch `%2e%2e`),
/// then double-decodes and checks again (to catch `%252e%252e`).
fn has_path_traversal(uri: &str) -> bool {
    if has_dotdot_segment(uri) {
        return true;
    }
    // Decode once and check
    let decoded = percent_encoding::percent_decode_str(uri).decode_utf8_lossy();
    if has_dotdot_segment(&decoded) {
        return true;
    }
    // Double-decode and check (catches %252e%252e → %2e%2e → ..)
    let double_decoded = percent_encoding::percent_decode_str(&decoded).decode_utf8_lossy();
    if double_decoded != decoded && has_dotdot_segment(&double_decoded) {
        return true;
    }
    false
}

/// Check if a string contains `..` as a path segment (not as part of a filename).
///
/// Matches: `..`, `../`, `/../`, `/..` at end, bare `..`
fn has_dotdot_segment(s: &str) -> bool {
    // Exact match
    if s == ".." {
        return true;
    }
    // Starts with ../
    if s.starts_with("../") {
        return true;
    }
    // Ends with /..
    if s.ends_with("/..") {
        return true;
    }
    // Contains /../ anywhere
    if s.contains("/../") {
        return true;
    }
    false
}

/// Read a resource by URI from a downstream server via the ResourceDispatcher.
///
/// Enforces URI validation (SR-R1), per-execution rate limiting (SR-R3),
/// max resource size truncation (SR-R2), and error redaction (SR-R5).
#[op2]
#[string]
pub async fn op_forge_read_resource(
    op_state: Rc<RefCell<OpState>>,
    #[string] server: String,
    #[string] uri: String,
) -> Result<String, JsErrorBox> {
    tracing::debug!(
        server = %server,
        uri = %uri,
        "resource read dispatched"
    );

    // SR-R1: Validate URI
    validate_resource_uri(&uri).map_err(JsErrorBox::generic)?;

    // SR-R6: Reject unknown server names before dispatch
    {
        let st = op_state.borrow();
        if let Some(known) = st.try_borrow::<KnownServers>() {
            if !known.0.contains(&server) {
                return Err(JsErrorBox::generic(format!("unknown server: '{server}'")));
            }
        }
    }

    // SR-R3: Check and increment tool call limits (shared with tool calls)
    {
        let mut st = op_state.borrow_mut();
        let limits = st.borrow_mut::<ToolCallLimits>();
        if limits.calls_made >= limits.max_calls {
            return Err(JsErrorBox::generic(format!(
                "tool call limit exceeded (max {} calls per execution)",
                limits.max_calls
            )));
        }
        limits.calls_made += 1;
    }

    // Get dispatcher and max_resource_size from OpState
    let (dispatcher, max_resource_size) = {
        let st = op_state.borrow();
        let d = st.borrow::<Arc<dyn ResourceDispatcher>>().clone();
        let max_size = st
            .try_borrow::<MaxResourceSize>()
            .map(|m| m.0)
            .unwrap_or(crate::ipc::DEFAULT_MAX_RESOURCE_SIZE);
        (d, max_size)
    };

    let result = match dispatcher.read_resource(&server, &uri).await {
        Ok(val) => val,
        Err(e) => {
            let known = {
                let st = op_state.borrow();
                st.try_borrow::<KnownTools>()
                    .map(|kt| kt.0.clone())
                    .unwrap_or_default()
            };
            let pairs: Vec<(&str, &str)> = known
                .iter()
                .map(|(s, t)| (s.as_str(), t.as_str()))
                .collect();
            let mut structured = e.to_structured_error(Some(&pairs));
            crate::redact::redact_structured_error(&server, "readResource", &mut structured);
            return serde_json::to_string(&structured)
                .map_err(|e| JsErrorBox::generic(format!("error serialization failed: {e}")));
        }
    };

    // SR-R2: Serialize and truncate if > max_resource_size
    let mut json = serde_json::to_string(&result)
        .map_err(|e| JsErrorBox::generic(format!("result serialization failed: {e}")))?;

    if json.len() > max_resource_size {
        let original_size = json.len();
        let end = floor_char_boundary(&json, max_resource_size);
        json = serde_json::json!({
            "_truncated": true,
            "_data_is_fragment": true,
            "_original_bytes": original_size,
            "_shown_bytes": end,
            "data": &json[..end],
        })
        .to_string();
    }

    Ok(json)
}

fn floor_char_boundary(s: &str, max: usize) -> usize {
    let mut end = max.min(s.len());
    while end > 0 && !s.is_char_boundary(end) {
        end -= 1;
    }
    end
}

/// Store a value in the session stash via the StashDispatcher.
///
/// - `key`: The stash key (alphanumeric + `_-.:`).
/// - `value_json`: JSON-serialized value to store.
/// - `ttl_secs`: TTL in seconds; 0 means use server default.
#[op2]
#[string]
pub async fn op_forge_stash_put(
    op_state: Rc<RefCell<OpState>>,
    #[string] key: String,
    #[string] value_json: String,
    #[smi] ttl_secs: u32,
) -> Result<String, JsErrorBox> {
    // Defense-in-depth: validate key at op boundary before IPC traversal
    validate_key(&key).map_err(|e| JsErrorBox::generic(e.to_string()))?;

    // Check stash operation limit
    if let Some(limits) = op_state.borrow_mut().try_borrow_mut::<StashCallLimits>() {
        limits.check_limit().map_err(JsErrorBox::generic)?;
    }

    let (dispatcher, current_group) = {
        let st = op_state.borrow();
        let d = st.borrow::<Arc<dyn StashDispatcher>>().clone();
        let g = st.borrow::<CurrentGroup>().0.clone();
        (d, g)
    };

    let value: serde_json::Value = serde_json::from_str(&value_json)
        .map_err(|e| JsErrorBox::generic(format!("invalid JSON value: {e}")))?;

    let ttl = if ttl_secs == 0 { None } else { Some(ttl_secs) };

    let result = dispatcher
        .put(&key, value, ttl, current_group)
        .await
        .map_err(|e| JsErrorBox::generic(e.to_string()))?;

    serde_json::to_string(&result)
        .map_err(|e| JsErrorBox::generic(format!("result serialization failed: {e}")))
}

/// Retrieve a value from the session stash via the StashDispatcher.
#[op2]
#[string]
pub async fn op_forge_stash_get(
    op_state: Rc<RefCell<OpState>>,
    #[string] key: String,
) -> Result<String, JsErrorBox> {
    validate_key(&key).map_err(|e| JsErrorBox::generic(e.to_string()))?;

    if let Some(limits) = op_state.borrow_mut().try_borrow_mut::<StashCallLimits>() {
        limits.check_limit().map_err(JsErrorBox::generic)?;
    }

    let (dispatcher, current_group) = {
        let st = op_state.borrow();
        let d = st.borrow::<Arc<dyn StashDispatcher>>().clone();
        let g = st.borrow::<CurrentGroup>().0.clone();
        (d, g)
    };

    let result = dispatcher
        .get(&key, current_group)
        .await
        .map_err(|e| JsErrorBox::generic(e.to_string()))?;

    serde_json::to_string(&result)
        .map_err(|e| JsErrorBox::generic(format!("result serialization failed: {e}")))
}

/// Delete an entry from the session stash via the StashDispatcher.
#[op2]
#[string]
pub async fn op_forge_stash_delete(
    op_state: Rc<RefCell<OpState>>,
    #[string] key: String,
) -> Result<String, JsErrorBox> {
    validate_key(&key).map_err(|e| JsErrorBox::generic(e.to_string()))?;

    if let Some(limits) = op_state.borrow_mut().try_borrow_mut::<StashCallLimits>() {
        limits.check_limit().map_err(JsErrorBox::generic)?;
    }

    let (dispatcher, current_group) = {
        let st = op_state.borrow();
        let d = st.borrow::<Arc<dyn StashDispatcher>>().clone();
        let g = st.borrow::<CurrentGroup>().0.clone();
        (d, g)
    };

    let result = dispatcher
        .delete(&key, current_group)
        .await
        .map_err(|e| JsErrorBox::generic(e.to_string()))?;

    serde_json::to_string(&result)
        .map_err(|e| JsErrorBox::generic(format!("result serialization failed: {e}")))
}

/// List all keys visible to the current group from the session stash.
#[op2]
#[string]
pub async fn op_forge_stash_keys(op_state: Rc<RefCell<OpState>>) -> Result<String, JsErrorBox> {
    if let Some(limits) = op_state.borrow_mut().try_borrow_mut::<StashCallLimits>() {
        limits.check_limit().map_err(JsErrorBox::generic)?;
    }

    let (dispatcher, current_group) = {
        let st = op_state.borrow();
        let d = st.borrow::<Arc<dyn StashDispatcher>>().clone();
        let g = st.borrow::<CurrentGroup>().0.clone();
        (d, g)
    };

    let result = dispatcher
        .keys(current_group)
        .await
        .map_err(|e| JsErrorBox::generic(e.to_string()))?;

    serde_json::to_string(&result)
        .map_err(|e| JsErrorBox::generic(format!("result serialization failed: {e}")))
}

deno_core::extension!(
    forge_ext,
    ops = [
        op_forge_log,
        op_forge_set_result,
        op_forge_call_tool,
        op_forge_read_resource,
        op_forge_stash_put,
        op_forge_stash_get,
        op_forge_stash_delete,
        op_forge_stash_keys
    ],
);

#[cfg(test)]
mod tests {
    use super::*;

    // --- SK-V01: stash key validation rejects control characters ---
    #[test]
    fn sk_v01_stash_key_rejects_control_chars() {
        let err = validate_key("key\x01value").unwrap_err();
        assert!(
            matches!(err, crate::stash::StashError::InvalidKey),
            "expected InvalidKey, got: {err}"
        );
    }

    // --- SK-V02: stash key validation rejects path separators ---
    #[test]
    fn sk_v02_stash_key_rejects_path_separators() {
        assert!(validate_key("key/value").is_err());
        assert!(validate_key("key\\value").is_err());
        assert!(validate_key("../etc/passwd").is_err());
    }

    // --- SK-V03: stash key validation rejects empty and oversized keys ---
    #[test]
    fn sk_v03_stash_key_rejects_empty_and_oversized() {
        assert!(validate_key("").is_err());
        let long_key = "a".repeat(257);
        let err = validate_key(&long_key).unwrap_err();
        assert!(
            matches!(err, crate::stash::StashError::KeyTooLong { len: 257 }),
            "expected KeyTooLong, got: {err}"
        );
    }

    // --- SK-V04: stash key validation accepts valid patterns ---
    #[test]
    fn sk_v04_stash_key_accepts_valid_patterns() {
        assert!(validate_key("simple-key").is_ok());
        assert!(validate_key("key_with.dots:colons").is_ok());
        assert!(validate_key("CamelCase123").is_ok());
        assert!(validate_key("a").is_ok());
        let max_key = "x".repeat(256);
        assert!(validate_key(&max_key).is_ok());
    }

    // --- SK-V05: stash key validation rejects unicode ---
    #[test]
    fn sk_v05_stash_key_rejects_unicode() {
        assert!(validate_key("key\u{0000}null").is_err());
        assert!(validate_key("key with space").is_err());
        assert!(validate_key("emoji\u{1F600}").is_err());
    }

    // --- RS-U04: reject URIs with path traversal (..) ---
    #[test]
    fn rs_u04_rejects_uri_with_path_traversal() {
        assert!(validate_resource_uri("file:///logs/../../../etc/passwd").is_err());
        assert!(validate_resource_uri("file:///..").is_err());
        assert!(validate_resource_uri("..").is_err());
        assert!(validate_resource_uri("a/../../b").is_err());
        // Valid URI without traversal should pass
        assert!(validate_resource_uri("file:///logs/app.log").is_ok());
        assert!(validate_resource_uri("postgres://db/table").is_ok());
    }

    // --- URI-V01: legitimate double dots in filenames are allowed ---
    #[test]
    fn uri_v01_allows_legitimate_double_dots() {
        // Double dots as part of a filename (not a path segment) should be allowed
        assert!(validate_resource_uri("file:///v2..backup").is_ok());
        assert!(validate_resource_uri("file:///data..2024.csv").is_ok());
        assert!(validate_resource_uri("file:///config..old").is_ok());
    }

    // --- URI-V02: URL-encoded traversal (%2e%2e) is blocked ---
    #[test]
    fn uri_v02_blocks_url_encoded_traversal() {
        // %2e = '.', so %2e%2e/%2e%2e = ../../..
        assert!(validate_resource_uri("file:///logs/%2e%2e/%2e%2e/etc/passwd").is_err());
        assert!(validate_resource_uri("file:///%2e%2e/secret").is_err());
    }

    // --- URI-V03: double-encoded traversal (%252e%252e) is blocked ---
    #[test]
    fn uri_v03_blocks_double_encoded_traversal() {
        // %252e decodes to %2e, which decodes to '.'
        assert!(validate_resource_uri("file:///logs/%252e%252e/%252e%252e/etc/passwd").is_err());
    }

    // --- URI-V04: mixed-case encoded traversal is blocked ---
    #[test]
    fn uri_v04_blocks_mixed_case_encoded_traversal() {
        assert!(validate_resource_uri("file:///logs/%2E%2E/secret").is_err());
        assert!(validate_resource_uri("file:///logs/%2e%2E/secret").is_err());
    }

    // --- RS-U05: reject URIs longer than 2048 bytes ---
    #[test]
    fn rs_u05_rejects_uri_longer_than_2048_bytes() {
        let long_uri = "x".repeat(2049);
        let err = validate_resource_uri(&long_uri).unwrap_err();
        assert!(err.contains("too long"), "should mention too long: {err}");

        // Exactly 2048 should be OK
        let ok_uri = "x".repeat(2048);
        assert!(validate_resource_uri(&ok_uri).is_ok());
    }

    // --- RS-U06: reject URIs with null bytes ---
    #[test]
    fn rs_u06_rejects_uri_with_null_bytes() {
        let uri = "file:///logs\0/app.log";
        let err = validate_resource_uri(uri).unwrap_err();
        assert!(err.contains("null"), "should mention null: {err}");
    }

    // --- RS-U07: reject URIs with control characters ---
    #[test]
    fn rs_u07_rejects_uri_with_control_characters() {
        // SOH (0x01)
        let err = validate_resource_uri("file:///logs\x01/app.log").unwrap_err();
        assert!(err.contains("control"), "should mention control: {err}");

        // Tab (0x09)
        assert!(validate_resource_uri("file:///logs\t/app.log").is_err());

        // Newline (0x0A)
        assert!(validate_resource_uri("file:///logs\n/app.log").is_err());

        // DEL (0x7F)
        assert!(validate_resource_uri("file:///logs\x7f/app.log").is_err());
    }

    // --- RS-S04: path traversal attack variants ---
    #[test]
    fn rs_s04_path_traversal_attack_variants() {
        // Classic traversal
        assert!(validate_resource_uri("../../../etc/passwd").is_err());
        // Encoded traversal
        assert!(validate_resource_uri("file:///logs/%2e%2e/%2e%2e/etc/passwd").is_err());
        // Double dots at start
        assert!(validate_resource_uri("..").is_err());
        // Double dots embedded
        assert!(validate_resource_uri("file:///../").is_err());
        // Traversal after normal path
        assert!(validate_resource_uri("file:///a/b/../../../etc/shadow").is_err());
    }

    // --- M2: URI Scheme Validation Tests ---

    #[test]
    fn uri_m2_01_allows_http_scheme() {
        assert!(validate_resource_uri("http://example.com/resource").is_ok());
    }

    #[test]
    fn uri_m2_02_allows_https_scheme() {
        assert!(validate_resource_uri("https://example.com/resource").is_ok());
    }

    #[test]
    fn uri_m2_03_allows_file_scheme() {
        assert!(validate_resource_uri("file:///logs/app.log").is_ok());
    }

    #[test]
    fn uri_m2_04_rejects_data_scheme() {
        let err = validate_resource_uri("data:text/plain;base64,SGVsbG8=").unwrap_err();
        assert!(
            err.contains("not allowed"),
            "expected 'not allowed' in error: {err}"
        );
    }

    #[test]
    fn uri_m2_05_rejects_javascript_scheme() {
        let err = validate_resource_uri("javascript:alert(1)").unwrap_err();
        assert!(err.contains("not allowed"), "error: {err}");
    }

    #[test]
    fn uri_m2_06_rejects_ftp_scheme() {
        let err = validate_resource_uri("ftp://evil.com/malware").unwrap_err();
        assert!(err.contains("not allowed"), "error: {err}");
    }

    #[test]
    fn uri_m2_07_rejects_gopher_scheme() {
        let err = validate_resource_uri("gopher://evil.com/0").unwrap_err();
        assert!(err.contains("not allowed"), "error: {err}");
    }

    #[test]
    fn uri_m2_08_allows_custom_mcp_scheme() {
        // Custom MCP resource URIs should be allowed
        assert!(validate_resource_uri("postgres://db/table").is_ok());
        assert!(validate_resource_uri("redis://localhost:6379/0").is_ok());
        assert!(validate_resource_uri("mongodb://host/db").is_ok());
    }

    #[test]
    fn uri_m2_09_allows_schemeless_uri() {
        // Bare resource identifiers without any scheme
        assert!(validate_resource_uri("some-resource-id").is_ok());
        assert!(validate_resource_uri("table_name").is_ok());
        assert!(validate_resource_uri("logs/2024/app.log").is_ok());
    }

    #[test]
    fn uri_m2_10_case_insensitive_scheme_check() {
        // Mixed case should be blocked
        assert!(validate_resource_uri("JAVASCRIPT:alert(1)").is_err());
        assert!(validate_resource_uri("JavaScript:void(0)").is_err());
        assert!(validate_resource_uri("DATA:text/plain,hello").is_err());
        assert!(validate_resource_uri("FTP://evil.com/file").is_err());
        assert!(validate_resource_uri("Gopher://host/0").is_err());
        assert!(validate_resource_uri("TELNET://host:23").is_err());
        assert!(validate_resource_uri("LDAP://host/dc=com").is_err());
        assert!(validate_resource_uri("DICT://host/define").is_err());
    }

    // --- Phase 7: Stash call limits tests ---

    #[test]
    fn stash_l4_01_stash_calls_count_against_limit() {
        let mut limits = StashCallLimits {
            max_calls: Some(3),
            calls_made: 0,
        };
        assert!(limits.check_limit().is_ok());
        assert!(limits.check_limit().is_ok());
        assert!(limits.check_limit().is_ok());
        // 4th call should fail
        assert!(limits.check_limit().is_err());
    }

    #[test]
    fn stash_l4_02_stash_limit_rejection_message() {
        let mut limits = StashCallLimits {
            max_calls: Some(1),
            calls_made: 0,
        };
        assert!(limits.check_limit().is_ok());
        let err = limits.check_limit().unwrap_err();
        assert!(err.contains("limit reached"), "should mention limit: {err}");
        assert!(
            err.contains("1 calls"),
            "should mention the limit count: {err}"
        );
    }

    #[test]
    fn stash_l4_03_stash_limit_independent_of_tool_limit() {
        // Stash limits track separately from tool call limits
        let mut stash_limits = StashCallLimits {
            max_calls: Some(5),
            calls_made: 0,
        };
        let tool_limits = ToolCallLimits {
            max_calls: 0, // tool calls exhausted
            max_args_size: 1024,
            calls_made: 0,
        };
        // Stash should still work even if tool limit is at 0
        assert!(stash_limits.check_limit().is_ok());
        let _ = tool_limits;
    }

    #[test]
    fn stash_l4_04_stash_limit_configurable() {
        // None means unlimited
        let mut unlimited = StashCallLimits {
            max_calls: None,
            calls_made: 0,
        };
        for _ in 0..1000 {
            assert!(unlimited.check_limit().is_ok());
        }

        // Some(N) means N calls max
        let mut limited = StashCallLimits {
            max_calls: Some(2),
            calls_made: 0,
        };
        assert!(limited.check_limit().is_ok());
        assert!(limited.check_limit().is_ok());
        assert!(limited.check_limit().is_err());
    }
}