libmagic-rs 0.5.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
// Copyright (c) 2025-2026 the libmagic-rs contributors
// SPDX-License-Identifier: Apache-2.0

//! Integration tests for directory loading functionality.
//!
//! These tests validate the `load_magic_directory()` function's behavior
//! with various directory structures and content scenarios.

use libmagic_rs::parser::load_magic_directory;
use std::fs;
use std::path::{Path, PathBuf};
use tempfile::TempDir;

/// Helper function to create a test magic file in a directory.
fn create_test_magic_file(dir: &Path, name: &str, content: &str) -> PathBuf {
    let file_path = dir.join(name);
    fs::write(&file_path, content).expect("Failed to write test magic file");
    file_path
}

/// Helper function to create a realistic Magdir-style directory structure.
fn create_magdir_structure(dir: &Path) -> Vec<PathBuf> {
    vec![
        // ELF file detection
        create_test_magic_file(
            dir,
            "01-elf",
            "# ELF executables\n\
             0 string \\x7fELF ELF executable\n\
             >4 byte 1 32-bit\n\
             >4 byte 2 64-bit\n",
        ),
        // Archive formats
        create_test_magic_file(
            dir,
            "02-archive",
            "# Archive formats\n\
             0 string \\x21\\x3c ar archive\n\
             0 string \\x50\\x4b\\x03\\x04 ZIP archive\n",
        ),
        // Text files
        create_test_magic_file(
            dir,
            "03-text",
            "# Text files\n\
             0 string \\x23\\x21 shell script\n\
             0 string \\x23\\x21 bash script\n",
        ),
    ]
}

#[test]
fn test_load_empty_directory() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let rules = load_magic_directory(temp_dir.path()).expect("Failed to load empty directory");

    assert_eq!(rules.len(), 0, "Empty directory should return no rules");
}

#[test]
fn test_load_directory_single_file() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    create_test_magic_file(
        temp_dir.path(),
        "test.magic",
        "0 string \\x7fELF ELF executable\n\
         >4 byte 1 32-bit\n\
         >4 byte 2 64-bit\n",
    );

    let rules = load_magic_directory(temp_dir.path()).expect("Failed to load directory");

    assert_eq!(rules.len(), 1, "Should load one top-level rule");
    assert_eq!(rules[0].message, "ELF executable");
    assert_eq!(rules[0].children.len(), 2, "Should have 2 child rules");
}

#[test]
fn test_load_directory_multiple_files() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    create_test_magic_file(
        temp_dir.path(),
        "elf.magic",
        "0 string \\x7fELF ELF executable\n",
    );

    create_test_magic_file(
        temp_dir.path(),
        "archive.magic",
        "0 string \\x21\\x3c ar archive\n\
         0 string \\x50\\x4b\\x03\\x04 ZIP archive\n",
    );

    create_test_magic_file(
        temp_dir.path(),
        "script.magic",
        "0 string \\x23\\x21 shell script\n",
    );

    let rules = load_magic_directory(temp_dir.path()).expect("Failed to load directory");

    assert_eq!(rules.len(), 4, "Should load all rules from all files");

    // Verify we got rules from all three files
    let messages: Vec<&str> = rules.iter().map(|r| r.message.as_str()).collect();
    assert!(messages.contains(&"ar archive"));
    assert!(messages.contains(&"ZIP archive"));
    assert!(messages.contains(&"ELF executable"));
    assert!(messages.contains(&"shell script"));
}

#[test]
fn test_load_directory_preserves_order() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    // Create files with specific ordering - using valid magic syntax with hex escapes
    create_test_magic_file(
        temp_dir.path(),
        "01-first.magic",
        "0 string \\x01\\x02\\x03 first file\n",
    );

    create_test_magic_file(
        temp_dir.path(),
        "02-second.magic",
        "0 string \\x04\\x05\\x06 second file\n",
    );

    create_test_magic_file(
        temp_dir.path(),
        "03-third.magic",
        "0 string \\x07\\x08\\x09 third file\n",
    );

    let rules = load_magic_directory(temp_dir.path()).expect("Failed to load directory");

    assert_eq!(rules.len(), 3);
    // Files should be processed in alphabetical order
    assert_eq!(rules[0].message, "first file");
    assert_eq!(rules[1].message, "second file");
    assert_eq!(rules[2].message, "third file");
}

#[test]
fn test_load_directory_skips_subdirectories() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    // Create a file in the main directory
    create_test_magic_file(
        temp_dir.path(),
        "main.magic",
        "0 string \\x01\\x02 main file\n",
    );

    // Create a subdirectory with a magic file
    let subdir = temp_dir.path().join("subdir");
    fs::create_dir(&subdir).expect("Failed to create subdirectory");
    create_test_magic_file(&subdir, "sub.magic", "0 string \\x03\\x04 sub file\n");

    let rules = load_magic_directory(temp_dir.path()).expect("Failed to load directory");

    // Should only load the main file, not the one in subdirectory
    assert_eq!(rules.len(), 1);
    assert_eq!(rules[0].message, "main file");
}

#[test]
#[cfg(unix)] // Symlink creation is platform-specific
fn test_load_directory_skips_symlinks() {
    use std::os::unix::fs::symlink;

    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    // Create a regular file
    let _regular_file = create_test_magic_file(
        temp_dir.path(),
        "regular.magic",
        "0 string \\x01\\x02 regular file\n",
    );

    // Create another file outside the directory
    let external_dir = TempDir::new().expect("Failed to create external temp dir");
    let external_file = create_test_magic_file(
        external_dir.path(),
        "external.magic",
        "0 string \\x03\\x04 external file\n",
    );

    // Create a symlink to the external file
    let symlink_path = temp_dir.path().join("symlink.magic");
    symlink(&external_file, &symlink_path).expect("Failed to create symlink");

    let rules = load_magic_directory(temp_dir.path()).expect("Failed to load directory");

    // Should only load the regular file, not the symlinked one
    assert_eq!(rules.len(), 1, "Should skip symlinks");
    assert_eq!(rules[0].message, "regular file");
}

#[test]
fn test_load_directory_with_parse_errors() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    // Create a valid file
    create_test_magic_file(
        temp_dir.path(),
        "01-valid.magic",
        "0 string \\x01\\x02 valid file\n",
    );

    // Create an invalid file (malformed syntax)
    create_test_magic_file(
        temp_dir.path(),
        "02-invalid.magic",
        "this is not valid magic file syntax\n\
         completely broken\n",
    );

    // Create another valid file
    create_test_magic_file(
        temp_dir.path(),
        "03-valid.magic",
        "0 string \\x03\\x04 another valid file\n",
    );

    // Should succeed and load only the valid files
    let rules = load_magic_directory(temp_dir.path()).expect("Failed to load directory");

    assert_eq!(
        rules.len(),
        2,
        "Should load only valid files, skipping invalid ones"
    );
    assert_eq!(rules[0].message, "valid file");
    assert_eq!(rules[1].message, "another valid file");
}

#[test]
fn test_load_directory_io_error() {
    let non_existent_path = Path::new("/this/path/should/not/exist/anywhere");

    let result = load_magic_directory(non_existent_path);

    assert!(
        result.is_err(),
        "Should return error for non-existent directory"
    );

    let err_msg = result.unwrap_err().to_string();
    assert!(
        err_msg.contains("Failed to read directory"),
        "Error should mention directory read failure"
    );
}

#[test]
fn test_load_directory_with_comments() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    create_test_magic_file(
        temp_dir.path(),
        "commented.magic",
        "# This is a comment\n\
         # Another comment\n\
         0 string \\x01\\x02 test file\n\
         # Inline comment\n\
         >4 byte 1 version 1\n\
         \n\
         # Empty lines above\n",
    );

    let rules = load_magic_directory(temp_dir.path()).expect("Failed to load directory");

    assert_eq!(rules.len(), 1);
    assert_eq!(rules[0].message, "test file");
    assert_eq!(rules[0].children.len(), 1);
}

#[test]
fn test_load_directory_with_nested_rules() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    create_test_magic_file(
        temp_dir.path(),
        "nested.magic",
        "0 string \\x7fELF ELF executable\n\
         >4 byte 1 32-bit\n\
         >>16 short 2 executable\n\
         >>16 short 3 shared object\n\
         >4 byte 2 64-bit\n",
    );

    let rules = load_magic_directory(temp_dir.path()).expect("Failed to load directory");

    assert_eq!(rules.len(), 1, "Should have one top-level rule");
    assert_eq!(rules[0].children.len(), 2, "Should have two child rules");

    // Check first child has nested children
    assert_eq!(
        rules[0].children[0].children.len(),
        2,
        "First child should have 2 nested children"
    );
}

#[test]
fn test_load_directory_rule_count() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    create_magdir_structure(temp_dir.path());

    let rules = load_magic_directory(temp_dir.path()).expect("Failed to load directory");

    // Count total rules from create_magdir_structure:
    // 01-elf: 1 top-level (ELF executable) with 2 children = 1 top-level rule
    // 02-archive: 2 top-level (ar archive, ZIP archive) = 2 top-level rules
    // 03-text: 2 top-level (shell script, bash script) = 2 top-level rules
    // Total: 5 top-level rules
    assert_eq!(
        rules.len(),
        5,
        "Should have 5 top-level rules from Magdir structure"
    );
}

#[test]
fn test_load_directory_empty_files() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    // Create an empty file
    create_test_magic_file(temp_dir.path(), "empty.magic", "");

    // Create a file with only whitespace
    create_test_magic_file(temp_dir.path(), "whitespace.magic", "   \n\n  \n");

    // Create a valid file
    create_test_magic_file(
        temp_dir.path(),
        "valid.magic",
        "0 string \\x01\\x02 valid file\n",
    );

    let rules = load_magic_directory(temp_dir.path()).expect("Failed to load directory");

    // Empty files should be handled gracefully
    assert_eq!(
        rules.len(),
        1,
        "Should load only the valid file, empty files contribute no rules"
    );
    assert_eq!(rules[0].message, "valid file");
}

#[test]
fn test_load_directory_mixed_extensions() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    // Various file extensions
    create_test_magic_file(
        temp_dir.path(),
        "file.magic",
        "0 string \\x01\\x02 magic ext\n",
    );

    create_test_magic_file(temp_dir.path(), "file.txt", "0 string \\x03\\x04 txt ext\n");

    create_test_magic_file(temp_dir.path(), "noext", "0 string \\x05\\x06 no ext\n");

    let rules = load_magic_directory(temp_dir.path()).expect("Failed to load directory");

    // All files should be processed regardless of extension
    assert_eq!(
        rules.len(),
        3,
        "Should process all files regardless of extension"
    );

    let messages: Vec<&str> = rules.iter().map(|r| r.message.as_str()).collect();
    assert!(messages.contains(&"magic ext"));
    assert!(messages.contains(&"txt ext"));
    assert!(messages.contains(&"no ext"));
}

#[test]
fn test_load_directory_all_files_fail_to_parse() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    // Create files with invalid magic syntax
    create_test_magic_file(
        temp_dir.path(),
        "bad1",
        "this is not valid magic file syntax at all",
    );

    create_test_magic_file(temp_dir.path(), "bad2", "also invalid\nno proper format\n");

    // When all files fail to parse, we should get an error
    let result = load_magic_directory(temp_dir.path());

    assert!(
        result.is_err(),
        "Should return error when all files fail to parse"
    );

    let err = result.unwrap_err();
    let err_msg = err.to_string();
    assert!(
        err_msg.contains("All") && err_msg.contains("failed to parse"),
        "Error message should indicate all files failed: {err_msg}"
    );
}

#[test]
fn test_load_directory_partial_failure_succeeds() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    // One valid file
    create_test_magic_file(temp_dir.path(), "good", "0 string \\x00 valid rule\n");

    // One invalid file
    create_test_magic_file(temp_dir.path(), "bad", "not valid magic syntax");

    // Should succeed because at least one file parsed
    let rules = load_magic_directory(temp_dir.path()).expect("Should succeed with partial failure");

    assert_eq!(rules.len(), 1, "Should have one rule from the valid file");
    assert_eq!(rules[0].message, "valid rule");
}