bssh 2.0.1

Parallel SSH command execution tool for cluster management
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
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
// Copyright 2025 Lablup Inc. and Jeongkyu Shin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Pattern-based matchers for file transfer filtering.
//!
//! This module provides matchers that use pattern matching:
//! - [`GlobMatcher`] - Matches paths using glob patterns (e.g., "*.key", "*.{tar,zip}")
//! - [`RegexMatcher`] - Matches paths using regular expressions

use std::path::Path;

use anyhow::{Context, Result};
use glob::Pattern;
use regex::{Regex, RegexBuilder};

use super::policy::Matcher;

/// Mode for glob pattern matching.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum GlobMatchMode {
    /// Match against the full path or just the filename.
    /// This is the default and most permissive mode.
    /// A pattern like "*.key" will match "/etc/secret.key" because
    /// the filename "secret.key" matches the pattern.
    #[default]
    PathOrFilename,
    /// Match against the full path only.
    /// A pattern like "*.key" will NOT match "/etc/secret.key" because
    /// the full path doesn't start with "*".
    /// Use patterns like "**/*.key" for recursive matching.
    FullPathOnly,
    /// Match against the filename only.
    /// A pattern like "*.key" will match any file ending in .key
    /// regardless of its directory.
    FilenameOnly,
}

/// Matches paths using glob patterns.
///
/// Glob patterns support wildcards and character classes:
/// - `*` matches any sequence of characters (except path separators in some modes)
/// - `?` matches any single character
/// - `[abc]` matches any character in the set
/// - `[!abc]` or `[^abc]` matches any character not in the set
/// - `**` matches zero or more directories (when enabled)
///
/// # Matching Behavior
///
/// By default, patterns are matched against both the full path and the filename.
/// This means a pattern like "*.key" will match:
/// - "secret.key" (direct match)
/// - "/etc/ssl/private.key" (filename match)
///
/// Use [`GlobMatchMode`] for more explicit control:
/// - `PathOrFilename` (default): Try full path, then filename
/// - `FullPathOnly`: Only match against full path (use "**/*.key" for recursive)
/// - `FilenameOnly`: Only match against filename
///
/// # Security Note
///
/// For security-sensitive filtering, consider using `FullPathOnly` mode with
/// explicit path patterns to avoid unintended matches.
///
/// # Example
///
/// ```rust
/// use bssh::server::filter::pattern::GlobMatcher;
/// use bssh::server::filter::policy::Matcher;
/// use std::path::Path;
///
/// let matcher = GlobMatcher::new("*.key").unwrap();
///
/// assert!(matcher.matches(Path::new("secret.key")));
/// assert!(matcher.matches(Path::new("/etc/ssl/private.key")));
/// assert!(!matcher.matches(Path::new("keyboard.txt")));
/// ```
#[derive(Debug, Clone)]
pub struct GlobMatcher {
    pattern: Pattern,
    raw: String,
    mode: GlobMatchMode,
}

impl GlobMatcher {
    /// Create a new glob matcher with default mode (PathOrFilename).
    ///
    /// # Arguments
    ///
    /// * `pattern` - The glob pattern to match against
    ///
    /// # Errors
    ///
    /// Returns an error if the pattern is invalid.
    ///
    /// # Example
    ///
    /// ```rust
    /// use bssh::server::filter::pattern::GlobMatcher;
    ///
    /// let matcher = GlobMatcher::new("*.{key,pem}").unwrap();
    /// ```
    pub fn new(pattern: &str) -> Result<Self> {
        Self::with_mode(pattern, GlobMatchMode::default())
    }

    /// Create a new glob matcher with explicit match mode.
    ///
    /// # Arguments
    ///
    /// * `pattern` - The glob pattern to match against
    /// * `mode` - The matching mode to use
    ///
    /// # Errors
    ///
    /// Returns an error if the pattern is invalid.
    ///
    /// # Example
    ///
    /// ```rust
    /// use bssh::server::filter::pattern::{GlobMatcher, GlobMatchMode};
    ///
    /// // Only match full paths
    /// let matcher = GlobMatcher::with_mode("**/*.key", GlobMatchMode::FullPathOnly).unwrap();
    /// ```
    pub fn with_mode(pattern: &str, mode: GlobMatchMode) -> Result<Self> {
        let glob_pattern =
            Pattern::new(pattern).with_context(|| format!("Invalid glob pattern: {}", pattern))?;

        Ok(Self {
            pattern: glob_pattern,
            raw: pattern.to_string(),
            mode,
        })
    }

    /// Get the raw pattern string.
    pub fn pattern(&self) -> &str {
        &self.raw
    }

    /// Get the match mode.
    pub fn mode(&self) -> GlobMatchMode {
        self.mode
    }

    /// Check if the filename matches the pattern.
    fn matches_filename(&self, path: &Path) -> bool {
        if let Some(filename) = path.file_name() {
            if let Some(filename_str) = filename.to_str() {
                return self.pattern.matches(filename_str);
            }
        }
        false
    }
}

impl Matcher for GlobMatcher {
    fn matches(&self, path: &Path) -> bool {
        match self.mode {
            GlobMatchMode::PathOrFilename => {
                // Try matching the full path first
                if self.pattern.matches_path(path) {
                    return true;
                }
                // Also try matching just the filename for patterns like "*.key"
                self.matches_filename(path)
            }
            GlobMatchMode::FullPathOnly => self.pattern.matches_path(path),
            GlobMatchMode::FilenameOnly => self.matches_filename(path),
        }
    }

    fn clone_box(&self) -> Box<dyn Matcher> {
        Box::new(self.clone())
    }

    fn pattern_description(&self) -> String {
        format!("glob:{}", self.raw)
    }
}

/// Matches paths using regular expressions.
///
/// Regular expressions provide the most flexibility for pattern matching,
/// but are also more complex and potentially slower than glob patterns.
///
/// # Example
///
/// ```rust
/// use bssh::server::filter::pattern::RegexMatcher;
/// use bssh::server::filter::policy::Matcher;
/// use std::path::Path;
///
/// // Match files with version numbers in names
/// let matcher = RegexMatcher::new(r".*-v\d+\.\d+\.\d+\.tar\.gz$").unwrap();
///
/// assert!(matcher.matches(Path::new("/releases/app-v1.2.3.tar.gz")));
/// assert!(!matcher.matches(Path::new("/releases/app.tar.gz")));
/// ```
#[derive(Debug, Clone)]
pub struct RegexMatcher {
    regex: Regex,
    raw: String,
}

impl RegexMatcher {
    /// Default size limit for compiled regex (1MB)
    const DEFAULT_SIZE_LIMIT: usize = 1024 * 1024;

    /// Create a new regex matcher.
    ///
    /// # Arguments
    ///
    /// * `pattern` - The regular expression pattern
    ///
    /// # Errors
    ///
    /// Returns an error if the regex pattern is invalid or exceeds size limits.
    ///
    /// # Security
    ///
    /// Uses RegexBuilder with size limits to prevent ReDoS attacks.
    /// The compiled regex is limited to 1MB by default.
    ///
    /// # Example
    ///
    /// ```rust
    /// use bssh::server::filter::pattern::RegexMatcher;
    ///
    /// // Match private key files
    /// let matcher = RegexMatcher::new(r"(?i)\.key$|id_rsa$|id_dsa$").unwrap();
    /// ```
    pub fn new(pattern: &str) -> Result<Self> {
        let regex = RegexBuilder::new(pattern)
            .size_limit(Self::DEFAULT_SIZE_LIMIT)
            .dfa_size_limit(Self::DEFAULT_SIZE_LIMIT)
            .build()
            .with_context(|| format!("Invalid regex pattern: {}", pattern))?;

        Ok(Self {
            regex,
            raw: pattern.to_string(),
        })
    }

    /// Create a new regex matcher with custom size limits.
    ///
    /// # Arguments
    ///
    /// * `pattern` - The regular expression pattern
    /// * `size_limit` - Maximum size in bytes for the compiled regex
    ///
    /// # Errors
    ///
    /// Returns an error if the regex pattern is invalid or exceeds the size limit.
    pub fn with_size_limit(pattern: &str, size_limit: usize) -> Result<Self> {
        let regex = RegexBuilder::new(pattern)
            .size_limit(size_limit)
            .dfa_size_limit(size_limit)
            .build()
            .with_context(|| format!("Invalid regex pattern: {}", pattern))?;

        Ok(Self {
            regex,
            raw: pattern.to_string(),
        })
    }

    /// Get the raw pattern string.
    pub fn pattern(&self) -> &str {
        &self.raw
    }
}

impl Matcher for RegexMatcher {
    fn matches(&self, path: &Path) -> bool {
        self.regex.is_match(&path.to_string_lossy())
    }

    fn clone_box(&self) -> Box<dyn Matcher> {
        Box::new(self.clone())
    }

    fn pattern_description(&self) -> String {
        format!("regex:{}", self.raw)
    }
}

/// A matcher that combines multiple matchers with OR logic.
///
/// The combined matcher returns true if any of its inner matchers match.
///
/// # Example
///
/// ```rust
/// use bssh::server::filter::pattern::{GlobMatcher, CombinedMatcher};
/// use bssh::server::filter::policy::Matcher;
/// use std::path::Path;
///
/// let matcher = CombinedMatcher::new(vec![
///     Box::new(GlobMatcher::new("*.key").unwrap()),
///     Box::new(GlobMatcher::new("*.pem").unwrap()),
/// ]);
///
/// assert!(matcher.matches(Path::new("secret.key")));
/// assert!(matcher.matches(Path::new("cert.pem")));
/// assert!(!matcher.matches(Path::new("document.txt")));
/// ```
#[derive(Debug, Clone)]
pub struct CombinedMatcher {
    matchers: Vec<Box<dyn Matcher>>,
}

impl CombinedMatcher {
    /// Create a new combined matcher.
    ///
    /// # Arguments
    ///
    /// * `matchers` - The matchers to combine with OR logic
    pub fn new(matchers: Vec<Box<dyn Matcher>>) -> Self {
        Self { matchers }
    }

    /// Add a matcher to the combination.
    pub fn with_matcher(mut self, matcher: Box<dyn Matcher>) -> Self {
        self.matchers.push(matcher);
        self
    }

    /// Get the number of matchers in this combination.
    pub fn len(&self) -> usize {
        self.matchers.len()
    }

    /// Check if the combination is empty.
    pub fn is_empty(&self) -> bool {
        self.matchers.is_empty()
    }
}

impl Matcher for CombinedMatcher {
    fn matches(&self, path: &Path) -> bool {
        self.matchers.iter().any(|m| m.matches(path))
    }

    fn clone_box(&self) -> Box<dyn Matcher> {
        Box::new(self.clone())
    }

    fn pattern_description(&self) -> String {
        let descriptions: Vec<_> = self
            .matchers
            .iter()
            .map(|m| m.pattern_description())
            .collect();
        format!("any_of:[{}]", descriptions.join(", "))
    }
}

/// A matcher that inverts another matcher's result.
///
/// # Example
///
/// ```rust
/// use bssh::server::filter::pattern::{GlobMatcher, NotMatcher};
/// use bssh::server::filter::policy::Matcher;
/// use std::path::Path;
///
/// // Match everything EXCEPT .key files
/// let matcher = NotMatcher::new(Box::new(GlobMatcher::new("*.key").unwrap()));
///
/// assert!(!matcher.matches(Path::new("secret.key")));
/// assert!(matcher.matches(Path::new("document.txt")));
/// ```
#[derive(Debug, Clone)]
pub struct NotMatcher {
    inner: Box<dyn Matcher>,
}

impl NotMatcher {
    /// Create a new negating matcher.
    ///
    /// # Arguments
    ///
    /// * `inner` - The matcher to invert
    pub fn new(inner: Box<dyn Matcher>) -> Self {
        Self { inner }
    }
}

impl Matcher for NotMatcher {
    fn matches(&self, path: &Path) -> bool {
        !self.inner.matches(path)
    }

    fn clone_box(&self) -> Box<dyn Matcher> {
        Box::new(self.clone())
    }

    fn pattern_description(&self) -> String {
        format!("not({})", self.inner.pattern_description())
    }
}

/// A matcher that combines multiple matchers with AND logic.
///
/// The combined matcher returns true only if ALL of its inner matchers match.
///
/// # Example
///
/// ```rust
/// use bssh::server::filter::pattern::{GlobMatcher, AllMatcher};
/// use bssh::server::filter::path::PrefixMatcher;
/// use bssh::server::filter::policy::Matcher;
/// use std::path::Path;
///
/// // Match .env files only in /home directory
/// let matcher = AllMatcher::new(vec![
///     Box::new(GlobMatcher::new("*.env").unwrap()),
///     Box::new(PrefixMatcher::new("/home")),
/// ]);
///
/// assert!(matcher.matches(Path::new("/home/user/.env")));
/// assert!(!matcher.matches(Path::new("/etc/.env"))); // Not in /home
/// assert!(!matcher.matches(Path::new("/home/user/config.txt"))); // Not .env
/// ```
#[derive(Debug, Clone)]
pub struct AllMatcher {
    matchers: Vec<Box<dyn Matcher>>,
}

impl AllMatcher {
    /// Create a new AND matcher.
    ///
    /// # Arguments
    ///
    /// * `matchers` - The matchers to combine with AND logic
    pub fn new(matchers: Vec<Box<dyn Matcher>>) -> Self {
        Self { matchers }
    }

    /// Add a matcher to the combination.
    pub fn with_matcher(mut self, matcher: Box<dyn Matcher>) -> Self {
        self.matchers.push(matcher);
        self
    }

    /// Get the number of matchers in this combination.
    pub fn len(&self) -> usize {
        self.matchers.len()
    }

    /// Check if the combination is empty.
    pub fn is_empty(&self) -> bool {
        self.matchers.is_empty()
    }
}

impl Matcher for AllMatcher {
    fn matches(&self, path: &Path) -> bool {
        // Empty matcher matches nothing
        if self.matchers.is_empty() {
            return false;
        }
        self.matchers.iter().all(|m| m.matches(path))
    }

    fn clone_box(&self) -> Box<dyn Matcher> {
        Box::new(self.clone())
    }

    fn pattern_description(&self) -> String {
        let descriptions: Vec<_> = self
            .matchers
            .iter()
            .map(|m| m.pattern_description())
            .collect();
        format!("all_of:[{}]", descriptions.join(", "))
    }
}

/// Enum representing composite matcher logic.
///
/// This provides a unified interface for creating AND, OR, and NOT matchers.
///
/// # Example
///
/// ```rust
/// use bssh::server::filter::pattern::{GlobMatcher, CompositeMatcher};
/// use bssh::server::filter::path::PrefixMatcher;
/// use bssh::server::filter::policy::Matcher;
/// use std::path::Path;
///
/// // Create an AND matcher
/// let and_matcher = CompositeMatcher::and(vec![
///     Box::new(GlobMatcher::new("*.env").unwrap()),
///     Box::new(PrefixMatcher::new("/home")),
/// ]);
///
/// // Create an OR matcher
/// let or_matcher = CompositeMatcher::or(vec![
///     Box::new(GlobMatcher::new("*.key").unwrap()),
///     Box::new(GlobMatcher::new("*.pem").unwrap()),
/// ]);
///
/// // Create a NOT matcher
/// let not_matcher = CompositeMatcher::not(
///     Box::new(PrefixMatcher::new("/home")),
/// );
/// ```
#[derive(Debug, Clone)]
pub enum CompositeMatcher {
    /// All matchers must match (AND logic)
    And(Vec<Box<dyn Matcher>>),
    /// Any matcher must match (OR logic)
    Or(Vec<Box<dyn Matcher>>),
    /// Invert the inner matcher (NOT logic)
    Not(Box<dyn Matcher>),
}

impl CompositeMatcher {
    /// Create an AND composite matcher.
    pub fn and(matchers: Vec<Box<dyn Matcher>>) -> Self {
        CompositeMatcher::And(matchers)
    }

    /// Create an OR composite matcher.
    pub fn or(matchers: Vec<Box<dyn Matcher>>) -> Self {
        CompositeMatcher::Or(matchers)
    }

    /// Create a NOT composite matcher.
    pub fn not(matcher: Box<dyn Matcher>) -> Self {
        CompositeMatcher::Not(matcher)
    }
}

impl Matcher for CompositeMatcher {
    fn matches(&self, path: &Path) -> bool {
        match self {
            CompositeMatcher::And(matchers) => {
                if matchers.is_empty() {
                    return false;
                }
                matchers.iter().all(|m| m.matches(path))
            }
            CompositeMatcher::Or(matchers) => matchers.iter().any(|m| m.matches(path)),
            CompositeMatcher::Not(matcher) => !matcher.matches(path),
        }
    }

    fn clone_box(&self) -> Box<dyn Matcher> {
        Box::new(self.clone())
    }

    fn pattern_description(&self) -> String {
        match self {
            CompositeMatcher::And(matchers) => {
                let descriptions: Vec<_> =
                    matchers.iter().map(|m| m.pattern_description()).collect();
                format!("and:[{}]", descriptions.join(", "))
            }
            CompositeMatcher::Or(matchers) => {
                let descriptions: Vec<_> =
                    matchers.iter().map(|m| m.pattern_description()).collect();
                format!("or:[{}]", descriptions.join(", "))
            }
            CompositeMatcher::Not(matcher) => {
                format!("not({})", matcher.pattern_description())
            }
        }
    }
}

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

    #[test]
    fn test_glob_matcher_basic() {
        let matcher = GlobMatcher::new("*.key").unwrap();

        assert!(matcher.matches(Path::new("secret.key")));
        assert!(matcher.matches(Path::new("/etc/ssl/private.key")));
        assert!(!matcher.matches(Path::new("keyboard.txt")));
        assert!(!matcher.matches(Path::new("key")));
    }

    #[test]
    fn test_glob_matcher_extensions() {
        // Note: The glob crate doesn't support brace expansion like {tar,zip,gz}
        // Test individual patterns instead
        let tar_matcher = GlobMatcher::new("*.tar").unwrap();
        let zip_matcher = GlobMatcher::new("*.zip").unwrap();
        let gz_matcher = GlobMatcher::new("*.gz").unwrap();

        assert!(tar_matcher.matches(Path::new("archive.tar")));
        assert!(zip_matcher.matches(Path::new("archive.zip")));
        assert!(gz_matcher.matches(Path::new("archive.gz")));
        assert!(!tar_matcher.matches(Path::new("archive.rar")));
    }

    #[test]
    fn test_glob_matcher_character_class() {
        let matcher = GlobMatcher::new("file[0-9].txt").unwrap();

        assert!(matcher.matches(Path::new("file1.txt")));
        assert!(matcher.matches(Path::new("file9.txt")));
        assert!(!matcher.matches(Path::new("fileA.txt")));
        assert!(!matcher.matches(Path::new("file.txt")));
    }

    #[test]
    fn test_glob_matcher_question_mark() {
        let matcher = GlobMatcher::new("test?.log").unwrap();

        assert!(matcher.matches(Path::new("test1.log")));
        assert!(matcher.matches(Path::new("testA.log")));
        assert!(!matcher.matches(Path::new("test12.log")));
        assert!(!matcher.matches(Path::new("test.log")));
    }

    #[test]
    fn test_glob_matcher_invalid_pattern() {
        assert!(GlobMatcher::new("[").is_err());
    }

    #[test]
    fn test_glob_matcher_clone() {
        let matcher = GlobMatcher::new("*.pem").unwrap();
        let cloned = matcher.clone_box();

        assert!(cloned.matches(Path::new("cert.pem")));
        assert_eq!(cloned.pattern_description(), "glob:*.pem");
    }

    #[test]
    fn test_regex_matcher_basic() {
        let matcher = RegexMatcher::new(r"\.key$").unwrap();

        assert!(matcher.matches(Path::new("/etc/secret.key")));
        assert!(matcher.matches(Path::new("private.key")));
        assert!(!matcher.matches(Path::new("keyboard.txt")));
    }

    #[test]
    fn test_regex_matcher_case_insensitive() {
        let matcher = RegexMatcher::new(r"(?i)\.exe$").unwrap();

        assert!(matcher.matches(Path::new("program.exe")));
        assert!(matcher.matches(Path::new("PROGRAM.EXE")));
        assert!(matcher.matches(Path::new("Program.Exe")));
    }

    #[test]
    fn test_regex_matcher_complex() {
        let matcher = RegexMatcher::new(r".*-v\d+\.\d+\.\d+\.tar\.gz$").unwrap();

        assert!(matcher.matches(Path::new("/releases/app-v1.2.3.tar.gz")));
        assert!(matcher.matches(Path::new("lib-v10.20.30.tar.gz")));
        assert!(!matcher.matches(Path::new("app.tar.gz")));
        assert!(!matcher.matches(Path::new("app-v1.tar.gz")));
    }

    #[test]
    fn test_regex_matcher_with_size_limit() {
        // Normal pattern should work with default limit
        let matcher = RegexMatcher::with_size_limit(r"test", 1024 * 1024);
        assert!(matcher.is_ok());

        // Very small size limit should reject patterns
        let _result = RegexMatcher::with_size_limit(r"(a+)+", 10);
        // Size limit is applied during compilation
        // Complex patterns may exceed small limits
    }

    #[test]

    fn test_regex_matcher_invalid_pattern() {
        assert!(RegexMatcher::new(r"[").is_err());
    }

    #[test]
    fn test_regex_matcher_clone() {
        let matcher = RegexMatcher::new(r"test").unwrap();
        let cloned = matcher.clone_box();

        assert!(cloned.matches(Path::new("/test/file")));
        assert_eq!(cloned.pattern_description(), "regex:test");
    }

    #[test]
    fn test_combined_matcher_basic() {
        let matcher = CombinedMatcher::new(vec![
            Box::new(GlobMatcher::new("*.key").unwrap()),
            Box::new(GlobMatcher::new("*.pem").unwrap()),
        ]);

        assert!(matcher.matches(Path::new("secret.key")));
        assert!(matcher.matches(Path::new("cert.pem")));
        assert!(!matcher.matches(Path::new("document.txt")));
    }

    #[test]
    fn test_combined_matcher_add() {
        let matcher = CombinedMatcher::new(vec![Box::new(GlobMatcher::new("*.key").unwrap())])
            .with_matcher(Box::new(GlobMatcher::new("*.pem").unwrap()));

        assert_eq!(matcher.len(), 2);
        assert!(matcher.matches(Path::new("cert.pem")));
    }

    #[test]
    fn test_combined_matcher_empty() {
        let matcher = CombinedMatcher::new(vec![]);

        assert!(matcher.is_empty());
        assert!(!matcher.matches(Path::new("anything")));
    }

    #[test]
    fn test_combined_matcher_clone() {
        let matcher = CombinedMatcher::new(vec![
            Box::new(GlobMatcher::new("*.a").unwrap()),
            Box::new(GlobMatcher::new("*.b").unwrap()),
        ]);
        let cloned = matcher.clone_box();

        assert!(cloned.matches(Path::new("file.a")));
        assert!(cloned.matches(Path::new("file.b")));
        assert!(cloned.pattern_description().contains("any_of:"));
    }

    #[test]
    fn test_not_matcher_basic() {
        let matcher = NotMatcher::new(Box::new(GlobMatcher::new("*.key").unwrap()));

        assert!(!matcher.matches(Path::new("secret.key")));
        assert!(matcher.matches(Path::new("document.txt")));
    }

    #[test]
    fn test_not_matcher_clone() {
        let matcher = NotMatcher::new(Box::new(GlobMatcher::new("*.log").unwrap()));
        let cloned = matcher.clone_box();

        assert!(!cloned.matches(Path::new("app.log")));
        assert!(cloned.matches(Path::new("app.txt")));
        assert!(cloned.pattern_description().starts_with("not("));
    }

    #[test]
    fn test_nested_matchers() {
        // Create a complex matcher: not any of (*.key, *.pem)
        let inner = CombinedMatcher::new(vec![
            Box::new(GlobMatcher::new("*.key").unwrap()),
            Box::new(GlobMatcher::new("*.pem").unwrap()),
        ]);
        let matcher = NotMatcher::new(Box::new(inner));

        assert!(!matcher.matches(Path::new("secret.key")));
        assert!(!matcher.matches(Path::new("cert.pem")));
        assert!(matcher.matches(Path::new("document.txt")));
    }

    #[test]
    fn test_glob_matcher_with_paths() {
        // Test path-based patterns
        let matcher = GlobMatcher::new("/etc/**").unwrap();

        assert!(matcher.matches(Path::new("/etc/passwd")));
        assert!(matcher.matches(Path::new("/etc/ssh/sshd_config")));
        // Note: glob behavior for paths can be platform-dependent
    }

    #[test]
    fn test_regex_matcher_path_separators() {
        // Use both forward slashes and backslashes in pattern
        let matcher = RegexMatcher::new(r"/tmp/.*\.tmp$").unwrap();

        assert!(matcher.matches(Path::new("/tmp/file.tmp")));
        assert!(matcher.matches(Path::new("/tmp/subdir/file.tmp")));
        assert!(!matcher.matches(Path::new("/var/file.tmp")));
    }

    #[test]
    fn test_glob_match_mode_full_path_only() {
        // Note: glob crate's matches_path with * matches any chars including path separators
        let matcher = GlobMatcher::with_mode("*.key", GlobMatchMode::FullPathOnly).unwrap();

        assert!(matcher.matches(Path::new("secret.key"))); // Direct match
                                                           // * in glob matches path separators too, so this actually matches
        assert!(matcher.matches(Path::new("/etc/secret.key")));
    }

    #[test]
    fn test_glob_match_mode_filename_only() {
        let matcher = GlobMatcher::with_mode("secret*", GlobMatchMode::FilenameOnly).unwrap();

        assert!(matcher.matches(Path::new("/etc/secret.key")));
        assert!(matcher.matches(Path::new("secret_file.txt")));
        // other.txt doesn't start with secret
        assert!(!matcher.matches(Path::new("/secret/other.txt")));
    }

    #[test]
    fn test_glob_match_mode_default() {
        let matcher = GlobMatcher::new("*.key").unwrap();

        // Default mode matches both full path and filename
        assert!(matcher.matches(Path::new("secret.key")));
        assert!(matcher.matches(Path::new("/etc/ssl/private.key"))); // Matches via filename
        assert_eq!(matcher.mode(), GlobMatchMode::PathOrFilename);
    }

    #[test]
    fn test_glob_matcher_pattern_accessor() {
        let matcher = GlobMatcher::new("*.{key,pem}").unwrap();
        assert_eq!(matcher.pattern(), "*.{key,pem}");
    }

    #[test]
    fn test_regex_matcher_pattern_accessor() {
        let matcher = RegexMatcher::new(r"(?i)\.key$").unwrap();
        assert_eq!(matcher.pattern(), r"(?i)\.key$");
    }

    #[test]
    fn test_combined_matcher_len_and_is_empty() {
        let empty = CombinedMatcher::new(vec![]);
        assert!(empty.is_empty());
        assert_eq!(empty.len(), 0);

        let non_empty = CombinedMatcher::new(vec![
            Box::new(GlobMatcher::new("*.key").unwrap()),
            Box::new(GlobMatcher::new("*.pem").unwrap()),
        ]);
        assert!(!non_empty.is_empty());
        assert_eq!(non_empty.len(), 2);
    }

    #[test]
    fn test_glob_match_mode_enum() {
        // Test that GlobMatchMode implements Default correctly
        assert_eq!(GlobMatchMode::default(), GlobMatchMode::PathOrFilename);

        // Test each mode
        assert_ne!(GlobMatchMode::PathOrFilename, GlobMatchMode::FullPathOnly);
        assert_ne!(GlobMatchMode::PathOrFilename, GlobMatchMode::FilenameOnly);
        assert_ne!(GlobMatchMode::FullPathOnly, GlobMatchMode::FilenameOnly);
    }

    // Tests for AllMatcher (AND logic)
    #[test]
    fn test_all_matcher_basic() {
        use crate::server::filter::path::PrefixMatcher;

        // Match .env files only in /home directory
        let matcher = AllMatcher::new(vec![
            Box::new(GlobMatcher::new("*.env").unwrap()),
            Box::new(PrefixMatcher::new("/home")),
        ]);

        assert!(matcher.matches(Path::new("/home/user/.env")));
        assert!(!matcher.matches(Path::new("/etc/.env"))); // Not in /home
        assert!(!matcher.matches(Path::new("/home/user/config.txt"))); // Not .env
    }

    #[test]
    fn test_all_matcher_empty() {
        let matcher = AllMatcher::new(vec![]);

        assert!(matcher.is_empty());
        assert_eq!(matcher.len(), 0);
        // Empty AllMatcher matches nothing
        assert!(!matcher.matches(Path::new("/any/path")));
    }

    #[test]
    fn test_all_matcher_single() {
        let matcher = AllMatcher::new(vec![Box::new(GlobMatcher::new("*.key").unwrap())]);

        assert_eq!(matcher.len(), 1);
        assert!(matcher.matches(Path::new("secret.key")));
        assert!(!matcher.matches(Path::new("secret.txt")));
    }

    #[test]
    fn test_all_matcher_with_matcher() {
        let matcher = AllMatcher::new(vec![Box::new(GlobMatcher::new("*.key").unwrap())])
            .with_matcher(Box::new(GlobMatcher::new("secret*").unwrap()));

        assert_eq!(matcher.len(), 2);
        assert!(matcher.matches(Path::new("secret.key"))); // Both match
        assert!(!matcher.matches(Path::new("public.key"))); // Only first matches
        assert!(!matcher.matches(Path::new("secret.txt"))); // Only second matches
    }

    #[test]
    fn test_all_matcher_clone() {
        use crate::server::filter::path::PrefixMatcher;

        let matcher = AllMatcher::new(vec![
            Box::new(GlobMatcher::new("*.log").unwrap()),
            Box::new(PrefixMatcher::new("/var/log")),
        ]);
        let cloned = matcher.clone_box();

        assert!(cloned.matches(Path::new("/var/log/app.log")));
        assert!(cloned.pattern_description().contains("all_of:"));
    }

    // Tests for CompositeMatcher (unified AND/OR/NOT)
    #[test]
    fn test_composite_matcher_and() {
        use crate::server::filter::path::PrefixMatcher;

        let matcher = CompositeMatcher::and(vec![
            Box::new(GlobMatcher::new("*.env").unwrap()),
            Box::new(PrefixMatcher::new("/home")),
        ]);

        assert!(matcher.matches(Path::new("/home/user/.env")));
        assert!(!matcher.matches(Path::new("/etc/.env")));
        assert!(matcher.pattern_description().contains("and:"));
    }

    #[test]
    fn test_composite_matcher_or() {
        let matcher = CompositeMatcher::or(vec![
            Box::new(GlobMatcher::new("*.key").unwrap()),
            Box::new(GlobMatcher::new("*.pem").unwrap()),
        ]);

        assert!(matcher.matches(Path::new("secret.key")));
        assert!(matcher.matches(Path::new("cert.pem")));
        assert!(!matcher.matches(Path::new("document.txt")));
        assert!(matcher.pattern_description().contains("or:"));
    }

    #[test]
    fn test_composite_matcher_not() {
        use crate::server::filter::path::PrefixMatcher;

        let matcher = CompositeMatcher::not(Box::new(PrefixMatcher::new("/home")));

        assert!(!matcher.matches(Path::new("/home/user/file")));
        assert!(matcher.matches(Path::new("/etc/passwd")));
        assert!(matcher.pattern_description().contains("not("));
    }

    #[test]
    fn test_composite_matcher_empty_and() {
        let matcher = CompositeMatcher::And(vec![]);

        // Empty AND should match nothing
        assert!(!matcher.matches(Path::new("/any/path")));
    }

    #[test]
    fn test_composite_matcher_empty_or() {
        let matcher = CompositeMatcher::Or(vec![]);

        // Empty OR should match nothing
        assert!(!matcher.matches(Path::new("/any/path")));
    }

    #[test]
    fn test_composite_matcher_complex() {
        use crate::server::filter::path::PrefixMatcher;

        // Complex rule: (.env files NOT in /home) OR (.key files)
        let env_not_home = CompositeMatcher::and(vec![
            Box::new(GlobMatcher::new("*.env").unwrap()),
            Box::new(CompositeMatcher::not(Box::new(PrefixMatcher::new("/home")))),
        ]);

        let key_files = GlobMatcher::new("*.key").unwrap();

        let matcher = CompositeMatcher::or(vec![Box::new(env_not_home), Box::new(key_files)]);

        assert!(matcher.matches(Path::new("/etc/.env"))); // .env not in /home
        assert!(!matcher.matches(Path::new("/home/user/.env"))); // .env in /home
        assert!(matcher.matches(Path::new("/home/user/secret.key"))); // .key file
    }

    #[test]
    fn test_composite_matcher_clone() {
        let matcher = CompositeMatcher::and(vec![
            Box::new(GlobMatcher::new("*.a").unwrap()),
            Box::new(GlobMatcher::new("test*").unwrap()),
        ]);
        let cloned = matcher.clone_box();

        assert!(cloned.matches(Path::new("test.a")));
        assert!(!cloned.matches(Path::new("test.b")));
    }
}