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()
}
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")
}
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, "--"]);
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"));
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);
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() {
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() {
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() {
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() {
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() {
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() {
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() {
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");
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() {
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() {
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() {
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() {
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() {
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() {
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() {
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() {
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() {
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"));
}
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
}
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()
)));
}
#[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",
));
}
#[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());
}
#[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()
)));
}