flpdf-cli 0.3.0

Command-line tools for flpdf, mirroring qpdf inspection and rewrite subcommands.
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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
//! CLI integration tests for qpdf-compatible `--check` / `check` exit codes.
//!
//! # Exit-code semantics (flpdf-9hc.23.2)
//!
//! Source: qpdf manual §"Exit Status"
//!   <https://qpdf.readthedocs.io/en/stable/cli.html#exit-status>
//! Confirmed by `qpdf/include/qpdf/Constants.h`:
//!   qpdf_exit_success = 0  (no errors or warnings)
//!   qpdf_exit_error   = 2  (errors found)
//!   qpdf_exit_warning = 3  (warnings found, no errors)
//!
//! Three fixture classes are exercised:
//!   1. clean PDF            → exit 0
//!   2. warnings-only PDF    → exit 3
//!   3. corrupt/error PDF    → exit 2

use assert_cmd::Command;
use predicates::prelude::*;
use std::io::Write;

// ---------------------------------------------------------------------------
// Fixture builders
// ---------------------------------------------------------------------------

/// Minimal but fully valid single-page PDF — produces exit 0.
fn clean_pdf_bytes() -> Vec<u8> {
    let mut pdf = Vec::new();
    pdf.extend_from_slice(b"%PDF-1.4\n");
    let off1 = pdf.len();
    pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
    let off2 = pdf.len();
    pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
    let off3 = pdf.len();
    pdf.extend_from_slice(
        b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
    );
    let xref_start = pdf.len();
    pdf.extend_from_slice(
        format!(
            "xref\n0 4\n0000000000 65535 f \n{off1:010} 00000 n \n{off2:010} 00000 n \n{off3:010} 00000 n \n"
        )
        .as_bytes(),
    );
    pdf.extend_from_slice(
        format!("trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n").as_bytes(),
    );
    pdf
}

/// PDF with a deliberately corrupt xref table.  When opened with `--repair`
/// the parser recovers via linear scan and emits a "xref repaired" warning
/// (no errors) → exit 3.
fn warnings_only_corrupt_xref_bytes() -> Vec<u8> {
    let mut pdf = Vec::new();
    pdf.extend_from_slice(b"%PDF-1.4\n");
    let offsets: Vec<usize> = {
        let objects: &[&[u8]] = &[
            b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n",
            b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n",
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
        ];
        let mut offs = Vec::new();
        for obj in objects {
            offs.push(pdf.len());
            pdf.extend_from_slice(obj);
        }
        offs
    };
    let xref_start = pdf.len();
    pdf.extend_from_slice(format!("xref\n0 {}\n", offsets.len() + 1).as_bytes());
    pdf.extend_from_slice(b"0000000000 65535 f \n");
    for off in &offsets {
        pdf.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
    }
    pdf.extend_from_slice(
        format!(
            "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n",
            offsets.len() + 1
        )
        .as_bytes(),
    );

    // Corrupt the xref keyword so the parser must repair.
    let xref_pos = pdf.windows(4).position(|w| w == b"xref").unwrap();
    pdf[xref_pos + 2] = b'z'; // "xref" → "xrzf"

    pdf
}

/// PDF that is irrecoverably corrupt — no valid objects reachable, causing
/// the check to report errors → exit 2.
fn corrupt_pdf_bytes() -> Vec<u8> {
    b"%PDF-1.4\nthis is not a valid pdf at all\n%%EOF\n".to_vec()
}

/// A structurally valid single-page PDF whose page `/Contents 4 0 R` is a
/// `/FlateDecode` stream whose body is not valid zlib. The document opens
/// cleanly (correct xref/trailer), so the only error is the decode failure of
/// the content stream — `--check` reports it as an error → exit 2.
fn corrupt_content_stream_pdf_bytes() -> Vec<u8> {
    // The literal payload is deliberately not a zlib stream; its byte length is
    // written verbatim into `/Length` so the object parses but fails to decode.
    let payload: &[u8] = b"this is not valid zlib data at all";

    let mut pdf = Vec::new();
    pdf.extend_from_slice(b"%PDF-1.4\n");

    let off1 = pdf.len();
    pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");

    let off2 = pdf.len();
    pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");

    let off3 = pdf.len();
    pdf.extend_from_slice(
        b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R >>\nendobj\n",
    );

    let off4 = pdf.len();
    pdf.extend_from_slice(
        format!(
            "4 0 obj\n<< /Filter /FlateDecode /Length {} >>\nstream\n",
            payload.len()
        )
        .as_bytes(),
    );
    pdf.extend_from_slice(payload);
    pdf.extend_from_slice(b"\nendstream\nendobj\n");

    let xref_start = pdf.len();
    pdf.extend_from_slice(
        format!(
            "xref\n0 5\n0000000000 65535 f \n{off1:010} 00000 n \n{off2:010} 00000 n \n{off3:010} 00000 n \n{off4:010} 00000 n \n"
        )
        .as_bytes(),
    );
    pdf.extend_from_slice(
        format!("trailer\n<< /Size 5 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n").as_bytes(),
    );
    pdf
}

/// A structurally valid single-page PDF whose page `/Contents 4 0 R` is a
/// *valid* FlateDecode stream that inflates to `decoded_len` bytes (small
/// compressed, large inflated). Exercises the opt-in `--decode-memory-limit`
/// guard: the stream is intact, so without a cap it is clean, and with a tight
/// cap it trips the guard as a warning.
fn bomb_content_stream_pdf_bytes(decoded_len: usize) -> Vec<u8> {
    let mut flate_dict = flpdf::Dictionary::new();
    flate_dict.insert("Filter", flpdf::Object::Name(b"FlateDecode".to_vec()));
    let encoded = flpdf::filters::encode_stream_data(&flate_dict, &vec![0u8; decoded_len]).unwrap();

    let mut pdf = Vec::new();
    pdf.extend_from_slice(b"%PDF-1.4\n");
    let off1 = pdf.len();
    pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
    let off2 = pdf.len();
    pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
    let off3 = pdf.len();
    pdf.extend_from_slice(
        b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R >>\nendobj\n",
    );
    let off4 = pdf.len();
    pdf.extend_from_slice(
        format!(
            "4 0 obj\n<< /Filter /FlateDecode /Length {} >>\nstream\n",
            encoded.len()
        )
        .as_bytes(),
    );
    pdf.extend_from_slice(&encoded);
    pdf.extend_from_slice(b"\nendstream\nendobj\n");
    let xref_start = pdf.len();
    pdf.extend_from_slice(
        format!(
            "xref\n0 5\n0000000000 65535 f \n{off1:010} 00000 n \n{off2:010} 00000 n \n{off3:010} 00000 n \n{off4:010} 00000 n \n"
        )
        .as_bytes(),
    );
    pdf.extend_from_slice(
        format!("trailer\n<< /Size 5 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n").as_bytes(),
    );
    pdf
}

/// Valid xref but the trailer lacks /Root — opens fine, check reports an
/// error-severity diagnostic → exit 2.
fn missing_root_pdf_bytes() -> Vec<u8> {
    let mut pdf = Vec::new();
    pdf.extend_from_slice(b"%PDF-1.4\n");
    let off1 = pdf.len();
    pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
    let off2 = pdf.len();
    pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [] /Count 0 >>\nendobj\n");
    let xref_start = pdf.len();
    pdf.extend_from_slice(
        format!("xref\n0 3\n0000000000 65535 f \n{off1:010} 00000 n \n{off2:010} 00000 n \n")
            .as_bytes(),
    );
    pdf.extend_from_slice(
        format!("trailer\n<< /Size 3 >>\nstartxref\n{xref_start}\n%%EOF\n").as_bytes(),
    );
    pdf
}

/// Clean PDF whose catalog declares an Adobe extension level
/// (`/Extensions /ADBE /ExtensionLevel 8`). qpdf appends `extension level 8` to
/// its `PDF Version:` banner.
fn extension_level_pdf_bytes() -> Vec<u8> {
    let mut pdf = Vec::new();
    pdf.extend_from_slice(b"%PDF-1.7\n");
    let off1 = pdf.len();
    pdf.extend_from_slice(
        b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /Extensions << /ADBE << /BaseVersion /1.7 /ExtensionLevel 8 >> >> >>\nendobj\n",
    );
    let off2 = pdf.len();
    pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
    let off3 = pdf.len();
    pdf.extend_from_slice(
        b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
    );
    let xref_start = pdf.len();
    pdf.extend_from_slice(
        format!(
            "xref\n0 4\n0000000000 65535 f \n{off1:010} 00000 n \n{off2:010} 00000 n \n{off3:010} 00000 n \n"
        )
        .as_bytes(),
    );
    pdf.extend_from_slice(
        format!("trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n").as_bytes(),
    );
    pdf
}

/// Valid PDF whose first object (object 1) carries `/Linearized 1`. flpdf's
/// structural detector (`Pdf::linearized_hint_ref`, object (1,0)) reports this
/// as linearized, which pushes the "linearized PDF detected" advisory warning
/// → exit 3. (Full qpdf-accurate linearization parity is tracked in flpdf-u1ro.)
fn linearized_obj1_pdf_bytes() -> Vec<u8> {
    let mut pdf = Vec::new();
    pdf.extend_from_slice(b"%PDF-1.4\n");
    let off1 = pdf.len();
    pdf.extend_from_slice(
        b"1 0 obj\n<< /Linearized 1 /L 0 /H [ 0 0 ] /O 4 /E 0 /N 1 /T 0 >>\nendobj\n",
    );
    let off2 = pdf.len();
    pdf.extend_from_slice(b"2 0 obj\n<< /Type /Catalog /Pages 3 0 R >>\nendobj\n");
    let off3 = pdf.len();
    pdf.extend_from_slice(b"3 0 obj\n<< /Type /Pages /Kids [4 0 R] /Count 1 >>\nendobj\n");
    let off4 = pdf.len();
    pdf.extend_from_slice(
        b"4 0 obj\n<< /Type /Page /Parent 3 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
    );
    let xref_start = pdf.len();
    pdf.extend_from_slice(
        format!(
            "xref\n0 5\n0000000000 65535 f \n{off1:010} 00000 n \n{off2:010} 00000 n \n{off3:010} 00000 n \n{off4:010} 00000 n \n"
        )
        .as_bytes(),
    );
    pdf.extend_from_slice(
        format!("trailer\n<< /Size 5 /Root 2 0 R >>\nstartxref\n{xref_start}\n%%EOF\n").as_bytes(),
    );
    pdf
}

// ---------------------------------------------------------------------------
// Tests: exit 0 — clean PDF
// ---------------------------------------------------------------------------

#[test]
fn check_clean_pdf_exits_0() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&clean_pdf_bytes()).unwrap();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.args(["--check", f.path().to_str().unwrap()])
        .assert()
        .code(0)
        .stdout(predicate::str::contains("File is not encrypted\n"))
        .stdout(predicate::str::contains("PDF check succeeded").not())
        .stderr(predicate::str::is_empty());
}

#[test]
fn check_subcommand_clean_pdf_exits_0() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&clean_pdf_bytes()).unwrap();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.args(["check", f.path().to_str().unwrap()])
        .assert()
        .code(0)
        .stdout(predicate::str::contains("File is not encrypted\n"))
        .stdout(predicate::str::contains("PDF check succeeded").not())
        .stderr(predicate::str::is_empty());
}

// ---------------------------------------------------------------------------
// Tests: qpdf-compatible stdout "checking" block
// ---------------------------------------------------------------------------

/// A clean plaintext PDF prints qpdf's full check block: the `checking <file>`
/// banner, header version, encryption + linearization status, and the trailing
/// reassurance note. The subject of that note is `progname()` (here `flpdf`).
#[test]
fn check_clean_pdf_emits_qpdf_block() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&clean_pdf_bytes()).unwrap();
    let path = f.path().to_str().unwrap().to_string();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.env_remove("FLPDF_PROGNAME")
        .args(["--check", &path])
        .assert()
        .code(0)
        .stdout(predicate::str::contains(format!("checking {path}\n")))
        .stdout(predicate::str::contains("PDF Version: 1.4\n"))
        .stdout(predicate::str::contains("File is not encrypted\n"))
        .stdout(predicate::str::contains("File is not linearized\n"))
        .stdout(predicate::str::contains(
            "No syntax or stream encoding errors found; the file may still contain\nerrors that flpdf cannot detect\n",
        ))
        .stdout(predicate::str::contains("PDF check succeeded").not());
}

/// On exit 3 (warnings, no errors) the block is still printed, but qpdf omits
/// the trailing "No syntax ..." reassurance note (warnings go to stderr).
#[test]
fn check_warnings_emit_block_without_trailing_line() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&warnings_only_corrupt_xref_bytes()).unwrap();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.env_remove("FLPDF_PROGNAME")
        .args(["--check", "--repair", f.path().to_str().unwrap()])
        .assert()
        .code(3)
        .stdout(predicate::str::contains("File is not encrypted\n"))
        .stdout(predicate::str::contains("File is not linearized\n"))
        .stdout(predicate::str::contains("No syntax or stream encoding errors found").not())
        .stdout(predicate::str::contains("PDF check succeeded").not());
}

/// A catalog `/Extensions /ADBE /ExtensionLevel` is appended to the version
/// banner, matching qpdf (`PDF Version: 1.7 extension level 8`).
#[test]
fn check_appends_adobe_extension_level_to_version() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&extension_level_pdf_bytes()).unwrap();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.env_remove("FLPDF_PROGNAME")
        .args(["--check", f.path().to_str().unwrap()])
        .assert()
        .code(0)
        .stdout(predicate::str::contains(
            "PDF Version: 1.7 extension level 8\n",
        ));
}

/// A file whose first object is a `/Linearized` dictionary prints
/// `File is linearized`. flpdf's structural detector also pushes the
/// linearization advisory warning, so the run exits 3 (and therefore omits the
/// trailing reassurance note). Full qpdf-accurate behaviour is tracked in
/// flpdf-u1ro.
#[test]
fn check_linearized_pdf_reports_linearized_line() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&linearized_obj1_pdf_bytes()).unwrap();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.env_remove("FLPDF_PROGNAME")
        .args(["--check", f.path().to_str().unwrap()])
        .assert()
        .code(3)
        .stdout(predicate::str::contains("File is linearized\n"))
        .stdout(predicate::str::contains("File is not linearized").not());
}

// ---------------------------------------------------------------------------
// Tests: exit 3 — warnings without errors (corrupt xref, repaired)
// ---------------------------------------------------------------------------

#[test]
fn check_warnings_only_pdf_exits_3() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&warnings_only_corrupt_xref_bytes()).unwrap();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    // --repair triggers the recovery heuristic; the resulting "xref repaired"
    // diagnostic is a warning (no error) → exit 3.
    cmd.args(["--check", "--repair", f.path().to_str().unwrap()])
        .assert()
        .code(3)
        .stdout(predicate::str::contains("File is not encrypted\n"))
        .stderr(predicate::str::contains("WARNING: "));
}

#[test]
fn check_subcommand_warnings_only_pdf_exits_3() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&warnings_only_corrupt_xref_bytes()).unwrap();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.args(["check", "--repair", f.path().to_str().unwrap()])
        .assert()
        .code(3)
        .stdout(predicate::str::contains("File is not encrypted\n"))
        .stderr(predicate::str::contains("WARNING: "));
}

#[test]
fn check_warnings_use_qpdf_stderr_format() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&warnings_only_corrupt_xref_bytes()).unwrap();
    let path = f.path().to_str().unwrap().to_string();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.env_remove("FLPDF_PROGNAME")
        .args(["--check", "--repair", &path])
        .assert()
        .code(3)
        .stdout(predicate::str::contains("File is not encrypted\n"))
        // qpdf shape: WARNING: <file>: <msg>, surrounding warnings without
        // offset, then the trailing summary line.
        .stderr(predicate::str::contains(format!(
            "WARNING: {path}: file is damaged\n"
        )))
        .stderr(predicate::str::contains(
            "Attempting to reconstruct cross-reference table\n",
        ))
        .stderr(predicate::str::contains(
            "flpdf: operation succeeded with warnings\n",
        ))
        // The old lowercase `warning: <msg>` prefix must be gone.
        .stderr(predicate::str::contains("warning: ").not());
}

/// The trigger warning (and only the trigger warning) carries `(offset N)`.
#[test]
fn check_trigger_warning_carries_offset() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&warnings_only_corrupt_xref_bytes()).unwrap();
    let path = f.path().to_str().unwrap().to_string();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.args(["--check", "--repair", &path])
        .assert()
        .code(3)
        .stderr(
            predicate::str::is_match(format!(
                "WARNING: {} \\(offset \\d+\\): ",
                regex::escape(&path)
            ))
            .unwrap(),
        )
        .stderr(predicate::str::contains(format!("WARNING: {path} (offset")).count(1));
}

// ---------------------------------------------------------------------------
// Tests: exit 2 — errors / corrupt PDF
// ---------------------------------------------------------------------------

#[test]
fn check_corrupt_pdf_exits_2() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&corrupt_pdf_bytes()).unwrap();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.args(["--check", f.path().to_str().unwrap()])
        .assert()
        .code(2);
}

/// A document that opens cleanly but whose page content stream fails to decode
/// is an error, not a warning: `--check` exits 2 and, because the run is not
/// valid, suppresses the trailing "No syntax or stream encoding errors found"
/// reassurance note (which is only printed on a clean exit-0 run). The decode
/// failure is reported on stderr, which also proves the exit-2 comes from the
/// content stream rather than a structural parse failure.
#[test]
fn check_corrupt_content_stream_exits_2_without_clean_note() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&corrupt_content_stream_pdf_bytes()).unwrap();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.env_remove("FLPDF_PROGNAME")
        .args(["--check", f.path().to_str().unwrap()])
        .assert()
        .code(2)
        .stdout(predicate::str::contains("No syntax or stream encoding errors found").not())
        .stderr(predicate::str::contains(
            "errors while decoding content stream",
        ));
}

/// qpdf prints check errors as a single `<progname>: <file>: <msg>` line and
/// no extra "check failed" summary (observed with qpdf 11.9.0 on the same
/// fixture: `qpdf: noroot.pdf: unable to find /Root dictionary`).
#[test]
fn check_error_diagnostics_use_qpdf_stderr_format() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&missing_root_pdf_bytes()).unwrap();
    let path = f.path().to_str().unwrap().to_string();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.env_remove("FLPDF_PROGNAME")
        .args(["--check", &path])
        .assert()
        .code(2)
        .stderr(predicate::str::contains(format!(
            "flpdf: {path}: trailer is missing /Root\n"
        )))
        .stderr(predicate::str::contains("PDF check failed").not())
        .stderr(predicate::str::contains("error: ").not())
        // exit 2 emits no stdout block at all: qpdf throws during document init
        // (missing /Root) before printing the `checking` banner, and flpdf
        // matches by gating the block on a valid report.
        .stdout(predicate::str::is_empty());
}

/// Fatal open errors carry the input path: `<progname>: <file>: <msg>`
/// (observed qpdf shape: `qpdf: notpdf.pdf: unable to find trailer
/// dictionary while recovering damaged file`).
#[test]
fn fatal_open_error_includes_filename() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&corrupt_pdf_bytes()).unwrap();
    let path = f.path().to_str().unwrap().to_string();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.env_remove("FLPDF_PROGNAME")
        .args(["--check", &path])
        .assert()
        .code(2)
        .stderr(predicate::str::contains(format!("flpdf: {path}: ")));
}

/// FLPDF_PROGNAME swaps the program-name prefix (the qpdf qtest harness shim
/// sets FLPDF_PROGNAME=qpdf); diagnostics are otherwise identical.
#[test]
fn flpdf_progname_env_swaps_prefix() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&warnings_only_corrupt_xref_bytes()).unwrap();
    let path = f.path().to_str().unwrap().to_string();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.env("FLPDF_PROGNAME", "qpdf")
        .args(["--check", "--repair", &path])
        .assert()
        .code(3)
        .stderr(predicate::str::contains(
            "qpdf: operation succeeded with warnings\n",
        ))
        .stderr(predicate::str::contains("flpdf:").not());
}

/// An empty FLPDF_PROGNAME falls back to the default prefix instead of
/// rendering a broken `: <message>` line.
#[test]
fn flpdf_progname_empty_env_falls_back_to_default() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&warnings_only_corrupt_xref_bytes()).unwrap();
    let path = f.path().to_str().unwrap().to_string();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.env("FLPDF_PROGNAME", "")
        .args(["--check", "--repair", &path])
        .assert()
        .code(3)
        .stderr(predicate::str::contains(
            "flpdf: operation succeeded with warnings\n",
        ));
}

/// Same prefix swap on the fatal-open-error path, which is rendered by
/// main()'s result handler rather than run_check itself.
#[test]
fn flpdf_progname_env_swaps_prefix_on_fatal_error() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&corrupt_pdf_bytes()).unwrap();
    let path = f.path().to_str().unwrap().to_string();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.env("FLPDF_PROGNAME", "qpdf")
        .args(["--check", &path])
        .assert()
        .code(2)
        .stderr(predicate::str::contains(format!("qpdf: {path}: ")))
        .stderr(predicate::str::contains("flpdf:").not());
}

#[test]
fn check_subcommand_corrupt_pdf_exits_2() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&corrupt_pdf_bytes()).unwrap();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.args(["check", f.path().to_str().unwrap()])
        .assert()
        .code(2);
}

/// Repair warnings emitted while opening for any subcommand (here: rewrite)
/// use the same qpdf shape as check.
#[test]
fn rewrite_repair_warnings_use_qpdf_stderr_format() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&warnings_only_corrupt_xref_bytes()).unwrap();
    let path = f.path().to_str().unwrap().to_string();
    let out = tempfile::NamedTempFile::new().unwrap();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.env_remove("FLPDF_PROGNAME")
        .args(["rewrite", "--repair", &path, out.path().to_str().unwrap()])
        .assert()
        .success()
        .stderr(predicate::str::contains(format!(
            "WARNING: {path}: file is damaged\n"
        )))
        .stderr(predicate::str::contains("warning: ").not());
}

// ---------------------------------------------------------------------------
// Tests: opt-in `--decode-memory-limit` decompression-bomb guard
// ---------------------------------------------------------------------------

/// With `--decode-memory-limit` below the inflated size, the intact-but-large
/// content stream trips the decompression-bomb guard: a WARNING (exit 3), the
/// trailing "clean" note suppressed — NOT an error (exit 2).
#[test]
fn check_decode_memory_limit_bomb_warns_exit_3() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&bomb_content_stream_pdf_bytes(64 * 1024))
        .unwrap();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.env_remove("FLPDF_PROGNAME")
        .args([
            "--check",
            "--decode-memory-limit",
            "1024",
            f.path().to_str().unwrap(),
        ])
        .assert()
        .code(3)
        .stdout(predicate::str::contains("No syntax or stream encoding errors found").not())
        .stderr(predicate::str::contains("decode-bomb guard"));
}

/// Without the flag, the same large stream decodes fine: clean exit 0 (default
/// unlimited, matching qpdf).
#[test]
fn check_no_limit_large_stream_exits_0() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&bomb_content_stream_pdf_bytes(64 * 1024))
        .unwrap();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.args(["--check", f.path().to_str().unwrap()])
        .assert()
        .code(0);
}

/// The `check` subcommand carries the same flag.
#[test]
fn check_subcommand_decode_memory_limit_bomb_warns_exit_3() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&bomb_content_stream_pdf_bytes(64 * 1024))
        .unwrap();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.args([
        "check",
        "--decode-memory-limit",
        "1024",
        f.path().to_str().unwrap(),
    ])
    .assert()
    .code(3)
    .stderr(predicate::str::contains("decode-bomb guard"));
}

/// A genuinely corrupt content stream is still an error (exit 2) even with the
/// cap set — the limit path must not mask real decode failures.
#[test]
fn check_decode_memory_limit_does_not_mask_corruption() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&corrupt_content_stream_pdf_bytes()).unwrap();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.args([
        "--check",
        "--decode-memory-limit",
        "1024",
        f.path().to_str().unwrap(),
    ])
    .assert()
    .code(2)
    .stderr(predicate::str::contains(
        "errors while decoding content stream",
    ));
}

/// `--decode-memory-limit` only affects the `--check` audit path, so passing it
/// without `--check` is a clap usage error (`requires = "check"`) rather than a
/// silently-ignored flag. clap reports a missing-required-argument error
/// (exit 2) naming `--check`.
#[test]
fn decode_memory_limit_requires_check() {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(&clean_pdf_bytes()).unwrap();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.args(["--decode-memory-limit", "1024", f.path().to_str().unwrap()])
        .assert()
        .code(2)
        .stderr(predicate::str::contains("--check"));
}

// ---------------------------------------------------------------------------
// Tests: weak-crypto files are inspectable by `--check` (read-only parity)
//
// qpdf treats `--check` as a read-only inspection, like `--show-encryption`,
// `--requires-password`, and `--is-encrypted`: an RC4 / R=5 file opened with the
// CORRECT password and NO `--allow-weak-crypto` is checked and exits 0 with no
// weak-crypto warning. Verified with qpdf 11.9.0:
//   qpdf --check --password=user-v2 tests/fixtures/encrypted/v2-rc4-128-r3.pdf
//   → exit 0, prints the check block + "No syntax or stream encoding errors
//     found", and emits NO weak-crypto warning on stderr.
// flpdf previously hit the weak-crypto gate here and exited 2.
// ---------------------------------------------------------------------------

/// RC4 (weak crypto) fixture inspectable with the correct user password.
const WEAK_RC4_FIXTURE: &str = "../../tests/fixtures/encrypted/v2-rc4-128-r3.pdf";

#[test]
fn check_weak_rc4_correct_password_exits_0_as_inspection() {
    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.env_remove("FLPDF_PROGNAME")
        .args(["--check", "--password=user-v2", WEAK_RC4_FIXTURE])
        .assert()
        // exit 0: opened as a read-only inspection, no errors, no warnings.
        .code(0)
        // The trailing reassurance note is printed only on a clean exit-0 run,
        // so its presence proves both that the file opened AND that the
        // weak-crypto warning was suppressed (otherwise it would be exit 3).
        .stdout(predicate::str::contains(
            "No syntax or stream encoding errors found",
        ))
        // No weak-crypto error/warning surfaced anywhere — qpdf emits none.
        .stderr(predicate::str::contains("weak crypto").not());
}

#[test]
fn check_subcommand_weak_rc4_correct_password_exits_0() {
    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.env_remove("FLPDF_PROGNAME")
        .args(["check", "--password=user-v2", WEAK_RC4_FIXTURE])
        .assert()
        .code(0)
        .stdout(predicate::str::contains(
            "No syntax or stream encoding errors found",
        ))
        .stderr(predicate::str::contains("weak crypto").not());
}

/// Forcing the weak-crypto gate open for the inspection must NOT bypass
/// authentication: a wrong password still fails (exit 2), exactly as before.
#[test]
fn check_weak_rc4_wrong_password_still_exits_2() {
    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.env_remove("FLPDF_PROGNAME")
        .args(["--check", "--password=wrong", WEAK_RC4_FIXTURE])
        .assert()
        .code(2);
}