use assert_cmd::Command;
use predicates::prelude::*;
use std::path::{Path, PathBuf};
use std::process::Command as ShellCommand;
#[path = "support/text_newlines.rs"]
mod text_newlines;
use text_newlines::normalize_text_newlines;
const ENCRYPTED_FIXTURES: &[(&str, &str, bool)] = &[
("v1-rc4-40-r2.pdf", "user-v1", true),
("v2-rc4-128-r3.pdf", "user-v2", true),
("v4-rc4-128-r4.pdf", "user-v4-rc4", true),
("v4-aes-128-r4.pdf", "user-v4-aes", false),
("v5-aes-256-r5.pdf", "user-v5-r5", true),
("v5-aes-256-r6.pdf", "user-v5-r6", false),
];
#[test]
fn encrypted_fixtures_rewrite_preserves_encryption_matching_qpdf_objects() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
for (file_name, password, allow_weak_crypto) in ENCRYPTED_FIXTURES {
let input = encrypted_fixture(file_name);
let qpdf_output = tmp.path().join(format!("qpdf-{file_name}"));
let flpdf_output = tmp.path().join(format!("flpdf-{file_name}"));
run_qpdf_rewrite(&input, password, *allow_weak_crypto, &qpdf_output);
run_flpdf_rewrite(&input, password, *allow_weak_crypto, &flpdf_output);
assert_encrypted_pdf_is_readable(&flpdf_output, file_name, password);
let qpdf_objects = qpdf_objects_json(&qpdf_output, password, *allow_weak_crypto);
let flpdf_objects = qpdf_objects_json(&flpdf_output, password, *allow_weak_crypto);
assert_eq!(
flpdf_objects, qpdf_objects,
"{file_name}: encrypted rewrite differs from qpdf under qpdf --json=1 --json-key=objects"
);
}
}
#[test]
fn rc4_rewrite_accepts_correct_password_without_write_opt_in() {
if !ensure_qpdf_or_skip() {
return;
}
let input = encrypted_fixture("v2-rc4-128-r3.pdf");
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("rc4-rewrite.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--static-id", "--password=user-v2"])
.arg(&input)
.arg(&output)
.assert()
.success()
.stderr(predicates::str::contains("weak crypto").not());
assert_encrypted_pdf_is_readable(&output, "v2-rc4-128-r3.pdf", "user-v2");
}
fn encrypted_fixture(file_name: &str) -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/encrypted")
.join(file_name)
}
fn run_flpdf_rewrite(input: &Path, password: &str, allow_weak_crypto: bool, output: &Path) {
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.arg("rewrite")
.arg("--static-id")
.arg(format!("--password={password}"));
if allow_weak_crypto {
cmd.arg("--allow-weak-crypto");
}
cmd.arg(input).arg(output).assert().success();
}
fn run_qpdf_rewrite(input: &Path, password: &str, allow_weak_crypto: bool, output: &Path) {
let mut cmd = ShellCommand::new("qpdf");
cmd.arg(format!("--password={password}"));
if allow_weak_crypto {
cmd.arg("--allow-weak-crypto");
}
cmd.arg("--static-id");
let result = cmd.arg(input).arg(output).output().unwrap();
assert!(
result.status.success(),
"qpdf rewrite failed for {}: {}",
input.display(),
String::from_utf8_lossy(&result.stderr)
);
}
fn assert_encrypted_pdf_is_readable(output: &Path, file_name: &str, password: &str) {
let bytes = std::fs::read(output).unwrap();
assert!(
bytes.windows(b"/Encrypt".len()).any(|w| w == b"/Encrypt"),
"{file_name}: preserved rewrite must contain /Encrypt"
);
let check = ShellCommand::new("qpdf")
.arg(format!("--password={password}"))
.arg("--check")
.arg(output)
.output()
.unwrap();
assert!(
check.status.success(),
"{file_name}: qpdf could not authenticate/check preserved output: {}",
String::from_utf8_lossy(&check.stderr)
);
}
fn qpdf_objects_json(path: &Path, password: &str, allow_weak_crypto: bool) -> Vec<u8> {
let mut cmd = ShellCommand::new("qpdf");
cmd.arg(format!("--password={password}"));
if allow_weak_crypto {
cmd.arg("--allow-weak-crypto");
}
let result = cmd
.args(["--json=1", "--json-key=objects"])
.arg(path)
.output()
.unwrap();
assert!(
result.status.success(),
"qpdf --json=1 --json-key=objects failed for {}: {}",
path.display(),
String::from_utf8_lossy(&result.stderr)
);
result.stdout
}
const UNENCRYPTED_FIXTURE: &str = "../../tests/fixtures/minimal.pdf";
const REMOVE_RESTRICTIONS_DIAGNOSTIC: &str =
"flpdf: removed restrictions (digital-signature restrictions stripped)";
#[test]
fn remove_restrictions_preserves_encryption_without_diagnostic() {
let input = encrypted_fixture("v4-aes-128-r4.pdf");
let tmp = tempfile::tempdir().unwrap();
let qpdf_output = tmp.path().join("qpdf-derestricted.pdf");
let output = tmp.path().join("derestricted.pdf");
let qpdf = ShellCommand::new("qpdf")
.args(["--password=user-v4-aes", "--remove-restrictions"])
.arg(&input)
.arg(&qpdf_output)
.output()
.unwrap();
assert!(
qpdf.status.success(),
"qpdf remove-restrictions failed: {}",
String::from_utf8_lossy(&qpdf.stderr)
);
assert!(
qpdf.stderr.is_empty(),
"qpdf --remove-restrictions must not emit a custom diagnostic: {}",
String::from_utf8_lossy(&qpdf.stderr)
);
let qpdf_bytes = std::fs::read(&qpdf_output).unwrap();
assert!(
qpdf_bytes
.windows(b"/Encrypt".len())
.any(|w| w == b"/Encrypt"),
"qpdf --remove-restrictions must preserve /Encrypt without --decrypt"
);
Command::cargo_bin("flpdf")
.unwrap()
.args(["--remove-restrictions", "--password=user-v4-aes"])
.arg(&input)
.arg(&output)
.assert()
.success()
.stderr(predicates::str::contains(REMOVE_RESTRICTIONS_DIAGNOSTIC).not());
let bytes = std::fs::read(&output).unwrap();
assert!(
bytes.windows(b"/Encrypt".len()).any(|w| w == b"/Encrypt"),
"remove-restrictions output must preserve /Encrypt without --decrypt"
);
let check = ShellCommand::new("qpdf")
.args(["--password=user-v4-aes", "--check"])
.arg(&output)
.output()
.unwrap();
assert!(
check.status.success(),
"preserved output must remain qpdf-readable: {}",
String::from_utf8_lossy(&check.stderr)
);
}
#[test]
fn linearize_remove_restrictions_preserves_encryption() {
if !ensure_qpdf_or_skip() {
return;
}
let input = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/compat/encrypted-r4-three-page.pdf");
let tmp = tempfile::tempdir().unwrap();
let qpdf_output = tmp.path().join("qpdf-linearized.pdf");
let output = tmp.path().join("linearized.pdf");
let qpdf = ShellCommand::new("qpdf")
.args(["--password=", "--linearize", "--remove-restrictions"])
.arg(&input)
.arg(&qpdf_output)
.output()
.unwrap();
assert!(
qpdf.status.success(),
"qpdf linearized remove-restrictions failed: {}",
String::from_utf8_lossy(&qpdf.stderr)
);
let qpdf_bytes = std::fs::read(&qpdf_output).unwrap();
assert!(
qpdf_bytes
.windows(b"/Encrypt".len())
.any(|w| w == b"/Encrypt"),
"qpdf linearized --remove-restrictions must preserve /Encrypt"
);
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--linearize",
"--remove-restrictions",
"--password=",
])
.arg(&input)
.arg(&output)
.assert()
.success();
let bytes = std::fs::read(&output).unwrap();
assert!(
bytes.windows(b"/Encrypt".len()).any(|w| w == b"/Encrypt"),
"linearized --remove-restrictions output must preserve /Encrypt"
);
let check = ShellCommand::new("qpdf")
.args(["--password=", "--check"])
.arg(&output)
.output()
.unwrap();
assert!(
check.status.success(),
"linearized preserved output must remain qpdf-readable: {}",
String::from_utf8_lossy(&check.stderr)
);
}
#[test]
fn remove_restrictions_does_not_bypass_authentication() {
let input = encrypted_fixture("v4-aes-128-r4.pdf");
let tmp = tempfile::tempdir().unwrap();
let plain_out = tmp.path().join("plain.pdf");
let plain = Command::cargo_bin("flpdf")
.unwrap()
.arg("rewrite")
.arg(&input)
.arg(&plain_out)
.assert()
.failure();
let plain_code = plain.get_output().status.code();
let flag_out = tmp.path().join("flag.pdf");
let flagged = Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--remove-restrictions"])
.arg(&input)
.arg(&flag_out)
.assert()
.failure();
assert_eq!(
flagged.get_output().status.code(),
plain_code,
"--remove-restrictions must reject auth-requiring input identically to plain rewrite"
);
assert!(
!flag_out.exists(),
"no output must be produced when authentication fails"
);
}
#[test]
fn remove_restrictions_on_unencrypted_input_is_a_noop_rewrite() {
let input = Path::new(env!("CARGO_MANIFEST_DIR")).join(UNENCRYPTED_FIXTURE);
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("noop.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--remove-restrictions"])
.arg(&input)
.arg(&output)
.assert()
.success()
.stderr(predicates::str::contains(REMOVE_RESTRICTIONS_DIAGNOSTIC).not());
Command::cargo_bin("flpdf")
.unwrap()
.arg("check")
.arg(&output)
.assert()
.success()
.stdout(predicates::str::contains("File is not encrypted"));
}
#[test]
fn decrypt_on_encrypted_input_produces_plaintext_silently_at_top_level() {
let input = encrypted_fixture("v4-aes-128-r4.pdf");
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("decrypted-top.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["--decrypt", "--password=user-v4-aes"])
.arg(&input)
.arg(&output)
.assert()
.success()
.stderr(predicates::str::contains(REMOVE_RESTRICTIONS_DIAGNOSTIC).not());
let bytes = std::fs::read(&output).unwrap();
assert!(
!bytes.windows(b"/Encrypt".len()).any(|w| w == b"/Encrypt"),
"--decrypt output must not contain /Encrypt"
);
Command::cargo_bin("flpdf")
.unwrap()
.arg("show-encryption")
.arg(&output)
.assert()
.success()
.stdout(predicates::str::contains("File is not encrypted"));
}
#[test]
fn decrypt_on_encrypted_input_produces_plaintext_silently_at_subcommand() {
let input = encrypted_fixture("v4-aes-128-r4.pdf");
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("decrypted-sub.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--decrypt", "--password=user-v4-aes"])
.arg(&input)
.arg(&output)
.assert()
.success()
.stderr(predicates::str::contains(REMOVE_RESTRICTIONS_DIAGNOSTIC).not());
let bytes = std::fs::read(&output).unwrap();
assert!(
!bytes.windows(b"/Encrypt".len()).any(|w| w == b"/Encrypt"),
"--decrypt output must not contain /Encrypt"
);
}
#[test]
fn decrypt_on_unencrypted_input_is_a_silent_noop_rewrite() {
let input = Path::new(env!("CARGO_MANIFEST_DIR")).join(UNENCRYPTED_FIXTURE);
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("noop-decrypt.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--decrypt"])
.arg(&input)
.arg(&output)
.assert()
.success()
.stderr(predicates::str::contains(REMOVE_RESTRICTIONS_DIAGNOSTIC).not());
Command::cargo_bin("flpdf")
.unwrap()
.arg("check")
.arg(&output)
.assert()
.success()
.stdout(predicates::str::contains("File is not encrypted"));
}
#[test]
fn decrypt_does_not_bypass_authentication() {
let input = encrypted_fixture("v4-aes-128-r4.pdf");
let tmp = tempfile::tempdir().unwrap();
let plain_out = tmp.path().join("plain.pdf");
let plain = Command::cargo_bin("flpdf")
.unwrap()
.arg("rewrite")
.arg(&input)
.arg(&plain_out)
.assert()
.failure();
let plain_code = plain.get_output().status.code();
let flag_out = tmp.path().join("flag.pdf");
let flagged = Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--decrypt"])
.arg(&input)
.arg(&flag_out)
.assert()
.failure();
assert_eq!(
flagged.get_output().status.code(),
plain_code,
"--decrypt must reject auth-requiring input identically to plain rewrite"
);
assert!(
!flag_out.exists(),
"no output must be produced when authentication fails"
);
}
#[test]
fn decrypt_combined_with_remove_restrictions_is_silent() {
let input = encrypted_fixture("v4-aes-128-r4.pdf");
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("decrypt-and-rm-restrictions.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--decrypt",
"--remove-restrictions",
"--password=user-v4-aes",
])
.arg(&input)
.arg(&output)
.assert()
.success()
.stderr(predicates::str::contains(REMOVE_RESTRICTIONS_DIAGNOSTIC).not());
let bytes = std::fs::read(&output).unwrap();
assert!(
!bytes.windows(b"/Encrypt".len()).any(|w| w == b"/Encrypt"),
"combined --decrypt --remove-restrictions output must not contain /Encrypt"
);
}
#[test]
fn decrypt_with_check_inspection_matches_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let input = Path::new(env!("CARGO_MANIFEST_DIR")).join(UNENCRYPTED_FIXTURE);
let qpdf = ShellCommand::new("qpdf")
.args(["--check", "--decrypt"])
.arg(&input)
.output()
.unwrap();
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(["--check", "--decrypt"])
.arg(&input)
.output()
.unwrap();
assert_eq!(flpdf.status.code(), qpdf.status.code());
assert_eq!(
normalize_text_newlines(&flpdf.stdout),
normalize_text_newlines(&qpdf.stdout)
);
assert_eq!(
normalize_text_newlines(&flpdf.stderr),
normalize_text_newlines(&qpdf.stderr)
);
}
#[test]
fn decrypt_is_applied_to_rewrite_page_operations() {
if !ensure_qpdf_or_skip() {
return;
}
let input = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/compat/encrypted-r4-three-page.pdf");
let input = input.to_str().unwrap().to_owned();
for (label, operation, page_selection, split) in [
("pages", Vec::<String>::new(), true, false),
("rotate", vec!["--rotate=+90".to_owned()], false, false),
("split", vec!["--split-pages=1".to_owned()], false, true),
] {
let tmp = tempfile::tempdir().unwrap();
let qpdf_output = tmp.path().join("q-output.pdf");
let flpdf_output = tmp.path().join("f-output.pdf");
let mut qpdf_args = vec![
"--qdf".to_owned(),
"--static-id".to_owned(),
"--no-original-object-ids".to_owned(),
"--stream-data=uncompress".to_owned(),
"--decrypt".to_owned(),
"--password=".to_owned(),
];
qpdf_args.extend(operation.iter().cloned());
qpdf_args.push(input.clone());
if page_selection {
qpdf_args.extend([
"--pages".to_owned(),
input.clone(),
"1-2".to_owned(),
"--".to_owned(),
]);
}
qpdf_args.push(qpdf_output.to_str().unwrap().to_owned());
let mut flpdf_args = vec![
"rewrite".to_owned(),
"--qdf".to_owned(),
"--static-id".to_owned(),
"--no-original-object-ids".to_owned(),
"--stream-data=uncompress".to_owned(),
"--decrypt".to_owned(),
"--password=".to_owned(),
];
flpdf_args.extend(operation);
flpdf_args.push(input.clone());
flpdf_args.push(flpdf_output.to_str().unwrap().to_owned());
if page_selection {
flpdf_args.extend([
"--pages".to_owned(),
input.clone(),
"1-2".to_owned(),
"--".to_owned(),
]);
}
let qpdf = ShellCommand::new("qpdf").args(&qpdf_args).output().unwrap();
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_STATIC_ID_QUIET", "1")
.args(&flpdf_args)
.output()
.unwrap();
assert_eq!(
flpdf.status.code(),
qpdf.status.code(),
"{label}: exit status differs: qpdf={} flpdf={}",
String::from_utf8_lossy(&qpdf.stderr),
String::from_utf8_lossy(&flpdf.stderr)
);
assert_eq!(flpdf.stdout, qpdf.stdout, "{label}: stdout differs");
assert_eq!(flpdf.stderr, qpdf.stderr, "{label}: stderr differs");
assert!(qpdf.status.success(), "qpdf {label} failed");
if split {
for page in 1..=3 {
let qpdf_chunk = qpdf_output.with_file_name(format!("q-output-{page}.pdf"));
let flpdf_chunk = flpdf_output.with_file_name(format!("f-output-{page}.pdf"));
assert!(qpdf_chunk.is_file(), "qpdf {label} chunk {page} must exist");
assert!(
flpdf_chunk.is_file(),
"flpdf {label} chunk {page} must exist"
);
assert_eq!(
std::fs::read(&flpdf_chunk).unwrap(),
std::fs::read(&qpdf_chunk).unwrap(),
"{label} chunk {page} differs"
);
}
} else {
assert_eq!(
std::fs::read(&flpdf_output).unwrap(),
std::fs::read(&qpdf_output).unwrap(),
"{label} output differs"
);
}
}
}
#[test]
fn copy_encryption_is_applied_to_rewrite_page_selection() {
if !ensure_qpdf_or_skip() {
return;
}
let input =
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/compat/three-page.pdf");
let donor = encrypted_fixture("v4-aes-128-r4.pdf");
let tmp = tempfile::tempdir().unwrap();
let qpdf_output = tmp.path().join("qpdf-copied-encryption.pdf");
let flpdf_output = tmp.path().join("flpdf-copied-encryption.pdf");
let common = [
"--static-id".to_owned(),
format!("--copy-encryption={}", donor.display()),
"--encryption-file-password=user-v4-aes".to_owned(),
];
let input = input.to_str().unwrap().to_owned();
let mut qpdf_args = common.to_vec();
qpdf_args.extend([
input.clone(),
"--pages".to_owned(),
input.clone(),
"1-2".to_owned(),
"--".to_owned(),
qpdf_output.to_str().unwrap().to_owned(),
]);
let mut flpdf_args = vec!["rewrite".to_owned()];
flpdf_args.extend(common);
flpdf_args.extend([
input.clone(),
flpdf_output.to_str().unwrap().to_owned(),
"--pages".to_owned(),
input,
"1-2".to_owned(),
"--".to_owned(),
]);
let qpdf = ShellCommand::new("qpdf").args(&qpdf_args).output().unwrap();
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_STATIC_ID_QUIET", "1")
.args(&flpdf_args)
.output()
.unwrap();
assert_eq!(
flpdf.status.code(),
qpdf.status.code(),
"copy encryption status"
);
assert_eq!(flpdf.stdout, qpdf.stdout, "copy encryption stdout");
assert_eq!(flpdf.stderr, qpdf.stderr, "copy encryption stderr");
assert!(
qpdf.status.success(),
"qpdf copy-encryption page selection failed"
);
let qpdf_bytes = std::fs::read(&qpdf_output).unwrap();
let flpdf_bytes = std::fs::read(&flpdf_output).unwrap();
assert!(qpdf_bytes
.windows(b"/Encrypt".len())
.any(|w| w == b"/Encrypt"));
assert!(flpdf_bytes
.windows(b"/Encrypt".len())
.any(|w| w == b"/Encrypt"));
assert_eq!(
qpdf_objects_json(&qpdf_output, "user-v4-aes", false),
qpdf_objects_json(&flpdf_output, "user-v4-aes", false),
"rewrite page selection copy-encryption objects must match qpdf"
);
}
#[test]
fn copy_encryption_is_applied_to_rewrite_rotate_and_split() {
if !ensure_qpdf_or_skip() {
return;
}
let input =
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/compat/three-page.pdf");
let donor = encrypted_fixture("v4-aes-128-r4.pdf");
let input = input.to_str().unwrap().to_owned();
let common = [
"--static-id".to_owned(),
format!("--copy-encryption={}", donor.display()),
"--encryption-file-password=user-v4-aes".to_owned(),
];
for (label, operation, split) in [
("rotate", "--rotate=+90", false),
("split", "--split-pages=1", true),
] {
let tmp = tempfile::tempdir().unwrap();
let qpdf_output = tmp.path().join("q-output.pdf");
let flpdf_output = tmp.path().join("f-output.pdf");
let mut qpdf_args = common.to_vec();
qpdf_args.extend([
operation.to_owned(),
input.clone(),
qpdf_output.to_str().unwrap().to_owned(),
]);
let mut flpdf_args = vec!["rewrite".to_owned()];
flpdf_args.extend(common.iter().cloned());
flpdf_args.extend([
operation.to_owned(),
input.clone(),
flpdf_output.to_str().unwrap().to_owned(),
]);
let qpdf = ShellCommand::new("qpdf").args(&qpdf_args).output().unwrap();
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_STATIC_ID_QUIET", "1")
.args(&flpdf_args)
.output()
.unwrap();
assert_eq!(flpdf.status.code(), qpdf.status.code(), "{label}: status");
assert_eq!(flpdf.stdout, qpdf.stdout, "{label}: stdout");
assert_eq!(flpdf.stderr, qpdf.stderr, "{label}: stderr");
assert!(qpdf.status.success(), "qpdf {label} failed");
if split {
for page in 1..=3 {
let qpdf_chunk = qpdf_output.with_file_name(format!("q-output-{page}.pdf"));
let flpdf_chunk = flpdf_output.with_file_name(format!("f-output-{page}.pdf"));
assert!(qpdf_chunk.is_file(), "qpdf {label} chunk {page} must exist");
assert!(
flpdf_chunk.is_file(),
"flpdf {label} chunk {page} must exist"
);
assert_eq!(
qpdf_objects_json(&flpdf_chunk, "user-v4-aes", false),
qpdf_objects_json(&qpdf_chunk, "user-v4-aes", false),
"{label} chunk {page} objects differ"
);
}
} else {
assert_eq!(
qpdf_objects_json(&flpdf_output, "user-v4-aes", false),
qpdf_objects_json(&qpdf_output, "user-v4-aes", false),
"{label} objects differ"
);
}
}
}
fn ensure_qpdf_or_skip() -> bool {
let available = ShellCommand::new("qpdf")
.arg("--version")
.output()
.map(|output| output.status.success())
.unwrap_or(false);
if available {
return true;
}
let on_ci = std::env::var_os("CI").is_some();
if on_ci {
panic!(
"qpdf is required for encrypted rewrite tests on CI; install qpdf before running this test suite"
);
}
eprintln!(
"skipping: qpdf not available (target_os={}, CI={})",
std::env::consts::OS,
on_ci
);
false
}