use assert_cmd::Command;
use predicates::prelude::*;
use std::io::Write as _;
fn minimal_pdf_bytes() -> Vec<u8> {
let mut pdf = Vec::new();
pdf.extend_from_slice(b"%PDF-1.4\n");
let off1 = pdf.len();
pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
let off2 = pdf.len();
pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
let off3 = pdf.len();
pdf.extend_from_slice(
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
);
let xref_start = pdf.len();
let xref = format!(
"xref\n0 4\n0000000000 65535 f \n{:010} 00000 n \n{:010} 00000 n \n{:010} 00000 n \n",
off1, off2, off3,
);
pdf.extend_from_slice(xref.as_bytes());
let trailer = format!("trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n");
pdf.extend_from_slice(trailer.as_bytes());
pdf
}
fn write_temp(bytes: &[u8]) -> tempfile::NamedTempFile {
let mut f = tempfile::NamedTempFile::new().unwrap();
f.write_all(bytes).unwrap();
f
}
fn linearized_fixture_bytes() -> Vec<u8> {
include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../tests/fixtures/compat/linearized-one-page.pdf"
))
.to_vec()
}
fn replace_linearization_parameter(bytes: &mut [u8], key: &[u8], replacement: &[u8]) {
let mut needle = key.to_vec();
needle.push(b' ');
let start = bytes
.windows(needle.len())
.position(|window| window == needle)
.map(|position| position + needle.len())
.unwrap_or_else(|| panic!("missing linearization parameter {:?}", key));
let end = start
+ bytes[start..]
.iter()
.position(|byte| !byte.is_ascii_digit())
.expect("linearization parameter must be decimal");
assert_eq!(
end - start,
replacement.len(),
"replacement width must match"
);
bytes[start..end].copy_from_slice(replacement);
}
#[test]
fn rewrite_linearize_then_check_passes() {
let input = write_temp(&minimal_pdf_bytes());
let outdir = tempfile::tempdir().unwrap();
let output = outdir.path().join("linearized.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--linearize",
input.path().to_str().unwrap(),
output.to_str().unwrap(),
])
.assert()
.success();
assert!(output.exists(), "linearized output file must be created");
assert!(
std::fs::metadata(&output).unwrap().len() > 0,
"linearized output must not be empty"
);
Command::cargo_bin("flpdf")
.unwrap()
.args(["check-linearization", output.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("no linearization errors"));
}
#[test]
fn check_linearization_tampered_l_reports_not_linearized() {
let input = write_temp(&minimal_pdf_bytes());
let outdir = tempfile::tempdir().unwrap();
let linearized_path = outdir.path().join("linearized.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--linearize",
input.path().to_str().unwrap(),
linearized_path.to_str().unwrap(),
])
.assert()
.success();
let mut bytes = std::fs::read(&linearized_path).unwrap();
let needle = b"/L ";
let pos = bytes
.windows(needle.len())
.position(|w| w == needle)
.expect("could not find '/L ' in linearized output for tampering");
let val_start = pos + needle.len();
let val_end = val_start
+ bytes[val_start..]
.iter()
.position(|&b| !b.is_ascii_digit())
.expect("/L value must terminate at a non-digit");
assert!(val_end > val_start, "/L value must have at least one digit");
let last = val_end - 1;
bytes[last] = if bytes[last] == b'9' {
b'0'
} else {
bytes[last] + 1
};
let tampered_path = outdir.path().join("tampered.pdf");
std::fs::write(&tampered_path, &bytes).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["check-linearization", tampered_path.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("is not linearized"));
}
#[test]
fn check_reports_all_linearization_soft_warnings() {
let outdir = tempfile::tempdir().unwrap();
let input = outdir.path().join("o-and-t-mismatch.pdf");
let mut bytes = linearized_fixture_bytes();
replace_linearization_parameter(&mut bytes, b"/O", b"7");
replace_linearization_parameter(&mut bytes, b"/T", b"1522");
std::fs::write(&input, bytes).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_PROGNAME", "qpdf")
.args(["check", input.to_str().unwrap()])
.assert()
.failure()
.code(3)
.stderr(predicate::str::contains(
"WARNING: ".to_owned() + input.to_str().unwrap() + ": first page object (/O) mismatch",
))
.stderr(predicate::str::contains(
"space before first xref item (/T) mismatch (computed = 1524; file = 1522",
));
}
#[test]
fn check_reports_qpdf_linearization_parameter_offset() {
let outdir = tempfile::tempdir().unwrap();
let input = outdir.path().join("n-mismatch.pdf");
let mut bytes = linearized_fixture_bytes();
replace_linearization_parameter(&mut bytes, b"/N", b"2");
std::fs::write(&input, bytes).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_PROGNAME", "qpdf")
.args(["check", input.to_str().unwrap()])
.assert()
.failure()
.code(3)
.stderr(predicate::str::contains(
"(linearization hint table, offset 908): /N does not match number of pages",
));
}
#[test]
fn check_linearization_non_linearized_exits_0() {
let input = write_temp(&minimal_pdf_bytes());
Command::cargo_bin("flpdf")
.unwrap()
.args(["check-linearization", input.path().to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("is not linearized"));
}
#[test]
fn show_linearization_dumps_structure() {
let input = write_temp(&minimal_pdf_bytes());
let outdir = tempfile::tempdir().unwrap();
let output = outdir.path().join("linearized.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--linearize",
"--static-id",
input.path().to_str().unwrap(),
output.to_str().unwrap(),
])
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--show-linearization", output.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("linearization data:"))
.stdout(predicate::str::contains("Page Offsets Hint Table"))
.stdout(predicate::str::contains("Shared Objects Hint Table"));
}
#[test]
fn show_linearization_soft_warnings_exit_3_after_dump() {
let outdir = tempfile::tempdir().unwrap();
let input = outdir.path().join("o-and-t-mismatch.pdf");
let mut bytes = linearized_fixture_bytes();
replace_linearization_parameter(&mut bytes, b"/O", b"7");
replace_linearization_parameter(&mut bytes, b"/T", b"1522");
std::fs::write(&input, bytes).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_PROGNAME", "qpdf")
.args(["--show-linearization", input.to_str().unwrap()])
.assert()
.failure()
.code(3)
.stdout(predicate::str::contains("linearization data:"))
.stderr(predicate::str::contains("first page object (/O) mismatch"))
.stderr(predicate::str::contains(
"space before first xref item (/T) mismatch",
))
.stderr(predicate::str::contains(
"qpdf: operation succeeded with warnings",
));
}
#[test]
fn show_linearization_parameter_warning_exits_3_without_dump() {
let outdir = tempfile::tempdir().unwrap();
let input = outdir.path().join("n-mismatch.pdf");
let mut bytes = linearized_fixture_bytes();
replace_linearization_parameter(&mut bytes, b"/N", b"2");
std::fs::write(&input, bytes).unwrap();
let input_name = input.to_string_lossy();
Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_PROGNAME", "qpdf")
.args(["--show-linearization", input.to_str().unwrap()])
.assert()
.failure()
.code(3)
.stdout(predicate::str::is_empty())
.stderr(predicate::str::contains(format!(
"WARNING: {input_name}: {input_name} (linearization hint table, offset 908): /N does not match number of pages"
)))
.stderr(predicate::str::contains(
"qpdf: operation succeeded with warnings",
));
}
#[test]
fn show_linearization_non_linearized_exits_0() {
let input = write_temp(&minimal_pdf_bytes());
Command::cargo_bin("flpdf")
.unwrap()
.args(["--show-linearization", input.path().to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("is not linearized"));
}
#[test]
fn show_linearization_missing_file_exits_2() {
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--show-linearization",
"/tmp/this_file_does_not_exist_flpdf_showlin_test.pdf",
])
.assert()
.failure()
.code(2);
}
#[test]
fn rewrite_without_linearize_flag_still_works() {
let outdir = tempfile::tempdir().unwrap();
let output = outdir.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"../../tests/fixtures/minimal.pdf",
output.to_str().unwrap(),
])
.assert()
.success();
assert!(output.exists());
assert!(std::fs::metadata(&output).unwrap().len() > 0);
}
#[test]
fn check_linearization_missing_file_exits_2() {
Command::cargo_bin("flpdf")
.unwrap()
.args([
"check-linearization",
"/tmp/this_file_does_not_exist_flpdf_test.pdf",
])
.assert()
.failure()
.code(2);
}
#[test]
fn linearize_inherits_source_version() {
let outdir = tempfile::tempdir().unwrap();
let output = outdir.path().join("lin.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--linearize",
"../../tests/fixtures/compat/one-page.pdf",
output.to_str().unwrap(),
])
.assert()
.success();
let bytes = std::fs::read(&output).unwrap();
assert!(
bytes.starts_with(b"%PDF-1.3\n"),
"linearized header must be %PDF-1.3 (inherited from source); got: {}",
String::from_utf8_lossy(&bytes[..bytes.len().min(20)])
);
}
#[test]
fn linearize_min_version_raises_header() {
let outdir = tempfile::tempdir().unwrap();
let output = outdir.path().join("lin-min17.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--linearize",
"--min-version=1.7",
"../../tests/fixtures/compat/one-page.pdf",
output.to_str().unwrap(),
])
.assert()
.success();
let bytes = std::fs::read(&output).unwrap();
assert!(
bytes.starts_with(b"%PDF-1.7\n"),
"with --min-version=1.7 the header must be %PDF-1.7; got: {}",
String::from_utf8_lossy(&bytes[..bytes.len().min(20)])
);
}
#[test]
fn linearize_force_version_overrides() {
let outdir = tempfile::tempdir().unwrap();
let output = outdir.path().join("lin-force14.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--linearize",
"--force-version=1.4",
"../../tests/fixtures/compat/one-page.pdf",
output.to_str().unwrap(),
])
.assert()
.success();
let bytes = std::fs::read(&output).unwrap();
assert!(
bytes.starts_with(b"%PDF-1.4\n"),
"with --force-version=1.4 the header must be %PDF-1.4; got: {}",
String::from_utf8_lossy(&bytes[..bytes.len().min(20)])
);
}
#[test]
fn linearize_force_version_overrides_linearize_floor() {
let outdir = tempfile::tempdir().unwrap();
let output = outdir.path().join("lin-force10.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--linearize",
"--force-version=1.0",
"../../tests/fixtures/compat/one-page.pdf",
output.to_str().unwrap(),
])
.assert()
.success();
let bytes = std::fs::read(&output).unwrap();
assert!(
bytes.starts_with(b"%PDF-1.0\n"),
"with --force-version=1.0 the header must be %PDF-1.0; got: {}",
String::from_utf8_lossy(&bytes[..bytes.len().min(20)])
);
}
fn first_id_pair(bytes: &[u8]) -> (Vec<u8>, Vec<u8>) {
let pos = bytes
.windows(3)
.position(|w| w == b"/ID")
.expect("/ID key present");
let lb = bytes[pos..]
.iter()
.position(|&b| b == b'[')
.map(|i| pos + i)
.expect("/ID array open bracket");
let rb = bytes[lb..]
.iter()
.position(|&b| b == b']')
.map(|i| lb + i)
.expect("/ID array close bracket");
let slice = &bytes[lb + 1..rb];
let mut hexes = slice
.split(|&b| b == b'<' || b == b'>')
.filter(|s| !s.is_empty() && s.iter().all(|&c| c.is_ascii_hexdigit()))
.map(|s| s.to_vec());
let a = hexes.next().expect("/ID element 1");
let b = hexes.next().expect("/ID element 2");
(a, b)
}
#[test]
fn linearize_no_source_id_emits_fresh_random_id() {
let input = write_temp(&minimal_pdf_bytes());
let run = || {
let outdir = tempfile::tempdir().unwrap();
let output = outdir.path().join("linearized.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--linearize",
input.path().to_str().unwrap(),
output.to_str().unwrap(),
])
.assert()
.success();
std::fs::read(&output).unwrap()
};
let bytes1 = run();
let bytes2 = run();
let id_needle = b"/ID";
assert!(
bytes1.windows(id_needle.len()).any(|w| w == id_needle),
"default strategy must emit /ID even when source has none"
);
let (a1, b1) = first_id_pair(&bytes1);
let (a2, b2) = first_id_pair(&bytes2);
assert_eq!(a1.len(), 32, "/ID element 1 must be 16 bytes (32 hex)");
assert_eq!(b1.len(), 32, "/ID element 2 must be 16 bytes (32 hex)");
let pi = b"31415926535897932384626433832795";
assert_ne!(a1.as_slice(), pi, "/ID[0] must not be the π constant");
assert_ne!(b1.as_slice(), pi, "/ID[1] must not be the π constant");
assert!(a1.iter().any(|&c| c != b'0'), "/ID[0] must not be all-zero");
assert!(b1.iter().any(|&c| c != b'0'), "/ID[1] must not be all-zero");
assert!(
(a1, b1) != (a2, b2),
"default /ID must differ between independent runs"
);
}
#[test]
fn linearize_static_id_emits_id_key() {
let input = write_temp(&minimal_pdf_bytes());
let outdir = tempfile::tempdir().unwrap();
let output = outdir.path().join("linearized-static.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--linearize",
"--static-id",
input.path().to_str().unwrap(),
output.to_str().unwrap(),
])
.assert()
.success();
let bytes = std::fs::read(&output).unwrap();
let id_needle = b"/ID";
assert!(
bytes.windows(id_needle.len()).any(|w| w == id_needle),
"linearized output with --static-id must contain /ID"
);
}
#[test]
fn parse_pdf_version_valid() {
use flpdf::{parse_pdf_version, PdfVersion};
assert_eq!(parse_pdf_version("1.3"), Some(PdfVersion::new(1, 3, 0)));
assert_eq!(parse_pdf_version("1.7"), Some(PdfVersion::new(1, 7, 0)));
assert_eq!(parse_pdf_version("2.0"), Some(PdfVersion::new(2, 0, 0)));
assert_eq!(parse_pdf_version("1.10"), Some(PdfVersion::new(1, 10, 0)));
assert_eq!(parse_pdf_version("invalid"), None);
assert_eq!(parse_pdf_version(""), None);
}
#[test]
fn linearize_part1_startxref_is_zero_final_startxref_points_at_first_page_xref() {
let input = write_temp(&minimal_pdf_bytes());
let outdir = tempfile::tempdir().unwrap();
let output = outdir.path().join("linearized.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--linearize",
"--static-id",
input.path().to_str().unwrap(),
output.to_str().unwrap(),
])
.assert()
.success();
let bytes = std::fs::read(&output).unwrap();
let needle = b"startxref\n";
let parse_val = |pos: usize| -> usize {
let val_start = pos + needle.len();
let val_end = bytes[val_start..]
.iter()
.position(|&b| b == b'\n')
.map(|p| val_start + p)
.expect("startxref value must be newline-terminated");
std::str::from_utf8(&bytes[val_start..val_end])
.expect("UTF-8")
.trim()
.parse()
.expect("decimal")
};
let first_pos = bytes
.windows(needle.len())
.position(|w| w == needle)
.expect("must have at least one startxref");
let part1_val: usize = parse_val(first_pos);
assert_eq!(
part1_val, 0,
"Part 1 first trailer startxref must be 0 (qpdf linearized convention)"
);
let last_pos = bytes
.windows(needle.len())
.rposition(|w| w == needle)
.expect("must have at least two startxref");
let final_val: usize = parse_val(last_pos);
let is_standalone_xref = |i: usize| -> bool {
&bytes[i..i + 4] == b"xref"
&& (i == 0 || bytes[i - 1].is_ascii_whitespace())
&& (i + 4 >= bytes.len() || bytes[i + 4].is_ascii_whitespace())
};
let first_xref_pos = (0..bytes.len().saturating_sub(3))
.find(|&i| is_standalone_xref(i))
.expect("must have at least one standalone xref keyword");
let last_xref_pos = (0..bytes.len().saturating_sub(3))
.rev()
.find(|&i| is_standalone_xref(i))
.expect("must have at least one standalone xref keyword");
assert!(
first_xref_pos < last_xref_pos,
"first-page xref ({first_xref_pos}) must precede the main xref ({last_xref_pos})"
);
assert_eq!(
final_val, first_xref_pos,
"final startxref ({final_val}) must equal the FIRST-PAGE xref keyword \
offset ({first_xref_pos}) — qpdf classic linearized layout"
);
}
fn extract_int_field(bytes: &[u8], key: &[u8]) -> (usize, Vec<u8>) {
let pos = bytes
.windows(key.len())
.position(|w| w == key)
.unwrap_or_else(|| {
panic!(
"param dict key {:?} not found",
String::from_utf8_lossy(key)
)
});
let val_start = pos + key.len();
let val_end = bytes[val_start..]
.iter()
.position(|&b| !b.is_ascii_digit())
.map(|p| val_start + p)
.expect("integer field must terminate");
(val_start, bytes[val_start..val_end].to_vec())
}
#[test]
fn linearize_param_dict_integers_are_variable_width_decimal() {
let outdir = tempfile::tempdir().unwrap();
let output = outdir.path().join("lin.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--linearize",
"--static-id",
"../../tests/fixtures/compat/one-page.pdf",
output.to_str().unwrap(),
])
.assert()
.success();
let bytes = std::fs::read(&output).unwrap();
let check_no_leading_zero = |label: &str, digits: &[u8]| {
let s = std::str::from_utf8(digits).expect("digits utf-8");
let parsed: u64 = s
.parse()
.unwrap_or_else(|e| panic!("{label} value '{s}' must be a valid decimal integer: {e}"));
let canonical = parsed.to_string();
assert_eq!(
s, canonical,
"{label} must be variable-width decimal with no zero-padding; \
got '{s}', expected '{canonical}' (= {parsed})"
);
};
let (_, l_digits) = extract_int_field(&bytes, b"/L ");
check_no_leading_zero("/L", &l_digits);
let h_pos = bytes
.windows(b"/H [ ".len())
.position(|w| w == b"/H [ ")
.expect("/H array");
let h_inner_start = h_pos + b"/H [ ".len();
let space1 = bytes[h_inner_start..]
.iter()
.position(|&b| b == b' ')
.map(|p| h_inner_start + p)
.expect("/H[0] terminator");
check_no_leading_zero("/H[0]", &bytes[h_inner_start..space1]);
let h1_start = space1 + 1;
let space2 = bytes[h1_start..]
.iter()
.position(|&b| b == b' ')
.map(|p| h1_start + p)
.expect("/H[1] terminator");
check_no_leading_zero("/H[1]", &bytes[h1_start..space2]);
let (_, o_digits) = extract_int_field(&bytes, b"/O ");
check_no_leading_zero("/O", &o_digits);
let (_, e_digits) = extract_int_field(&bytes, b"/E ");
check_no_leading_zero("/E", &e_digits);
let (_, n_digits) = extract_int_field(&bytes, b"/N ");
check_no_leading_zero("/N", &n_digits);
let (_, t_digits) = extract_int_field(&bytes, b"/T ");
check_no_leading_zero("/T", &t_digits);
}
#[test]
fn linearize_l_value_equals_file_length_post_compact() {
let outdir = tempfile::tempdir().unwrap();
let output = outdir.path().join("lin.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--linearize",
"--static-id",
"../../tests/fixtures/compat/one-page.pdf",
output.to_str().unwrap(),
])
.assert()
.success();
let bytes = std::fs::read(&output).unwrap();
let (_, l_digits) = extract_int_field(&bytes, b"/L ");
let l_val: usize = std::str::from_utf8(&l_digits)
.unwrap()
.parse()
.expect("/L numeric");
assert_eq!(
l_val,
bytes.len(),
"/L ({l_val}) must equal the total file length ({})",
bytes.len()
);
}