flpdf-cli 0.10.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
//! End-to-end CLI wiring tests for `--overlay` / `--underlay` (not byte-level).
//!
//! These run in the default Pure-Rust build (no `qpdf-zlib-compat`): they
//! exercise the full CLI path — raw-argv pre-split (`extract_overlay_groups`),
//! source open + `flpdf::OverlaySpec` build (`build_overlay_specs`), the
//! `run_rewrite` overlay-stacking step, and the write — and assert observable
//! outcomes (exit status, page count, presence of the overlay XObject markers).
//!
//! Byte-identity to qpdf is proven at the library layer (the `overlay::byte_gate`
//! tests in `crates/flpdf/src/overlay.rs`) and — for the plain full-rewrite path
//! — at the CLI layer in `cli_byte_identical`, both run with `qpdf-zlib-compat`.
//! The default Pure-Rust build's DEFLATE bytes still diverge from qpdf's zlib
//! output (see `tests/golden/compat-matrix.md`), so these tests assert wiring
//! behavior rather than exact output bytes.

use std::path::{Path, PathBuf};

use assert_cmd::Command;
use predicates::prelude::*;

fn fixtures_dir() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat")
        .to_path_buf()
}

fn fixture(name: &str) -> String {
    fixtures_dir().join(name).to_str().unwrap().to_string()
}

/// Run `flpdf rewrite <dest> <overlay_args...> <OUT>` and return the output
/// bytes, asserting exit 0.
fn run_overlay_ok(dest: &str, overlay_args: &[&str]) -> Vec<u8> {
    let tmp = tempfile::tempdir().expect("tempdir");
    let out = tmp.path().join("overlay-out.pdf");

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.arg("rewrite").arg(fixture(dest));
    for a in overlay_args {
        cmd.arg(a);
    }
    cmd.arg(&out);
    cmd.assert().success();

    std::fs::read(&out).expect("output file present after success")
}

/// Like [`run_overlay_ok`] but injects `--static-id` so two separate invocations
/// produce byte-comparable output (the trailer /ID is otherwise randomized per
/// run). `FLPDF_STATIC_ID_QUIET` suppresses the testing-only stderr warning.
fn run_overlay_static_id(dest: &str, overlay_args: &[&str]) -> Vec<u8> {
    let tmp = tempfile::tempdir().expect("tempdir");
    let out = tmp.path().join("overlay-out.pdf");

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    cmd.env("FLPDF_STATIC_ID_QUIET", "1");
    cmd.arg("rewrite").arg("--static-id").arg(fixture(dest));
    for a in overlay_args {
        cmd.arg(a);
    }
    cmd.arg(&out);
    cmd.assert().success();

    std::fs::read(&out).expect("output file present after success")
}

#[test]
fn overlay_succeeds_and_output_parses_with_same_page_count() {
    let one = fixture("one-page.pdf");
    let bytes = run_overlay_ok("three-page.pdf", &["--overlay", &one, "--"]);

    // The output must be a valid PDF flpdf can re-open with the dest page count
    // unchanged (overlay stacks content, it does not add/remove pages).
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("reparse.pdf");
    std::fs::write(&path, &bytes).unwrap();
    Command::cargo_bin("flpdf")
        .unwrap()
        .arg("--show-npages")
        .arg(&path)
        .assert()
        .success()
        .stdout(predicate::str::contains("3"));

    // The applied overlay rebuilds page 1's resources as /Fx0 (the page) + /Fx1
    // (the source); their presence proves the stacking step actually ran.
    let text = String::from_utf8_lossy(&bytes);
    assert!(
        text.contains("/Fx0"),
        "overlay must convert the page to /Fx0"
    );
    assert!(
        text.contains("/Fx1"),
        "overlay must import the source as /Fx1"
    );
}

#[test]
fn two_overlays_compose_successfully() {
    let one = fixture("one-page.pdf");
    let two = fixture("two-page.pdf");
    let bytes = run_overlay_ok(
        "three-page.pdf",
        &["--overlay", &one, "--", "--overlay", &two, "--"],
    );
    let text = String::from_utf8_lossy(&bytes);
    // Page 1 receives both sources: /Fx0 (page) + /Fx1 + /Fx2.
    assert!(
        text.contains("/Fx2"),
        "two overlays must produce /Fx2: composed"
    );
}

#[test]
fn overlay_and_underlay_compose_successfully() {
    let one = fixture("one-page.pdf");
    let two = fixture("two-page.pdf");
    let bytes = run_overlay_ok(
        "three-page.pdf",
        &["--overlay", &one, "--", "--underlay", &two, "--"],
    );
    let text = String::from_utf8_lossy(&bytes);
    assert!(
        text.contains("/Fx2"),
        "mixed overlay+underlay must produce /Fx2"
    );
}

#[test]
fn overlay_with_from_range_succeeds() {
    // `--from=2` selects source page 2 first; the CLI must thread the range
    // through `build_overlay_specs` so the overlay still stacks (p1 <- s2).
    let two = fixture("two-page.pdf");
    let bytes = run_overlay_ok("three-page.pdf", &["--overlay", &two, "--from=2", "--"]);
    let text = String::from_utf8_lossy(&bytes);
    assert!(text.contains("/Fx0"), "page must become /Fx0");
    assert!(
        text.contains("/Fx1"),
        "--from-selected source must import as /Fx1"
    );
}

#[test]
fn empty_from_differs_from_absent_from() {
    // qpdf parity: an explicit empty `--from=` is an empty source set, so
    // `--repeat` cycles from the first dest page (every dest page <- s2). This is
    // observably different from an absent `--from` (p1<-s1, p2<-s2, then repeat),
    // so the two invocations must NOT produce identical output.
    let two = fixture("two-page.pdf");
    let absent = run_overlay_ok("three-page.pdf", &["--overlay", &two, "--repeat=2", "--"]);
    let empty = run_overlay_ok(
        "three-page.pdf",
        &["--overlay", &two, "--from=", "--repeat=2", "--"],
    );
    assert_ne!(
        absent, empty,
        "explicit empty --from= must be distinguished from an absent --from"
    );
}

#[test]
fn empty_to_is_a_noop_and_differs_from_absent_to() {
    // qpdf parity: an explicit empty `--to=` is an empty destination set, so the
    // overlay applies to no page (a no-op). The output must equal a plain rewrite
    // of the destination (no source imported -> no `/Fx1` marker) and be
    // observably different from an absent `--to` (which overlays every page).
    // `--static-id` pins the trailer /ID so the two runs are byte-comparable.
    let two = fixture("two-page.pdf");
    let passthrough = run_overlay_static_id("three-page.pdf", &[]);
    let empty_to = run_overlay_static_id("three-page.pdf", &["--overlay", &two, "--to=", "--"]);
    let absent_to = run_overlay_static_id("three-page.pdf", &["--overlay", &two, "--"]);

    assert_eq!(
        empty_to, passthrough,
        "empty --to= overlay must be a no-op (== plain rewrite of the dest)"
    );
    assert!(
        !String::from_utf8_lossy(&empty_to).contains("/Fx1"),
        "no-op overlay must not import the source as /Fx1"
    );
    assert_ne!(
        empty_to, absent_to,
        "explicit empty --to= must be distinguished from an absent --to"
    );
}

#[test]
fn empty_repeat_equals_absent_repeat_and_differs_from_a_set_repeat() {
    // qpdf parity: an explicit empty `--repeat=` means no repetition, identical
    // to an absent `--repeat`. Both must produce the same output, and both must
    // differ from a non-empty `--repeat=1` (which cycles the source onto the
    // surplus destination pages). `--static-id` pins the trailer /ID so the runs
    // are byte-comparable.
    let two = fixture("two-page.pdf");
    let absent = run_overlay_static_id("three-page.pdf", &["--overlay", &two, "--"]);
    let empty = run_overlay_static_id("three-page.pdf", &["--overlay", &two, "--repeat=", "--"]);
    let set = run_overlay_static_id("three-page.pdf", &["--overlay", &two, "--repeat=1", "--"]);

    assert_eq!(
        empty, absent,
        "empty --repeat= must behave as no repeat (== absent --repeat)"
    );
    assert_ne!(empty, set, "a non-empty --repeat=1 must still take effect");
}

#[test]
fn single_underlay_succeeds() {
    // A lone `--underlay` (no overlay) must stack the source beneath the page.
    let two = fixture("two-page.pdf");
    let bytes = run_overlay_ok("three-page.pdf", &["--underlay", &two, "--"]);
    let text = String::from_utf8_lossy(&bytes);
    assert!(text.contains("/Fx0"), "page must become /Fx0");
    assert!(text.contains("/Fx1"), "underlay source must import as /Fx1");
}

#[test]
fn overlay_with_pages_composes_page_selection_then_overlay() {
    // qpdf runs page-selection FIRST, then applies overlays on the reduced
    // page set (mirror `libqpdf/QPDFJob.cc`). `--pages . 1-2` extracts pages
    // 1-2 of three-page.pdf; the overlay's `--to`/`--from` (default 1-z)
    // then references the two extracted pages, not the original three.
    let one = fixture("one-page.pdf");
    let tmp = tempfile::tempdir().unwrap();
    let out = tmp.path().join("o.pdf");
    Command::cargo_bin("flpdf")
        .unwrap()
        .arg("rewrite")
        .arg(fixture("three-page.pdf"))
        .args(["--overlay", &one, "--"])
        .args(["--pages", ".", "1-2", "--"])
        .arg(out.to_str().unwrap())
        .assert()
        .success();
    let bytes = std::fs::read(&out).unwrap();
    let text = String::from_utf8_lossy(&bytes);
    assert!(
        text.contains("/Fx0"),
        "overlay leaves /Fx0 marker on each page"
    );
}

#[test]
fn overlay_with_rotate_alone_still_rejected() {
    // --rotate/--split-pages without --pages goes through
    // `run_rewrite_with_page_ops`, which does not run overlay stacking;
    // reject the combination loudly instead of dropping the overlays.
    let one = fixture("one-page.pdf");
    let tmp = tempfile::tempdir().unwrap();
    let out = tmp.path().join("o.pdf");
    Command::cargo_bin("flpdf")
        .unwrap()
        .arg("rewrite")
        .arg(fixture("three-page.pdf"))
        .args(["--overlay", &one, "--"])
        .args(["--rotate=+90:1"])
        .arg(out.to_str().unwrap())
        .assert()
        .failure()
        .stderr(predicate::str::contains(
            "--rotate/--split-pages alone (no --pages)",
        ));
}

#[test]
fn overlay_with_linearize_is_accepted() {
    let one = fixture("one-page.pdf");
    let tmp = tempfile::tempdir().unwrap();
    let out = tmp.path().join("o.pdf");
    Command::cargo_bin("flpdf")
        .unwrap()
        .arg("rewrite")
        .arg("--linearize")
        .arg(fixture("three-page.pdf"))
        .args(["--overlay", &one, "--"])
        .arg(out.to_str().unwrap())
        .assert()
        .success();
    assert!(out.is_file(), "linearized overlay output must be written");
}

#[test]
fn unterminated_overlay_group_treats_the_output_token_as_a_second_file() {
    let one = fixture("one-page.pdf");
    let tmp = tempfile::tempdir().unwrap();
    let out = tmp.path().join("o.pdf");
    // Without the bare `--`, qpdf keeps parsing the output token inside the
    // underlay/overlay table, so it is the second file and not the output yet.
    Command::cargo_bin("flpdf")
        .unwrap()
        .arg("rewrite")
        .arg(fixture("three-page.pdf"))
        .args(["--overlay", &one])
        .arg(out.to_str().unwrap())
        .assert()
        .failure()
        .stderr(predicate::str::contains("overlay file already specified"));
}

#[test]
fn top_level_overlay_with_pages_composes() {
    // Top-level (subcommand-less) qpdf-shaped invocation must also compose
    // page-selection with overlay (same ordering as the `rewrite` surface).
    let one = fixture("one-page.pdf");
    let tmp = tempfile::tempdir().unwrap();
    let out = tmp.path().join("o.pdf");
    Command::cargo_bin("flpdf")
        .unwrap()
        .arg(fixture("three-page.pdf"))
        .args(["--overlay", &one, "--"])
        .args(["--pages", ".", "1-2", "--"])
        .arg(out.to_str().unwrap())
        .assert()
        .success();
    let bytes = std::fs::read(&out).unwrap();
    let text = String::from_utf8_lossy(&bytes);
    assert!(
        text.contains("/Fx0"),
        "overlay leaves /Fx0 marker on each page"
    );
}

#[test]
fn unterminated_underlay_group_treats_the_output_token_as_a_second_file() {
    let two = fixture("two-page.pdf");
    let tmp = tempfile::tempdir().unwrap();
    let out = tmp.path().join("o.pdf");
    Command::cargo_bin("flpdf")
        .unwrap()
        .arg("rewrite")
        .arg(fixture("three-page.pdf"))
        .args(["--underlay", &two])
        .arg(out.to_str().unwrap())
        .assert()
        .failure()
        .stderr(predicate::str::contains("underlay file already specified"));
}

#[test]
fn top_level_overlay_alias_succeeds() {
    // qpdf-shaped top-level form: `flpdf in --overlay f -- out`.
    let one = fixture("one-page.pdf");
    let tmp = tempfile::tempdir().unwrap();
    let out = tmp.path().join("o.pdf");
    Command::cargo_bin("flpdf")
        .unwrap()
        .arg(fixture("three-page.pdf"))
        .args(["--overlay", &one, "--"])
        .arg(out.to_str().unwrap())
        .assert()
        .success();
    let bytes = std::fs::read(&out).unwrap();
    assert!(String::from_utf8_lossy(&bytes).contains("/Fx0"));
}

#[test]
fn overlay_encrypted_source_with_correct_password_succeeds() {
    // The source is AES-256 encrypted (user password "u"). The segment's
    // --password= must be threaded to the source open so the page can be
    // imported as the overlay XObject. (Output is not byte-compared here — see
    // the module doc; byte-identity for a higher-version source is checked
    // separately by the version-floor propagation tests.)
    let enc = fixture("one-page-enc-u.pdf");
    let bytes = run_overlay_ok("three-page.pdf", &["--overlay", &enc, "--password=u", "--"]);
    let text = String::from_utf8_lossy(&bytes);
    assert!(text.contains("/Fx0"), "page must become /Fx0");
    assert!(
        text.contains("/Fx1"),
        "decrypted source must import as /Fx1"
    );
}

#[test]
fn overlay_encrypted_source_with_wrong_password_fails() {
    let enc = fixture("one-page-enc-u.pdf");
    let tmp = tempfile::tempdir().unwrap();
    let out = tmp.path().join("o.pdf");
    Command::cargo_bin("flpdf")
        .unwrap()
        .arg("rewrite")
        .arg(fixture("three-page.pdf"))
        .args(["--overlay", &enc, "--password=wrong", "--"])
        .arg(out.to_str().unwrap())
        .assert()
        .failure();
}

#[test]
fn overlay_encrypted_source_without_password_fails() {
    let enc = fixture("one-page-enc-u.pdf");
    let tmp = tempfile::tempdir().unwrap();
    let out = tmp.path().join("o.pdf");
    Command::cargo_bin("flpdf")
        .unwrap()
        .arg("rewrite")
        .arg(fixture("three-page.pdf"))
        .args(["--overlay", &enc, "--"])
        .arg(out.to_str().unwrap())
        .assert()
        .failure();
}

#[test]
fn overlay_on_non_rewrite_subcommand_is_rejected() {
    // An overlay group is stripped from argv before clap; on a non-rewrite
    // command it must fail loudly, not be silently ignored.
    let one = fixture("one-page.pdf");
    Command::cargo_bin("flpdf")
        .unwrap()
        .arg("check")
        .arg(fixture("three-page.pdf"))
        .args(["--overlay", &one, "--"])
        .assert()
        .failure()
        .stderr(predicate::str::contains(
            "can only be used with rewrite output",
        ));
}

#[test]
fn overlay_equals_form_without_a_positional_source_is_rejected() {
    // qpdf discards the value attached to its bare `--overlay` option. With no
    // following positional source, both qpdf and flpdf reject the empty group.
    let one = fixture("one-page.pdf");
    let tmp = tempfile::tempdir().unwrap();
    let out = tmp.path().join("o.pdf");
    Command::cargo_bin("flpdf")
        .unwrap()
        .arg("rewrite")
        .arg(fixture("three-page.pdf"))
        .arg(format!("--overlay={one}"))
        .arg("--")
        .arg(out.to_str().unwrap())
        .assert()
        .failure()
        .stderr(predicate::str::contains("overlay file not specified"));
}

#[test]
fn overlay_on_top_level_inspection_is_accepted() {
    // qpdf applies the overlay during createQPDF before --show-npages. The
    // qpdf-zlib differential suite checks the transformed page content; this
    // default-build test pins the accepted top-level inspection surface.
    let one = fixture("one-page.pdf");
    Command::cargo_bin("flpdf")
        .unwrap()
        .arg("--show-npages")
        .arg(fixture("three-page.pdf"))
        .args(["--overlay", &one, "--"])
        .assert()
        .success()
        .stdout(predicate::str::contains("3"));
}

#[test]
fn overlay_bumps_header_from_non_encrypted_higher_version_source() {
    // Dest is 1.3 (three-page.pdf) and the overlay source is a non-encrypted
    // 1.7 PDF with no /Extensions/ADBE. The CLI accumulator (main.rs) must
    // set options.min_version to max(dest, all sources) so the output header
    // is bumped to %PDF-1.7, but the source has ext_level == 0 so no
    // /Extensions/ADBE injection should occur. Structural, not byte-level:
    // deflate byte-parity vs qpdf requires `qpdf-zlib-compat` (see the module
    // doc).
    let src = fixture("one-page-v17.pdf");
    let bytes = run_overlay_ok("three-page.pdf", &["--overlay", &src, "--"]);

    assert!(
        bytes.starts_with(b"%PDF-1.7\n"),
        "expected header %PDF-1.7 after floor to 1.7 source, got {:?}",
        bytes.get(..12),
    );

    let mut opened =
        flpdf::Pdf::open(std::io::Cursor::new(bytes)).expect("output reopens as a valid PDF");
    assert_eq!(
        opened.adobe_extension_level().expect("extension level"),
        None,
        "no /Extensions/ADBE must be injected when every source has ext_level == 0",
    );
}

#[test]
fn overlay_bumps_header_and_injects_adbe_from_encrypted_source() {
    // Dest is 1.3 (three-page.pdf) and the overlay source is an AES-256
    // encrypted 1.7 PDF whose Catalog carries /Extensions /ADBE
    // /ExtensionLevel 8 (the standard marker for the AES-256 crypto handler).
    // The CLI accumulator must (1) floor min_version to 1.7 and (2) propagate
    // ext_level 8 so the writer injects /Extensions /ADBE into the output
    // Catalog. Structural, not byte-level (see the module doc).
    let src = fixture("one-page-enc-u.pdf");
    let bytes = run_overlay_ok("three-page.pdf", &["--overlay", &src, "--password=u", "--"]);

    assert!(
        bytes.starts_with(b"%PDF-1.7\n"),
        "expected header %PDF-1.7 after floor to 1.7 source, got {:?}",
        bytes.get(..12),
    );

    let mut opened =
        flpdf::Pdf::open(std::io::Cursor::new(bytes)).expect("output reopens as a valid PDF");
    assert_eq!(
        opened.adobe_extension_level().expect("extension level"),
        Some(8),
        "expected /Extensions/ADBE/ExtensionLevel 8 propagated from AES-256 source",
    );
}

#[test]
fn overlay_from_rc4_source_opens_without_allow_weak_crypto() {
    // qpdf-parity for qtest form-xobject 31 (uo-7): an RC4-encrypted overlay
    // source with correct --password must NOT require the top-level
    // --allow-weak-crypto flag. The flag gates weak-crypto WRITES; opening
    // an overlay source is a read-only inspection.
    //
    // The repo's RC4 fixture (`v2-rc4-128-r3.pdf`) has zero pages (by design
    // of the encrypted-fixture generator, which starts from `minimal.pdf`),
    // so this invocation still fails downstream with a page_count error.
    // That failure shape is exactly what proves the RC4 open succeeded —
    // before this fix, the same command failed earlier with a
    // "encryption uses weak crypto (RC4)" error. Asserting the ABSENCE of
    // that phrase (and the PRESENCE of the downstream error) is the
    // observable regression check.
    let dest = fixture("one-page.pdf");
    let rc4_src = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/encrypted/v2-rc4-128-r3.pdf")
        .to_str()
        .unwrap()
        .to_string();
    let tmp = tempfile::tempdir().expect("tempdir");
    let out = tmp.path().join("overlay-out.pdf");

    Command::cargo_bin("flpdf")
        .unwrap()
        .arg("rewrite")
        .arg(&dest)
        .arg(&out)
        .arg("--overlay")
        .arg(&rc4_src)
        .arg("--password=user-v2")
        .arg("--")
        .assert()
        .failure()
        .stderr(predicate::str::contains("weak crypto").not())
        .stderr(predicate::str::contains("page_count"));
}

// ── Overlay/underlay source repair-warning propagation ────────────────────
//
// qpdf 11.9.0 empirical: when `--overlay`/`--underlay` is given a source PDF
// whose open triggers `Pdf::repair_diagnostics()` (e.g. a corrupt xref), qpdf
// prints each warning to stderr in the shape
// `WARNING: <path>[ (offset N)]: <message>` and STILL exits 0 for
// "clean-primary + warning-bearing overlay/underlay source" — qpdf does not
// add overlay/underlay source warnings to its exit-code accumulator; the
// "operation succeeded with warnings" summary is not printed either. The
// tests below assert that flpdf mirrors that observability (stderr) and exit
// (0) shape.

/// Return bytes for a 1-page PDF whose `xref` keyword is corrupted so that
/// `open_with_repair` runs the reconstruction path and records warning
/// diagnostics. Duplicated from the private helper in `cli_tests.rs` to keep
/// this test file self-contained.
fn corrupt_xref_with_info_pdf() -> Vec<u8> {
    let mut bytes = b"%PDF-1.7\n".to_vec();

    let obj1 = b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /Info 5 0 R >>\nendobj\n".to_vec();
    let obj2 = b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n".to_vec();
    let obj3 = b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Contents 4 0 R >>\nendobj\n".to_vec();
    let obj4 = b"4 0 obj\n<< /Length 0 >>\nstream\nendstream\nendobj\n".to_vec();
    let obj5 = b"5 0 obj\n<< /Title (Corrupt fixture) /Creator (flpdf) >>\nendobj\n".to_vec();

    let mut offsets = Vec::new();
    for object in [&obj1, &obj2, &obj3, &obj4, &obj5] {
        offsets.push(bytes.len());
        bytes.extend_from_slice(object);
    }

    let start_xref = bytes.len();
    bytes.extend_from_slice(format!("xref\n0 {}\n", offsets.len() + 1).as_bytes());
    bytes.extend_from_slice(b"0000000000 65535 f\n");
    for offset in &offsets {
        bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
    }

    bytes.extend_from_slice(
        format!(
            "trailer\n<< /Size {} /Root 1 0 R /Info 5 0 R >>\nstartxref\n{start_xref}\n%%EOF\n",
            offsets.len() + 1
        )
        .as_bytes(),
    );

    let mut corrupted = bytes;
    let Some(pos) = corrupted.windows(4).position(|window| window == b"xref") else {
        unreachable!("fixture should contain xref token")
    };
    if let Some(byte) = corrupted.get_mut(pos + 2) {
        *byte = b'z';
    }

    corrupted
}

/// Write [`corrupt_xref_with_info_pdf`] into `dir` and return the resulting
/// path. Named so the test's intent — "here is a source PDF whose open will
/// warn" — reads clearly at the call site.
fn write_corrupt_fixture(dir: &Path, name: &str) -> PathBuf {
    let path = dir.join(name);
    std::fs::write(&path, corrupt_xref_with_info_pdf()).unwrap();
    path
}

#[test]
fn overlay_corrupt_source_emits_source_warnings_and_exits_zero() {
    let tmp = tempfile::tempdir().unwrap();
    let corrupt = write_corrupt_fixture(tmp.path(), "corrupt-overlay.pdf");
    let out = tmp.path().join("out.pdf");
    let dest = fixture("one-page.pdf");

    Command::cargo_bin("flpdf")
        .unwrap()
        .arg("rewrite")
        .arg("--repair")
        .arg(&dest)
        .arg("--overlay")
        .arg(&corrupt)
        .arg("--")
        .arg(&out)
        .assert()
        .success()
        .stderr(predicate::str::contains(format!(
            "WARNING: {}: file is damaged",
            corrupt.display()
        )))
        .stderr(predicate::str::contains(format!(
            "WARNING: {} (offset ",
            corrupt.display()
        )))
        .stderr(predicate::str::contains(
            "Attempting to reconstruct cross-reference table",
        ));
}

#[test]
fn underlay_corrupt_source_emits_source_warnings_and_exits_zero() {
    let tmp = tempfile::tempdir().unwrap();
    let corrupt = write_corrupt_fixture(tmp.path(), "corrupt-underlay.pdf");
    let out = tmp.path().join("out.pdf");
    let dest = fixture("one-page.pdf");

    Command::cargo_bin("flpdf")
        .unwrap()
        .arg("rewrite")
        .arg("--repair")
        .arg(&dest)
        .arg("--underlay")
        .arg(&corrupt)
        .arg("--")
        .arg(&out)
        .assert()
        .success()
        .stderr(predicate::str::contains(format!(
            "WARNING: {}: file is damaged",
            corrupt.display()
        )));
}

/// Regression: qpdf's cross-reference recovery permission is on by default
/// (`include/qpdf/QPDF.hh:1458-1462`), so a corrupt-but-recoverable
/// `--overlay` source must still recover and succeed even when the caller
/// omits `--repair`. `build_overlay_specs` used to construct
/// `PdfOpenOptions` from the raw `--repair` flag directly, bypassing the
/// `pdf_open_options` helper's default-recovery treatment — the flag's
/// absence turned recovery off for the overlay source specifically (the
/// primary document was unaffected), diverging from qpdf.
#[test]
fn overlay_corrupt_source_recovers_without_explicit_repair_flag() {
    let tmp = tempfile::tempdir().unwrap();
    let corrupt = write_corrupt_fixture(tmp.path(), "corrupt-overlay-no-flag.pdf");
    let out = tmp.path().join("out.pdf");
    let dest = fixture("one-page.pdf");

    Command::cargo_bin("flpdf")
        .unwrap()
        .arg("rewrite")
        .arg(&dest)
        .arg("--overlay")
        .arg(&corrupt)
        .arg("--")
        .arg(&out)
        .assert()
        .success()
        .stderr(predicate::str::contains(format!(
            "WARNING: {}: file is damaged",
            corrupt.display()
        )))
        .stderr(predicate::str::contains(
            "Attempting to reconstruct cross-reference table",
        ));
}

/// Regression guard: an overlay source with no `repair_diagnostics` must not
/// add any `WARNING:` line — the emit helper must stay silent on a clean
/// source. Also verifies that a re-parseable, warning-free source path does
/// not accidentally acquire a WARNING through some other channel.
#[test]
fn overlay_clean_source_emits_no_open_warnings() {
    let tmp = tempfile::tempdir().unwrap();
    let out = tmp.path().join("out.pdf");
    let dest = fixture("one-page.pdf");
    let clean_source = fixture("one-page.pdf");

    Command::cargo_bin("flpdf")
        .unwrap()
        .arg("rewrite")
        .arg(&dest)
        .arg("--overlay")
        .arg(&clean_source)
        .arg("--")
        .arg(&out)
        .assert()
        .success()
        .stderr(predicate::str::contains("WARNING:").not());
}

/// Two corrupt overlay sources → each source's warnings are emitted
/// independently (three warning lines per source; assert the "file is
/// damaged" line names each source path).
#[test]
fn two_corrupt_overlay_sources_each_emit_warnings() {
    let tmp = tempfile::tempdir().unwrap();
    let a = write_corrupt_fixture(tmp.path(), "corrupt-a.pdf");
    let b = write_corrupt_fixture(tmp.path(), "corrupt-b.pdf");
    let out = tmp.path().join("out.pdf");
    let dest = fixture("one-page.pdf");

    Command::cargo_bin("flpdf")
        .unwrap()
        .arg("rewrite")
        .arg("--repair")
        .arg(&dest)
        .arg("--overlay")
        .arg(&a)
        .arg("--")
        .arg("--overlay")
        .arg(&b)
        .arg("--")
        .arg(&out)
        .assert()
        .success()
        .stderr(predicate::str::contains(format!(
            "WARNING: {}: file is damaged",
            a.display()
        )))
        .stderr(predicate::str::contains(format!(
            "WARNING: {}: file is damaged",
            b.display()
        )));
}