sqry-core 6.0.18

Core library for sqry - semantic code search engine
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
//! Recursion limits configuration for sqry.
//!
//! This module enforces recursion depth limits to prevent resource exhaustion
//! and stack overflow attacks from deeply nested code structures.
//!
//! # Security Model
//!
//! Defense-in-depth approach with multiple layers:
//!
//! 1. **Default limits**: Conservative defaults (100 file ops, 1000 expr fuel)
//! 2. **Configurable limits**: Users can adjust based on their needs
//! 3. **Hard caps**: Absolute maximums that cannot be bypassed (200 file ops, 10,000 expr fuel)
//! 4. **Validation**: All values validated against hard caps to prevent config injection
//!
//! # Attack Vectors Mitigated
//!
//! - **Stack overflow**: Deep recursion exhausting call stack
//! - **Resource exhaustion**: Unbounded recursion consuming CPU/memory
//! - **Config injection**: Malicious config files setting extreme limits
//! - **AST bombs**: Pathological inputs with extreme nesting depth

use anyhow::{Result, bail};
use serde::{Deserialize, Serialize};
use std::env;

/// Recursion limits configuration
///
/// Controls maximum depth for recursive operations to prevent stack overflow
/// from pathological inputs (deeply nested AST structures, complex expressions).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RecursionLimits {
    /// Maximum depth for file operation recursion (AST traversal, directory walking)
    ///
    /// Controls how deep the AST traversal can go when processing source files.
    /// This prevents stack overflow from pathological code like:
    /// ```text
    /// fn f0() { fn f1() { fn f2() { ... fn f1000() {} ... } } }
    /// ```
    ///
    /// # Validation
    /// - Minimum: 50 (must handle moderately nested code)
    /// - Maximum: 150 (recommended for deeply nested code)
    /// - Hard cap: 200 (absolute maximum, NON-NEGOTIABLE security constraint)
    ///
    /// # Environment Override
    /// Can be overridden with `SQRY_RECURSION_FILE_OPS_DEPTH` environment variable.
    pub file_ops_depth: usize,

    /// Maximum depth for expression evaluation (query expressions, AST patterns)
    ///
    /// Controls how deep expression trees can be when evaluating queries.
    /// This prevents stack overflow from complex nested boolean expressions:
    /// ```text
    /// (((((a AND b) OR c) AND d) OR e) AND ...)
    /// ```
    ///
    /// # Validation
    /// - Minimum: 10 (must handle basic expressions)
    /// - Maximum: 100 (recommended)
    /// - Hard cap: 200 (absolute maximum, security constraint)
    ///
    /// # Environment Override
    /// Can be overridden with `SQRY_RECURSION_EXPR_DEPTH` environment variable.
    pub expr_depth: usize,

    /// Fuel limit for expression evaluation (operation counter)
    ///
    /// Alternative to depth limiting using an operation counter ("fuel").
    /// Each recursive call consumes fuel, preventing both deep and wide
    /// recursion patterns.
    ///
    /// # Validation
    /// - Minimum: 100 (must handle basic queries)
    /// - Maximum: 5000 (recommended)
    /// - Hard cap: 10,000 (absolute maximum, NON-NEGOTIABLE security constraint)
    ///
    /// # Environment Override
    /// Can be overridden with `SQRY_RECURSION_EXPR_FUEL` environment variable.
    pub expr_fuel: usize,
}

impl Default for RecursionLimits {
    fn default() -> Self {
        Self {
            file_ops_depth: 100,
            expr_depth: 100,
            expr_fuel: 1000,
        }
    }
}

impl RecursionLimits {
    /// Minimum allowed file ops depth
    pub const MIN_FILE_OPS_DEPTH: usize = 50;

    /// Maximum recommended file ops depth
    pub const MAX_FILE_OPS_DEPTH: usize = 150;

    /// Absolute hard cap for file ops depth (NON-NEGOTIABLE)
    ///
    /// Set to 200 (2x default) to handle legitimate deep directory structures
    /// while preventing resource exhaustion. This limit has been security-reviewed
    /// and balances usability with protection against stack overflow attacks.
    pub const ABSOLUTE_MAX_FILE_OPS_DEPTH: usize = 200;

    /// Minimum allowed expression depth
    pub const MIN_EXPR_DEPTH: usize = 10;

    /// Maximum recommended expression depth
    pub const MAX_EXPR_DEPTH: usize = 100;

    /// Absolute hard cap for expression depth
    pub const ABSOLUTE_MAX_EXPR_DEPTH: usize = 200;

    /// Minimum allowed expression fuel
    pub const MIN_EXPR_FUEL: usize = 100;

    /// Maximum recommended expression fuel
    pub const MAX_EXPR_FUEL: usize = 5_000;

    /// Absolute hard cap for expression fuel (NON-NEGOTIABLE)
    ///
    /// Set to 10,000 to prevent expression bombs (deeply nested operators) from
    /// causing stack overflows during query validation and normalization.
    /// This limit has been security-reviewed and prevents resource exhaustion attacks.
    pub const ABSOLUTE_MAX_EXPR_FUEL: usize = 10_000;

    /// Create a new recursion limits configuration with custom values
    ///
    /// # Errors
    ///
    /// Returns an error if the provided values violate safety constraints (e.g., values are
    /// below minimum thresholds or exceed maximum limits).
    pub fn new(file_ops_depth: usize, expr_depth: usize, expr_fuel: usize) -> Result<Self> {
        let config = Self {
            file_ops_depth,
            expr_depth,
            expr_fuel,
        };
        config.validate()?;
        Ok(config)
    }

    /// Load configuration with environment variable overrides
    ///
    /// # Errors
    ///
    /// Returns an error if environment variables contain invalid values or if the resulting
    /// configuration violates safety constraints.
    pub fn load_or_default() -> Result<Self> {
        let mut config = Self::default();

        // Apply environment variable overrides if present
        if let Ok(file_ops_str) = env::var("SQRY_RECURSION_FILE_OPS_DEPTH") {
            config.file_ops_depth =
                Self::parse_env_var(&file_ops_str, "SQRY_RECURSION_FILE_OPS_DEPTH")?;
        }

        if let Ok(expr_depth_str) = env::var("SQRY_RECURSION_EXPR_DEPTH") {
            config.expr_depth = Self::parse_env_var(&expr_depth_str, "SQRY_RECURSION_EXPR_DEPTH")?;
        }

        if let Ok(expr_fuel_str) = env::var("SQRY_RECURSION_EXPR_FUEL") {
            config.expr_fuel = Self::parse_env_var(&expr_fuel_str, "SQRY_RECURSION_EXPR_FUEL")?;
        }

        config.validate()?;
        Ok(config)
    }

    /// Get effective file ops depth with validation
    ///
    /// # Errors
    ///
    /// Returns an error if the configured value is 0 (unlimited not allowed), below the minimum
    /// threshold, or exceeds the absolute maximum limit.
    pub fn effective_file_ops_depth(&self) -> Result<usize> {
        if self.file_ops_depth == 0 {
            bail!("recursion.file_ops_depth cannot be 0 (unlimited not allowed for safety)");
        }

        if self.file_ops_depth < Self::MIN_FILE_OPS_DEPTH {
            bail!(
                "recursion.file_ops_depth {} is below minimum {}",
                self.file_ops_depth,
                Self::MIN_FILE_OPS_DEPTH
            );
        }

        if self.file_ops_depth > Self::MAX_FILE_OPS_DEPTH {
            tracing::warn!(
                "recursion.file_ops_depth {} exceeds recommended maximum {}",
                self.file_ops_depth,
                Self::MAX_FILE_OPS_DEPTH
            );
        }

        if self.file_ops_depth > Self::ABSOLUTE_MAX_FILE_OPS_DEPTH {
            bail!(
                "recursion.file_ops_depth {} exceeds absolute hard cap {}",
                self.file_ops_depth,
                Self::ABSOLUTE_MAX_FILE_OPS_DEPTH
            );
        }

        Ok(self.file_ops_depth)
    }

    /// Get effective expression depth with validation
    ///
    /// # Errors
    ///
    /// Returns an error if the configured value is 0 (unlimited not allowed), below the minimum
    /// threshold, or exceeds the absolute maximum limit.
    pub fn effective_expr_depth(&self) -> Result<usize> {
        if self.expr_depth == 0 {
            bail!("recursion.expr_depth cannot be 0 (unlimited not allowed for safety)");
        }

        if self.expr_depth < Self::MIN_EXPR_DEPTH {
            bail!(
                "recursion.expr_depth {} is below minimum {}",
                self.expr_depth,
                Self::MIN_EXPR_DEPTH
            );
        }

        if self.expr_depth > Self::MAX_EXPR_DEPTH {
            tracing::warn!(
                "recursion.expr_depth {} exceeds recommended maximum {}",
                self.expr_depth,
                Self::MAX_EXPR_DEPTH
            );
        }

        if self.expr_depth > Self::ABSOLUTE_MAX_EXPR_DEPTH {
            bail!(
                "recursion.expr_depth {} exceeds absolute hard cap {}",
                self.expr_depth,
                Self::ABSOLUTE_MAX_EXPR_DEPTH
            );
        }

        Ok(self.expr_depth)
    }

    /// Get effective expression fuel with validation
    ///
    /// # Errors
    ///
    /// Returns an error if the configured value is 0 (unlimited not allowed), below the minimum
    /// threshold, or exceeds the absolute maximum limit.
    pub fn effective_expr_fuel(&self) -> Result<usize> {
        if self.expr_fuel == 0 {
            bail!("recursion.expr_fuel cannot be 0 (unlimited not allowed for safety)");
        }

        if self.expr_fuel < Self::MIN_EXPR_FUEL {
            bail!(
                "recursion.expr_fuel {} is below minimum {}",
                self.expr_fuel,
                Self::MIN_EXPR_FUEL
            );
        }

        if self.expr_fuel > Self::MAX_EXPR_FUEL {
            tracing::warn!(
                "recursion.expr_fuel {} exceeds recommended maximum {}",
                self.expr_fuel,
                Self::MAX_EXPR_FUEL
            );
        }

        if self.expr_fuel > Self::ABSOLUTE_MAX_EXPR_FUEL {
            bail!(
                "recursion.expr_fuel {} exceeds absolute hard cap {}",
                self.expr_fuel,
                Self::ABSOLUTE_MAX_EXPR_FUEL
            );
        }

        Ok(self.expr_fuel)
    }

    /// Validate the configuration
    fn validate(&self) -> Result<()> {
        // Validation happens in effective_* methods
        self.effective_file_ops_depth()?;
        self.effective_expr_depth()?;
        self.effective_expr_fuel()?;
        Ok(())
    }

    /// Parse environment variable with strict error handling
    fn parse_env_var(value: &str, var_name: &str) -> Result<usize> {
        match value.parse::<usize>() {
            Ok(parsed) => Ok(parsed),
            Err(_) => bail!("Invalid value for {var_name}: '{value}'. Expected usize"),
        }
    }
}

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

    #[test]
    fn test_default_config() {
        let config = RecursionLimits::default();
        assert_eq!(config.file_ops_depth, 100);
        assert_eq!(config.expr_depth, 100);
        assert_eq!(config.expr_fuel, 1000);
        assert!(config.effective_file_ops_depth().is_ok());
        assert!(config.effective_expr_depth().is_ok());
        assert!(config.effective_expr_fuel().is_ok());
    }

    #[test]
    fn test_new_with_valid_values() {
        let config = RecursionLimits::new(200, 50, 5000).unwrap();
        assert_eq!(config.effective_file_ops_depth().unwrap(), 200);
        assert_eq!(config.effective_expr_depth().unwrap(), 50);
        assert_eq!(config.effective_expr_fuel().unwrap(), 5000);
    }

    #[test]
    fn test_file_ops_depth_zero_fails() {
        let result = RecursionLimits::new(0, 100, 1000);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("cannot be 0"));
    }

    #[test]
    fn test_expr_depth_zero_fails() {
        let result = RecursionLimits::new(100, 0, 1000);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("cannot be 0"));
    }

    #[test]
    fn test_expr_fuel_zero_fails() {
        let result = RecursionLimits::new(100, 100, 0);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("cannot be 0"));
    }

    #[test]
    fn test_file_ops_depth_below_minimum_fails() {
        let result = RecursionLimits::new(25, 100, 1000);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("below minimum 50"));
    }

    #[test]
    fn test_expr_depth_below_minimum_fails() {
        let result = RecursionLimits::new(100, 5, 1000);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("below minimum 10"));
    }

    #[test]
    fn test_expr_fuel_below_minimum_fails() {
        let result = RecursionLimits::new(100, 100, 50);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("below minimum 100")
        );
    }

    #[test]
    fn test_file_ops_depth_at_minimum_succeeds() {
        let config = RecursionLimits::new(50, 100, 1000).unwrap();
        assert_eq!(config.effective_file_ops_depth().unwrap(), 50);
    }

    #[test]
    fn test_expr_depth_at_minimum_succeeds() {
        let config = RecursionLimits::new(100, 10, 1000).unwrap();
        assert_eq!(config.effective_expr_depth().unwrap(), 10);
    }

    #[test]
    fn test_expr_fuel_at_minimum_succeeds() {
        let config = RecursionLimits::new(100, 100, 100).unwrap();
        assert_eq!(config.effective_expr_fuel().unwrap(), 100);
    }

    #[test]
    fn test_file_ops_depth_at_hard_cap_succeeds() {
        let config = RecursionLimits::new(200, 100, 1000).unwrap();
        assert_eq!(config.effective_file_ops_depth().unwrap(), 200);
    }

    #[test]
    fn test_expr_depth_at_hard_cap_succeeds() {
        let config = RecursionLimits::new(100, 200, 1000).unwrap();
        assert_eq!(config.effective_expr_depth().unwrap(), 200);
    }

    #[test]
    fn test_expr_fuel_at_hard_cap_succeeds() {
        let config = RecursionLimits::new(100, 100, 10_000).unwrap();
        assert_eq!(config.effective_expr_fuel().unwrap(), 10_000);
    }

    #[test]
    fn test_file_ops_depth_above_hard_cap_fails() {
        let result = RecursionLimits::new(201, 100, 1000);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("exceeds absolute hard cap")
        );
    }

    #[test]
    fn test_expr_depth_above_hard_cap_fails() {
        let result = RecursionLimits::new(100, 201, 1000);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("exceeds absolute hard cap")
        );
    }

    #[test]
    fn test_expr_fuel_above_hard_cap_fails() {
        let result = RecursionLimits::new(100, 100, 10_001);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("exceeds absolute hard cap")
        );
    }

    #[test]
    fn test_parse_env_var_valid() {
        let result = RecursionLimits::parse_env_var("150", "TEST_VAR");
        assert_eq!(result.unwrap(), 150);
    }

    #[test]
    fn test_parse_env_var_invalid() {
        let result = RecursionLimits::parse_env_var("abc", "TEST_VAR");
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Invalid value for TEST_VAR")
        );
    }

    #[test]
    fn test_parse_env_var_negative() {
        let result = RecursionLimits::parse_env_var("-100", "TEST_VAR");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Invalid value"));
    }
}