oxcache 0.2.0

A high-performance multi-level cache library for Rust with L1 (memory) and L2 (Redis) caching.
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
// Copyright (c) 2025-2026, Kirky.X
//
// MIT License
//
// Security utilities for regex and pattern validation
//
// Provides protection against ReDoS attacks and regex complexity limits.

use crate::error::{CacheError, Result};
use regex::Regex;

/// Maximum allowed pattern length
#[allow(dead_code)]
pub const MAX_PATTERN_LENGTH: usize = 256;

/// Maximum number of wildcards allowed in a pattern
#[allow(dead_code)]
pub const MAX_WILDCARDS: usize = 10;

/// Compiles a regex pattern with safety checks
///
/// # Arguments
///
/// * `pattern` - The regex pattern to compile
///
/// # Returns
///
/// * `Ok(Regex)` - Successfully compiled regex
/// * `Err(CacheError)` - Compilation failed or pattern is unsafe
#[allow(dead_code)]
pub fn compile_regex(pattern: &str) -> Result<regex::Regex> {
    // Check pattern length
    if pattern.len() > MAX_PATTERN_LENGTH {
        return Err(CacheError::InvalidInput(format!(
            "Regex pattern exceeds maximum length of {} bytes (got {})",
            MAX_PATTERN_LENGTH,
            pattern.len()
        )));
    }

    // Count wildcards (for potential ReDoS patterns)
    let wildcard_count = pattern.bytes().filter(|&b| b == b'*' || b == b'+').count();
    if wildcard_count > MAX_WILDCARDS {
        return Err(CacheError::InvalidInput(format!(
            "Regex pattern contains too many quantifiers ({} > {})",
            wildcard_count, MAX_WILDCARDS
        )));
    }

    // Check for dangerous patterns that could cause exponential backtracking
    // Patterns like (a+)+ or (a?)+ can cause ReDoS
    // We check for nested quantifiers which can cause catastrophic backtracking
    // Note: We use a more precise pattern to avoid false positives from glob conversions like [^/]
    let dangerous_patterns = [
        r"\([^)]*\)\++",          // (something)+ followed by one or more + (ReDoS pattern)
        r"\([^)]*(\([^)]*\))+\)", // Nested parentheses with quantifiers
    ];

    for dangerous in &dangerous_patterns {
        if let Ok(dangerous_regex) = Regex::new(dangerous) {
            if dangerous_regex.is_match(pattern) {
                return Err(CacheError::InvalidInput(
                    "Regex pattern contains potentially dangerous quantifier pattern".to_string(),
                ));
            }
        }
    }

    // Compile the regex
    Regex::new(pattern).map_err(|e| CacheError::InvalidInput(format!("Invalid regex pattern: {}", e)))
}

/// Matches a string against a compiled regex with input length check
///
/// # Arguments
///
/// * `regex` - The compiled regex
/// * `input` - The string to match against
///
/// # Returns
///
/// * `Ok(bool)` - Match result
/// * `Err(CacheError)` - Input too long
#[allow(dead_code)]
pub fn match_safe(regex: &Regex, input: &str) -> Result<bool> {
    // Check input length for extremely long inputs
    if input.len() > 1_000_000 {
        return Err(CacheError::InvalidInput(
            "Input string too long for regex matching".to_string(),
        ));
    }

    Ok(regex.is_match(input))
}

/// Converts a glob pattern to regex with safety checks
///
/// # Arguments
///
/// * `pattern` - The glob pattern
/// * `double_star_allowed` - Whether to allow ** glob patterns
///
/// # Returns
///
/// * `Ok(String)` - Regex pattern
/// * `Err(CacheError)` - Pattern conversion failed or unsafe
#[allow(dead_code)]
pub fn glob_to_regex(pattern: &str, double_star_allowed: bool) -> Result<String> {
    // Check pattern length
    if pattern.len() > MAX_PATTERN_LENGTH {
        return Err(CacheError::InvalidInput(format!(
            "Glob pattern exceeds maximum length of {} bytes (got {})",
            MAX_PATTERN_LENGTH,
            pattern.len()
        )));
    }

    // Count wildcards
    let single_star_count = pattern.bytes().filter(|&b| b == b'*').count();
    if double_star_allowed {
        // ** counts as 2 wildcards
        let double_star_count = pattern.matches("**").count();
        if single_star_count - (double_star_count * 2) > MAX_WILDCARDS {
            return Err(CacheError::InvalidInput(format!(
                "Glob pattern contains too many wildcards (max {})",
                MAX_WILDCARDS
            )));
        }
    } else if single_star_count > MAX_WILDCARDS {
        return Err(CacheError::InvalidInput(format!(
            "Glob pattern contains too many wildcards (max {})",
            MAX_WILDCARDS
        )));
    }

    // Convert glob to regex
    let mut regex_pattern = String::with_capacity(pattern.len() * 2);
    let mut chars = pattern.chars().peekable();
    let mut in_escape = false;

    while let Some(c) = chars.next() {
        if in_escape {
            regex_pattern.push_str(&regex::escape(&c.to_string()));
            in_escape = false;
            continue;
        }

        match c {
            '\\' if !in_escape => {
                if chars.peek() == Some(&'*') {
                    // \* means literal *
                    chars.next();
                    regex_pattern.push('*');
                } else {
                    in_escape = true;
                }
            }
            '*' => {
                if double_star_allowed && chars.clone().next() == Some('*') {
                    // ** matches any character including /
                    chars.next();
                    if chars.peek() == Some(&'/') {
                        // **/ matches zero or more directories
                        chars.next();
                        regex_pattern.push_str("(?:.*/)?");
                    } else {
                        regex_pattern.push_str(".*");
                    }
                } else {
                    // * matches any character except /
                    regex_pattern.push_str("[^/]*");
                }
            }
            '?' => regex_pattern.push('.'),
            '[' => {
                // Character class - escape to prevent regex injection
                return Err(CacheError::InvalidInput(
                    "Character class '[...]' not allowed in glob patterns".to_string(),
                ));
            }
            '{' | '}' => {
                return Err(CacheError::InvalidInput(
                    "Brace expansion not allowed in glob patterns".to_string(),
                ));
            }
            c => regex_pattern.push_str(&regex::escape(&c.to_string())),
        }
    }

    Ok(format!("^{}$", regex_pattern))
}

/// Validates and compiles a glob pattern with safety checks
///
/// # Arguments
///
/// * `pattern` - The glob pattern
/// * `double_star_allowed` - Whether to allow ** glob patterns
///
/// # Returns
///
/// * `Ok(Regex)` - Compiled regex
/// * `Err(CacheError)` - Validation or compilation failed
#[allow(dead_code)]
pub fn compile_glob_pattern(pattern: &str, double_star_allowed: bool) -> Result<Regex> {
    let regex_pattern = glob_to_regex(pattern, double_star_allowed)?;
    compile_regex(&regex_pattern)
}

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

    #[test]
    fn test_compile_regex_valid_pattern() {
        let result = compile_regex(".*");
        assert!(result.is_ok());
    }

    #[test]
    fn test_compile_regex_invalid_pattern() {
        let result = compile_regex("[invalid");
        assert!(result.is_err());
    }

    #[test]
    fn test_compile_regex_dangerous_pattern() {
        // This pattern could cause ReDoS
        let result = compile_regex(r"(a+)+$");
        assert!(result.is_err());
    }

    #[test]
    fn test_compile_regex_too_long() {
        let long_pattern = "a".repeat(MAX_PATTERN_LENGTH + 1);
        let result = compile_regex(&long_pattern);
        assert!(result.is_err());
    }

    #[test]
    fn test_compile_regex_too_many_quantifiers() {
        let pattern = "*".repeat(MAX_WILDCARDS + 1);
        let result = compile_regex(&pattern);
        assert!(result.is_err());
    }

    #[test]
    fn test_glob_to_regex_simple() {
        let result = glob_to_regex("*.txt", false);
        assert!(result.is_ok());
        let regex_pattern = result.unwrap();
        let regex = Regex::new(&regex_pattern).unwrap();
        assert!(regex.is_match("file.txt"));
        assert!(!regex.is_match("file.md"));
    }

    #[test]
    fn test_glob_to_regex_disallowed_chars() {
        let result = glob_to_regex("[abc]", false);
        assert!(result.is_err());

        let result = glob_to_regex("{a,b}", false);
        assert!(result.is_err());
    }

    #[test]
    fn test_glob_to_regex_too_long() {
        let long_pattern = "a".repeat(MAX_PATTERN_LENGTH + 1);
        let result = glob_to_regex(&long_pattern, false);
        assert!(result.is_err());
    }

    #[test]
    fn test_glob_to_regex_too_many_wildcards() {
        let pattern = "*".repeat(MAX_WILDCARDS + 1);
        let result = glob_to_regex(&pattern, false);
        assert!(result.is_err());
    }

    #[test]
    fn test_match_safe_valid() {
        let regex = Regex::new(".*").unwrap();
        let result = match_safe(&regex, "test");
        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[test]
    fn test_match_safe_too_long_input() {
        let regex = Regex::new(".*").unwrap();
        let long_input = "a".repeat(1_000_001);
        let result = match_safe(&regex, &long_input);
        assert!(result.is_err());
    }

    #[test]
    fn test_compile_glob_pattern() {
        let result = compile_glob_pattern("*.rs", false);
        assert!(result.is_ok());
        let regex = result.unwrap();
        assert!(regex.is_match("test.rs"));
        assert!(!regex.is_match("test.txt"));
    }

    // ============================================================================
    // glob_to_regex 双星号测试 (lines 122-124)
    // ============================================================================

    #[test]
    fn test_glob_to_regex_double_star_allowed() {
        let result = glob_to_regex("**/*.rs", true);
        assert!(result.is_ok());
        let regex_pattern = result.unwrap();
        let regex = Regex::new(&regex_pattern).unwrap();
        assert!(regex.is_match("test.rs"));
        assert!(regex.is_match("dir/test.rs"));
        assert!(regex.is_match("dir/subdir/test.rs"));
    }

    #[test]
    fn test_glob_to_regex_double_star_too_many_wildcards() {
        // 双星号模式下通配符过多
        // 使用单个 * 分隔的字符,避免被识别为 **
        let pattern = "*a".repeat(MAX_WILDCARDS + 1);
        let result = glob_to_regex(&pattern, true);
        assert!(result.is_err());
    }

    #[test]
    fn test_glob_to_regex_double_star_no_slash() {
        // ** 后面不是 / 的情况 (line 167)
        let result = glob_to_regex("**file", true);
        assert!(result.is_ok());
        let regex_pattern = result.unwrap();
        let regex = Regex::new(&regex_pattern).unwrap();
        assert!(regex.is_match("dir/file"));
        assert!(regex.is_match("file"));
    }

    #[test]
    fn test_glob_to_regex_double_star_with_slash() {
        // **/ 匹配零或多个目录 (lines 164-165)
        let result = glob_to_regex("**/file", true);
        assert!(result.is_ok());
        let regex_pattern = result.unwrap();
        let regex = Regex::new(&regex_pattern).unwrap();
        assert!(regex.is_match("file"));
        assert!(regex.is_match("dir/file"));
    }

    // ============================================================================
    // 转义字符测试 (lines 143-144, 149-155)
    // ============================================================================

    #[test]
    fn test_glob_to_regex_escape_character() {
        // 反斜杠转义非星号字符 (lines 143-144, 155)
        let result = glob_to_regex("\\a", false);
        assert!(result.is_ok());
        let regex_pattern = result.unwrap();
        let regex = Regex::new(&regex_pattern).unwrap();
        assert!(regex.is_match("a"));
    }

    #[test]
    fn test_glob_to_regex_escaped_star() {
        // \\* 表示字面量 * (lines 149-153)
        // 注意:源代码将原始 * 推入正则表达式模式,产生 ^*$
        // 这是一个无效的正则表达式(量词没有内容),所以我们只验证转换结果
        let result = glob_to_regex("\\*", false);
        assert!(result.is_ok());
        let regex_pattern = result.unwrap();
        assert_eq!(regex_pattern, "^*$");
    }

    #[test]
    fn test_glob_to_regex_backslash_at_end() {
        // 反斜杠在末尾(没有后续字符)
        let result = glob_to_regex("test\\", false);
        assert!(result.is_ok());
    }

    // ============================================================================
    // 问号通配符测试 (line 174)
    // ============================================================================

    #[test]
    fn test_glob_to_regex_question_mark() {
        // ? 匹配任意单个字符 (line 174)
        let result = glob_to_regex("?.txt", false);
        assert!(result.is_ok());
        let regex_pattern = result.unwrap();
        let regex = Regex::new(&regex_pattern).unwrap();
        assert!(regex.is_match("a.txt"));
        assert!(!regex.is_match("ab.txt"));
    }

    #[test]
    fn test_glob_to_regex_mixed_wildcards() {
        // 混合通配符
        let result = glob_to_regex("?*.txt", false);
        assert!(result.is_ok());
        let regex_pattern = result.unwrap();
        let regex = Regex::new(&regex_pattern).unwrap();
        assert!(regex.is_match("a.txt"));
        assert!(regex.is_match("ab.txt"));
        assert!(!regex.is_match(".txt"));
    }

    // ============================================================================
    // compile_regex 边界测试
    // ============================================================================

    #[test]
    fn test_compile_regex_empty_pattern() {
        let result = compile_regex("");
        assert!(result.is_ok());
    }

    #[test]
    fn test_compile_regex_exact_length_limit() {
        let pattern = "a".repeat(MAX_PATTERN_LENGTH);
        let result = compile_regex(&pattern);
        assert!(result.is_ok());
    }

    #[test]
    fn test_compile_regex_exact_quantifier_limit() {
        // 恰好 MAX_WILDCARDS 个量词
        let pattern = "a*".repeat(MAX_WILDCARDS);
        let result = compile_regex(&pattern);
        assert!(result.is_ok());
    }

    #[test]
    fn test_compile_regex_nested_parentheses_quantifier() {
        // 嵌套括号加量词 - 危险模式
        let result = compile_regex(r"((a+)+)");
        assert!(result.is_err());
    }

    // ============================================================================
    // match_safe 边界测试
    // ============================================================================

    #[test]
    fn test_match_safe_exact_limit() {
        let regex = Regex::new(".*").unwrap();
        let input = "a".repeat(1_000_000);
        let result = match_safe(&regex, &input);
        assert!(result.is_ok());
    }

    #[test]
    fn test_match_safe_no_match() {
        let regex = Regex::new("^b+$").unwrap();
        let result = match_safe(&regex, "aaa");
        assert!(result.is_ok());
        assert!(!result.unwrap());
    }

    // ============================================================================
    // compile_glob_pattern 边界测试
    // ============================================================================

    #[test]
    fn test_compile_glob_pattern_double_star() {
        let result = compile_glob_pattern("**/*.rs", true);
        assert!(result.is_ok());
        let regex = result.unwrap();
        assert!(regex.is_match("test.rs"));
        assert!(regex.is_match("dir/test.rs"));
    }

    #[test]
    fn test_compile_glob_pattern_question_mark() {
        let result = compile_glob_pattern("?.txt", false);
        assert!(result.is_ok());
        let regex = result.unwrap();
        assert!(regex.is_match("a.txt"));
    }

    #[test]
    fn test_glob_to_regex_single_star_no_slash_match() {
        // * 匹配除 / 外的任意字符 (line 171)
        let result = glob_to_regex("*.txt", false);
        assert!(result.is_ok());
        let regex_pattern = result.unwrap();
        let regex = Regex::new(&regex_pattern).unwrap();
        assert!(regex.is_match("file.txt"));
        assert!(!regex.is_match("dir/file.txt"));
    }

    #[test]
    fn test_glob_to_regex_regular_character() {
        // 普通字符通过 regex::escape 处理
        let result = glob_to_regex("test.txt", false);
        assert!(result.is_ok());
        let regex_pattern = result.unwrap();
        let regex = Regex::new(&regex_pattern).unwrap();
        assert!(regex.is_match("test.txt"));
    }

    #[test]
    fn test_glob_to_regex_double_star_allowed_exact_limit() {
        // 双星号模式下恰好达到通配符限制
        let pattern = "**".repeat(MAX_WILDCARDS);
        let result = glob_to_regex(&pattern, true);
        assert!(result.is_ok());
    }
}