libmagic-rs 0.6.0

A pure-Rust implementation of libmagic for file type identification
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
// Copyright (c) 2025-2026 the libmagic-rs contributors
// SPDX-License-Identifier: Apache-2.0

//! Evaluation configuration for magic rule processing.
//!
//! Defines [`EvaluationConfig`], which controls recursion depth, string length
//! limits, matching strategy, MIME type mapping, and timeouts during rule
//! evaluation. Extracted from `lib.rs` to keep that module under the project's
//! file-size limit.

use crate::Result;
use crate::error::LibmagicError;

/// Configuration for rule evaluation
///
/// This struct controls various aspects of magic rule evaluation behavior,
/// including performance limits, output options, and matching strategies.
///
/// # Forward compatibility
///
/// This struct is marked `#[non_exhaustive]`: new configuration fields may
/// be added in any release without it being a breaking change. Construct
/// instances via one of the factory constructors
/// ([`EvaluationConfig::default()`], [`EvaluationConfig::new()`],
/// [`EvaluationConfig::performance()`],
/// [`EvaluationConfig::comprehensive()`]) and then chain `with_*`
/// builder-style setters:
///
/// ```rust
/// use libmagic_rs::EvaluationConfig;
///
/// let custom_config = EvaluationConfig::default()
///     .with_max_recursion_depth(10)
///     .with_timeout_ms(Some(5_000));
/// ```
///
/// Direct struct-literal construction (`EvaluationConfig { .. }`) is
/// rejected by the compiler from outside this crate because of
/// `#[non_exhaustive]`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct EvaluationConfig {
    /// Maximum recursion depth for nested rules
    ///
    /// This prevents infinite recursion in malformed magic files and limits
    /// the depth of rule hierarchy traversal. Default is 20.
    pub max_recursion_depth: u32,

    /// Maximum string length to read
    ///
    /// This limits the amount of data read for string types to prevent
    /// excessive memory usage. Default is 8192 bytes.
    pub max_string_length: usize,

    /// Stop at first match or continue for all matches
    ///
    /// When `true`, evaluation stops after the first matching rule.
    /// When `false`, all rules are evaluated to find all matches.
    /// Default is `true` for performance.
    ///
    /// # Semantics
    ///
    /// "First match" refers to the first *top-level* rule that matches.
    /// Children of the first matching top-level rule are always evaluated
    /// before the stop check; the stop check applies to subsequent
    /// top-level rules. In other words, `stop_at_first_match = true` does
    /// not truncate the child subtree of the matching rule -- it only
    /// prevents later sibling top-level rules from being evaluated. A
    /// successful top-level match therefore returns one parent `RuleMatch`
    /// plus any descendant `RuleMatch` values its children produced.
    pub stop_at_first_match: bool,

    /// Enable MIME type mapping in results
    ///
    /// When `true`, the evaluator will attempt to map file type descriptions
    /// to standard MIME types. Default is `false`.
    pub enable_mime_types: bool,

    /// Timeout for evaluation in milliseconds
    ///
    /// If set, evaluation will be aborted if it takes longer than this duration.
    /// `None` means no timeout. Default is `None`.
    pub timeout_ms: Option<u64>,
}

impl Default for EvaluationConfig {
    /// Returns the default evaluation configuration.
    ///
    /// # Security
    ///
    /// The default configuration has no timeout. When processing untrusted
    /// input, use [`EvaluationConfig::performance()`] or set `timeout_ms`
    /// explicitly to prevent denial of service.
    fn default() -> Self {
        Self {
            max_recursion_depth: 20,
            max_string_length: 8192,
            stop_at_first_match: true,
            enable_mime_types: false,
            timeout_ms: None,
        }
    }
}

impl EvaluationConfig {
    /// Create a new configuration with default values
    ///
    /// # Examples
    ///
    /// ```rust
    /// use libmagic_rs::EvaluationConfig;
    ///
    /// let config = EvaluationConfig::new();
    /// assert_eq!(config.max_recursion_depth, 20);
    /// assert_eq!(config.max_string_length, 8192);
    /// assert!(config.stop_at_first_match);
    /// assert!(!config.enable_mime_types);
    /// assert_eq!(config.timeout_ms, None);
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a configuration optimized for performance
    ///
    /// This configuration prioritizes speed over completeness:
    /// - Lower recursion depth limit
    /// - Smaller string length limit
    /// - Stop at first match
    /// - No MIME type mapping
    /// - Short timeout
    ///
    /// # Examples
    ///
    /// ```rust
    /// use libmagic_rs::EvaluationConfig;
    ///
    /// let config = EvaluationConfig::performance();
    /// assert_eq!(config.max_recursion_depth, 10);
    /// assert_eq!(config.max_string_length, 1024);
    /// assert!(config.stop_at_first_match);
    /// assert!(!config.enable_mime_types);
    /// assert_eq!(config.timeout_ms, Some(1000));
    /// ```
    #[must_use]
    pub const fn performance() -> Self {
        Self {
            max_recursion_depth: 10,
            max_string_length: 1024,
            stop_at_first_match: true,
            enable_mime_types: false,
            timeout_ms: Some(1000), // 1 second
        }
    }

    /// Create a configuration optimized for completeness
    ///
    /// This configuration prioritizes finding all matches over speed:
    /// - Higher recursion depth limit
    /// - Larger string length limit
    /// - Find all matches
    /// - Enable MIME type mapping
    /// - Longer timeout
    ///
    /// # Examples
    ///
    /// ```rust
    /// use libmagic_rs::EvaluationConfig;
    ///
    /// let config = EvaluationConfig::comprehensive();
    /// assert_eq!(config.max_recursion_depth, 50);
    /// assert_eq!(config.max_string_length, 32768);
    /// assert!(!config.stop_at_first_match);
    /// assert!(config.enable_mime_types);
    /// assert_eq!(config.timeout_ms, Some(30000));
    /// ```
    #[must_use]
    pub const fn comprehensive() -> Self {
        Self {
            max_recursion_depth: 50,
            max_string_length: 32768,
            stop_at_first_match: false,
            enable_mime_types: true,
            timeout_ms: Some(30000), // 30 seconds
        }
    }

    /// Sets the maximum recursion depth for nested rule evaluation.
    ///
    /// Builder-style setter for consumers outside this crate. Direct
    /// struct-literal construction is blocked by `#[non_exhaustive]`, so
    /// chain `with_*` calls after one of the factory constructors
    /// (`default`, `performance`, `comprehensive`, `new`).
    #[must_use]
    pub const fn with_max_recursion_depth(mut self, depth: u32) -> Self {
        self.max_recursion_depth = depth;
        self
    }

    /// Sets the maximum string length (in bytes) read for string types.
    #[must_use]
    pub const fn with_max_string_length(mut self, length: usize) -> Self {
        self.max_string_length = length;
        self
    }

    /// Sets whether evaluation stops after the first top-level match.
    #[must_use]
    pub const fn with_stop_at_first_match(mut self, stop: bool) -> Self {
        self.stop_at_first_match = stop;
        self
    }

    /// Enables or disables MIME type mapping in results.
    #[must_use]
    pub const fn with_mime_types(mut self, enable: bool) -> Self {
        self.enable_mime_types = enable;
        self
    }

    /// Sets the evaluation timeout in milliseconds. Pass `None` for
    /// unbounded evaluation (not recommended on untrusted input).
    #[must_use]
    pub const fn with_timeout_ms(mut self, timeout_ms: Option<u64>) -> Self {
        self.timeout_ms = timeout_ms;
        self
    }

    /// Validate the configuration settings
    ///
    /// Performs comprehensive security validation of all configuration values
    /// to prevent malicious configurations that could lead to resource exhaustion,
    /// denial of service, or other security issues.
    ///
    /// # Security
    ///
    /// This validation prevents:
    /// - Stack overflow attacks through excessive recursion depth
    /// - Memory exhaustion through oversized string limits
    /// - Denial of service through excessive timeouts
    /// - Integer overflow in configuration calculations
    ///
    /// # Errors
    ///
    /// Returns `LibmagicError::ConfigError` if any configuration values
    /// are invalid or out of reasonable bounds.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use libmagic_rs::EvaluationConfig;
    ///
    /// let config = EvaluationConfig::default();
    /// assert!(config.validate().is_ok());
    ///
    /// let invalid_config = EvaluationConfig::default().with_max_recursion_depth(0);
    /// assert!(invalid_config.validate().is_err());
    /// ```
    pub fn validate(&self) -> Result<()> {
        self.validate_recursion_depth()?;
        self.validate_string_length()?;
        self.validate_timeout()?;
        self.validate_resource_combination()?;
        Ok(())
    }

    /// Validate recursion depth to prevent stack overflow attacks
    fn validate_recursion_depth(&self) -> Result<()> {
        const MAX_SAFE_RECURSION_DEPTH: u32 = 1000;

        if self.max_recursion_depth == 0 {
            return Err(LibmagicError::ConfigError {
                reason: "max_recursion_depth must be greater than 0".to_string(),
            });
        }

        if self.max_recursion_depth > MAX_SAFE_RECURSION_DEPTH {
            return Err(LibmagicError::ConfigError {
                reason: format!(
                    "max_recursion_depth must not exceed {MAX_SAFE_RECURSION_DEPTH} to prevent stack overflow"
                ),
            });
        }

        Ok(())
    }

    /// Validate string length to prevent memory exhaustion
    fn validate_string_length(&self) -> Result<()> {
        const MAX_SAFE_STRING_LENGTH: usize = 1_048_576; // 1MB

        if self.max_string_length == 0 {
            return Err(LibmagicError::ConfigError {
                reason: "max_string_length must be greater than 0".to_string(),
            });
        }

        if self.max_string_length > MAX_SAFE_STRING_LENGTH {
            return Err(LibmagicError::ConfigError {
                reason: format!(
                    "max_string_length must not exceed {MAX_SAFE_STRING_LENGTH} bytes to prevent memory exhaustion"
                ),
            });
        }

        Ok(())
    }

    /// Validate timeout to prevent denial of service
    fn validate_timeout(&self) -> Result<()> {
        const MAX_SAFE_TIMEOUT_MS: u64 = 300_000; // 5 minutes

        if let Some(timeout) = self.timeout_ms {
            if timeout == 0 {
                return Err(LibmagicError::ConfigError {
                    reason: "timeout_ms must be greater than 0 if specified".to_string(),
                });
            }

            if timeout > MAX_SAFE_TIMEOUT_MS {
                return Err(LibmagicError::ConfigError {
                    reason: format!(
                        "timeout_ms must not exceed {MAX_SAFE_TIMEOUT_MS} (5 minutes) to prevent denial of service"
                    ),
                });
            }
        }

        Ok(())
    }

    /// Validate resource combination to prevent resource exhaustion
    fn validate_resource_combination(&self) -> Result<()> {
        const HIGH_RECURSION_THRESHOLD: u32 = 100;
        const LARGE_STRING_THRESHOLD: usize = 65536;

        if self.max_recursion_depth > HIGH_RECURSION_THRESHOLD
            && self.max_string_length > LARGE_STRING_THRESHOLD
        {
            return Err(LibmagicError::ConfigError {
                reason: format!(
                    "High recursion depth (>{HIGH_RECURSION_THRESHOLD}) combined with large string length (>{LARGE_STRING_THRESHOLD}) may cause resource exhaustion"
                ),
            });
        }

        Ok(())
    }
}

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

    // ── Presets ──────────────────────────────────────────────────

    #[test]
    fn test_default_validates() {
        assert!(EvaluationConfig::default().validate().is_ok());
    }

    #[test]
    fn test_performance_validates() {
        assert!(EvaluationConfig::performance().validate().is_ok());
    }

    #[test]
    fn test_comprehensive_validates() {
        assert!(EvaluationConfig::comprehensive().validate().is_ok());
    }

    // ── Recursion depth boundaries ──────────────────────────────

    #[test]
    fn test_recursion_depth_zero_rejected() {
        let cfg = EvaluationConfig {
            max_recursion_depth: 0,
            ..Default::default()
        };
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_recursion_depth_one_accepted() {
        let cfg = EvaluationConfig {
            max_recursion_depth: 1,
            ..Default::default()
        };
        assert!(cfg.validate().is_ok());
    }

    #[test]
    fn test_recursion_depth_at_max_accepted() {
        let cfg = EvaluationConfig {
            max_recursion_depth: 1000,
            ..Default::default()
        };
        assert!(cfg.validate().is_ok());
    }

    #[test]
    fn test_recursion_depth_above_max_rejected() {
        let cfg = EvaluationConfig {
            max_recursion_depth: 1001,
            ..Default::default()
        };
        assert!(cfg.validate().is_err());
    }

    // ── String length boundaries ────────────────────────────────

    #[test]
    fn test_string_length_zero_rejected() {
        let cfg = EvaluationConfig {
            max_string_length: 0,
            ..Default::default()
        };
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_string_length_one_accepted() {
        let cfg = EvaluationConfig {
            max_string_length: 1,
            ..Default::default()
        };
        assert!(cfg.validate().is_ok());
    }

    #[test]
    fn test_string_length_at_max_accepted() {
        let cfg = EvaluationConfig {
            max_string_length: 1_048_576,
            ..Default::default()
        };
        assert!(cfg.validate().is_ok());
    }

    #[test]
    fn test_string_length_above_max_rejected() {
        let cfg = EvaluationConfig {
            max_string_length: 1_048_577,
            ..Default::default()
        };
        assert!(cfg.validate().is_err());
    }

    // ── Timeout boundaries ──────────────────────────────────────

    #[test]
    fn test_timeout_none_accepted() {
        let cfg = EvaluationConfig {
            timeout_ms: None,
            ..Default::default()
        };
        assert!(cfg.validate().is_ok());
    }

    #[test]
    fn test_timeout_zero_rejected() {
        let cfg = EvaluationConfig {
            timeout_ms: Some(0),
            ..Default::default()
        };
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_timeout_one_accepted() {
        let cfg = EvaluationConfig {
            timeout_ms: Some(1),
            ..Default::default()
        };
        assert!(cfg.validate().is_ok());
    }

    #[test]
    fn test_timeout_at_max_accepted() {
        let cfg = EvaluationConfig {
            timeout_ms: Some(300_000),
            ..Default::default()
        };
        assert!(cfg.validate().is_ok());
    }

    #[test]
    fn test_timeout_above_max_rejected() {
        let cfg = EvaluationConfig {
            timeout_ms: Some(300_001),
            ..Default::default()
        };
        assert!(cfg.validate().is_err());
    }

    // ── Resource combination guard ──────────────────────────────

    #[test]
    fn test_high_recursion_with_large_string_rejected() {
        let cfg = EvaluationConfig {
            max_recursion_depth: 101,
            max_string_length: 65537,
            ..Default::default()
        };
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_high_recursion_with_normal_string_accepted() {
        let cfg = EvaluationConfig {
            max_recursion_depth: 101,
            max_string_length: 65536,
            ..Default::default()
        };
        assert!(cfg.validate().is_ok());
    }

    #[test]
    fn test_normal_recursion_with_large_string_accepted() {
        let cfg = EvaluationConfig {
            max_recursion_depth: 100,
            max_string_length: 65537,
            ..Default::default()
        };
        assert!(cfg.validate().is_ok());
    }

    // ── evaluate_rules_with_config rejects invalid config ───────

    #[test]
    fn test_evaluate_rules_with_config_rejects_invalid() {
        use crate::evaluator::evaluate_rules_with_config;

        let invalid_cfg = EvaluationConfig {
            max_recursion_depth: 0,
            ..Default::default()
        };
        let result = evaluate_rules_with_config(&[], &[], &invalid_cfg);
        assert!(result.is_err());
    }
}