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;
#[path = "support/eol.rs"]
mod eol;
use eol::EOL;
#[path = "support/text_newlines.rs"]
mod text_newlines;
use text_newlines::normalize_text_newlines;
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;
const LINEARIZE_OBJSTM_ENCRYPTION_FIXTURE: &str =
"../../tests/fixtures/compat/objstm-lin-disc-2-250-2.pdf";
#[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";
#[cfg(feature = "qpdf-zlib-compat")]
const OBJSTM_LINEARIZE_FIXTURE: &str = "../../tests/fixtures/compat/objstm-gen-nostream-130rev.pdf";
const DIRECT_ENCRYPTION_MATRIX: &[(&str, &[&str], bool, &str)] = &[
(
"v1-r2",
&["--allow-weak-crypto", "--encrypt", "u", "o", "40", "--"],
true,
"R = 2",
),
(
"v2-r3",
&["--allow-weak-crypto", "--encrypt", "u", "o", "128", "--"],
true,
"R = 3",
),
(
"v4-rc4-r4",
&[
"--allow-weak-crypto",
"--encrypt",
"u",
"o",
"128",
"--force-V4",
"--",
],
true,
"R = 4",
),
(
"v4-aes-r4",
&["--encrypt", "u", "o", "128", "--use-aes=y", "--"],
false,
"R = 4",
),
(
"v5-r5",
&[
"--allow-weak-crypto",
"--encrypt",
"u",
"o",
"256",
"--force-R5",
"--",
],
true,
"R = 5",
),
(
"v5-r6",
&["--encrypt", "u", "o", "256", "--"],
false,
"R = 6",
),
];
fn fixture(rel: &str) -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join(rel)
}
fn qpdf_available() -> bool {
ShellCommand::new("qpdf")
.arg("--version")
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
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_unencrypted_output(output: &Path) {
let show = ShellCommand::new("qpdf")
.arg("--show-encryption")
.arg(output)
.output()
.expect("run qpdf --show-encryption");
assert!(
show.status.success(),
"qpdf --show-encryption failed: {}",
String::from_utf8_lossy(&show.stderr)
);
assert_eq!(
show.stdout,
format!("File is not encrypted{EOL}").into_bytes()
);
let check = ShellCommand::new("qpdf")
.arg("--check")
.arg(output)
.output()
.expect("run qpdf --check");
assert!(
check.status.success(),
"qpdf --check failed: stdout={} stderr={}",
String::from_utf8_lossy(&check.stdout),
String::from_utf8_lossy(&check.stderr)
);
}
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.is_encrypted(),
"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 encrypted_qdf_document_is_byte_identical_to_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let ours = tmp.path().join("flpdf-qdf.pdf");
let theirs = tmp.path().join("qpdf-qdf.pdf");
let input = fixture(QDF_ENCRYPTION_FIXTURE);
let args = [
"--qdf",
"--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 = ShellCommand::new("qpdf")
.args(args)
.arg(&input)
.arg(&theirs)
.output()
.unwrap();
assert!(
qpdf.status.success(),
"qpdf reference run failed: {}",
String::from_utf8_lossy(&qpdf.stderr)
);
assert_eq!(
std::fs::read(&ours).unwrap(),
std::fs::read(&theirs).unwrap(),
"encrypted QDF framing must be byte-identical to qpdf 11.9.0"
);
}
#[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_missing_v4_v5_cf_type_warning_matches_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
for (fixture_name, cf_dictionary, password, output_name) in [
(
"../../tests/fixtures/encrypted/v4-aes-128-r4.pdf",
"/CF << /StdCF << /AuthEvent /DocOpen /CFM /AESV2 /Length 16 >> >>",
"user-v4-aes",
"v4-aes-no-cf.pdf",
),
(
"../../tests/fixtures/encrypted/v5-aes-256-r5.pdf",
"/CF << /StdCF << /AuthEvent /DocOpen /CFM /AESV3 /Length 32 >> >>",
"user-v5-r5",
"v5-aes-no-cf.pdf",
),
] {
let mut bytes = std::fs::read(fixture(fixture_name))
.unwrap_or_else(|error| panic!("read encryption fixture {fixture_name}: {error}"));
let cf_dictionary = cf_dictionary.as_bytes();
let absent_cf = vec![b' '; cf_dictionary.len()];
replace_fixture_token(&mut bytes, cf_dictionary, &absent_cf);
let input = tmp.path().join(output_name);
std::fs::write(&input, bytes).expect("write fixture without /CF");
let password_arg = format!("--password={password}");
let qpdf = ShellCommand::new("qpdf")
.args(["--show-encryption", &password_arg])
.arg(&input)
.output()
.expect("run qpdf --show-encryption with missing /CF");
assert_eq!(qpdf.status.code(), Some(3), "qpdf warning exit status");
assert!(
String::from_utf8_lossy(&qpdf.stderr).contains(
"dictionary key /CF: operation for dictionary attempted on object of type null: treating as empty"
),
"qpdf must report getKeys' null type warning: {:?}",
String::from_utf8_lossy(&qpdf.stderr)
);
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_PROGNAME", "qpdf")
.args(["--show-encryption", &password_arg])
.arg(&input)
.output()
.expect("run flpdf --show-encryption with missing /CF");
assert_eq!(flpdf.status.code(), qpdf.status.code());
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_accepts_short_v2_o_and_u_like_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
for (parameter, output_name) in [
(b"/O <".as_slice(), "short-owner-entry.pdf"),
(b"/U <".as_slice(), "short-user-entry.pdf"),
] {
let mut bytes = std::fs::read(fixture("../../tests/fixtures/encrypted/v2-rc4-128-r3.pdf"))
.expect("read V2/R3 encryption fixture");
blank_hex_suffix(&mut bytes, parameter, 1);
let input = tmp.path().join(output_name);
std::fs::write(&input, bytes).expect("write short V2/R3 encryption fixture");
let qpdf = ShellCommand::new("qpdf")
.args(["--show-encryption", "--password=user-v2"])
.arg(&input)
.output()
.expect("run qpdf with short V2/R3 encryption entry");
assert!(qpdf.status.success(), "qpdf must pad a short {parameter:?}");
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_PROGNAME", "qpdf")
.args(["--show-encryption", "--password=user-v2"])
.arg(&input)
.output()
.expect("run flpdf with short V2/R3 encryption entry");
assert_eq!(flpdf.status.code(), qpdf.status.code());
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 subfilter_warning_precedes_encryption_parameter_type_error_matches_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let mut bytes = std::fs::read(fixture("../../tests/fixtures/encrypted/v4-aes-128-r4.pdf"))
.expect("read V=4 AES encryption fixture");
insert_subfilter_and_corrupt_v4_type(&mut bytes);
let input = tmp.path().join("subfilter-bad-v.pdf");
std::fs::write(&input, bytes).expect("write bad V/SubFilter encryption fixture");
let qpdf = ShellCommand::new("qpdf")
.args(["--show-encryption", "--password=user-v4-aes"])
.arg(&input)
.output()
.expect("run qpdf with bad V and SubFilter");
assert_eq!(qpdf.status.code(), Some(2));
let qpdf_stderr = String::from_utf8_lossy(&qpdf.stderr);
let warning = qpdf_stderr
.find("file uses encryption SubFilters, which qpdf does not support")
.expect("qpdf emits the SubFilter warning");
let error = qpdf_stderr
.find("some encryption dictionary parameters are missing or the wrong type")
.expect("qpdf emits the required-parameter type error");
assert!(warning < error, "qpdf warning must precede the type error");
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_PROGNAME", "qpdf")
.args(["--show-encryption", "--password=user-v4-aes"])
.arg(&input)
.output()
.expect("run flpdf with bad V and SubFilter");
assert_eq!(flpdf.status.code(), qpdf.status.code());
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_subfilter_warning_exit_matches_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let mut bytes = std::fs::read(fixture("../../tests/fixtures/encrypted/v2-rc4-128-r3.pdf"))
.expect("read V2/R3 encryption fixture");
insert_subfilter_warning_into_encryption_dictionary(&mut bytes);
let input = tmp.path().join("subfilter-encryption.pdf");
std::fs::write(&input, bytes).expect("write SubFilter encryption fixture");
for (password, expected_exit) in [("wrong", 0), ("user-v2", 3)] {
let password_arg = format!("--password={password}");
let qpdf = ShellCommand::new("qpdf")
.args(["--show-encryption", &password_arg])
.arg(&input)
.output()
.expect("run qpdf --show-encryption with SubFilter");
assert_eq!(
qpdf.status.code(),
Some(expected_exit),
"qpdf password={password}"
);
assert!(
String::from_utf8_lossy(&qpdf.stderr).contains("file uses encryption SubFilters"),
"qpdf must preserve the SubFilter warning for password={password}: {:?}",
String::from_utf8_lossy(&qpdf.stderr)
);
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_PROGNAME", "qpdf")
.args(["--show-encryption", &password_arg])
.arg(&input)
.output()
.expect("run flpdf --show-encryption with SubFilter");
assert_eq!(
flpdf.status.code(),
qpdf.status.code(),
"flpdf password={password}"
);
if cfg!(windows) {
assert_eq!(
normalize_text_newlines(&flpdf.stdout),
normalize_text_newlines(&qpdf.stdout),
"stdout for password={password}"
);
assert_eq!(
normalize_text_newlines(&flpdf.stderr),
normalize_text_newlines(&qpdf.stderr),
"stderr for password={password}"
);
} else {
assert_eq!(flpdf.stdout, qpdf.stdout, "stdout for password={password}");
assert_eq!(flpdf.stderr, qpdf.stderr, "stderr for password={password}");
}
}
}
#[test]
fn json_encrypt_section_recovers_v2_user_password_from_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(["--json=2", "--json-key=encrypt", "--password=owner-v2"])
.arg(&input)
.output()
.expect("run qpdf JSON encryption inspection");
assert!(
qpdf.status.success(),
"qpdf oracle failed: {:?}",
qpdf.status
);
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(["--json=2", "--json-key=encrypt", "--password=owner-v2"])
.arg(&input)
.output()
.expect("run flpdf JSON encryption inspection");
assert_eq!(flpdf.status, qpdf.status);
let qpdf_json: serde_json::Value = serde_json::from_slice(&qpdf.stdout).unwrap();
let flpdf_json: serde_json::Value = serde_json::from_slice(&flpdf.stdout).unwrap();
assert_eq!(
flpdf_json["encrypt"]["recovereduserpassword"],
qpdf_json["encrypt"]["recovereduserpassword"]
);
assert_eq!(
flpdf_json["encrypt"]["recovereduserpassword"],
serde_json::Value::String("user-v2".into())
);
}
#[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 invalid_encrypt_key_length_matches_qpdf_usage_message() {
if !ensure_qpdf_or_skip() {
return;
}
let temp = tempfile::tempdir().unwrap();
let qpdf_output = temp.path().join("qpdf.pdf");
let flpdf_output = temp.path().join("flpdf.pdf");
let fixture = fixture(UNENCRYPTED_FIXTURE);
let args = ["--encrypt", "u", "o", "999", "--"];
let qpdf = ShellCommand::new("qpdf")
.args(args)
.arg(&fixture)
.arg(&qpdf_output)
.output()
.unwrap();
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(args)
.arg(&fixture)
.arg(&flpdf_output)
.output()
.unwrap();
assert_eq!(qpdf.status.code(), Some(2));
assert_eq!(flpdf.status.code(), qpdf.status.code());
let normalize = |stderr: &[u8], program: &str| {
String::from_utf8_lossy(stderr)
.replace(&format!("{program}: "), "PROG: ")
.replace(&format!("{program} --help"), "PROG --help")
};
assert_eq!(
normalize(&flpdf.stderr, "flpdf"),
normalize(&qpdf.stderr, "qpdf")
);
assert!(!qpdf_output.exists());
assert!(!flpdf_output.exists());
}
#[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(),
"qpdf opens the output before weak-crypto refusal"
);
assert_eq!(std::fs::metadata(&output).unwrap().len(), 0);
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_ignores_an_attached_value() {
for form in ["--allow-insecure=false", "--allow-insecure="] {
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("insecure.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["--encrypt", "user-pw", "", "256", form, "--"])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.success();
assert!(
output.exists(),
"attached value must be discarded for {form:?}"
);
}
}
#[test]
fn weak_crypto_refusal_stderr_matches_qpdf_for_rc4_key_lengths() {
if !ensure_qpdf_or_skip() {
return;
}
for key_len in ["40", "128"] {
let tmp = tempfile::tempdir().expect("tempdir");
let qpdf_output = tmp.path().join("qpdf.pdf");
let flpdf_output = tmp.path().join("flpdf.pdf");
let input = fixture(UNENCRYPTED_FIXTURE);
let qpdf = ShellCommand::new("qpdf")
.args(["--encrypt", "u", "o", key_len, "--"])
.arg(&input)
.arg(&qpdf_output)
.output()
.expect("qpdf should spawn");
assert_eq!(qpdf.status.code(), Some(2), "qpdf stderr: {:?}", qpdf);
let flpdf = Command::cargo_bin("flpdf")
.expect("flpdf binary")
.env("FLPDF_PROGNAME", "qpdf")
.args(["--encrypt", "u", "o", key_len, "--"])
.arg(&input)
.arg(&flpdf_output)
.output()
.expect("flpdf should spawn");
assert_eq!(
flpdf.status.code(),
qpdf.status.code(),
"weak-crypto exit status mismatch for {key_len}: {}",
String::from_utf8_lossy(&flpdf.stderr)
);
assert_eq!(
normalize_text_newlines(&flpdf.stderr),
normalize_text_newlines(&qpdf.stderr),
"weak-crypto stderr mismatch for key length {key_len}"
);
}
}
#[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(),
"qpdf opens the output before weak-crypto refusal"
);
assert_eq!(std::fs::metadata(&output).unwrap().len(), 0);
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"],
"unrecognized argument --use-aes=y (40-bit encryption options must be terminated with --)",
),
(
&["u", "o", "40", "--force-V4"],
"unrecognized argument --force-V4 (40-bit encryption options must be terminated with --)",
),
(
&["u", "o", "40", "--allow-insecure"],
"unrecognized argument --allow-insecure (40-bit encryption options must be terminated with --)",
),
(
&["u", "o", "40", "--cleartext-metadata"],
"unrecognized argument --cleartext-metadata (40-bit encryption options must be terminated with --)",
),
(
&["u", "o", "40", "--form=y"],
"unrecognized argument --form=y (40-bit encryption options must be terminated with --)",
),
(
&["u", "o", "40", "--assemble=y"],
"unrecognized argument --assemble=y (40-bit encryption options must be terminated with --)",
),
(
&["u", "o", "40", "--accessibility=y"],
"unrecognized argument --accessibility=y (40-bit encryption options must be terminated with --)",
),
(
&["u", "o", "40", "--modify-other=y"],
"unrecognized argument --modify-other=y (40-bit encryption options must be terminated with --)",
),
(
&["u", "o", "128", "--force-R5"],
"unrecognized argument --force-R5 (128-bit encryption options must be terminated with --)",
),
(
&["u", "", "128", "--allow-insecure"],
"unrecognized argument --allow-insecure (128-bit encryption options must be terminated with --)",
),
(
&["u", "o", "256", "--use-aes=y"],
"unrecognized argument --use-aes=y (256-bit encryption options must be terminated with --)",
),
(
&["u", "o", "256", "--force-V4"],
"unrecognized argument --force-V4 (256-bit encryption options must be terminated with --)",
),
(
&["u", "o", "256", "--potato"],
"unrecognized argument --potato (256-bit encryption options must be terminated with --)",
),
(
&["u", "o", "256", "force-R5"],
"unrecognized argument force-R5 (256-bit encryption options must be terminated with --)",
),
(
&["--user-password=u", "--allow-insecure", "--bits=256"],
"unrecognized argument",
),
(
&["--user-password=u", "--bits=256", "--bits=128"],
"unrecognized argument --bits=128 (256-bit encryption options must be terminated with --)",
),
];
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_dashed_bits_uses_qpdf_choices_wording_not_positional_wording() {
if !ensure_qpdf_or_skip() {
return;
}
let cases: &[(&[&str], &str)] = &[
(&["--bits"], "--bits must be given as --bits={128,256,40}"),
(
&["--bits=999"],
"--bits must be given as --bits={128,256,40}",
),
];
for (enc_args, expected_line) in cases {
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("nope.pdf");
let mut qpdf_cmd = ShellCommand::new("qpdf");
qpdf_cmd.arg("--encrypt");
for a in *enc_args {
qpdf_cmd.arg(a);
}
qpdf_cmd
.arg("--")
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output);
let qpdf_output = qpdf_cmd.output().expect("run qpdf --encrypt");
let mut flpdf_cmd = Command::cargo_bin("flpdf").unwrap();
flpdf_cmd.env("FLPDF_PROGNAME", "qpdf").arg("--encrypt");
for a in *enc_args {
flpdf_cmd.arg(a);
}
flpdf_cmd
.arg("--")
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output);
let flpdf_output = flpdf_cmd.output().expect("run flpdf --encrypt");
assert_eq!(flpdf_output.status.code(), qpdf_output.status.code());
assert_eq!(
normalize_text_newlines(&flpdf_output.stderr),
normalize_text_newlines(&qpdf_output.stderr)
);
assert!(
String::from_utf8_lossy(&qpdf_output.stderr).contains(expected_line),
"qpdf oracle itself no longer contains the expected line {expected_line:?}: {:?}",
String::from_utf8_lossy(&qpdf_output.stderr)
);
assert!(!output.exists());
}
}
#[test]
fn encrypt_empty_segment_is_rejected_not_treated_as_absent() {
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("nope.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args(["--encrypt", "--"])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.failure()
.stderr(predicates::str::contains(
"encryption key length is required",
));
assert!(
!output.exists(),
"no output must be written for an empty --encrypt segment"
);
}
#[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();
let ok_v4_rc4 = tmp.path().join("ct128rc4.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--allow-weak-crypto",
"--encrypt",
"u",
"o",
"128",
"--cleartext-metadata",
"--",
])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&ok_v4_rc4)
.assert()
.success();
let bytes = std::fs::read(&ok_v4_rc4).unwrap();
assert!(bytes
.windows(b"/EncryptMetadata false".len())
.any(|w| { w == b"/EncryptMetadata false" }));
let args = [
"--allow-weak-crypto",
"--encrypt",
"u",
"o",
"40",
"--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(
"unrecognized argument --cleartext-metadata",
));
assert!(!nope.exists(), "no output for rejected combo {args:?}");
}
#[test]
fn encrypt_invalid_key_len_value_is_rejected() {
let tmp = tempfile::tempdir().unwrap();
for value in ["not-a-number", "", "40.5", "040"] {
let output = tmp.path().join(format!("nope-{}.pdf", value.len()));
Command::cargo_bin("flpdf")
.unwrap()
.args(["--encrypt", "u", "o", value, "--"])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.failure()
.stderr(predicates::str::contains(
"encryption key length must be 40, 128, or 256",
));
assert!(!output.exists(), "no output for invalid KEY-LEN {value:?}");
}
}
#[test]
fn encrypt_with_check_inspection_matches_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let input = fixture(UNENCRYPTED_FIXTURE);
let args = ["--check", "--encrypt", "u", "o", "128", "--use-aes=y", "--"];
let qpdf = ShellCommand::new("qpdf")
.args(args)
.arg(&input)
.output()
.unwrap();
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(args)
.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 encrypt_with_show_npages_matches_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let input = fixture(ONE_PAGE_FIXTURE);
let args = [
"--show-npages",
"--encrypt",
"u",
"o",
"128",
"--use-aes=y",
"--",
];
let qpdf = ShellCommand::new("qpdf")
.args(args)
.arg(&input)
.output()
.unwrap();
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(args)
.arg(&input)
.output()
.unwrap();
assert_eq!(flpdf.status.code(), qpdf.status.code());
assert_eq!(flpdf.stdout, qpdf.stdout);
assert_eq!(flpdf.stderr, qpdf.stderr);
}
#[test]
fn encrypt_succeeds_when_combined_with_pages_top_level() {
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("encrypted-pages.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--encrypt",
"u",
"o",
"128",
"--use-aes=y",
"--",
"--pages",
".",
"1-z",
"--",
])
.arg(fixture(ONE_PAGE_FIXTURE))
.arg(&output)
.assert()
.success();
if !ensure_qpdf_or_skip() {
return;
}
let check = ShellCommand::new("qpdf")
.args(["--password=u", "--show-encryption"])
.arg(&output)
.output()
.unwrap();
assert!(check.status.success());
assert!(String::from_utf8_lossy(&check.stdout).contains("R = 4"));
}
#[test]
fn encrypt_succeeds_when_combined_with_pages_subcommand() {
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("encrypted-pages.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--encrypt",
"u",
"o",
"128",
"--use-aes=y",
"--",
"--pages",
".",
"1-z",
"--",
])
.arg(fixture(ONE_PAGE_FIXTURE))
.arg(&output)
.assert()
.success();
if !ensure_qpdf_or_skip() {
return;
}
let check = ShellCommand::new("qpdf")
.args(["--password=u", "--show-encryption"])
.arg(&output)
.output()
.unwrap();
assert!(check.status.success());
assert!(String::from_utf8_lossy(&check.stdout).contains("R = 4"));
}
#[test]
fn encrypt_follows_decrypt_flag_in_argv_order() {
let tmp = tempfile::tempdir().unwrap();
let output = tmp.path().join("encrypted.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--decrypt",
"--encrypt",
"u",
"o",
"128",
"--use-aes=y",
"--",
])
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&output)
.assert()
.success();
if !ensure_qpdf_or_skip() {
return;
}
let check = ShellCommand::new("qpdf")
.args(["--password=u", "--show-encryption"])
.arg(&output)
.output()
.unwrap();
assert!(check.status.success());
assert!(String::from_utf8_lossy(&check.stdout).contains("R = 4"));
}
#[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() {
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 mine = std::fs::read(&ours).unwrap();
let golden =
fixture("../../tests/golden/references/encrypted-document-is-byte-identical-to-qpdf.pdf");
let expected = std::fs::read(&golden)
.unwrap_or_else(|e| panic!("read qpdf 11.9.0 golden {golden:?}: {e}"));
assert_eq!(
mine, expected,
"AES-128 (V=4/AESV2): flpdf output must match the committed qpdf 11.9.0 golden"
);
if !qpdf_available() {
eprintln!("skipping the live qpdf cross-check: qpdf not available");
return;
}
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 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"
);
}
#[test]
fn encrypted_writer_direct_handler_matrix_matches_qpdf_after_decrypt() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let input = fixture(ONE_PAGE_FIXTURE);
for (label, encrypt_args, allow_weak_crypto, expected_revision) in DIRECT_ENCRYPTION_MATRIX {
let qpdf_output = tmp.path().join(format!("{label}-qpdf.pdf"));
let flpdf_output = tmp.path().join(format!("{label}-flpdf.pdf"));
write_qpdf_direct_encryption(&input, &qpdf_output, encrypt_args);
Command::cargo_bin("flpdf")
.unwrap()
.args(["--static-id", "--static-aes-iv", "--object-streams=disable"])
.args(*encrypt_args)
.arg(&input)
.arg(&flpdf_output)
.assert()
.success();
let show = ShellCommand::new("qpdf")
.arg("--password=u")
.arg("--allow-weak-crypto")
.arg("--show-encryption")
.arg(&flpdf_output)
.output()
.unwrap();
assert!(
show.status.success(),
"{label}: qpdf could not inspect flpdf output: {}",
String::from_utf8_lossy(&show.stderr)
);
assert!(
String::from_utf8_lossy(&show.stdout).contains(expected_revision),
"{label}: expected {expected_revision}, got {}",
String::from_utf8_lossy(&show.stdout)
);
let qpdf_qdf = tmp.path().join(format!("{label}-qpdf.qdf"));
let flpdf_qdf = tmp.path().join(format!("{label}-flpdf.qdf"));
decrypt_to_qdf(&qpdf_output, &qpdf_qdf, *allow_weak_crypto);
decrypt_to_qdf(&flpdf_output, &flpdf_qdf, *allow_weak_crypto);
assert_eq!(
std::fs::read(&flpdf_qdf).unwrap(),
std::fs::read(&qpdf_qdf).unwrap(),
"{label}: decrypted semantic/structural QDF must match qpdf 11.9.0"
);
}
}
#[cfg(feature = "qpdf-zlib-compat")]
#[test]
fn encrypted_writer_deterministic_direct_handler_matrix_is_byte_identical_to_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let input = fixture(ONE_PAGE_FIXTURE);
for (label, encrypt_args, _allow_weak_crypto, _expected_revision) in
DIRECT_ENCRYPTION_MATRIX.iter().take(4)
{
let qpdf_output = tmp.path().join(format!("{label}-qpdf.pdf"));
let flpdf_output = tmp.path().join(format!("{label}-flpdf.pdf"));
write_qpdf_direct_encryption(&input, &qpdf_output, encrypt_args);
Command::cargo_bin("flpdf")
.unwrap()
.args(["--static-id", "--static-aes-iv", "--object-streams=disable"])
.args(*encrypt_args)
.arg(&input)
.arg(&flpdf_output)
.assert()
.success();
assert_eq!(
std::fs::read(&flpdf_output).unwrap(),
std::fs::read(&qpdf_output).unwrap(),
"{label}: deterministic direct encryption must be byte-identical to qpdf 11.9.0"
);
}
}
#[cfg(feature = "qpdf-zlib-compat")]
#[test]
fn encrypted_writer_copy_encryption_tuple_is_byte_identical_to_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let input = fixture(ONE_PAGE_FIXTURE);
let donor = tmp.path().join("donor-qpdf.pdf");
let donor_result = ShellCommand::new("qpdf")
.args([
"--static-id",
"--static-aes-iv",
"--encrypt",
"",
"",
"128",
"--use-aes=y",
"--",
])
.arg(&input)
.arg(&donor)
.output()
.unwrap();
assert!(
donor_result.status.success(),
"qpdf donor generation failed: {}",
String::from_utf8_lossy(&donor_result.stderr)
);
let qpdf_output = tmp.path().join("copy-qpdf.pdf");
let flpdf_output = tmp.path().join("copy-flpdf.pdf");
let qpdf = ShellCommand::new("qpdf")
.args(["--static-id", "--static-aes-iv", "--object-streams=disable"])
.arg(format!("--copy-encryption={}", donor.display()))
.args(["--encryption-file-password=", "--"])
.arg(&input)
.arg(&qpdf_output)
.output()
.unwrap();
assert!(
qpdf.status.success(),
"qpdf copy-encryption reference failed: {}",
String::from_utf8_lossy(&qpdf.stderr)
);
Command::cargo_bin("flpdf")
.unwrap()
.args(["--static-id", "--static-aes-iv", "--object-streams=disable"])
.arg(format!("--copy-encryption={}", donor.display()))
.arg("--encryption-file-password=")
.arg("--")
.arg(&input)
.arg(&flpdf_output)
.assert()
.success();
assert_eq!(
std::fs::read(&flpdf_output).unwrap(),
std::fs::read(&qpdf_output).unwrap(),
"fixed V4 AES-128 copy-encryption tuple must be byte-identical to qpdf 11.9.0"
);
}
fn write_qpdf_direct_encryption(input: &Path, output: &Path, encrypt_args: &[&str]) {
let result = ShellCommand::new("qpdf")
.args(["--static-id", "--static-aes-iv", "--object-streams=disable"])
.args(encrypt_args)
.arg(input)
.arg(output)
.output()
.unwrap();
assert!(
result.status.success(),
"qpdf direct encryption failed: {}",
String::from_utf8_lossy(&result.stderr)
);
}
fn decrypt_to_qdf(input: &Path, output: &Path, allow_weak_crypto: bool) {
let mut command = ShellCommand::new("qpdf");
command
.arg("--password=u")
.arg("--decrypt")
.arg("--qdf")
.arg("--object-streams=disable")
.arg("--static-id");
if allow_weak_crypto {
command.arg("--allow-weak-crypto");
}
let result = command.arg(input).arg(output).output().unwrap();
assert!(
result.status.success(),
"qpdf decrypt-to-QDF failed for {}: {}",
input.display(),
String::from_utf8_lossy(&result.stderr)
);
}
#[cfg(feature = "qpdf-zlib-compat")]
#[test]
fn encrypted_generate_objstm_direct_and_copy_are_byte_identical_to_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let input = fixture("../../tests/fixtures/compat/objstm-gen-nostream-130rev.pdf");
let direct_args = [
"--static-id",
"--static-aes-iv",
"--object-streams=generate",
"--encrypt",
"",
"",
"128",
"--use-aes=y",
"--",
];
let direct_qpdf = tmp.path().join("direct-qpdf.pdf");
let direct_flpdf = tmp.path().join("direct-flpdf.pdf");
let qpdf = ShellCommand::new("qpdf")
.args(direct_args)
.arg(&input)
.arg(&direct_qpdf)
.output()
.unwrap();
assert!(
qpdf.status.success(),
"qpdf direct Generate reference failed: {}",
String::from_utf8_lossy(&qpdf.stderr)
);
Command::cargo_bin("flpdf")
.unwrap()
.args(direct_args)
.arg(&input)
.arg(&direct_flpdf)
.assert()
.success();
assert_eq!(
std::fs::read(&direct_flpdf).unwrap(),
std::fs::read(&direct_qpdf).unwrap(),
"direct encrypted Generate output must be byte-identical to qpdf 11.9.0"
);
let donor = tmp.path().join("donor.pdf");
let donor_args = [
"--static-id",
"--static-aes-iv",
"--encrypt",
"",
"",
"128",
"--use-aes=y",
"--",
];
let donor_result = ShellCommand::new("qpdf")
.args(donor_args)
.arg(fixture(ONE_PAGE_FIXTURE))
.arg(&donor)
.output()
.unwrap();
assert!(
donor_result.status.success(),
"qpdf donor generation failed: {}",
String::from_utf8_lossy(&donor_result.stderr)
);
let copy_qpdf = tmp.path().join("copy-qpdf.pdf");
let copy_flpdf = tmp.path().join("copy-flpdf.pdf");
let qpdf = ShellCommand::new("qpdf")
.args([
"--static-id",
"--static-aes-iv",
"--object-streams=generate",
])
.arg(format!("--copy-encryption={}", donor.display()))
.args(["--encryption-file-password=", "--"])
.arg(&input)
.arg(©_qpdf)
.output()
.unwrap();
assert!(
qpdf.status.success(),
"qpdf copy-encryption Generate reference failed: {}",
String::from_utf8_lossy(&qpdf.stderr)
);
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--static-id",
"--static-aes-iv",
"--object-streams=generate",
])
.arg(format!("--copy-encryption={}", donor.display()))
.arg("--encryption-file-password=")
.arg("--")
.arg(&input)
.arg(©_flpdf)
.assert()
.success();
assert_eq!(
std::fs::read(©_flpdf).unwrap(),
std::fs::read(©_qpdf).unwrap(),
"copy-encryption Generate 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(format!("--copy-encryption={}", donor.display()))
.arg("--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()
.arg(format!("--copy-encryption={}", donor.display()))
.arg("--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"
);
}
#[cfg(feature = "qpdf-zlib-compat")]
#[test]
fn copy_encryption_v2_r3_donor_is_byte_identical_to_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let donor = fixture("../../tests/fixtures/encrypted/v2-rc4-128-r3.pdf");
let input = fixture("../../tests/fixtures/compat/one-page.pdf");
let qpdf_output = tmp.path().join("qpdf-v2-r3-copy.pdf");
let flpdf_output = tmp.path().join("flpdf-v2-r3-copy.pdf");
let copy_option = format!("--copy-encryption={}", donor.display());
let qpdf = ShellCommand::new("qpdf")
.args(["--static-id", "--object-streams=disable"])
.arg(©_option)
.arg("--encryption-file-password=user-v2")
.arg("--")
.arg(&input)
.arg(&qpdf_output)
.output()
.expect("run qpdf --copy-encryption with the valid V2/R3 donor");
assert!(
qpdf.status.success(),
"qpdf V2/R3 donor copy failed: {}",
String::from_utf8_lossy(&qpdf.stderr)
);
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(["--static-id", "--object-streams=disable"])
.arg(©_option)
.arg("--encryption-file-password=user-v2")
.arg("--")
.arg(&input)
.arg(&flpdf_output)
.output()
.expect("run flpdf --copy-encryption with the valid V2/R3 donor");
assert_eq!(flpdf.status, qpdf.status, "CLI exit status");
assert_eq!(flpdf.stdout, qpdf.stdout, "CLI stdout");
assert_eq!(flpdf.stderr, qpdf.stderr, "CLI stderr");
assert_eq!(
std::fs::read(&flpdf_output).expect("read flpdf copy output"),
std::fs::read(&qpdf_output).expect("read qpdf copy output"),
"valid V2/R3 donor copy must be byte-identical to qpdf 11.9.0"
);
}
#[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()
.arg(format!("--copy-encryption={}", donor.display()))
.arg("--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()
.arg(format!("--copy-encryption={}", donor.display()))
.arg("--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()
.arg(format!("--copy-encryption={}", donor.display()))
.arg("--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"])
.arg(format!("--copy-encryption={}", donor.display()))
.arg("--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(format!("--copy-encryption={}", donor.display()))
.arg("--encryption-file-password=user-pw")
.arg("--")
.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_a_noop() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let out = tmp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.arg("--static-id")
.arg(format!(
"--copy-encryption={}",
fixture(UNENCRYPTED_FIXTURE).display()
))
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&out)
.assert()
.success()
.stdout("")
.stderr("");
assert_unencrypted_output(&out);
}
#[test]
fn rewrite_copy_encryption_unencrypted_donor_is_a_noop() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let out = tmp.path().join("rewrite-out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.arg("rewrite")
.arg(format!(
"--copy-encryption={}",
fixture(UNENCRYPTED_FIXTURE).display()
))
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&out)
.assert()
.success()
.stdout("")
.stderr("");
assert_unencrypted_output(&out);
}
#[test]
fn pages_copy_encryption_unencrypted_donor_is_a_noop() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let out = tmp.path().join("pages-out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.arg(format!(
"--copy-encryption={}",
fixture(UNENCRYPTED_FIXTURE).display()
))
.arg(fixture(ONE_PAGE_FIXTURE))
.args(["--pages", ".", "1", "--"])
.arg(&out)
.assert()
.success()
.stdout("")
.stderr("");
assert_unencrypted_output(&out);
}
#[test]
fn copy_encryption_v5_aes256_donor_succeeds() {
if !ensure_qpdf_or_skip() {
return;
}
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()
.arg(format!("--copy-encryption={}", donor.display()))
.arg("--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 must accept the V=5 copied output: {}",
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 the copied V=5/R=6 handler and user password: {stdout}"
);
}
fn copy_encryption_failure_stderr(donor: &Path, password: Option<&str>, out: &Path) -> String {
let mut command = Command::cargo_bin("flpdf").unwrap();
command.arg(format!("--copy-encryption={}", donor.display()));
if let Some(password) = password {
command.arg(format!("--encryption-file-password={password}"));
}
let assert = command
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(out)
.assert()
.failure()
.code(2);
let stderr = String::from_utf8_lossy(&assert.get_output().stderr).into_owned();
assert!(
!stderr.contains("--copy-encryption:"),
"donor failures must not carry an option-specific prefix qpdf never \
emits: {stderr}"
);
stderr
}
fn replace_fixture_token(bytes: &mut [u8], from: &[u8], to: &[u8]) {
assert_eq!(from.len(), to.len(), "fixture edit preserves xref offsets");
let matches = bytes
.windows(from.len())
.enumerate()
.filter_map(|(index, window)| (window == from).then_some(index))
.collect::<Vec<_>>();
assert_eq!(matches.len(), 1, "expected one occurrence of {from:?}");
let start = matches[0];
bytes[start..start + to.len()].copy_from_slice(to);
}
fn blank_hex_suffix(bytes: &mut [u8], parameter: &[u8], suffix_bytes: usize) {
let matches = bytes
.windows(parameter.len())
.enumerate()
.filter_map(|(index, window)| (window == parameter).then_some(index))
.collect::<Vec<_>>();
assert_eq!(matches.len(), 1, "fixture has one {parameter:?} entry");
let value_start = matches[0] + parameter.len();
let value_end = value_start
+ bytes[value_start..]
.iter()
.position(|byte| *byte == b'>')
.expect("PDF hex string has a closing delimiter");
let suffix_hex_bytes = suffix_bytes.checked_mul(2).expect("hex byte count fits");
assert!(value_end - value_start > suffix_hex_bytes);
bytes[value_end - suffix_hex_bytes..value_end].fill(b' ');
}
fn insert_subfilter_warning_into_encryption_dictionary(bytes: &mut Vec<u8>) {
let filter = b"/Filter /Standard";
let matches = bytes
.windows(filter.len())
.enumerate()
.filter_map(|(index, window)| (window == filter).then_some(index))
.collect::<Vec<_>>();
assert_eq!(
matches.len(),
1,
"fixture has one Standard encryption dictionary"
);
let insert_at = matches[0] + filter.len();
let first_xref = bytes
.windows(b"xref\n".len())
.position(|window| window == b"xref\n")
.expect("classic fixture has an xref table");
let encryption_object = bytes
.windows(b"3 0 obj\n".len())
.position(|window| window == b"3 0 obj\n")
.expect("fixture has the indirect encryption dictionary object");
assert!(encryption_object < insert_at && insert_at < first_xref);
assert!(
!bytes[insert_at..first_xref]
.windows(b" obj\n".len())
.any(|window| window == b" obj\n"),
"encryption dictionary object is final before the xref table"
);
bytes.splice(insert_at..insert_at, b" /SubFilter /Bogus".iter().copied());
let xref_offset = bytes
.windows(b"xref\n".len())
.position(|window| window == b"xref\n")
.expect("classic fixture still has an xref table");
let startxref_marker = b"startxref\n";
let startxref = bytes
.windows(startxref_marker.len())
.rposition(|window| window == startxref_marker)
.expect("classic fixture has startxref");
let value_start = startxref + startxref_marker.len();
let value_end = value_start
+ bytes[value_start..]
.iter()
.position(|byte| !byte.is_ascii_digit())
.expect("startxref has a numeric offset");
bytes.splice(value_start..value_end, xref_offset.to_string().bytes());
}
fn insert_subfilter_and_corrupt_v4_type(bytes: &mut Vec<u8>) {
let object_marker = b"3 0 obj\n";
assert_eq!(
bytes
.windows(object_marker.len())
.filter(|window| *window == object_marker)
.count(),
1
);
let object_start = bytes
.windows(object_marker.len())
.position(|window| window == object_marker)
.expect("fixture has one encryption dictionary object");
let filter = b"/Filter /Standard";
assert_eq!(
bytes
.windows(filter.len())
.filter(|window| *window == filter)
.count(),
1
);
let insert_at = bytes
.windows(filter.len())
.position(|window| window == filter)
.expect("fixture has a Standard encryption dictionary")
+ filter.len();
let first_xref = bytes
.windows(b"xref\n".len())
.position(|window| window == b"xref\n")
.expect("fixture has a classic xref table");
assert!(object_start < insert_at && insert_at < first_xref);
assert!(
!bytes[insert_at..first_xref]
.windows(b" obj\n".len())
.any(|window| window == b" obj\n"),
"encryption dictionary is the final object before xref"
);
bytes.splice(insert_at..insert_at, b" /SubFilter /Bogus".iter().copied());
let version = b"/V 4";
assert_eq!(
bytes
.windows(version.len())
.filter(|window| *window == version)
.count(),
1
);
let version_start = bytes
.windows(version.len())
.position(|window| window == version)
.expect("fixture has a V=4 encryption entry");
bytes.splice(
version_start..version_start + version.len(),
b"/V /NotAnInt".iter().copied(),
);
let xref_offset = bytes
.windows(b"xref\n".len())
.position(|window| window == b"xref\n")
.expect("mutated fixture has an xref table");
let startxref_marker = b"startxref\n";
let startxref = bytes
.windows(startxref_marker.len())
.rposition(|window| window == startxref_marker)
.expect("fixture has startxref");
let offset_start = startxref + startxref_marker.len();
let offset_end = offset_start
+ bytes[offset_start..]
.iter()
.position(|byte| !byte.is_ascii_digit())
.expect("startxref has a numeric xref offset");
bytes.splice(offset_start..offset_end, xref_offset.to_string().bytes());
}
fn replace_fixture_encrypt_dictionary_with_integer(bytes: &mut [u8]) {
let object_marker = b"3 0 obj\n";
assert_eq!(
bytes
.windows(object_marker.len())
.filter(|window| *window == object_marker)
.count(),
1
);
let object_start = bytes
.windows(object_marker.len())
.position(|window| window == object_marker)
.expect("fixture has one indirect encryption dictionary object");
let dictionary_start = object_start + object_marker.len();
assert!(bytes[dictionary_start..].starts_with(b"<<"));
let object_end = dictionary_start
+ bytes[dictionary_start..]
.windows(b"endobj".len())
.position(|window| window == b"endobj")
.expect("encryption dictionary object has endobj");
let relative_end = bytes[dictionary_start..object_end]
.windows(2)
.rposition(|window| window == b">>")
.expect("encryption dictionary has a closing delimiter")
+ 2;
let dictionary_end = dictionary_start + relative_end;
let span_len = dictionary_end - dictionary_start;
assert!(span_len >= b"123".len());
bytes[dictionary_start..dictionary_end].fill(b' ');
bytes[dictionary_start..dictionary_start + b"123".len()].copy_from_slice(b"123");
}
#[test]
fn invalid_encryption_dictionary_errors_match_qpdf_across_cli_routes() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let base = std::fs::read(fixture("../../tests/fixtures/encrypted/v2-rc4-128-r3.pdf"))
.expect("read qpdf V2/R3 donor fixture");
struct Mutation {
name: &'static str,
from: &'static [u8],
to: &'static [u8],
}
let cases = [
Mutation {
name: "v3-r3",
from: b"/V 2",
to: b"/V 3",
},
Mutation {
name: "bad-filter",
from: b"/Standard",
to: b"/BadValue",
},
];
for Mutation {
name: case,
from,
to,
} in cases
{
let mut bytes = base.clone();
replace_fixture_token(&mut bytes, from, to);
let donor = tmp.path().join(format!("{case}.pdf"));
std::fs::write(&donor, bytes).expect("write mutated donor fixture");
for route in ["show", "check", "copy"] {
let qpdf = match route {
"show" => ShellCommand::new("qpdf")
.arg("--show-encryption")
.arg(&donor)
.output()
.expect("run qpdf --show-encryption"),
"check" => ShellCommand::new("qpdf")
.arg("--check")
.arg(&donor)
.output()
.expect("run qpdf --check"),
_ => ShellCommand::new("qpdf")
.arg("--empty")
.arg(format!("--copy-encryption={}", donor.display()))
.arg(tmp.path().join(format!("qpdf-{case}.pdf")))
.output()
.expect("run qpdf --copy-encryption"),
};
let flpdf = match route {
"show" => Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_PROGNAME", "qpdf")
.arg("--show-encryption")
.arg(&donor)
.output()
.expect("run flpdf --show-encryption"),
"check" => Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_PROGNAME", "qpdf")
.arg("--check")
.arg(&donor)
.output()
.expect("run flpdf --check"),
_ => Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_PROGNAME", "qpdf")
.arg("--empty")
.arg(format!("--copy-encryption={}", donor.display()))
.arg(tmp.path().join(format!("flpdf-{case}.pdf")))
.output()
.expect("run flpdf --copy-encryption"),
};
assert_eq!(qpdf.status.code(), Some(2), "qpdf {case}/{route}");
assert_eq!(
flpdf.status.code(),
qpdf.status.code(),
"flpdf {case}/{route}"
);
assert_eq!(flpdf.stdout, qpdf.stdout, "stdout for {case}/{route}");
assert_eq!(flpdf.stderr, qpdf.stderr, "stderr for {case}/{route}");
}
}
}
#[test]
fn indirect_non_dictionary_encrypt_context_matches_qpdf_across_cli_routes() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let mut bytes = std::fs::read(fixture("../../tests/fixtures/encrypted/v2-rc4-128-r3.pdf"))
.expect("read qpdf V2/R3 fixture");
replace_fixture_encrypt_dictionary_with_integer(&mut bytes);
let donor = tmp.path().join("indirect-encrypt.pdf");
std::fs::write(&donor, bytes).expect("write mutated indirect /Encrypt fixture");
for route in ["show", "check", "copy"] {
let qpdf = match route {
"show" => ShellCommand::new("qpdf")
.arg("--show-encryption")
.arg(&donor)
.output()
.expect("run qpdf --show-encryption"),
"check" => ShellCommand::new("qpdf")
.arg("--check")
.arg(&donor)
.output()
.expect("run qpdf --check"),
_ => ShellCommand::new("qpdf")
.arg("--empty")
.arg(format!("--copy-encryption={}", donor.display()))
.arg(tmp.path().join("qpdf-output.pdf"))
.output()
.expect("run qpdf --copy-encryption"),
};
let flpdf = match route {
"show" => Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_PROGNAME", "qpdf")
.arg("--show-encryption")
.arg(&donor)
.output()
.expect("run flpdf --show-encryption"),
"check" => Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_PROGNAME", "qpdf")
.arg("--check")
.arg(&donor)
.output()
.expect("run flpdf --check"),
_ => Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_PROGNAME", "qpdf")
.arg("--empty")
.arg(format!("--copy-encryption={}", donor.display()))
.arg(tmp.path().join("flpdf-output.pdf"))
.output()
.expect("run flpdf --copy-encryption"),
};
assert_eq!(
qpdf.status.code(),
Some(2),
"qpdf indirect /Encrypt/{route}"
);
assert_eq!(
flpdf.status.code(),
qpdf.status.code(),
"flpdf indirect /Encrypt/{route}"
);
assert_eq!(flpdf.stdout, qpdf.stdout, "stdout for {route}");
assert_eq!(flpdf.stderr, qpdf.stderr, "stderr for {route}");
}
}
#[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");
let stderr = copy_encryption_failure_stderr(&donor, Some("wrongpw"), &out);
assert_eq!(
stderr,
format!("flpdf: {}: invalid password{EOL}", donor.display())
);
assert!(!out.exists());
}
#[test]
fn copy_encryption_missing_password_reports_invalid_password() {
let tmp = tempfile::tempdir().unwrap();
let donor = make_donor_pdf(&tmp, "correctpw", "ownerpw");
let out = tmp.path().join("out.pdf");
let stderr = copy_encryption_failure_stderr(&donor, None, &out);
assert_eq!(
stderr,
format!("flpdf: {}: invalid password{EOL}", donor.display())
);
assert!(!out.exists());
}
#[test]
fn copy_encryption_missing_donor_reports_open_failure() {
let tmp = tempfile::tempdir().unwrap();
let donor = tmp.path().join("no-such-donor.pdf");
let out = tmp.path().join("out.pdf");
let stderr = copy_encryption_failure_stderr(&donor, None, &out);
assert_eq!(
stderr,
format!(
"flpdf: open {}: No such file or directory{EOL}",
donor.display()
)
);
assert!(!out.exists());
let assert = Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_PROGNAME", "qpdf")
.arg(format!("--copy-encryption={}", donor.display()))
.arg(fixture(UNENCRYPTED_FIXTURE))
.arg(&out)
.assert()
.failure()
.code(2);
assert_eq!(
String::from_utf8_lossy(&assert.get_output().stderr),
format!(
"qpdf: open {}: No such file or directory{EOL}",
donor.display()
)
);
}
#[test]
fn copy_encryption_non_pdf_donor_reports_recovery_failure() {
let tmp = tempfile::tempdir().unwrap();
let donor = tmp.path().join("not-a-pdf.txt");
std::fs::write(&donor, b"this is not a PDF\n").unwrap();
let out = tmp.path().join("out.pdf");
let stderr = copy_encryption_failure_stderr(&donor, None, &out);
let path = donor.display().to_string();
let lines: Vec<&str> = stderr.lines().collect();
let (terminal, warnings) = lines.split_last().unwrap();
assert_eq!(
*terminal,
format!("flpdf: {path}: unable to find trailer dictionary while recovering damaged file")
);
assert!(!warnings.is_empty(), "donor recovery warnings: {stderr}");
for warning in warnings {
assert!(
warning.starts_with(&format!("WARNING: {path}: ")),
"donor diagnostics must name the donor: {stderr}"
);
}
assert!(!out.exists());
}
#[cfg(unix)]
#[test]
fn copy_encryption_directory_donor_reports_read_failure() {
let tmp = tempfile::tempdir().unwrap();
let donor = tmp.path().join("donor-dir");
std::fs::create_dir(&donor).unwrap();
let out = tmp.path().join("out.pdf");
let stderr = copy_encryption_failure_stderr(&donor, None, &out);
assert_eq!(
stderr,
format!("flpdf: {}: read 1024 bytes{EOL}", donor.display())
);
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_ignores_attached_value() {
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()
.success();
assert!(
output.exists(),
"attached bare-option value must be discarded"
);
}
#[test]
fn encrypt_force_r5_succeeds_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()
.success();
assert!(
output.exists(),
"qpdf's force-R5 path must write an output PDF"
);
}
#[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_uses_classic_xref_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_classic_xref.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 not use xref stream form when the output ObjStm map is empty"
);
assert!(
bytes.windows(b"\nxref\n".len()).any(|w| w == b"\nxref\n"),
"output must use a classic xref table when the output ObjStm map is empty"
);
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_classic_xref.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, rewrite) in [("rewrite", true), ("top-level", false)] {
let output = tmp.path().join(format!("lin-copy-enc-{surface}.pdf"));
let mut command = Command::cargo_bin("flpdf").unwrap();
if rewrite {
command.arg("rewrite");
}
command
.arg("--linearize")
.arg(format!("--copy-encryption={}", donor.display()))
.arg("--encryption-file-password=donor-user")
.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 linearize_encrypt_nonempty_objstm_is_byte_identical_to_qpdf() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let source = tmp.path().join("source-objstm.pdf");
let prepared = ShellCommand::new("qpdf")
.args([
"--object-streams=generate",
"--static-id",
"--warning-exit-0",
])
.arg(fixture(OBJSTM_LINEARIZE_FIXTURE))
.arg(&source)
.output()
.unwrap();
assert!(
prepared.status.success(),
"qpdf ObjStm preparation failed: {}",
String::from_utf8_lossy(&prepared.stderr)
);
for (mode, compress_arg) in [
("compressed", None),
("uncompressed", Some("--compress-streams=n")),
] {
let mut qpdf_args = vec![
"--linearize",
"--object-streams=generate",
"--static-id",
"--static-aes-iv",
];
if let Some(arg) = compress_arg {
qpdf_args.push(arg);
}
qpdf_args.extend(["--encrypt", "", "", "128", "--use-aes=y", "--"]);
let qpdf_output = tmp.path().join(format!("{mode}-qpdf.pdf"));
let qpdf = ShellCommand::new("qpdf")
.args(&qpdf_args)
.arg(&source)
.arg(&qpdf_output)
.output()
.unwrap();
assert!(
qpdf.status.success(),
"{mode}: qpdf encrypted linearization failed: {}",
String::from_utf8_lossy(&qpdf.stderr)
);
let reference = std::fs::read(&qpdf_output).unwrap();
for (surface, rewrite) in [("top-level", false), ("rewrite", true)] {
let output = tmp.path().join(format!("{mode}-{surface}.pdf"));
let mut command = Command::cargo_bin("flpdf").unwrap();
if rewrite {
command.arg("rewrite");
}
command
.args(&qpdf_args)
.arg(&source)
.arg(&output)
.assert()
.success();
let actual = std::fs::read(&output).unwrap();
assert_eq!(
actual, reference,
"{mode}/{surface}: non-empty encrypted ObjStm linearization must match qpdf"
);
let check = ShellCommand::new("qpdf")
.args(["--password=", "--check"])
.arg(&output)
.output()
.unwrap();
assert!(
check.status.success(),
"{mode}/{surface}: qpdf --check failed: stdout={} stderr={}",
String::from_utf8_lossy(&check.stdout),
String::from_utf8_lossy(&check.stderr)
);
let check_stdout = String::from_utf8_lossy(&check.stdout);
assert!(
check_stdout.contains("File is linearized"),
"{mode}/{surface}: output must remain linearized: {check_stdout}"
);
let xref = ShellCommand::new("qpdf")
.args(["--password=", "--show-xref"])
.arg(&output)
.output()
.unwrap();
let xref_stdout = String::from_utf8_lossy(&xref.stdout);
assert!(
xref.status.success()
&& xref_stdout.lines().any(|line| line.contains("compressed")),
"{mode}/{surface}: output must contain non-empty ObjStm members: {xref_stdout}"
);
}
}
}
#[test]
fn linearize_encrypted_input_with_generated_objstm_has_valid_hint_table() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
for (mode, encryption_args) in [
("rc4-128", &["--bits=128", "--use-aes=n"][..]),
("aes-128", &["--bits=128", "--use-aes=y"][..]),
("aes-256", &["--bits=256"][..]),
] {
let encrypted = tmp.path().join(format!("{mode}-encrypted.pdf"));
let encrypt = ShellCommand::new("qpdf")
.args([
"--static-id",
"--allow-weak-crypto",
"--encrypt",
"--user-password=",
"--owner-password=o",
])
.args(encryption_args)
.arg("--")
.arg(fixture(LINEARIZE_OBJSTM_ENCRYPTION_FIXTURE))
.arg(&encrypted)
.output()
.unwrap();
assert!(
encrypt.status.success(),
"{mode}: qpdf encryption fixture preparation failed: {}",
String::from_utf8_lossy(&encrypt.stderr)
);
for (surface, rewrite) in [("top-level", false), ("rewrite", true)] {
let output = tmp.path().join(format!("{mode}-{surface}-linearized.pdf"));
let mut command = Command::cargo_bin("flpdf").unwrap();
if rewrite {
command.arg("rewrite");
}
command
.args([
"--static-id",
"--password=o",
"--linearize",
"--object-streams=generate",
"--",
])
.arg(&encrypted)
.arg(&output)
.assert()
.success();
let check = ShellCommand::new("qpdf")
.args(["--password=o", "--check-linearization"])
.arg(&output)
.output()
.unwrap();
assert!(
check.status.success(),
"{mode}/{surface}: qpdf --check-linearization failed: stdout={} stderr={}",
String::from_utf8_lossy(&check.stdout),
String::from_utf8_lossy(&check.stderr)
);
let check_stdout = String::from_utf8_lossy(&check.stdout);
let check_stderr = String::from_utf8_lossy(&check.stderr);
assert!(
check_stdout.contains("no linearization errors")
&& !check_stdout.contains("WARNING:")
&& !check_stderr.contains("WARNING:"),
"{mode}/{surface}: qpdf must report clean linearization: stdout={check_stdout} stderr={check_stderr}"
);
}
}
}
#[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_combines_with_show_encryption_like_qpdf() {
let input = fixture(UNENCRYPTED_FIXTURE);
let qpdf = ShellCommand::new("qpdf")
.args(["--check-linearization", "--show-encryption"])
.arg(&input)
.output()
.unwrap();
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_PROGNAME", "qpdf")
.args(["--check-linearization", "--show-encryption"])
.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 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(
"no output file may be given for this option",
));
}
#[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(
"no output file may be given for this option",
));
}
#[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!(
no_warn.stdout,
format!("File is not encrypted{EOL}").into_bytes(),
"--no-warn --show-encryption must print only the qpdf report body"
);
}
#[test]
fn accessibility_disabled_notice_repeats_once_per_split_pages_chunk() {
if !ensure_qpdf_or_skip() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let source = tmp.path().join("three-pages.pdf");
let build = ShellCommand::new("qpdf")
.arg("--empty")
.arg("--pages")
.arg(fixture(ONE_PAGE_FIXTURE))
.arg("1")
.arg(fixture(ONE_PAGE_FIXTURE))
.arg("1")
.arg(fixture(ONE_PAGE_FIXTURE))
.arg("1")
.arg("--")
.arg(&source)
.status()
.unwrap();
assert!(build.success(), "qpdf must build the 3-page source fixture");
let split_args = [
"--split-pages",
"--encrypt",
"",
"",
"128",
"--accessibility=n",
"--use-aes=y",
"--",
];
let qpdf_out = tmp.path().join("qpdf-split-%d.pdf");
let qpdf_result = ShellCommand::new("qpdf")
.args(split_args)
.arg(&source)
.arg(&qpdf_out)
.output()
.unwrap();
assert!(
qpdf_result.status.success(),
"qpdf split-pages with --accessibility=n must succeed: {}",
String::from_utf8_lossy(&qpdf_result.stderr)
);
let qpdf_notice_count = String::from_utf8_lossy(&qpdf_result.stderr)
.matches("-accessibility=n is ignored for modern encryption formats")
.count();
assert_eq!(
qpdf_notice_count,
3,
"sanity check: real qpdf 11.9.0 must repeat the notice once per \
3-page-source, 1-page-chunk split: {}",
String::from_utf8_lossy(&qpdf_result.stderr)
);
let flpdf_out = tmp.path().join("flpdf-split-%d.pdf");
let flpdf_result = Command::cargo_bin("flpdf")
.unwrap()
.args(split_args)
.arg(&source)
.arg(&flpdf_out)
.output()
.unwrap();
assert!(
flpdf_result.status.success(),
"flpdf split-pages with --accessibility=n must succeed: {}",
String::from_utf8_lossy(&flpdf_result.stderr)
);
let flpdf_notice_count = String::from_utf8_lossy(&flpdf_result.stderr)
.matches("-accessibility=n is ignored for modern encryption formats")
.count();
assert_eq!(
flpdf_notice_count,
3,
"flpdf must repeat the notice once per chunk, matching qpdf: {}",
String::from_utf8_lossy(&flpdf_result.stderr)
);
}