mod common;
use common::PdfCanonicalTestExt;
use assert_cmd::Command;
use flpdf::{Pdf, PdfOpenOptions};
use predicates::prelude::*;
use std::io::Cursor;
use std::path::{Path, PathBuf};
use std::process::Command as ShellCommand;
fn normalize_text_newlines(bytes: &[u8]) -> Vec<u8> {
let mut normalized = Vec::with_capacity(bytes.len());
let mut remaining = bytes;
while let Some((&byte, rest)) = remaining.split_first() {
if byte == b'\r' && rest.first() == Some(&b'\n') {
normalized.push(b'\n');
remaining = &rest[1..];
} else {
normalized.push(byte);
remaining = rest;
}
}
normalized
}
const UNENCRYPTED_FIXTURE: &str = "../../tests/fixtures/minimal.pdf";
const ONE_PAGE_FIXTURE: &str = "../../tests/fixtures/compat/one-page.pdf";
const QDF_ENCRYPTION_FIXTURE: &str = ONE_PAGE_FIXTURE;
#[cfg(feature = "qpdf-zlib-compat")]
const TWO_PAGE_FIXTURE: &str = "../../tests/fixtures/compat/two-page.pdf";
#[cfg(feature = "qpdf-zlib-compat")]
const THREE_PAGE_FIXTURE: &str = "../../tests/fixtures/compat/three-page.pdf";
fn fixture(rel: &str) -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join(rel)
}
fn ensure_qpdf_or_skip() -> bool {
let available = ShellCommand::new("qpdf")
.arg("--version")
.output()
.map(|o| o.status.success())
.unwrap_or(false);
if available {
return true;
}
if std::env::var_os("CI").is_some() {
panic!("qpdf required for --encrypt CLI tests on CI");
}
eprintln!("skipping: qpdf not available");
false
}
fn assert_qdf_encrypted_output(output: &Path, password: &str) {
let bytes = std::fs::read(output).expect("read encrypted QDF output");
assert!(
bytes.windows(b"%QDF-1.0".len()).any(|w| w == b"%QDF-1.0"),
"encrypted QDF output must carry the QDF marker"
);
assert!(
bytes.windows(b"/Encrypt".len()).any(|w| w == b"/Encrypt"),
"encrypted QDF output must carry /Encrypt"
);
let trailer_marker = b"\ntrailer <<\n";
let trailer_start = bytes
.windows(trailer_marker.len())
.rposition(|window| window == trailer_marker)
.expect("encrypted QDF output has a classic trailer")
+ trailer_marker.len();
let trailer = &bytes[trailer_start..];
let id_offset = trailer
.windows(b" /ID ".len())
.position(|window| window == b" /ID ")
.expect("encrypted QDF trailer has /ID");
let encrypt_offset = trailer
.windows(b" /Encrypt ".len())
.position(|window| window == b" /Encrypt ")
.expect("encrypted QDF trailer has /Encrypt");
let encrypt_line_end = trailer[encrypt_offset..]
.iter()
.position(|byte| *byte == b'\n')
.map(|offset| encrypt_offset + offset)
.expect("encrypted QDF trailer /Encrypt line is terminated");
let encrypt_fields: Vec<&[u8]> = trailer[encrypt_offset..encrypt_line_end]
.split(|byte| byte.is_ascii_whitespace())
.filter(|field| !field.is_empty())
.collect();
assert!(
id_offset < encrypt_offset
&& !trailer[id_offset..encrypt_offset].contains(&b'\n')
&& encrypt_fields.len() == 4
&& encrypt_fields[0] == b"/Encrypt"
&& !encrypt_fields[1].is_empty()
&& encrypt_fields[1].iter().all(|byte| byte.is_ascii_digit())
&& encrypt_fields[2] == b"0"
&& encrypt_fields[3] == b"R"
&& trailer[encrypt_line_end..].starts_with(b"\n>>\n"),
"qpdf writes /ID then a final /Encrypt N 0 R on the same QDF trailer line: {}",
String::from_utf8_lossy(trailer)
);
let check = ShellCommand::new("qpdf")
.arg(format!("--password={password}"))
.arg("--check")
.arg(output)
.output()
.expect("run qpdf --check on encrypted QDF output");
assert!(
check.status.success(),
"qpdf --check failed: stdout={} stderr={}",
String::from_utf8_lossy(&check.stdout),
String::from_utf8_lossy(&check.stderr)
);
let mut reopened = Pdf::open_with_options(
Cursor::new(bytes),
PdfOpenOptions {
password: password.as_bytes().to_vec(),
..PdfOpenOptions::default()
},
)
.expect("flpdf must reopen and authenticate encrypted QDF output");
assert!(
reopened
.encryption_info()
.expect("read encryption information")
.is_some(),
"reopened QDF output must remain encrypted"
);
let root_ref = reopened.root_ref().expect("encrypted QDF output has /Root");
reopened
.resolve_canonical_object(root_ref)
.expect("authenticated reader resolves the QDF root");
}
fn xref_stream_dictionary(bytes: &[u8]) -> &[u8] {
let type_marker = b"/Type /XRef";
let type_start = bytes
.windows(type_marker.len())
.rposition(|window| window == type_marker)
.expect("xref stream dictionary has /Type /XRef");
let object_header = b" obj\n";
let object_end = bytes[..type_start]
.windows(object_header.len())
.rposition(|window| window == object_header)
.map(|offset| offset + object_header.len())
.expect("xref stream has an indirect-object header");
let dictionary_start = object_end
+ bytes[object_end..type_start]
.windows(2)
.position(|window| window == b"<<")
.expect("xref stream has a dictionary");
let dictionary_end = type_start
+ bytes[type_start..]
.windows(b">>\nstream".len())
.position(|window| window == b">>\nstream")
.expect("xref stream dictionary has a stream terminator")
+ 2;
&bytes[dictionary_start..dictionary_end]
}
fn xref_stream_dictionary_keys(dictionary: &[u8]) -> Vec<&'static str> {
const KEYS: [&str; 10] = [
"/Type",
"/Length",
"/Filter",
"/DecodeParms",
"/W",
"/Info",
"/Root",
"/Size",
"/ID",
"/Encrypt",
];
let mut positions = KEYS
.iter()
.filter_map(|key| {
dictionary
.windows(key.len())
.position(|window| window == key.as_bytes())
.map(|position| (position, *key))
})
.collect::<Vec<_>>();
positions.sort_unstable_by_key(|(position, _)| *position);
positions.into_iter().map(|(_, key)| key).collect()
}
fn assert_qpdf_xref_stream_dictionary_contract(dictionary: &[u8]) {
assert!(dictionary
.windows(b"/Filter /FlateDecode".len())
.any(|window| { window == b"/Filter /FlateDecode" }));
assert!(dictionary
.windows(b"/DecodeParms << /Columns 4 /Predictor 12 >>".len())
.any(|window| window == b"/DecodeParms << /Columns 4 /Predictor 12 >>"));
assert!(dictionary
.windows(b"/W [ 1 2 1 ]".len())
.any(|window| window == b"/W [ 1 2 1 ]"));
assert!(!dictionary
.windows(b"/Index".len())
.any(|window| window == b"/Index"));
}
fn assert_qpdf_uncompressed_xref_stream_dictionary_contract(dictionary: &[u8]) {
assert!(dictionary
.windows(b"/W [ 1 2 1 ]".len())
.any(|window| window == b"/W [ 1 2 1 ]"));
assert!(!dictionary
.windows(b"/Filter".len())
.any(|window| window == b"/Filter"));
assert!(!dictionary
.windows(b"/DecodeParms".len())
.any(|window| window == b"/DecodeParms"));
assert!(!dictionary
.windows(b"/Index".len())
.any(|window| window == b"/Index"));
}
#[test]
fn top_level_encrypt_v4_aes_128_round_trips_via_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("encrypted.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--encrypt",
"user-pw",
"owner-pw",
"128",
"--use-aes=y",
"--",
])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.success();
let bytes = std::fs::read(&output).unwrap();
assert!(
bytes.windows(b"/Encrypt".len()).any(|w| w == b"/Encrypt"),
"encrypted output must carry /Encrypt"
);
let check = ShellCommand::new("qpdf")
.arg("--password=user-pw")
.arg("--show-encryption")
.arg(&output)
.output()
.unwrap();
assert!(check.status.success());
let stdout = String::from_utf8_lossy(&check.stdout);
assert!(stdout.contains("R = 4"), "qpdf must report R=4: {stdout}");
assert!(
stdout.contains("Supplied password is user password"),
"qpdf must accept user password: {stdout}"
);
}
#[test]
fn top_level_encrypt_accepts_bare_hyphen_password() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("encrypted.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["--allow-weak-crypto", "--encrypt", "-", "-", "128", "--"])
.arg(fixture(ONE_PAGE_FIXTURE))
.arg(&output)
.assert()
.success();
let check = ShellCommand::new("qpdf")
.arg("--password=-")
.arg("--check")
.arg(&output)
.output()
.unwrap();
assert!(
check.status.success(),
"qpdf must authenticate with bare-hyphen password: stdout={} stderr={}",
String::from_utf8_lossy(&check.stdout),
String::from_utf8_lossy(&check.stderr)
);
}
#[test]
fn rewrite_subcommand_encrypt_v4_aes_128_round_trips_via_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("encrypted.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--encrypt",
"user-pw",
"owner-pw",
"128",
"--use-aes=y",
"--",
])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.success();
let check = ShellCommand::new("qpdf")
.arg("--password=user-pw")
.arg("--show-encryption")
.arg(&output)
.output()
.unwrap();
assert!(
check.status.success(),
"qpdf --show-encryption failed: stderr={}",
String::from_utf8_lossy(&check.stderr)
);
let stdout = String::from_utf8_lossy(&check.stdout);
assert!(
stdout.contains("R = 4") && stdout.contains("Supplied password is user password"),
"qpdf must report R=4 + user-password match: {stdout}"
);
}
#[test]
fn qdf_direct_encryption_works_on_top_level_and_rewrite_surfaces() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
for (surface, rewrite) in [("top-level", false), ("rewrite", true)] {
let output = tmp.path().join(format!("{surface}-direct-qdf.pdf"));
let mut command = Command::cargo_bin("flpdf").unwrap();
if rewrite {
command.arg("rewrite");
}
command
.args([
"--qdf",
"--static-id",
"--static-aes-iv",
"--encrypt",
"qdf-user",
"qdf-owner",
"128",
"--use-aes=y",
"--",
])
.arg(fixture(QDF_ENCRYPTION_FIXTURE))
.arg(&output)
.assert()
.success();
assert_qdf_encrypted_output(&output, "qdf-user");
}
}
#[test]
fn top_level_encrypt_v5_r6_aes256_round_trips_via_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("encrypted-v5.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["--encrypt", "user-pw", "owner-pw", "256", "--"])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.success();
let bytes = std::fs::read(&output).unwrap();
assert!(
bytes.windows(b"/Encrypt".len()).any(|w| w == b"/Encrypt"),
"encrypted output must carry /Encrypt"
);
let user = ShellCommand::new("qpdf")
.arg("--password=user-pw")
.arg("--show-encryption")
.arg(&output)
.output()
.unwrap();
assert!(
user.status.success(),
"qpdf --show-encryption (user) failed: stderr={}",
String::from_utf8_lossy(&user.stderr)
);
let user_out = String::from_utf8_lossy(&user.stdout);
assert!(
user_out.contains("R = 6") && user_out.contains("Supplied password is user password"),
"qpdf must report R=6 + user-password match: {user_out}"
);
let owner = ShellCommand::new("qpdf")
.arg("--password=owner-pw")
.arg("--show-encryption")
.arg(&output)
.output()
.unwrap();
assert!(owner.status.success());
let owner_out = String::from_utf8_lossy(&owner.stdout);
assert!(
owner_out.contains("Supplied password is owner password"),
"qpdf must accept the owner password: {owner_out}"
);
}
#[test]
fn encrypt_v5_r6_aes256_flpdf_show_encryption_reports_scheme() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("encrypted-v5.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["--encrypt", "user-pw", "owner-pw", "256", "--"])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.success();
let qpdf = ShellCommand::new("qpdf")
.args(["--show-encryption", "--password=user-pw"])
.arg(&output)
.output()
.expect("run qpdf --show-encryption");
assert!(
qpdf.status.success(),
"qpdf oracle failed: {:?}",
qpdf.status
);
let show = Command::cargo_bin("flpdf")
.unwrap()
.args(["show-encryption"])
.arg(&output)
.arg("--password=user-pw")
.assert()
.success();
if cfg!(windows) {
assert_eq!(
normalize_text_newlines(&show.get_output().stdout),
normalize_text_newlines(&qpdf.stdout)
);
assert_eq!(
normalize_text_newlines(&show.get_output().stderr),
normalize_text_newlines(&qpdf.stderr)
);
} else {
assert_eq!(show.get_output().stdout, qpdf.stdout);
assert_eq!(show.get_output().stderr, qpdf.stderr);
}
}
#[test]
fn top_level_show_encryption_matches_qpdf_for_user_password() {
if !ensure_qpdf_or_skip() {
return;
}
let input = fixture("../../tests/fixtures/encrypted/v2-rc4-128-r3.pdf");
let qpdf = ShellCommand::new("qpdf")
.args(["--show-encryption", "--password=user-v2"])
.arg(&input)
.output()
.expect("run qpdf --show-encryption");
assert!(
qpdf.status.success(),
"qpdf oracle failed: {:?}",
qpdf.status
);
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(["--show-encryption", "--password=user-v2"])
.arg(&input)
.output()
.expect("run flpdf --show-encryption");
assert_eq!(flpdf.status, qpdf.status);
if cfg!(windows) {
assert_eq!(
normalize_text_newlines(&flpdf.stdout),
normalize_text_newlines(&qpdf.stdout)
);
assert_eq!(
normalize_text_newlines(&flpdf.stderr),
normalize_text_newlines(&qpdf.stderr)
);
} else {
assert_eq!(flpdf.stdout, qpdf.stdout);
assert_eq!(flpdf.stderr, qpdf.stderr);
}
}
#[test]
fn top_level_show_encryption_recovers_v2_user_password_for_owner_password() {
if !ensure_qpdf_or_skip() {
return;
}
let input = fixture("../../tests/fixtures/encrypted/v2-rc4-128-r3.pdf");
let qpdf = ShellCommand::new("qpdf")
.args(["--show-encryption", "--password=owner-v2"])
.arg(&input)
.output()
.expect("run qpdf --show-encryption with owner password");
assert!(
qpdf.status.success(),
"qpdf oracle failed: {:?}",
qpdf.status
);
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(["--show-encryption", "--password=owner-v2"])
.arg(&input)
.output()
.expect("run flpdf --show-encryption with owner password");
assert_eq!(flpdf.status, qpdf.status);
if cfg!(windows) {
assert_eq!(
normalize_text_newlines(&flpdf.stdout),
normalize_text_newlines(&qpdf.stdout)
);
assert_eq!(
normalize_text_newlines(&flpdf.stderr),
normalize_text_newlines(&qpdf.stderr)
);
} else {
assert_eq!(flpdf.stdout, qpdf.stdout);
assert_eq!(flpdf.stderr, qpdf.stderr);
}
}
#[test]
fn top_level_show_encryption_reports_wrong_password_without_failing() {
if !ensure_qpdf_or_skip() {
return;
}
let input = fixture("../../tests/fixtures/encrypted/v2-rc4-128-r3.pdf");
let qpdf = ShellCommand::new("qpdf")
.args(["--show-encryption", "--password=wrong"])
.arg(&input)
.output()
.expect("run qpdf --show-encryption with wrong password");
assert!(
qpdf.status.success(),
"qpdf oracle failed: {:?}",
qpdf.status
);
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(["--show-encryption", "--password=wrong"])
.arg(&input)
.output()
.expect("run flpdf --show-encryption with wrong password");
assert_eq!(flpdf.status, qpdf.status);
if cfg!(windows) {
assert_eq!(
normalize_text_newlines(&flpdf.stdout),
normalize_text_newlines(&qpdf.stdout)
);
assert_eq!(
normalize_text_newlines(&flpdf.stderr),
normalize_text_newlines(&qpdf.stderr)
);
} else {
assert_eq!(flpdf.stdout, qpdf.stdout);
assert_eq!(flpdf.stderr, qpdf.stderr);
}
}
#[test]
fn top_level_show_encryption_matches_qpdf_for_plaintext() {
if !ensure_qpdf_or_skip() {
return;
}
let input = fixture(UNENCRYPTED_FIXTURE);
let qpdf = ShellCommand::new("qpdf")
.arg("--show-encryption")
.arg(&input)
.output()
.expect("run qpdf --show-encryption on plaintext");
assert!(
qpdf.status.success(),
"qpdf oracle failed: {:?}",
qpdf.status
);
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(["--show-encryption"])
.arg(&input)
.output()
.expect("run flpdf --show-encryption on plaintext");
assert_eq!(flpdf.status, qpdf.status);
if cfg!(windows) {
assert_eq!(
normalize_text_newlines(&flpdf.stdout),
normalize_text_newlines(&qpdf.stdout)
);
assert_eq!(
normalize_text_newlines(&flpdf.stderr),
normalize_text_newlines(&qpdf.stderr)
);
} else {
assert_eq!(flpdf.stdout, qpdf.stdout);
assert_eq!(flpdf.stderr, qpdf.stderr);
}
}
#[test]
fn top_level_show_encryption_matches_qpdf_for_r5_without_write_opt_in() {
if !ensure_qpdf_or_skip() {
return;
}
let input = fixture("../../tests/fixtures/encrypted/v5-aes-256-r5.pdf");
let qpdf = ShellCommand::new("qpdf")
.args(["--show-encryption", "--password=user-v5-r5"])
.arg(&input)
.output()
.expect("run qpdf --show-encryption on R5 fixture");
assert!(
qpdf.status.success(),
"qpdf oracle failed: {:?}",
qpdf.status
);
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(["--show-encryption", "--password=user-v5-r5"])
.arg(&input)
.output()
.expect("run flpdf --show-encryption on R5 fixture");
assert_eq!(flpdf.status, qpdf.status);
if cfg!(windows) {
assert_eq!(
normalize_text_newlines(&flpdf.stdout),
normalize_text_newlines(&qpdf.stdout)
);
assert_eq!(
normalize_text_newlines(&flpdf.stderr),
normalize_text_newlines(&qpdf.stderr)
);
} else {
assert_eq!(flpdf.stdout, qpdf.stdout);
assert_eq!(flpdf.stderr, qpdf.stderr);
}
}
#[test]
fn encrypt_owner_password_authenticates_via_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("encrypted.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["--encrypt", "user", "owner", "128", "--use-aes=y", "--"])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.success();
let check = ShellCommand::new("qpdf")
.arg("--password=owner")
.arg("--show-encryption")
.arg(&output)
.output()
.unwrap();
assert!(check.status.success());
let stdout = String::from_utf8_lossy(&check.stdout);
assert!(
stdout.contains("Supplied password is owner password"),
"qpdf must accept owner password: {stdout}"
);
}
#[test]
fn encrypt_round_trip_on_one_page_decrypts_cleanly_via_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let encrypted = tmp.path().join("encrypted.pdf");
let decrypted = tmp.path().join("decrypted.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["--encrypt", "user", "owner", "128", "--use-aes=y", "--"])
.arg(fixture(ONE_PAGE_FIXTURE))
.arg(&encrypted)
.assert()
.success();
let decrypt = ShellCommand::new("qpdf")
.arg("--password=user")
.arg("--decrypt")
.arg(&encrypted)
.arg(&decrypted)
.output()
.unwrap();
assert!(
decrypt.status.success(),
"qpdf --decrypt failed: {}",
String::from_utf8_lossy(&decrypt.stderr)
);
let check = ShellCommand::new("qpdf")
.arg("--check")
.arg(&decrypted)
.output()
.unwrap();
assert!(
check.status.success(),
"qpdf --check on round-tripped plaintext failed: {}",
String::from_utf8_lossy(&check.stderr)
);
}
#[test]
fn encrypt_key_len_40_v1_rc4_requires_allow_weak_crypto() {
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("nope.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["--encrypt", "u", "o", "40", "--"])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.failure()
.stderr(predicates::str::contains("RC4"))
.stderr(predicates::str::contains("--allow-weak-crypto"));
assert!(!output.exists(), "no output without --allow-weak-crypto");
if !ensure_qpdf_or_skip() {
return;
}
let ok = tmp.path().join("v1.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["--allow-weak-crypto", "--encrypt", "u", "o", "40", "--"])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&ok)
.assert()
.success();
let check = ShellCommand::new("qpdf")
.arg("--password=u")
.arg("--show-encryption")
.arg(&ok)
.output()
.unwrap();
assert!(check.status.success());
let stdout = String::from_utf8_lossy(&check.stdout);
assert!(
stdout.contains("R = 2") && stdout.contains("Supplied password is user password"),
"qpdf must report R=2 + user-password match for V=1 RC4-40: {stdout}"
);
}
#[test]
fn encrypt_key_len_256_is_accepted_as_v5_r6() {
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("ok.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["--encrypt", "u", "o", "256", "--"])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.success();
assert!(
output.exists(),
"256 encryption must produce an output file"
);
let bytes = std::fs::read(&output).unwrap();
assert!(
bytes.windows(b"/Encrypt".len()).any(|w| w == b"/Encrypt"),
"V=5 R=6 output must carry /Encrypt"
);
}
#[test]
fn encrypt_v5_r6_empty_owner_nonempty_user_requires_allow_insecure() {
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("nope.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["--encrypt", "user-pw", "", "256", "--"])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.failure()
.stderr(predicates::str::contains("insecure"))
.stderr(predicates::str::contains("--allow-insecure"));
assert!(!output.exists(), "no output must be written when rejected");
}
#[test]
fn encrypt_v5_r6_empty_owner_with_allow_insecure_succeeds_via_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("insecure.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["--encrypt", "user-pw", "", "256", "--allow-insecure", "--"])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.success();
let check = ShellCommand::new("qpdf")
.arg("--password=user-pw")
.arg("--show-encryption")
.arg(&output)
.output()
.unwrap();
assert!(
check.status.success(),
"qpdf --show-encryption failed: stderr={}",
String::from_utf8_lossy(&check.stderr)
);
let stdout = String::from_utf8_lossy(&check.stdout);
assert!(
stdout.contains("R = 6") && stdout.contains("Supplied password is user password"),
"qpdf must report R=6 + user-password match for the --allow-insecure output: {stdout}"
);
}
#[test]
fn encrypt_v5_r6_both_passwords_no_allow_insecure_succeeds() {
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("secure.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["--encrypt", "user-pw", "owner-pw", "256", "--"])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.success();
assert!(output.exists(), "both-password 256 encryption must succeed");
}
#[test]
fn encrypt_allow_insecure_rejects_a_value() {
for form in ["--allow-insecure=false", "--allow-insecure="] {
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("nope.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["--encrypt", "user-pw", "", "256", form, "--"])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.failure()
.stderr(predicates::str::contains(
"--allow-insecure does not take a value",
));
assert!(
!output.exists(),
"no output must be written when {form:?} is rejected"
);
}
}
#[test]
fn encrypt_128_no_aes_is_v2_rc4_gated_by_weak_crypto() {
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("nope.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["--encrypt", "u", "o", "128", "--"])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.failure()
.stderr(predicates::str::contains("RC4"))
.stderr(predicates::str::contains("--allow-weak-crypto"));
assert!(!output.exists(), "no output without --allow-weak-crypto");
if !ensure_qpdf_or_skip() {
return;
}
let ok = tmp.path().join("v2.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["--allow-weak-crypto", "--encrypt", "u", "o", "128", "--"])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&ok)
.assert()
.success();
let check = ShellCommand::new("qpdf")
.arg("--password=u")
.arg("--show-encryption")
.arg(&ok)
.output()
.unwrap();
assert!(check.status.success());
let stdout = String::from_utf8_lossy(&check.stdout);
assert!(
stdout.contains("R = 3") && stdout.contains("Supplied password is user password"),
"qpdf must report R=3 for V=2 RC4-128: {stdout}"
);
}
#[test]
fn encrypt_128_force_v4_no_aes_is_v4_rc4() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let ok = tmp.path().join("v4rc4.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--allow-weak-crypto",
"--encrypt",
"u",
"o",
"128",
"--force-V4",
"--",
])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&ok)
.assert()
.success();
let check = ShellCommand::new("qpdf")
.arg("--password=u")
.arg("--show-encryption")
.arg(&ok)
.output()
.unwrap();
assert!(check.status.success());
let stdout = String::from_utf8_lossy(&check.stdout);
assert!(
stdout.contains("R = 4") && stdout.contains("Supplied password is user password"),
"qpdf must report R=4 for V=4 RC4-128: {stdout}"
);
}
#[test]
fn encrypt_incompatible_subflags_for_key_len_are_rejected() {
let cases: &[(&[&str], &str)] = &[
(&["u", "o", "40", "--use-aes=y"], "KEY-LEN=40"),
(&["u", "o", "40", "--force-V4"], "KEY-LEN=40"),
(&["u", "o", "40", "--allow-insecure"], "KEY-LEN=40"),
(&["u", "o", "256", "--use-aes=y"], "KEY-LEN=256"),
(&["u", "o", "256", "--force-V4"], "KEY-LEN=256"),
(&["u", "", "128", "--allow-insecure"], "KEY-LEN=128"),
];
for (enc_args, needle) in cases {
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("nope.pdf");
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.arg("--allow-weak-crypto").arg("--encrypt");
for a in *enc_args {
cmd.arg(a);
}
cmd.arg("--")
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.failure()
.stderr(predicates::str::contains(*needle));
assert!(
!output.exists(),
"no output for incompatible combo {enc_args:?}"
);
}
}
#[test]
fn encrypt_permission_sub_flags_match_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
fn perm_lines(p: &Path) -> Vec<String> {
let out = ShellCommand::new("qpdf")
.arg("--password=u")
.arg("--show-encryption")
.arg(p)
.output()
.unwrap();
assert!(out.status.success());
let s = String::from_utf8_lossy(&out.stdout);
let mut v: Vec<String> = s
.lines()
.filter(|l| l.ends_with("allowed"))
.map(|l| l.to_string())
.collect();
v.sort();
v
}
let profiles: &[(&str, &[&str], &[&str])] = &[
("256-r6", &[], &["--encrypt", "u", "o", "256"]),
(
"128-aes-r4",
&[],
&["--encrypt", "u", "o", "128", "--use-aes=y"],
),
(
"128-rc4-r3",
&["--allow-weak-crypto"],
&["--encrypt", "u", "o", "128"],
),
];
let combos: &[&[&str]] = &[
&["--modify=none"],
&["--modify=annotate"],
&["--print=low", "--extract=n"],
&["--modify=none", "--annotate=y"], &["--annotate=y", "--modify=none"], &["--print=none", "--modify=none", "--extract=n"], &["--accessibility=n"], ];
let tmp = tempfile::tempdir().unwrap();
for (label, prefix, enc_base) in profiles {
for combo in combos {
let flpdf_out = tmp.path().join("flpdf.pdf");
let qpdf_out = tmp.path().join("qpdf.pdf");
let mut c = Command::cargo_bin("flpdf").unwrap();
c.args(*prefix).args(*enc_base);
for a in *combo {
c.arg(a);
}
c.arg("--")
.arg(fixture(ONE_PAGE_FIXTURE))
.arg(&flpdf_out)
.assert()
.success();
let mut q = ShellCommand::new("qpdf");
q.args(*prefix).args(*enc_base);
for a in *combo {
q.arg(a);
}
let st = q
.arg("--")
.arg(fixture(ONE_PAGE_FIXTURE))
.arg(&qpdf_out)
.status()
.unwrap();
assert!(st.success(), "qpdf encrypt failed for {label} {combo:?}");
assert_eq!(
perm_lines(&flpdf_out),
perm_lines(&qpdf_out),
"/P permissions differ from qpdf for {label} {combo:?}"
);
}
}
}
#[test]
fn encrypt_cleartext_metadata_accept_reject_matrix() {
let tmp = tempfile::tempdir().unwrap();
let ok = tmp.path().join("ct256.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["--encrypt", "u", "o", "256", "--cleartext-metadata", "--"])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&ok)
.assert()
.success();
let bytes = std::fs::read(&ok).unwrap();
assert!(
bytes
.windows(b"/EncryptMetadata false".len())
.any(|w| w == b"/EncryptMetadata false"),
"256 --cleartext-metadata must emit /EncryptMetadata false"
);
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--encrypt",
"u",
"o",
"128",
"--use-aes=y",
"--cleartext-metadata",
"--",
])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(tmp.path().join("ct128aes.pdf"))
.assert()
.success();
for args in [
vec![
"--allow-weak-crypto",
"--encrypt",
"u",
"o",
"40",
"--cleartext-metadata",
"--",
],
vec![
"--allow-weak-crypto",
"--encrypt",
"u",
"o",
"128",
"--cleartext-metadata",
"--",
],
] {
let nope = tmp.path().join("nope.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(&args)
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&nope)
.assert()
.failure()
.stderr(predicates::str::contains(
"--cleartext-metadata requires V=4 or V=5",
));
assert!(!nope.exists(), "no output for rejected combo {args:?}");
}
}
#[test]
fn encrypt_invalid_key_len_value_is_rejected() {
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("nope.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["--encrypt", "u", "o", "not-a-number", "--"])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.failure()
.stderr(predicates::str::contains("KEY-LEN"));
}
#[test]
fn encrypt_conflicts_with_check_inspection_path() {
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("nope.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["--check", "--encrypt", "u", "o", "128", "--use-aes=y", "--"])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.failure()
.stderr(predicates::str::contains("cannot be used"));
}
#[test]
fn encrypt_is_rejected_when_combined_with_page_operations_top_level() {
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("nope.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--encrypt",
"u",
"o",
"128",
"--use-aes=y",
"--",
"--pages",
".",
"1-z",
"--",
])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.failure()
.stderr(predicates::str::contains("--encrypt"))
.stderr(predicates::str::contains("--pages"));
assert!(!output.exists());
}
#[test]
fn encrypt_is_rejected_when_combined_with_page_operations_subcommand() {
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("nope.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--encrypt",
"u",
"o",
"128",
"--use-aes=y",
"--",
"--pages",
".",
"1-z",
"--",
])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.failure()
.stderr(predicates::str::contains("--encrypt"))
.stderr(predicates::str::contains("--pages"));
assert!(!output.exists());
}
#[test]
fn encrypt_conflicts_with_decrypt_flag() {
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("nope.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--decrypt",
"--encrypt",
"u",
"o",
"128",
"--use-aes=y",
"--",
])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.failure()
.stderr(predicates::str::contains("cannot be used"));
}
#[test]
fn static_aes_iv_with_static_id_produces_deterministic_output() {
let tmp = tempfile::tempdir().unwrap();
let out1 = tmp.path().join("encrypted1.pdf");
let out2 = tmp.path().join("encrypted2.pdf");
let input = fixture(UNENCRYPTED_FIXTURE);
for output in [&out1, &out2] {
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--static-id",
"--static-aes-iv",
"--encrypt",
"user",
"owner",
"128",
"--use-aes=y",
"--",
])
.arg(&input)
.arg(output)
.assert()
.success();
}
let bytes1 = std::fs::read(&out1).unwrap();
let bytes2 = std::fs::read(&out2).unwrap();
assert_eq!(
bytes1, bytes2,
"--static-id --static-aes-iv must produce byte-identical output on two runs"
);
assert!(
bytes1.windows(b"/Encrypt".len()).any(|w| w == b"/Encrypt"),
"output must carry /Encrypt"
);
}
#[test]
fn static_aes_iv_matches_the_vector_qpdf_writes() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let ours = tmp.path().join("flpdf.pdf");
let theirs = tmp.path().join("qpdf.pdf");
let input = fixture(ONE_PAGE_FIXTURE);
for (bits, aes_flag) in [("128", Some("--use-aes=y")), ("256", None)] {
let mut args = vec!["--static-id", "--static-aes-iv", "--encrypt", "", "", bits];
args.extend(aes_flag);
args.push("--");
Command::cargo_bin("flpdf")
.unwrap()
.args(&args)
.arg(&input)
.arg(&ours)
.assert()
.success();
let qpdf = std::process::Command::new("qpdf")
.args(&args)
.arg(&input)
.arg(&theirs)
.output()
.unwrap();
assert!(
qpdf.status.success(),
"qpdf reference run failed for {bits}: {}",
String::from_utf8_lossy(&qpdf.stderr)
);
let mine = leading_stream_vector(&std::fs::read(&ours).unwrap());
let reference = leading_stream_vector(&std::fs::read(&theirs).unwrap());
assert_eq!(
mine, reference,
"{bits}-bit AES: the initialization vector must be the one qpdf writes"
);
}
}
#[cfg(feature = "qpdf-zlib-compat")]
#[test]
fn encrypted_document_is_byte_identical_to_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let ours = tmp.path().join("flpdf.pdf");
let theirs = tmp.path().join("qpdf.pdf");
let input = fixture(ONE_PAGE_FIXTURE);
let args = [
"--static-id",
"--static-aes-iv",
"--encrypt",
"",
"",
"128",
"--use-aes=y",
"--",
];
Command::cargo_bin("flpdf")
.unwrap()
.args(args)
.arg(&input)
.arg(&ours)
.assert()
.success();
let qpdf = std::process::Command::new("qpdf")
.args(args)
.arg(&input)
.arg(&theirs)
.output()
.unwrap();
assert!(
qpdf.status.success(),
"qpdf reference run failed: {}",
String::from_utf8_lossy(&qpdf.stderr)
);
let mine = std::fs::read(&ours).unwrap();
let reference = std::fs::read(&theirs).unwrap();
assert_eq!(
mine, reference,
"AES-128 (V=4/AESV2): flpdf output must be byte-identical to qpdf 11.9.0"
);
}
fn leading_stream_vector(pdf: &[u8]) -> Vec<u8> {
let needle = b"stream\n";
let at = pdf
.windows(needle.len())
.position(|w| w == needle)
.expect("an encrypted document has at least one stream")
+ needle.len();
pdf[at..at + 16].to_vec()
}
#[test]
fn without_static_aes_iv_two_runs_produce_different_bytes() {
let tmp = tempfile::tempdir().unwrap();
let out1 = tmp.path().join("encrypted1.pdf");
let out2 = tmp.path().join("encrypted2.pdf");
let input = fixture(ONE_PAGE_FIXTURE);
for output in [&out1, &out2] {
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--static-id",
"--encrypt",
"user",
"owner",
"128",
"--use-aes=y",
"--",
])
.arg(&input)
.arg(output)
.assert()
.success();
}
let bytes1 = std::fs::read(&out1).unwrap();
let bytes2 = std::fs::read(&out2).unwrap();
assert_ne!(
bytes1, bytes2,
"without --static-aes-iv, two encrypted runs with streams must differ (random IVs)"
);
}
#[test]
fn static_aes_iv_output_decrypts_cleanly_via_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let encrypted = tmp.path().join("encrypted.pdf");
let decrypted = tmp.path().join("decrypted.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--static-id",
"--static-aes-iv",
"--encrypt",
"user",
"owner",
"128",
"--use-aes=y",
"--",
])
.arg(fixture(ONE_PAGE_FIXTURE))
.arg(&encrypted)
.assert()
.success();
let decrypt = std::process::Command::new("qpdf")
.arg("--password=user")
.arg("--decrypt")
.arg(&encrypted)
.arg(&decrypted)
.output()
.unwrap();
assert!(
decrypt.status.success(),
"qpdf --decrypt failed on --static-aes-iv output: {}",
String::from_utf8_lossy(&decrypt.stderr)
);
}
#[test]
fn rewrite_subcommand_static_aes_iv_produces_deterministic_output() {
let tmp = tempfile::tempdir().unwrap();
let out1 = tmp.path().join("encrypted1.pdf");
let out2 = tmp.path().join("encrypted2.pdf");
let input = fixture(UNENCRYPTED_FIXTURE);
for output in [&out1, &out2] {
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--static-id",
"--static-aes-iv",
"--encrypt",
"user",
"owner",
"128",
"--use-aes=y",
"--",
])
.arg(&input)
.arg(output)
.assert()
.success();
}
let bytes1 = std::fs::read(&out1).unwrap();
let bytes2 = std::fs::read(&out2).unwrap();
assert_eq!(
bytes1, bytes2,
"rewrite --static-id --static-aes-iv must produce byte-identical output"
);
}
fn make_donor_pdf(tmp: &tempfile::TempDir, user_pw: &str, owner_pw: &str) -> PathBuf {
let donor = tmp.path().join("donor.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--static-id",
"--static-aes-iv",
"--encrypt",
user_pw,
owner_pw,
"128",
"--use-aes=y",
"--",
])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&donor)
.assert()
.success();
donor
}
#[test]
fn qdf_copy_encryption_works_on_top_level_and_rewrite_surfaces() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let donor = make_donor_pdf(&tmp, "donor-user", "donor-owner");
for (surface, rewrite) in [("top-level", false), ("rewrite", true)] {
let output = tmp.path().join(format!("{surface}-copied-qdf.pdf"));
let mut command = Command::cargo_bin("flpdf").unwrap();
if rewrite {
command.arg("rewrite");
}
command
.args(["--qdf", "--static-id", "--static-aes-iv"])
.arg("--copy-encryption")
.arg(&donor)
.args(["--encryption-file-password", "donor-user"])
.arg(fixture(QDF_ENCRYPTION_FIXTURE))
.arg(&output)
.assert()
.success();
assert_qdf_encrypted_output(&output, "donor-user");
}
}
#[test]
fn copy_encryption_output_has_encrypt_dict() {
let tmp = tempfile::tempdir().unwrap();
let donor = make_donor_pdf(&tmp, "secretuser", "secretowner");
let out = tmp.path().join("copy_out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--copy-encryption",
donor.to_str().unwrap(),
"--encryption-file-password",
"secretuser",
])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&out)
.assert()
.success();
let bytes = std::fs::read(&out).unwrap();
assert!(
bytes.windows(b"/Encrypt".len()).any(|w| w == b"/Encrypt"),
"copy-encryption output must carry /Encrypt"
);
}
#[test]
fn copy_encryption_decrypts_with_donor_user_password_via_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let donor = make_donor_pdf(&tmp, "donoruser", "donorowner");
let out = tmp.path().join("copy_out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--copy-encryption",
donor.to_str().unwrap(),
"--encryption-file-password",
"donoruser",
])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&out)
.assert()
.success();
let check = ShellCommand::new("qpdf")
.arg("--password=donoruser")
.arg("--show-encryption")
.arg(&out)
.output()
.unwrap();
assert!(
check.status.success(),
"qpdf --show-encryption failed with donor user password: {}",
String::from_utf8_lossy(&check.stderr)
);
let stdout = String::from_utf8_lossy(&check.stdout);
assert!(
stdout.contains("R = 4"),
"qpdf must report R=4 on copy-encryption output: {stdout}"
);
assert!(
stdout.contains("Supplied password is user password"),
"qpdf must accept donor user password: {stdout}"
);
}
#[test]
fn copy_encryption_decrypts_with_donor_owner_password_via_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let donor = make_donor_pdf(&tmp, "userpass", "ownerpass");
let out = tmp.path().join("copy_out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--copy-encryption",
donor.to_str().unwrap(),
"--encryption-file-password",
"userpass",
])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&out)
.assert()
.success();
let check = ShellCommand::new("qpdf")
.arg("--password=ownerpass")
.arg("--show-encryption")
.arg(&out)
.output()
.unwrap();
assert!(check.status.success());
let stdout = String::from_utf8_lossy(&check.stdout);
assert!(
stdout.contains("Supplied password is owner password"),
"qpdf must accept donor owner password: {stdout}"
);
}
#[test]
fn copy_encryption_round_trip_decrypts_cleanly_via_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let donor = make_donor_pdf(&tmp, "pw", "pw");
let encrypted = tmp.path().join("encrypted.pdf");
let decrypted = tmp.path().join("decrypted.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--copy-encryption",
donor.to_str().unwrap(),
"--encryption-file-password",
"pw",
])
.arg(fixture(ONE_PAGE_FIXTURE))
.arg(&encrypted)
.assert()
.success();
let decrypt = ShellCommand::new("qpdf")
.arg("--password=pw")
.arg("--decrypt")
.arg(&encrypted)
.arg(&decrypted)
.output()
.unwrap();
assert!(
decrypt.status.success(),
"qpdf --decrypt failed on copy-encryption output: {}",
String::from_utf8_lossy(&decrypt.stderr)
);
}
#[test]
fn rewrite_subcommand_copy_encryption_succeeds() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let donor = make_donor_pdf(&tmp, "donorpw", "ownerpw");
let out = tmp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--copy-encryption",
donor.to_str().unwrap(),
"--encryption-file-password",
"donorpw",
])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&out)
.assert()
.success();
let check = ShellCommand::new("qpdf")
.arg("--password=donorpw")
.arg("--show-encryption")
.arg(&out)
.output()
.unwrap();
assert!(check.status.success());
let stdout = String::from_utf8_lossy(&check.stdout);
assert!(
stdout.contains("R = 4") && stdout.contains("Supplied password is user password"),
"rewrite --copy-encryption: qpdf must report R=4 + user-password match: {stdout}"
);
}
#[test]
fn copy_encryption_floors_pdf_header_to_1_6() {
let tmp = tempfile::tempdir().unwrap();
let donor = make_donor_pdf(&tmp, "user-pw", "owner-pw");
let out = tmp.path().join("copied.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.arg("--copy-encryption")
.arg(&donor)
.args(["--encryption-file-password", "user-pw", "--"])
.arg(fixture(ONE_PAGE_FIXTURE))
.arg(&out)
.assert()
.success();
let bytes = std::fs::read(&out).unwrap();
assert!(
bytes.starts_with(b"%PDF-1.6"),
"copy-encryption (V=4 AES-128 donor) must floor the header to 1.6, got {:?}",
String::from_utf8_lossy(&bytes[..bytes.len().min(12)])
);
}
#[test]
fn copy_encryption_unencrypted_donor_is_rejected() {
let tmp = tempfile::tempdir().unwrap();
let out = tmp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--copy-encryption",
fixture(UNENCRYPTED_FIXTURE).to_str().unwrap(),
])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&out)
.assert()
.failure()
.stderr(predicates::str::contains("not encrypted"));
}
#[test]
fn copy_encryption_non_v4_aes128_donor_is_rejected() {
let tmp = tempfile::tempdir().unwrap();
let donor = tmp.path().join("donor256.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--static-id",
"--encrypt",
"donoruser",
"donorowner",
"256",
"--",
])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&donor)
.assert()
.success();
let out = tmp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--copy-encryption",
donor.to_str().unwrap(),
"--encryption-file-password",
"donoruser",
])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&out)
.assert()
.failure()
.stderr(predicates::str::contains(
"only V=4 AES-128 donors are accepted",
));
}
#[test]
fn copy_encryption_wrong_password_is_rejected() {
let tmp = tempfile::tempdir().unwrap();
let donor = make_donor_pdf(&tmp, "correctpw", "ownerpw");
let out = tmp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--copy-encryption",
donor.to_str().unwrap(),
"--encryption-file-password",
"wrongpw",
])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&out)
.assert()
.failure()
.stderr(predicates::str::contains("--copy-encryption"));
assert!(!out.exists());
}
#[test]
fn encrypt_force_r5_flpdf_show_encryption_reports_r5() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("r5.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--allow-weak-crypto",
"--encrypt",
"user-pw",
"owner-pw",
"256",
"--force-R5",
"--",
])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.success();
let qpdf = ShellCommand::new("qpdf")
.args(["--show-encryption", "--password=user-pw"])
.arg(&output)
.output()
.expect("run qpdf --show-encryption");
assert!(
qpdf.status.success(),
"qpdf oracle failed: {:?}",
qpdf.status
);
let show = Command::cargo_bin("flpdf")
.unwrap()
.args([
"show-encryption",
"--allow-weak-crypto",
"--password=user-pw",
])
.arg(&output)
.assert()
.success();
if cfg!(windows) {
assert_eq!(
normalize_text_newlines(&show.get_output().stdout),
normalize_text_newlines(&qpdf.stdout)
);
assert_eq!(
normalize_text_newlines(&show.get_output().stderr),
normalize_text_newlines(&qpdf.stderr)
);
} else {
assert_eq!(show.get_output().stdout, qpdf.stdout);
assert_eq!(show.get_output().stderr, qpdf.stderr);
}
}
#[test]
fn encrypt_force_r5_rejected_for_128_bit() {
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("nope.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["--encrypt", "u", "o", "128", "--force-R5", "--"])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.failure()
.stderr(predicates::str::contains("--force-R5"));
}
#[test]
fn encrypt_force_r5_rejected_for_40_bit() {
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("nope.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--allow-weak-crypto",
"--encrypt",
"u",
"o",
"40",
"--force-R5",
"--",
])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.failure()
.stderr(predicates::str::contains("--force-R5"));
}
#[test]
fn encrypt_force_r5_rejects_value_form() {
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("nope.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["--encrypt", "u", "o", "256", "--force-R5=y", "--"])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.failure()
.stderr(predicates::str::contains("does not take a value"));
}
#[test]
fn encrypt_force_r5_rejected_without_allow_weak_crypto() {
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("r5-gated.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--encrypt",
"user-pw",
"owner-pw",
"256",
"--force-R5",
"--",
])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.failure()
.stderr(predicates::str::contains("--allow-weak-crypto"));
assert!(
!output.exists(),
"no output file must be written when the R=5 weak-crypto gate fires"
);
}
#[test]
fn encrypt_r6_default_not_gated_without_allow_weak_crypto() {
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("r6.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["--encrypt", "user-pw", "owner-pw", "256", "--"])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.success();
let show = Command::cargo_bin("flpdf")
.unwrap()
.args(["show-encryption", "--password=user-pw"])
.arg(&output)
.assert()
.success();
let stdout = String::from_utf8_lossy(&show.get_output().stdout).into_owned();
assert!(
stdout.contains("R = 6"),
"default 256-bit output must be R=6: {stdout}"
);
}
#[test]
fn encrypt_force_r5_round_trips_via_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("r5-qpdf.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--allow-weak-crypto",
"--encrypt",
"user-pw",
"owner-pw",
"256",
"--force-R5",
"--",
])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.success();
let check = ShellCommand::new("qpdf")
.arg("--password=user-pw")
.arg("--allow-weak-crypto")
.arg("--show-encryption")
.arg(&output)
.output()
.unwrap();
assert!(
check.status.success(),
"qpdf --show-encryption failed: {}",
String::from_utf8_lossy(&check.stderr)
);
let stdout = String::from_utf8_lossy(&check.stdout);
assert!(
stdout.contains("R = 5") && stdout.contains("Supplied password is user password"),
"qpdf must report R=5 + user password match: {stdout}"
);
let owner_check = ShellCommand::new("qpdf")
.arg("--password=owner-pw")
.arg("--allow-weak-crypto")
.arg("--show-encryption")
.arg(&output)
.output()
.unwrap();
assert!(owner_check.status.success());
let owner_out = String::from_utf8_lossy(&owner_check.stdout);
assert!(
owner_out.contains("Supplied password is owner password"),
"qpdf must accept the owner password: {owner_out}"
);
}
#[test]
fn encrypt_with_generate_object_streams_round_trips_via_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("encrypted_objstm.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--object-streams=generate",
"--encrypt",
"user-pw",
"owner-pw",
"128",
"--use-aes=y",
"--",
])
.arg(fixture(ONE_PAGE_FIXTURE))
.arg(&output)
.assert()
.success();
let bytes = std::fs::read(&output).unwrap();
assert!(
bytes.windows(b"/ObjStm".len()).any(|w| w == b"/ObjStm"),
"output must contain at least one /ObjStm container"
);
assert!(
bytes.windows(b"/Encrypt".len()).any(|w| w == b"/Encrypt"),
"output must carry /Encrypt"
);
let qpdf_output = tmp.path().join("qpdf_encrypted_objstm.pdf");
let qpdf_result = ShellCommand::new("qpdf")
.args([
"--static-id",
"--static-aes-iv",
"--object-streams=generate",
"--encrypt",
"user-pw",
"owner-pw",
"128",
"--use-aes=y",
"--",
])
.arg(fixture(ONE_PAGE_FIXTURE))
.arg(&qpdf_output)
.output()
.unwrap();
assert!(
qpdf_result.status.success(),
"qpdf xref-stream reference failed:\n{}",
String::from_utf8_lossy(&qpdf_result.stderr)
);
let qpdf_bytes = std::fs::read(qpdf_output).unwrap();
let flpdf_dictionary = xref_stream_dictionary(&bytes);
let qpdf_dictionary = xref_stream_dictionary(&qpdf_bytes);
assert_eq!(
xref_stream_dictionary_keys(flpdf_dictionary),
xref_stream_dictionary_keys(qpdf_dictionary),
"flpdf and qpdf xref-stream dictionaries must use the same key order:\nflpdf={}\nqpdf={}",
String::from_utf8_lossy(flpdf_dictionary),
String::from_utf8_lossy(qpdf_dictionary)
);
assert_qpdf_xref_stream_dictionary_contract(flpdf_dictionary);
assert_qpdf_xref_stream_dictionary_contract(qpdf_dictionary);
let check = std::process::Command::new("qpdf")
.arg("--password=user-pw")
.arg("--show-encryption")
.arg(&output)
.output()
.unwrap();
assert!(
check.status.success(),
"qpdf --show-encryption failed:\n{}",
String::from_utf8_lossy(&check.stderr)
);
let stdout = String::from_utf8_lossy(&check.stdout);
assert!(stdout.contains("R = 4"), "qpdf must report R=4: {stdout}");
let decrypted = tmp.path().join("decrypted_from_objstm.pdf");
let decrypt_result = std::process::Command::new("qpdf")
.arg("--password=user-pw")
.arg("--decrypt")
.arg("--static-id")
.arg(&output)
.arg(&decrypted)
.output()
.unwrap();
assert!(
decrypt_result.status.success(),
"qpdf --decrypt failed:\n{}",
String::from_utf8_lossy(&decrypt_result.stderr)
);
let check_result = std::process::Command::new("qpdf")
.arg("--check")
.arg(&decrypted)
.output()
.unwrap();
assert!(
check_result.status.success(),
"qpdf --check on decrypted PDF failed:\n{}",
String::from_utf8_lossy(&check_result.stderr)
);
}
#[test]
fn encrypt_with_generate_object_streams_uncompressed_xref_matches_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("encrypted_objstm_uncompressed_xref.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--object-streams=generate",
"--compress-streams=n",
"--encrypt",
"user-pw",
"owner-pw",
"128",
"--use-aes=y",
"--",
])
.arg(fixture(ONE_PAGE_FIXTURE))
.arg(&output)
.assert()
.success();
let qpdf_output = tmp
.path()
.join("qpdf_encrypted_objstm_uncompressed_xref.pdf");
let qpdf_result = ShellCommand::new("qpdf")
.args([
"--static-id",
"--static-aes-iv",
"--object-streams=generate",
"--compress-streams=n",
"--encrypt",
"user-pw",
"owner-pw",
"128",
"--use-aes=y",
"--",
])
.arg(fixture(ONE_PAGE_FIXTURE))
.arg(&qpdf_output)
.output()
.unwrap();
assert!(
qpdf_result.status.success(),
"qpdf uncompressed xref-stream reference failed:\n{}",
String::from_utf8_lossy(&qpdf_result.stderr)
);
let flpdf_bytes = std::fs::read(&output).unwrap();
let qpdf_bytes = std::fs::read(&qpdf_output).unwrap();
let flpdf_dictionary = xref_stream_dictionary(&flpdf_bytes);
let qpdf_dictionary = xref_stream_dictionary(&qpdf_bytes);
assert_eq!(
xref_stream_dictionary_keys(flpdf_dictionary),
xref_stream_dictionary_keys(qpdf_dictionary),
"uncompressed flpdf and qpdf xref-stream dictionaries must use the same key order:\nflpdf={}\nqpdf={}",
String::from_utf8_lossy(flpdf_dictionary),
String::from_utf8_lossy(qpdf_dictionary)
);
assert_qpdf_uncompressed_xref_stream_dictionary_contract(flpdf_dictionary);
assert_qpdf_uncompressed_xref_stream_dictionary_contract(qpdf_dictionary);
}
#[test]
fn encrypt_preserves_xref_stream_form_when_objstm_disabled() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let xref_stream_source = tmp.path().join("xref_stream_source.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--object-streams=generate"])
.arg(fixture(ONE_PAGE_FIXTURE))
.arg(&xref_stream_source)
.assert()
.success();
let encrypted = tmp.path().join("encrypted_xref_stream.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--object-streams=disable",
"--encrypt",
"user-pw",
"owner-pw",
"128",
"--use-aes=y",
"--",
])
.arg(&xref_stream_source)
.arg(&encrypted)
.assert()
.success();
let bytes = std::fs::read(&encrypted).unwrap();
assert!(
bytes.windows(b"/XRef".len()).any(|w| w == b"/XRef"),
"output must use xref stream form (/Type /XRef), not a classic xref table"
);
assert!(
!bytes.windows(b"\nxref\n".len()).any(|w| w == b"\nxref\n"),
"output must not contain a classic xref table (\\nxref\\n keyword found)"
);
assert!(
!bytes.windows(b"/ObjStm".len()).any(|w| w == b"/ObjStm"),
"output must not contain ObjStm containers when --object-streams=disable"
);
assert!(
bytes.windows(b"/Encrypt".len()).any(|w| w == b"/Encrypt"),
"output must carry /Encrypt"
);
let check = std::process::Command::new("qpdf")
.arg("--password=user-pw")
.arg("--show-encryption")
.arg(&encrypted)
.output()
.unwrap();
assert!(
check.status.success(),
"qpdf --show-encryption failed:\n{}",
String::from_utf8_lossy(&check.stderr)
);
let stdout = String::from_utf8_lossy(&check.stdout);
assert!(stdout.contains("R = 4"), "qpdf must report R=4: {stdout}");
let decrypted = tmp.path().join("decrypted_xref_stream.pdf");
let decrypt_result = std::process::Command::new("qpdf")
.arg("--password=user-pw")
.arg("--decrypt")
.arg("--static-id")
.arg(&encrypted)
.arg(&decrypted)
.output()
.unwrap();
assert!(
decrypt_result.status.success(),
"qpdf --decrypt failed:\n{}",
String::from_utf8_lossy(&decrypt_result.stderr)
);
let check_result = std::process::Command::new("qpdf")
.arg("--check")
.arg(&decrypted)
.output()
.unwrap();
assert!(
check_result.status.success(),
"qpdf --check on decrypted PDF failed:\n{}",
String::from_utf8_lossy(&check_result.stderr)
);
}
#[test]
fn rewrite_linearize_encrypt_produces_valid_linearized_encrypted_pdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("lin-enc.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--linearize",
"--encrypt",
"",
"",
"128",
"--use-aes=y",
"--",
])
.arg(fixture(ONE_PAGE_FIXTURE))
.arg(&output)
.assert()
.success();
let bytes = std::fs::read(&output).unwrap();
assert!(
bytes.windows(b"/Encrypt".len()).any(|w| w == b"/Encrypt"),
"output must carry /Encrypt"
);
let check = ShellCommand::new("qpdf")
.arg("--check")
.arg(&output)
.output()
.unwrap();
assert!(
check.status.success(),
"qpdf --check failed on linearized+encrypted output: stdout={} stderr={}",
String::from_utf8_lossy(&check.stdout),
String::from_utf8_lossy(&check.stderr)
);
let stdout = String::from_utf8_lossy(&check.stdout);
assert!(
stdout.contains("File is linearized"),
"qpdf --check must report the output as linearized: {stdout}"
);
}
#[test]
fn top_level_linearize_encrypt_produces_valid_linearized_encrypted_pdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("lin-enc-top.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--linearize",
"--encrypt",
"user-pw",
"owner-pw",
"128",
"--use-aes=y",
"--",
])
.arg(fixture(ONE_PAGE_FIXTURE))
.arg(&output)
.assert()
.success();
let bytes = std::fs::read(&output).unwrap();
assert!(
bytes.windows(b"/Encrypt".len()).any(|w| w == b"/Encrypt"),
"output must carry /Encrypt"
);
let check = ShellCommand::new("qpdf")
.arg("--password=user-pw")
.arg("--check")
.arg(&output)
.output()
.unwrap();
assert!(
check.status.success(),
"qpdf --check failed on top-level linearized+encrypted output: stdout={} stderr={}",
String::from_utf8_lossy(&check.stdout),
String::from_utf8_lossy(&check.stderr)
);
let stdout = String::from_utf8_lossy(&check.stdout);
assert!(
stdout.contains("File is linearized"),
"qpdf --check must report the output as linearized: {stdout}"
);
assert!(
stdout.contains("Supplied password is user password"),
"qpdf must authenticate the user password on the top-level path: {stdout}"
);
}
#[test]
fn linearize_copy_encryption_produces_valid_encrypted_output() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let donor = make_donor_pdf(&tmp, "donor-user", "donor-owner");
for (surface, args) in [
(
"rewrite",
vec![
"rewrite",
"--linearize",
"--copy-encryption",
donor.to_str().unwrap(),
"--encryption-file-password",
"donor-user",
],
),
(
"top-level",
vec![
"--linearize",
"--copy-encryption",
donor.to_str().unwrap(),
"--encryption-file-password",
"donor-user",
],
),
] {
let output = tmp.path().join(format!("lin-copy-enc-{surface}.pdf"));
Command::cargo_bin("flpdf")
.unwrap()
.args(args)
.arg(fixture(ONE_PAGE_FIXTURE))
.arg(&output)
.assert()
.success();
let check = ShellCommand::new("qpdf")
.arg("--password=donor-user")
.arg("--check")
.arg(&output)
.output()
.unwrap();
assert!(
check.status.success(),
"qpdf --check failed on {surface} linearized copy-encryption output: stdout={} stderr={}",
String::from_utf8_lossy(&check.stdout),
String::from_utf8_lossy(&check.stderr)
);
let stdout = String::from_utf8_lossy(&check.stdout);
assert!(
stdout.contains("File is linearized")
&& stdout.contains("Supplied password is user password"),
"qpdf must report a valid linearized encrypted output on {surface}: {stdout}"
);
}
}
#[test]
fn rewrite_linearize_encrypt_object_streams_generate_produces_valid_output() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("lin-objstm-enc.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--linearize",
"--object-streams=generate",
"--encrypt",
"",
"",
"128",
"--use-aes=y",
"--",
])
.arg(fixture(ONE_PAGE_FIXTURE))
.arg(&output)
.assert()
.success();
let check = ShellCommand::new("qpdf")
.arg("--password=")
.arg("--check")
.arg(&output)
.output()
.unwrap();
assert!(
check.status.success(),
"qpdf --check failed on linearized object-stream encrypted output: stdout={} stderr={}",
String::from_utf8_lossy(&check.stdout),
String::from_utf8_lossy(&check.stderr)
);
let stdout = String::from_utf8_lossy(&check.stdout);
assert!(
stdout.contains("File is linearized")
&& stdout.contains("Supplied password is user password"),
"qpdf must report a valid linearized object-stream encrypted output: {stdout}"
);
}
#[cfg(feature = "qpdf-zlib-compat")]
#[test]
fn cli_linearize_encrypt_aes128_byte_identical_to_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let qpdf_args = [
"--linearize",
"--static-id",
"--static-aes-iv",
"--encrypt",
"",
"",
"128",
"--use-aes=y",
"--",
];
let run_flpdf = |subcommand: Option<&str>, input: &Path, tag: &str| -> Vec<u8> {
let out = tmp.path().join(format!("{tag}.pdf"));
let mut cmd = Command::cargo_bin("flpdf").unwrap();
if let Some(sub) = subcommand {
cmd.arg(sub);
}
cmd.args(qpdf_args).arg(input).arg(&out).assert().success();
std::fs::read(&out).unwrap()
};
for (case, fixture_path) in [
("one-page", ONE_PAGE_FIXTURE),
("two-page", TWO_PAGE_FIXTURE),
("three-page", THREE_PAGE_FIXTURE),
] {
let input = fixture(fixture_path);
let theirs = tmp.path().join(format!("{case}-qpdf.pdf"));
let qpdf = std::process::Command::new("qpdf")
.args(qpdf_args)
.arg(&input)
.arg(&theirs)
.output()
.unwrap();
assert!(
qpdf.status.success(),
"{case}: qpdf reference run failed: {}",
String::from_utf8_lossy(&qpdf.stderr)
);
let reference = std::fs::read(&theirs).unwrap();
let top_level_bytes = run_flpdf(None, &input, &format!("{case}-flpdf-top-level"));
assert_eq!(
top_level_bytes, reference,
"{case}: top-level `flpdf --linearize --encrypt` (AES-128) must be \
byte-identical to qpdf 11.9.0"
);
let rewrite_bytes = run_flpdf(Some("rewrite"), &input, &format!("{case}-flpdf-rewrite"));
assert_eq!(
rewrite_bytes, reference,
"{case}: `flpdf rewrite --linearize --encrypt` (AES-128) must be \
byte-identical to qpdf 11.9.0"
);
let top_level_again = run_flpdf(None, &input, &format!("{case}-flpdf-top-level-again"));
assert_eq!(
top_level_bytes, top_level_again,
"{case}: two flpdf top-level runs of the same --static-id \
--static-aes-iv invocation must be byte-identical to each other"
);
let rewrite_again = run_flpdf(
Some("rewrite"),
&input,
&format!("{case}-flpdf-rewrite-again"),
);
assert_eq!(
rewrite_bytes, rewrite_again,
"{case}: two `flpdf rewrite` runs of the same --static-id \
--static-aes-iv invocation must be byte-identical to each other"
);
}
}
#[test]
fn top_level_check_linearization_conflicts_with_show_encryption() {
Command::cargo_bin("flpdf")
.unwrap()
.args(["--check-linearization", "--show-encryption"])
.arg(fixture(UNENCRYPTED_FIXTURE))
.assert()
.failure()
.code(2)
.stderr(predicate::str::contains("cannot be used with"));
}
#[test]
fn top_level_json_conflicts_with_show_encryption() {
Command::cargo_bin("flpdf")
.unwrap()
.args(["--json", "--show-encryption"])
.arg(fixture(UNENCRYPTED_FIXTURE))
.assert()
.failure()
.code(2)
.stderr(predicate::str::contains("cannot be used with"));
}
#[test]
fn top_level_overlay_rejected_with_show_encryption() {
Command::cargo_bin("flpdf")
.unwrap()
.arg("--overlay")
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg("--")
.arg("--show-encryption")
.arg(fixture(UNENCRYPTED_FIXTURE))
.assert()
.failure()
.code(2)
.stderr(predicate::str::contains(
"--overlay/--underlay can only be used with rewrite output",
));
}
#[test]
fn top_level_show_encryption_rejects_output_file() {
Command::cargo_bin("flpdf")
.unwrap()
.arg("--show-encryption")
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg("/tmp/flpdf-show-encryption-output-must-be-rejected.pdf")
.assert()
.failure()
.code(2)
.stderr(predicate::str::contains("cannot be used with"));
}
#[test]
fn top_level_show_encryption_honors_update_from_json_routing() {
Command::cargo_bin("flpdf")
.unwrap()
.arg("--update-from-json=/nonexistent/does-not-exist.json")
.arg("--show-encryption")
.arg(fixture(UNENCRYPTED_FIXTURE))
.assert()
.failure();
}
#[test]
fn top_level_show_encryption_no_warn_suppresses_all_warning_output() {
let damaged = "../../tests/fixtures/test_driver/repairable_input.pdf";
let with_warnings = Command::cargo_bin("flpdf")
.unwrap()
.args(["--show-encryption", damaged])
.output()
.unwrap();
assert_eq!(with_warnings.status.code(), Some(3));
assert!(
String::from_utf8_lossy(&with_warnings.stderr).contains("WARNING"),
"sanity check: the undamaged-path run must still show warnings live: {:?}",
String::from_utf8_lossy(&with_warnings.stderr)
);
let no_warn = Command::cargo_bin("flpdf")
.unwrap()
.args(["--no-warn", "--show-encryption", damaged])
.output()
.unwrap();
assert_eq!(no_warn.status.code(), Some(3));
assert!(
no_warn.stderr.is_empty(),
"--no-warn must suppress all --show-encryption diagnostic output \
(live WARNING lines and the trailing summary), matching qpdf: {:?}",
String::from_utf8_lossy(&no_warn.stderr)
);
assert_eq!(
normalize_text_newlines(&no_warn.stdout),
b"File is not encrypted\n",
"--no-warn --show-encryption must print only the qpdf report body"
);
}