keyhog-sources 0.5.44

keyhog-sources: pluggable input backends for KeyHog (git, S3, GCS, Azure Blob, Docker, Web)
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
use super::{
    archive_unix_mode_is_special, emit_archive_entry_error, emit_archive_entry_over_cap_error,
    emit_archive_unreadable_error, report_archive_truncation, validate_scan_archive_entry_name,
};
use crate::filesystem::extract::tex_package::{
    member_needs_source_bytes, TexPackageAnalysis, TexPackageBuilder,
};
use crate::filesystem::filter;
use keyhog_core::{Chunk, SourceError};
use std::io::{Cursor, Read, Seek};
use std::path::Path;

mod duplicates;

pub(crate) fn duplicate_zip_central_entries_error_for_test(path: &Path) -> Result<String, String> {
    duplicates::read_central_zip_entries_error_for_test(path)
}

pub(crate) fn duplicate_zip_local_entry_data_error_for_test(
    path: &Path,
    compressed_size: u64,
) -> Result<String, String> {
    duplicates::read_local_zip_entry_data_error_for_test(path, compressed_size)
}

pub(crate) fn duplicate_zip_reopen_error_for_test(path: &Path) -> Option<String> {
    duplicates::duplicate_zip_reopen_error_for_test(path)
}

pub(super) fn extract_zip_archive(
    path: &Path,
    archive_display: &str,
    per_entry_cap: u64,
    total_budget: u64,
    respect_default_excludes: bool,
    emit: &mut dyn FnMut(Result<Chunk, SourceError>) -> bool,
) {
    match duplicates::duplicate_central_zip_entries(path) {
        Ok(Some(entries)) => {
            duplicates::extract_zip_archive_from_central_entries(
                path,
                archive_display,
                per_entry_cap,
                total_budget,
                respect_default_excludes,
                emit,
                entries,
            );
            return;
        }
        // No duplicate central-directory entries: the standard parser below sees
        // every entry, so its coverage of this archive is complete.
        Ok(None) => {}
        Err(error) => {
            // LAW 10: do NOT silently degrade. The duplicate-entry detector could
            // not run (e.g. a zip64 central directory it does not model, or a
            // malformed/truncated central directory), so the standard `zip` parser
            // below surfaces only one entry per name and may miss a duplicated /
            // shadow central-directory entry an attacker hid a secret in. Surface
            // the partial-coverage gap loudly and record it so the recall gap is
            // visible in the scan summary instead of vanishing.
            tracing::warn!(
                archive = %path.display(),
                %error,
                "zip duplicate-entry detection unavailable; scanning with the standard \
                 parser, which may miss a duplicated/shadow central-directory entry"
            );
            let _event =
                crate::record_skip_event(crate::SourceSkipEvent::ArchiveDuplicateScanUnavailable);
            if !emit(Err(SourceError::Other(format!(
                "ZIP duplicate-entry detection unavailable for '{archive_display}': {error}; scanning continued with the standard parser, which may miss duplicated or shadowed entries"
            )))) {
                return;
            }
        }
    }

    let file = match crate::filesystem::open_file_safe(path) {
        Ok(file) => file,
        Err(error) => {
            tracing::warn!(
                archive = %path.display(),
                %error,
                "cannot open archive; skipping"
            );
            let _event = crate::record_skip_event(crate::SourceSkipEvent::Unreadable);
            if !emit_archive_unreadable_error(
                emit,
                "ZIP archive",
                archive_display,
                "cannot open archive",
                error,
            ) {
                return;
            }
            return;
        }
    };
    let archive = match zip::ZipArchive::new(file) {
        Ok(archive) => archive,
        Err(error) => {
            tracing::warn!(
                archive = %path.display(),
                %error,
                "cannot read zip archive directory; skipping"
            );
            let _event = crate::record_skip_event(crate::SourceSkipEvent::Unreadable);
            if !emit_archive_unreadable_error(
                emit,
                "ZIP archive",
                archive_display,
                "cannot read zip archive directory",
                error,
            ) {
                return;
            }
            return;
        }
    };

    let mut total_uncompressed = 0u64;
    if !extract_zip_archive_entries(
        archive,
        archive_display,
        per_entry_cap,
        total_budget,
        &mut total_uncompressed,
        0,
        respect_default_excludes,
        emit,
    ) {
        return;
    }
}

pub(super) fn extract_embedded_zip_archive(
    content: Vec<u8>,
    archive_display: &str,
    per_entry_cap: u64,
    total_budget: u64,
    total_uncompressed: &mut u64,
    nested_depth: usize,
    respect_default_excludes: bool,
    emit: &mut dyn FnMut(Result<Chunk, SourceError>) -> bool,
) -> bool {
    let mut cursor = Cursor::new(content);
    match duplicates::duplicate_central_zip_entries_from_reader(&mut cursor) {
        Ok(Some(entries)) => {
            return duplicates::extract_zip_archive_from_central_entries_reader(
                &mut cursor,
                archive_display,
                per_entry_cap,
                total_budget,
                total_uncompressed,
                nested_depth,
                respect_default_excludes,
                emit,
                entries,
            );
        }
        Ok(None) => {}
        Err(error) => {
            tracing::warn!(
                archive = archive_display,
                %error,
                "embedded zip duplicate-entry detection unavailable; scanning with the standard \
                 parser, which may miss a duplicated/shadow central-directory entry"
            );
            let _event =
                crate::record_skip_event(crate::SourceSkipEvent::ArchiveDuplicateScanUnavailable);
            if !emit(Err(SourceError::Other(format!(
                "embedded ZIP duplicate-entry detection unavailable for '{archive_display}': {error}; scanning continued with the standard parser, which may miss duplicated or shadowed entries"
            )))) {
                return false;
            }
        }
    }

    let archive = match zip::ZipArchive::new(cursor) {
        Ok(archive) => archive,
        Err(error) => {
            tracing::warn!(
                archive = archive_display,
                %error,
                "cannot read embedded zip archive directory; skipping"
            );
            let _event = crate::record_skip_event(crate::SourceSkipEvent::Unreadable);
            return emit(Err(SourceError::Other(format!(
                "failed to scan embedded ZIP archive '{archive_display}': cannot read archive directory ({error}); embedded archive was not scanned"
            ))));
        }
    };

    extract_zip_archive_entries(
        archive,
        archive_display,
        per_entry_cap,
        total_budget,
        total_uncompressed,
        nested_depth,
        respect_default_excludes,
        emit,
    )
}

fn extract_zip_archive_entries<R: Read + Seek>(
    mut archive: zip::ZipArchive<R>,
    archive_display: &str,
    per_entry_cap: u64,
    total_budget: u64,
    total_uncompressed: &mut u64,
    nested_depth: usize,
    respect_default_excludes: bool,
    emit: &mut dyn FnMut(Result<Chunk, SourceError>) -> bool,
) -> bool {
    let mut tex_package = analyze_tex_package(&mut archive);
    if tex_package.is_bounded()
        && !emit(Err(SourceError::Other(format!(
            "TeX provenance analysis for '{archive_display}' exceeded its bounded member or source-byte budget; every archive member is still scanned without TeX role annotations"
        ))))
    {
        return false;
    }

    for index in 0..archive.len() {
        let mut entry = match archive.by_index(index) {
            Ok(entry) => entry,
            Err(error) => {
                tracing::warn!(
                    archive = archive_display,
                    index,
                    %error,
                    "cannot read archive entry metadata; skipping entry"
                );
                let _event = crate::record_skip_event(crate::SourceSkipEvent::Unreadable);
                if !emit(Err(SourceError::Other(format!(
                    "failed to scan ZIP entry #{index} in '{archive_display}': cannot read entry metadata ({error}); entry was not scanned"
                )))) {
                    return false;
                }
                continue;
            }
        };
        let entry_name = entry.name().to_string();
        if entry.is_dir() {
            continue;
        }
        if respect_default_excludes && filter::is_default_excluded(&entry_name) {
            super::super::record_default_excluded_archive_entry(archive_display, &entry_name);
            continue;
        }
        if let Err(reason) = validate_scan_archive_entry_name(&entry_name) {
            tracing::warn!(
                archive = archive_display,
                entry = %entry_name,
                reason,
                "skipping unsafe archive entry name"
            );
            let _event = crate::record_skip_event(crate::SourceSkipEvent::Unreadable);
            if !emit_archive_entry_error(emit, "ZIP entry", archive_display, &entry_name, reason) {
                return false;
            }
            continue;
        }
        if zip_entry_is_special(&entry) {
            tracing::warn!(
                archive = archive_display,
                entry = %entry_name,
                "skipping special archive entry"
            );
            let _event = crate::record_skip_event(crate::SourceSkipEvent::Unreadable);
            if !emit_archive_entry_error(
                emit,
                "ZIP entry",
                archive_display,
                &entry_name,
                "special file type",
            ) {
                return false;
            }
            continue;
        }

        let advertised_uncompressed = entry.size();
        if advertised_uncompressed > per_entry_cap {
            tracing::warn!(
                archive = archive_display,
                entry = %entry_name,
                size = advertised_uncompressed,
                "skipping archive entry: uncompressed size exceeds per-file cap"
            );
            let _event = crate::record_skip_event(crate::SourceSkipEvent::OverMaxSize);
            if !emit_archive_entry_over_cap_error(
                emit,
                "ZIP entry",
                archive_display,
                &entry_name,
                advertised_uncompressed,
                per_entry_cap,
                "uncompressed",
            ) {
                return false;
            }
            continue;
        }
        if advertised_uncompressed > 0
            && (*total_uncompressed).saturating_add(advertised_uncompressed) > total_budget
        {
            let error = report_archive_truncation(
                archive_display,
                (*total_uncompressed).saturating_add(advertised_uncompressed),
                total_budget,
            );
            if !emit(Err(error)) {
                return false;
            }
            break;
        }

        let remaining_budget = total_budget.saturating_sub(*total_uncompressed);
        let read_cap = per_entry_cap.min(remaining_budget);
        let read = if let Some(mut bytes) = tex_package.take_source_content(&entry_name) {
            let cap = usize::try_from(read_cap).unwrap_or(usize::MAX); // LAW10: recall-preserving bounded conversion saturates to the largest addressable buffer cap; every readable byte remains eligible.
            let truncated = bytes.len() > cap;
            bytes.truncate(cap);
            crate::capped_read::CappedRead { bytes, truncated }
        } else {
            match crate::capped_read::read_to_cap(
                &mut entry,
                read_cap,
                Some(advertised_uncompressed),
            ) {
                Ok(read) => read,
                Err(error) => {
                    tracing::warn!(
                        archive = archive_display,
                        entry = %entry_name,
                        %error,
                        "cannot read archive entry; skipping"
                    );
                    let _event = crate::record_skip_event(crate::SourceSkipEvent::Unreadable);
                    if !emit(Err(SourceError::Other(format!(
                        "failed to scan ZIP entry '{archive_display}//{entry_name}': cannot read entry ({error}); entry was not scanned"
                    )))) {
                        return false;
                    }
                    continue;
                }
            }
        };
        let content = read.bytes;

        let actual_uncompressed = match u64::try_from(content.len()) {
            Ok(len) => len,
            Err(error) => {
                tracing::warn!(
                    archive = archive_display,
                    entry = %entry_name,
                    %error,
                    "archive entry decoded length cannot be represented; skipping"
                );
                let _event = crate::record_skip_event(crate::SourceSkipEvent::Unreadable);
                if !emit(Err(SourceError::Other(format!(
                    "failed to scan ZIP entry '{archive_display}//{entry_name}': decoded length cannot be represented ({error}); entry was not scanned"
                )))) {
                    return false;
                }
                continue;
            }
        };
        if read.truncated && read_cap == per_entry_cap {
            let observed_uncompressed = read_cap.saturating_add(1);
            tracing::warn!(
                archive = archive_display,
                entry = %entry_name,
                size = observed_uncompressed,
                "skipping archive entry: decoded size exceeds per-file cap"
            );
            let _event = crate::record_skip_event(crate::SourceSkipEvent::OverMaxSize);
            if !emit_archive_entry_over_cap_error(
                emit,
                "ZIP entry",
                archive_display,
                &entry_name,
                observed_uncompressed,
                per_entry_cap,
                "decoded",
            ) {
                return false;
            }
            continue;
        }
        if read.truncated {
            let attempted_total = (*total_uncompressed).saturating_add(read_cap.saturating_add(1));
            let error = report_archive_truncation(archive_display, attempted_total, total_budget);
            if !emit(Err(error)) {
                return false;
            }
            break;
        }
        *total_uncompressed = (*total_uncompressed).saturating_add(actual_uncompressed);
        if *total_uncompressed > total_budget {
            let error =
                report_archive_truncation(archive_display, *total_uncompressed, total_budget);
            if !emit(Err(error)) {
                return false;
            }
            break;
        }

        if !super::emit_archive_content_with_tex_provenance(
            archive_display,
            &entry_name,
            content,
            per_entry_cap,
            total_budget,
            total_uncompressed,
            respect_default_excludes,
            nested_depth,
            tex_package.get(&entry_name),
            emit,
        ) {
            return false;
        }
    }
    true
}

fn analyze_tex_package<R: Read + Seek>(archive: &mut zip::ZipArchive<R>) -> TexPackageAnalysis {
    if !archive.file_names().any(member_needs_source_bytes) {
        return TexPackageAnalysis::default();
    }
    let mut builder = TexPackageBuilder::default();
    for index in 0..archive.len() {
        let mut entry = match archive.by_index(index) {
            Ok(entry) => entry,
            Err(_) => {
                // LAW10: TeX analysis marks bounded and the caller emits a visible coverage error; ordinary archive members are still scanned.
                builder.mark_bounded();
                continue;
            }
        };
        if entry.is_dir() || zip_entry_is_special(&entry) {
            continue;
        }
        let name = entry.name().to_string();
        if validate_scan_archive_entry_name(&name).is_err() {
            continue;
        }
        if !member_needs_source_bytes(&name) {
            builder.add_member(&name, None);
            continue;
        }
        let entry_size = entry.size();
        let read = match crate::capped_read::read_to_cap(
            &mut entry,
            TexPackageBuilder::source_member_read_cap(),
            Some(entry_size),
        ) {
            Ok(read) => read,
            Err(_) => {
                // LAW10: TeX analysis marks bounded and the caller emits a visible coverage error; this member is still scanned without TeX annotations.
                builder.mark_bounded();
                builder.add_member(&name, None);
                continue;
            }
        };
        if read.truncated {
            builder.mark_bounded();
            builder.add_member(&name, None);
        } else {
            builder.add_member(&name, Some(&read.bytes));
        }
    }
    builder.finish()
}

fn zip_entry_is_special(entry: &zip::read::ZipFile<'_>) -> bool {
    entry.unix_mode().is_some_and(archive_unix_mode_is_special)
}

fn zip_external_attrs_are_special(external_attrs: u32) -> bool {
    let mode = external_attrs >> 16;
    mode != 0 && archive_unix_mode_is_special(mode)
}

/// Open-safety for the ZIP archive path.
///
/// Every other archive type (7z, rar, gz/xz, pdf) reads through `open_file_safe`
/// or refuses a symlink path explicitly; ZIP was the lone holdout using raw
/// `File::open`, so a symlinked `.zip` was FOLLOWED (a possible escape out of the
/// scan root) and a FIFO swapped in at a `.zip` path would HANG the scan forever.
/// All three ZIP open sites now route through `open_file_safe`, which applies
/// `O_NOFOLLOW` + `O_NONBLOCK` + an `is_file()` guard. These tests drive each open
/// site directly (codewalk's `is_file()` filter hides them from a normal walk, so
/// the live exposure is the regular->special TOCTOU swap and explicit calls) and
/// assert refusal WITHOUT hanging. Unix-only because they fabricate FIFOs /
/// symlinks / devices; the `is_file()` guard they exercise is cross-platform.
#[cfg(all(test, unix))]
mod open_safety {
    use super::{duplicates, extract_zip_archive};
    use crate::filesystem::special_file_test_support::{make_fifo, symlink_to, within_timeout};
    use std::path::PathBuf;

    /// `duplicate_central_zip_entries` (open site #1) (returns Ok(has_dups)/Err).
    fn dup_central(path: PathBuf) -> Result<bool, String> {
        within_timeout(move || {
            duplicates::duplicate_central_zip_entries(&path).map(|o| o.is_some())
        })
    }

    /// `extract_zip_archive_from_central_entries` (open site #2). (chunks, errors).
    fn from_central(path: PathBuf) -> (usize, Vec<String>) {
        within_timeout(move || {
            let mut chunks = 0usize;
            let mut errors = Vec::new();
            duplicates::extract_zip_archive_from_central_entries(
                &path,
                "archive.zip",
                u64::MAX,
                u64::MAX,
                true,
                &mut |row| {
                    match row {
                        Ok(_) => chunks += 1,
                        Err(error) => errors.push(error.to_string()),
                    }
                    true
                },
                Vec::new(),
            );
            (chunks, errors)
        })
    }

    /// `extract_zip_archive` (the entry that chains all three opens). (chunks, errors).
    fn extract(path: PathBuf) -> (usize, Vec<String>) {
        within_timeout(move || {
            let mut chunks = 0usize;
            let mut errors = Vec::new();
            extract_zip_archive(&path, "archive.zip", u64::MAX, u64::MAX, true, &mut |row| {
                match row {
                    Ok(_) => chunks += 1,
                    Err(error) => errors.push(error.to_string()),
                }
                true
            });
            (chunks, errors)
        })
    }

    // ── open site #1: duplicate_central_zip_entries ─────────────────────

    #[test]
    fn dup_central_refuses_symlink() {
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("real.bin");
        std::fs::write(&target, b"not a zip").unwrap();
        let link = symlink_to(dir.path(), "a.zip", &target);
        assert!(
            dup_central(link).is_err(),
            "a symlinked zip must not be followed"
        );
    }

    #[test]
    fn dup_central_refuses_fifo_without_hanging() {
        let dir = tempfile::tempdir().unwrap();
        let fifo = make_fifo(dir.path(), "a.zip");
        assert!(
            dup_central(fifo).is_err(),
            "a FIFO at a zip path must be refused"
        );
    }

    #[test]
    fn dup_central_refuses_directory() {
        let dir = tempfile::tempdir().unwrap();
        assert!(dup_central(dir.path().to_path_buf()).is_err());
    }

    #[test]
    fn dup_central_refuses_dev_null() {
        assert!(dup_central(PathBuf::from("/dev/null")).is_err());
    }

    #[test]
    fn dup_central_refuses_symlink_to_fifo_without_hanging() {
        let dir = tempfile::tempdir().unwrap();
        let fifo = make_fifo(dir.path(), "pipe");
        let link = symlink_to(dir.path(), "a.zip", &fifo);
        assert!(dup_central(link).is_err());
    }

    #[test]
    fn dup_central_regular_non_zip_errs_without_hanging() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("junk.zip");
        std::fs::write(&path, b"this is not a zip central directory").unwrap();
        // Opens fine (regular file), then the central-directory parse fails, a
        // graceful error, never a hang.
        assert!(dup_central(path).is_err());
    }

    #[test]
    fn dup_central_nonexistent_path_errs() {
        let dir = tempfile::tempdir().unwrap();
        assert!(dup_central(dir.path().join("missing.zip")).is_err());
    }

    // ── open site #2: extract_zip_archive_from_central_entries ───────────

    #[test]
    fn from_central_refuses_symlink_with_loud_error() {
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("real.bin");
        std::fs::write(&target, b"not a zip").unwrap();
        let link = symlink_to(dir.path(), "a.zip", &target);
        let (chunks, errors) = from_central(link);
        assert_eq!(chunks, 0, "a symlinked zip must yield no chunks");
        assert!(
            !errors.is_empty(),
            "the refusal must be surfaced loudly (Law 10)"
        );
    }

    #[test]
    fn from_central_refuses_fifo_without_hanging() {
        let dir = tempfile::tempdir().unwrap();
        let fifo = make_fifo(dir.path(), "a.zip");
        let (chunks, _errors) = from_central(fifo);
        assert_eq!(chunks, 0, "a FIFO must yield no chunks");
    }

    #[test]
    fn from_central_refuses_directory() {
        let dir = tempfile::tempdir().unwrap();
        let (chunks, _errors) = from_central(dir.path().to_path_buf());
        assert_eq!(chunks, 0);
    }

    #[test]
    fn from_central_refuses_dev_null() {
        let (chunks, _errors) = from_central(PathBuf::from("/dev/null"));
        assert_eq!(chunks, 0);
    }

    // ── entry point: extract_zip_archive (chains all three opens) ────────

    #[test]
    fn extract_refuses_symlink_no_chunks() {
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("real.bin");
        std::fs::write(&target, b"not a zip").unwrap();
        let link = symlink_to(dir.path(), "a.zip", &target);
        let (chunks, _errors) = extract(link);
        assert_eq!(
            chunks, 0,
            "a symlinked zip must not be followed into chunks"
        );
    }

    #[test]
    fn extract_symlink_emits_loud_error() {
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("real.bin");
        std::fs::write(&target, b"not a zip").unwrap();
        let link = symlink_to(dir.path(), "a.zip", &target);
        let (_chunks, errors) = extract(link);
        assert!(
            !errors.is_empty(),
            "refusing a symlinked zip must be loud, never silent"
        );
    }

    #[test]
    fn extract_refuses_fifo_without_hanging() {
        let dir = tempfile::tempdir().unwrap();
        let fifo = make_fifo(dir.path(), "a.zip");
        let (chunks, _errors) = extract(fifo);
        assert_eq!(
            chunks, 0,
            "a FIFO at a zip path must yield no chunks and not hang"
        );
    }

    #[test]
    fn extract_fifo_emits_loud_error() {
        let dir = tempfile::tempdir().unwrap();
        let fifo = make_fifo(dir.path(), "a.zip");
        let (_chunks, errors) = extract(fifo);
        assert!(
            !errors.is_empty(),
            "refusing a FIFO zip must be surfaced loudly"
        );
    }

    #[test]
    fn extract_refuses_directory() {
        let dir = tempfile::tempdir().unwrap();
        let (chunks, _errors) = extract(dir.path().to_path_buf());
        assert_eq!(chunks, 0);
    }

    #[test]
    fn extract_refuses_dev_null() {
        let (chunks, _errors) = extract(PathBuf::from("/dev/null"));
        assert_eq!(chunks, 0);
    }

    #[test]
    fn extract_refuses_symlink_to_fifo_without_hanging() {
        let dir = tempfile::tempdir().unwrap();
        let fifo = make_fifo(dir.path(), "pipe");
        let link = symlink_to(dir.path(), "a.zip", &fifo);
        let (chunks, _errors) = extract(link);
        assert_eq!(chunks, 0);
    }

    #[test]
    fn extract_regular_non_zip_no_chunks_without_hanging() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("junk.zip");
        std::fs::write(&path, b"definitely not a zip").unwrap();
        let (chunks, _errors) = extract(path);
        assert_eq!(
            chunks, 0,
            "a non-zip regular file yields no chunks and must not hang"
        );
    }

    #[test]
    fn extract_nonexistent_path_emits_error() {
        let dir = tempfile::tempdir().unwrap();
        let (chunks, errors) = extract(dir.path().join("missing.zip"));
        assert_eq!(chunks, 0);
        assert!(
            !errors.is_empty(),
            "a missing archive must surface an error"
        );
    }

    #[test]
    fn from_central_regular_non_zip_no_chunks_without_hanging() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("junk.zip");
        std::fs::write(&path, b"definitely not a zip").unwrap();
        let (chunks, _errors) = from_central(path);
        assert_eq!(chunks, 0);
    }
}