mcpr-core 0.4.54

Core types, traits, protocol, and proxy engine for mcpr crates
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
//! # CSP — Declarative Content Security Policy for widgets
//!
//! This module owns the config types and the merge function that together decide
//! which domains appear in a widget's CSP when mcpr rewrites an MCP response.
//!
//! ## Model
//!
//! A widget's CSP has three independent directive arrays:
//!
//! - `connectDomains` — allowed targets for `fetch`, `WebSocket`, `EventSource`.
//! - `resourceDomains` — allowed sources for scripts, styles, images, fonts, media.
//! - `frameDomains` — allowed sources for nested `<iframe>` content.
//!
//! Each directive carries its own [`DirectivePolicy`] — a list of domains and a
//! [`Mode`] (`extend` or `replace`) that decides how to combine declared domains
//! with whatever the upstream MCP server already returned.
//!
//! A top-level [`CspConfig`] holds one policy per directive plus an optional list
//! of [`WidgetScoped`] entries. Widget entries match resource URIs with glob
//! patterns (e.g. `ui://widget/payment*`) and layer on top of the global policy.
//!
//! ## Merge
//!
//! [`effective_domains`] computes the final domain list for one directive, given
//! upstream domains, a resource URI, and the config. The rules are:
//!
//! 1. If the global directive's mode is `replace`, discard upstream entirely;
//!    otherwise start from upstream minus localhost and the upstream host itself.
//! 2. Append the global directive's declared domains.
//! 3. For each widget entry whose `match` glob matches the resource URI, in
//!    config order, either extend (append) or replace (overwrite) the working
//!    list with the widget's domains for this directive.
//! 4. Prepend the proxy URL and dedupe.
//!
//! Replace semantics are scoped: a global replace only ignores upstream; a
//! widget replace wipes everything accumulated above it.
//!
//! ## Example
//!
//! ```toml
//! [csp.connectDomains]
//! domains = ["api.example.com"]
//! mode    = "extend"
//!
//! [csp.resourceDomains]
//! domains = ["cdn.example.com"]
//! mode    = "extend"
//!
//! [csp.frameDomains]
//! domains = []
//! mode    = "replace"
//!
//! [[csp.widget]]
//! match              = "ui://widget/payment*"
//! connectDomains     = ["api.stripe.com"]
//! connectDomainsMode = "extend"
//! ```

use serde::Deserialize;

/// Merge mode for a single CSP directive.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Mode {
    /// Combine the directive's declared domains with upstream.
    #[default]
    Extend,
    /// Ignore upstream for this directive; use only declared domains.
    Replace,
}

impl std::fmt::Display for Mode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Mode::Extend => write!(f, "extend"),
            Mode::Replace => write!(f, "replace"),
        }
    }
}

/// Which of the three CSP directive arrays a policy targets.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Directive {
    Connect,
    Resource,
    Frame,
}

/// A domain list paired with a merge mode.
///
/// Empty `domains` combined with `Mode::Extend` is a no-op. Empty `domains`
/// combined with `Mode::Replace` explicitly clears the accumulated list.
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(default)]
pub struct DirectivePolicy {
    pub domains: Vec<String>,
    pub mode: Mode,
}

impl DirectivePolicy {
    /// Build a policy that clears the accumulated list — the default for
    /// `frameDomains`, which fails closed unless the operator opts in.
    pub fn strict() -> Self {
        Self {
            domains: Vec::new(),
            mode: Mode::Replace,
        }
    }
}

/// Per-widget override matched by glob on resource URI.
///
/// Directives are addressed as two paired fields: a domains list and a mode.
/// Omitting both pairs for a directive leaves that directive untouched by the
/// widget. Setting `mode = "replace"` with an empty domains list clears the
/// accumulated domains for that directive.
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(default)]
pub struct WidgetScoped {
    /// Glob pattern matched against a resource URI. `*` matches any sequence,
    /// `?` matches one character. Literal everywhere else.
    #[serde(rename = "match")]
    pub match_pattern: String,

    #[serde(rename = "connectDomains")]
    pub connect_domains: Vec<String>,
    #[serde(rename = "connectDomainsMode")]
    pub connect_domains_mode: Mode,

    #[serde(rename = "resourceDomains")]
    pub resource_domains: Vec<String>,
    #[serde(rename = "resourceDomainsMode")]
    pub resource_domains_mode: Mode,

    #[serde(rename = "frameDomains")]
    pub frame_domains: Vec<String>,
    #[serde(rename = "frameDomainsMode")]
    pub frame_domains_mode: Mode,
}

impl WidgetScoped {
    /// Fetch the (domains, mode) pair for one directive.
    fn for_directive(&self, d: Directive) -> (&[String], Mode) {
        match d {
            Directive::Connect => (&self.connect_domains, self.connect_domains_mode),
            Directive::Resource => (&self.resource_domains, self.resource_domains_mode),
            Directive::Frame => (&self.frame_domains, self.frame_domains_mode),
        }
    }
}

/// Complete CSP configuration: three global directives plus widget overrides.
#[derive(Clone, Debug)]
pub struct CspConfig {
    pub connect_domains: DirectivePolicy,
    pub resource_domains: DirectivePolicy,
    pub frame_domains: DirectivePolicy,
    pub widgets: Vec<WidgetScoped>,
}

impl Default for CspConfig {
    /// Defaults to permissive extend for connect and resource, and strict
    /// replace for frame. Frames default strict because nested iframes are
    /// rare in MCP widgets and the blast radius of an accidental allow is high.
    fn default() -> Self {
        Self {
            connect_domains: DirectivePolicy::default(),
            resource_domains: DirectivePolicy::default(),
            frame_domains: DirectivePolicy::strict(),
            widgets: Vec::new(),
        }
    }
}

impl CspConfig {
    fn policy(&self, d: Directive) -> &DirectivePolicy {
        match d {
            Directive::Connect => &self.connect_domains,
            Directive::Resource => &self.resource_domains,
            Directive::Frame => &self.frame_domains,
        }
    }
}

/// Compute the effective domain list for one directive.
///
/// - `upstream_domains` are the values the MCP server declared for this
///   directive; they pass through only when the global mode is `Extend`.
/// - `resource_uri` selects which `[[csp.widget]]` overrides apply.
/// - `upstream_host` is the bare host (no scheme) used to strip upstream
///   self-references that would leak localhost into the proxied CSP.
/// - `proxy_url` is always prepended so hosts let the widget reach the proxy.
pub fn effective_domains(
    cfg: &CspConfig,
    directive: Directive,
    resource_uri: Option<&str>,
    upstream_domains: &[String],
    upstream_host: &str,
    proxy_url: &str,
) -> Vec<String> {
    let global = cfg.policy(directive);

    // 1. Seed from upstream unless the global mode replaces it.
    let mut base: Vec<String> = if global.mode == Mode::Replace {
        Vec::new()
    } else {
        upstream_domains
            .iter()
            .filter(|d| !is_self_reference(d, upstream_host))
            .cloned()
            .collect()
    };

    // 2. Always add the globally declared domains.
    for d in &global.domains {
        push_unique(&mut base, d);
    }

    // 3. Walk widget overrides in config order. A widget with empty domains
    //    and extend mode is a no-op; we skip it to keep the diff clean.
    if let Some(uri) = resource_uri {
        for w in &cfg.widgets {
            if !glob_match(&w.match_pattern, uri) {
                continue;
            }
            let (domains, mode) = w.for_directive(directive);
            if domains.is_empty() && mode == Mode::Extend {
                continue;
            }
            if mode == Mode::Replace {
                base = domains.to_vec();
            } else {
                for d in domains {
                    push_unique(&mut base, d);
                }
            }
        }
    }

    // 4. Prepend proxy URL so the widget can always reach the proxy itself,
    //    then dedupe while preserving first-seen order.
    let mut out = vec![proxy_url.to_string()];
    for d in base {
        push_unique(&mut out, &d);
    }
    out
}

fn push_unique(list: &mut Vec<String>, value: &str) {
    if !list.iter().any(|s| s == value) {
        list.push(value.to_string());
    }
}

/// Returns true if `domain` points at the upstream MCP server itself or at
/// a local loopback address. These values only make sense in dev; the proxy
/// replaces them with its own URL so the widget reaches the proxy instead.
fn is_self_reference(domain: &str, upstream_host: &str) -> bool {
    if domain.contains("localhost") || domain.contains("127.0.0.1") {
        return true;
    }
    !upstream_host.is_empty() && domain.contains(upstream_host)
}

/// Minimal glob matcher over bytes. Supports `*` (any sequence) and `?`
/// (single character). Everything else matches literally.
pub fn glob_match(pattern: &str, input: &str) -> bool {
    glob_rec(pattern.as_bytes(), input.as_bytes())
}

fn glob_rec(p: &[u8], t: &[u8]) -> bool {
    if p.is_empty() {
        return t.is_empty();
    }
    if p[0] == b'*' {
        // `*` matches zero or more characters; try consuming none first, then
        // consume one from the input and retry. Patterns are short (tens of
        // bytes) so the recursion depth stays bounded.
        if glob_rec(&p[1..], t) {
            return true;
        }
        if !t.is_empty() {
            return glob_rec(p, &t[1..]);
        }
        return false;
    }
    if !t.is_empty() && (p[0] == b'?' || p[0] == t[0]) {
        return glob_rec(&p[1..], &t[1..]);
    }
    false
}

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

    // ── helpers ────────────────────────────────────────────────────────────

    fn policy(domains: &[&str], mode: Mode) -> DirectivePolicy {
        DirectivePolicy {
            domains: domains.iter().map(|s| s.to_string()).collect(),
            mode,
        }
    }

    fn widget(pattern: &str, connect: &[&str], mode: Mode) -> WidgetScoped {
        WidgetScoped {
            match_pattern: pattern.to_string(),
            connect_domains: connect.iter().map(|s| s.to_string()).collect(),
            connect_domains_mode: mode,
            ..Default::default()
        }
    }

    fn domains(items: &[&str]) -> Vec<String> {
        items.iter().map(|s| s.to_string()).collect()
    }

    // ── Mode serde ─────────────────────────────────────────────────────────

    #[test]
    fn mode__deserialises_extend() {
        let m: Mode = serde_json::from_str("\"extend\"").unwrap();
        assert_eq!(m, Mode::Extend);
    }

    #[test]
    fn mode__deserialises_replace() {
        let m: Mode = serde_json::from_str("\"replace\"").unwrap();
        assert_eq!(m, Mode::Replace);
    }

    #[test]
    fn mode__default_is_extend() {
        assert_eq!(Mode::default(), Mode::Extend);
    }

    // ── CspConfig defaults ─────────────────────────────────────────────────

    #[test]
    fn csp_config__default_strict_frames() {
        let c = CspConfig::default();
        assert_eq!(c.connect_domains.mode, Mode::Extend);
        assert_eq!(c.resource_domains.mode, Mode::Extend);
        assert_eq!(c.frame_domains.mode, Mode::Replace);
    }

    // ── effective_domains: global extend ───────────────────────────────────

    #[test]
    fn effective__extend_keeps_external_drops_upstream_host() {
        let cfg = CspConfig::default();
        let upstream = domains(&["https://api.external.com", "http://localhost:9000"]);

        let out = effective_domains(
            &cfg,
            Directive::Connect,
            None,
            &upstream,
            "localhost:9000",
            "https://proxy.example.com",
        );

        assert_eq!(
            out,
            domains(&["https://proxy.example.com", "https://api.external.com"])
        );
    }

    #[test]
    fn effective__extend_adds_global_domains() {
        let cfg = CspConfig {
            connect_domains: policy(&["https://api.mine.com"], Mode::Extend),
            ..CspConfig::default()
        };

        let out = effective_domains(
            &cfg,
            Directive::Connect,
            None,
            &domains(&["https://api.external.com"]),
            "upstream.internal",
            "https://proxy.example.com",
        );

        assert_eq!(
            out,
            domains(&[
                "https://proxy.example.com",
                "https://api.external.com",
                "https://api.mine.com",
            ])
        );
    }

    // ── effective_domains: global replace ──────────────────────────────────

    #[test]
    fn effective__replace_ignores_upstream() {
        let cfg = CspConfig {
            connect_domains: policy(&["https://api.mine.com"], Mode::Replace),
            ..CspConfig::default()
        };

        let out = effective_domains(
            &cfg,
            Directive::Connect,
            None,
            &domains(&["https://api.external.com"]),
            "upstream.internal",
            "https://proxy.example.com",
        );

        assert_eq!(
            out,
            domains(&["https://proxy.example.com", "https://api.mine.com"])
        );
    }

    #[test]
    fn effective__replace_with_empty_global_leaves_only_proxy() {
        let cfg = CspConfig {
            connect_domains: policy(&[], Mode::Replace),
            ..CspConfig::default()
        };

        let out = effective_domains(
            &cfg,
            Directive::Connect,
            None,
            &domains(&["https://api.external.com"]),
            "upstream.internal",
            "https://proxy.example.com",
        );

        assert_eq!(out, domains(&["https://proxy.example.com"]));
    }

    // ── effective_domains: widget extend ───────────────────────────────────

    #[test]
    fn effective__widget_extend_adds_on_top_of_global() {
        let cfg = CspConfig {
            connect_domains: policy(&["https://api.mine.com"], Mode::Extend),
            widgets: vec![widget(
                "ui://widget/payment*",
                &["https://api.stripe.com"],
                Mode::Extend,
            )],
            ..CspConfig::default()
        };

        let out = effective_domains(
            &cfg,
            Directive::Connect,
            Some("ui://widget/payment-form"),
            &[],
            "upstream.internal",
            "https://proxy.example.com",
        );

        assert_eq!(
            out,
            domains(&[
                "https://proxy.example.com",
                "https://api.mine.com",
                "https://api.stripe.com",
            ])
        );
    }

    #[test]
    fn effective__widget_with_no_matching_uri_is_ignored() {
        let cfg = CspConfig {
            widgets: vec![widget(
                "ui://widget/payment*",
                &["https://api.stripe.com"],
                Mode::Extend,
            )],
            ..CspConfig::default()
        };

        let out = effective_domains(
            &cfg,
            Directive::Connect,
            Some("ui://widget/search"),
            &[],
            "upstream.internal",
            "https://proxy.example.com",
        );

        assert_eq!(out, domains(&["https://proxy.example.com"]));
    }

    #[test]
    fn effective__widget_without_uri_context_falls_back_to_global() {
        let cfg = CspConfig {
            connect_domains: policy(&["https://api.mine.com"], Mode::Extend),
            widgets: vec![widget("*", &["https://should.not.apply"], Mode::Extend)],
            ..CspConfig::default()
        };

        let out = effective_domains(
            &cfg,
            Directive::Connect,
            None,
            &[],
            "upstream.internal",
            "https://proxy.example.com",
        );

        assert_eq!(
            out,
            domains(&["https://proxy.example.com", "https://api.mine.com"])
        );
    }

    // ── effective_domains: widget replace ──────────────────────────────────

    #[test]
    fn effective__widget_replace_wipes_everything_before_it() {
        let cfg = CspConfig {
            connect_domains: policy(&["https://api.mine.com"], Mode::Extend),
            widgets: vec![widget(
                "ui://widget/payment*",
                &["https://api.stripe.com"],
                Mode::Replace,
            )],
            ..CspConfig::default()
        };

        let out = effective_domains(
            &cfg,
            Directive::Connect,
            Some("ui://widget/payment-form"),
            &domains(&["https://api.external.com"]),
            "upstream.internal",
            "https://proxy.example.com",
        );

        assert_eq!(
            out,
            domains(&["https://proxy.example.com", "https://api.stripe.com"])
        );
    }

    #[test]
    fn effective__widget_replace_with_empty_domains_clears_list() {
        let cfg = CspConfig {
            connect_domains: policy(&["https://api.mine.com"], Mode::Extend),
            widgets: vec![widget("ui://widget/*", &[], Mode::Replace)],
            ..CspConfig::default()
        };

        let out = effective_domains(
            &cfg,
            Directive::Connect,
            Some("ui://widget/anything"),
            &domains(&["https://api.external.com"]),
            "upstream.internal",
            "https://proxy.example.com",
        );

        assert_eq!(out, domains(&["https://proxy.example.com"]));
    }

    #[test]
    fn effective__widget_extend_with_empty_domains_is_noop() {
        // An empty + extend widget entry must not change anything, even when
        // it matches the URI. Operators use this shape when they set modes
        // for some directives but not others on the same widget block.
        let cfg = CspConfig {
            connect_domains: policy(&["https://api.mine.com"], Mode::Extend),
            widgets: vec![widget("ui://widget/*", &[], Mode::Extend)],
            ..CspConfig::default()
        };

        let out = effective_domains(
            &cfg,
            Directive::Connect,
            Some("ui://widget/anything"),
            &[],
            "upstream.internal",
            "https://proxy.example.com",
        );

        assert_eq!(
            out,
            domains(&["https://proxy.example.com", "https://api.mine.com"])
        );
    }

    // ── effective_domains: widget ordering ────────────────────────────────

    #[test]
    fn effective__multiple_matching_widgets_apply_in_config_order() {
        let cfg = CspConfig {
            widgets: vec![
                widget("ui://widget/*", &["https://a.com"], Mode::Extend),
                widget("ui://widget/*", &["https://b.com"], Mode::Replace),
                widget("ui://widget/*", &["https://c.com"], Mode::Extend),
            ],
            ..CspConfig::default()
        };

        let out = effective_domains(
            &cfg,
            Directive::Connect,
            Some("ui://widget/anything"),
            &[],
            "upstream.internal",
            "https://proxy.example.com",
        );

        // First widget extends with a.com, second wipes and sets b.com,
        // third extends with c.com. Proxy URL is always prepended last.
        assert_eq!(
            out,
            domains(&[
                "https://proxy.example.com",
                "https://b.com",
                "https://c.com"
            ])
        );
    }

    // ── effective_domains: dedupe ──────────────────────────────────────────

    #[test]
    fn effective__dedupes_across_sources() {
        let cfg = CspConfig {
            connect_domains: policy(&["https://shared.com"], Mode::Extend),
            widgets: vec![widget(
                "ui://widget/*",
                &["https://shared.com"],
                Mode::Extend,
            )],
            ..CspConfig::default()
        };

        let out = effective_domains(
            &cfg,
            Directive::Connect,
            Some("ui://widget/x"),
            &domains(&["https://shared.com"]),
            "upstream.internal",
            "https://proxy.example.com",
        );

        assert_eq!(
            out,
            domains(&["https://proxy.example.com", "https://shared.com"])
        );
    }

    #[test]
    fn effective__dedupes_proxy_url_already_in_upstream() {
        let cfg = CspConfig::default();
        let out = effective_domains(
            &cfg,
            Directive::Connect,
            None,
            &domains(&["https://proxy.example.com", "https://api.external.com"]),
            "upstream.internal",
            "https://proxy.example.com",
        );
        let count = out
            .iter()
            .filter(|d| *d == "https://proxy.example.com")
            .count();
        assert_eq!(count, 1);
    }

    // ── self-reference stripping ───────────────────────────────────────────

    #[test]
    fn effective__strips_localhost() {
        let cfg = CspConfig::default();
        let out = effective_domains(
            &cfg,
            Directive::Connect,
            None,
            &domains(&["http://localhost:9000", "http://127.0.0.1:9000"]),
            "upstream.internal",
            "https://proxy.example.com",
        );
        assert_eq!(out, domains(&["https://proxy.example.com"]));
    }

    #[test]
    fn effective__strips_upstream_host() {
        let cfg = CspConfig::default();
        let out = effective_domains(
            &cfg,
            Directive::Connect,
            None,
            &domains(&["https://upstream.internal", "https://api.external.com"]),
            "upstream.internal",
            "https://proxy.example.com",
        );
        assert_eq!(
            out,
            domains(&["https://proxy.example.com", "https://api.external.com"])
        );
    }

    #[test]
    fn effective__empty_upstream_host_disables_self_stripping() {
        // When the upstream host is unknown (empty), only localhost heuristics
        // remain. External domains pass through.
        let cfg = CspConfig::default();
        let out = effective_domains(
            &cfg,
            Directive::Connect,
            None,
            &domains(&["https://api.external.com"]),
            "",
            "https://proxy.example.com",
        );
        assert_eq!(
            out,
            domains(&["https://proxy.example.com", "https://api.external.com"])
        );
    }

    // ── glob_match ─────────────────────────────────────────────────────────

    #[test]
    fn glob__literal_match() {
        assert!(glob_match("ui://widget/payment", "ui://widget/payment"));
    }

    #[test]
    fn glob__literal_mismatch() {
        assert!(!glob_match("ui://widget/payment", "ui://widget/search"));
    }

    #[test]
    fn glob__star_matches_suffix() {
        assert!(glob_match(
            "ui://widget/payment*",
            "ui://widget/payment-form"
        ));
        assert!(glob_match("ui://widget/payment*", "ui://widget/payment"));
    }

    #[test]
    fn glob__star_matches_any_sequence() {
        assert!(glob_match("ui://*/payment", "ui://widget/payment"));
        assert!(glob_match("ui://*/payment", "ui://nested/a/b/payment"));
    }

    #[test]
    fn glob__double_star_segment() {
        assert!(glob_match("ui://widget/*", "ui://widget/anything"));
    }

    #[test]
    fn glob__question_matches_single_char() {
        assert!(glob_match("ui://widget/a?c", "ui://widget/abc"));
        assert!(!glob_match("ui://widget/a?c", "ui://widget/ac"));
    }

    #[test]
    fn glob__empty_pattern_matches_empty_string_only() {
        assert!(glob_match("", ""));
        assert!(!glob_match("", "anything"));
    }

    #[test]
    fn glob__star_only_matches_anything() {
        assert!(glob_match("*", ""));
        assert!(glob_match("*", "anything"));
    }

    // ── Mode Display ───────────────────────────────────────────────────────

    #[test]
    fn mode__display() {
        assert_eq!(Mode::Extend.to_string(), "extend");
        assert_eq!(Mode::Replace.to_string(), "replace");
    }
}