Files
Pictor-public/crates/worker/tests/hostile_pdf.rs
T

295 lines
14 KiB
Rust

//! Mandatory test 2: hostile PDFs. Each fixture goes through the real worker process (open, render page 1, text,
//! metadata, a save with an annotation). Every step either works or fails with a typed error within its time cap;
//! a worker that crashes, hangs or runs out of memory is reported as such and replaced. This test process plays the
//! tray: it must never crash, and the next request after a bad file must work.
//! Fixtures are generated here; fixtures-fetch/fetch.ps1 adds real-world corpora under fixtures/fetched/ (optional).
use flate2::{Compression, write::ZlibEncoder};
use lopdf::{Document, Object, Stream, dictionary};
use pictor_worker::client::{Worker, WorkerError, WorkerOptions};
use serde_json::json;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
const CAP: Duration = Duration::from_secs(15);
fn worker() -> Worker {
let mut o = WorkerOptions::new(env!("CARGO_BIN_EXE_pictor-worker"));
o.pdfium_dir = Some(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../third_party/pdfium/bin"));
o.memory_mb = 1024;
o.debug = true;
Worker::new(o)
}
fn base_doc(content: &[u8]) -> Document {
let mut doc = Document::with_version("1.7");
let pages = doc.new_object_id();
let font = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica"});
let c = doc.add_object(Stream::new(dictionary! {}, content.to_vec()));
let page = doc.add_object(dictionary! {"Type" => "Page", "Parent" => pages, "Contents" => c,
"Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}});
doc.objects.insert(pages, Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => vec![page.into()], "Count" => 1,
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}));
let cat = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages});
doc.trailer.set("Root", cat);
doc
}
fn save(mut doc: Document) -> Vec<u8> {
let mut v = Vec::new();
doc.save_to(&mut v).unwrap();
v
}
fn valid() -> Vec<u8> {
save(base_doc(b"BT /F1 24 Tf 72 700 Td (Hello hostile world) Tj ET"))
}
fn replace(hay: &[u8], from: &[u8], to: &[u8]) -> Vec<u8> {
let i = hay.windows(from.len()).position(|w| w == from).expect("pattern");
[&hay[..i], to, &hay[i + from.len()..]].concat()
}
fn font_doc(font_key: &str, font_bytes: Vec<u8>) -> Vec<u8> {
let mut doc = base_doc(b"BT /F2 24 Tf 72 700 Td (Font) Tj ET");
let ff = doc.add_object(Stream::new(dictionary! {}, font_bytes));
let desc = doc.add_object(dictionary! {"Type" => "FontDescriptor", "FontName" => "Broken", "Flags" => 32,
"FontBBox" => vec![0.into(), 0.into(), 1000.into(), 1000.into()], "ItalicAngle" => 0, "Ascent" => 800,
"Descent" => -200, "CapHeight" => 700, "StemV" => 80, font_key => ff});
let font = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => if font_key == "FontFile" { "Type1" } else { "TrueType" },
"BaseFont" => "Broken", "FirstChar" => 32, "LastChar" => 126, "FontDescriptor" => desc});
let page = *doc.get_pages().values().next().unwrap();
doc.get_dictionary_mut(page).unwrap().set("Resources", dictionary! {"Font" => dictionary! {"F2" => font}});
save(doc)
}
fn fixtures() -> Vec<(&'static str, Vec<u8>)> {
let v = valid();
let mut out: Vec<(&str, Vec<u8>)> = vec![
("empty file", Vec::new()),
("header only", b"%PDF-1.7\n".to_vec()),
("truncated at 10%", v[..v.len() / 10].to_vec()),
("truncated at 50%", v[..v.len() / 2].to_vec()),
("truncated before the trailer", v[..v.len() - 40].to_vec()),
("random bytes after a header", {
let mut x = b"%PDF-1.7\n".to_vec();
let mut s = 0x2545_4446u32;
for _ in 0..20_000 {
s ^= s << 13;
s ^= s >> 17;
s ^= s << 5;
x.push(s as u8);
}
x
}),
];
// Broken xref: startxref points nowhere, then the table itself is garbage.
let sx = v.windows(9).rposition(|w| w == b"startxref").unwrap();
out.push(("startxref beyond the end", [&v[..sx], b"startxref\n99999999\n%%EOF\n"].concat()));
// lopdf writes a cross-reference stream: garble its binary table, or cut it off and leave a bare trailer.
let xr = v.windows(10).rposition(|w| w == b"/Type/XRef").unwrap();
let obj_kw = v[..xr].windows(4).rposition(|w| w == b"obj\n").unwrap();
let xr_obj = v[..obj_kw].iter().rposition(|&b| b == b'\n').map(|i| i + 1).unwrap_or(0);
let mut garbled = v.clone();
let data = xr + garbled[xr..].windows(7).position(|w| w == b"stream\n").unwrap() + 7;
let end = (data + 40).min(garbled.len());
for b in garbled[data..end].iter_mut() {
*b = b.wrapping_mul(31).wrapping_add(7);
}
out.push(("garbled xref table", garbled));
out.push(("no xref at all", [&v[..xr_obj], b"trailer\n<< /Root 5 0 R >>\n%%EOF\n"].concat()));
// Recursive references.
{
let mut doc = base_doc(b"");
let pages = doc.catalog().unwrap().get(b"Pages").unwrap().as_reference().unwrap();
doc.get_dictionary_mut(pages).unwrap().set("Kids", vec![Object::Reference(pages)]);
out.push(("page tree that contains itself", save(doc)));
}
{
let mut doc = base_doc(b"");
let page = *doc.get_pages().values().next().unwrap();
let pages = doc.catalog().unwrap().get(b"Pages").unwrap().as_reference().unwrap();
doc.get_dictionary_mut(pages).unwrap().set("Parent", Object::Reference(page));
out.push(("parent loop", save(doc)));
}
out.push(("object that is a reference to itself", replace(&valid(), b"/Contents 3 0 R", b"/Contents 99 0 R").into_iter().chain(b"\n99 0 obj\n99 0 R\nendobj\n".iter().copied()).collect()));
out.push(("deeply nested arrays", {
let mut deep = vec![b'['; 200_000];
deep.extend(vec![b']'; 200_000]);
replace(&valid(), b"/Type/Catalog", &[b"/Type/Catalog /Deep ".as_slice(), &deep].concat())
}));
out.push(("page count of two billion", replace(&valid(), b"/Count 1", b"/Count 2147483647")));
out.push(("media box of 1e30 points", replace(&valid(), b"/MediaBox[0 0 595 842]", b"/MediaBox[0 0 1e30 1e30]")));
// A 1 GB declared stream, and a deflate bomb that expands to 1 GiB.
{
let doc = base_doc(b"BT /F1 24 Tf 72 700 Td (x) Tj ET");
let bytes = save(doc);
let i = bytes.windows(7).position(|w| w == b"/Length").unwrap();
let end = i + bytes[i..].iter().position(|&b| b == b'>').unwrap();
out.push(("stream that declares 1 GB", [&bytes[..i], b"/Length 1073741824", &bytes[end..]].concat()));
}
{
let mut z = ZlibEncoder::new(Vec::new(), Compression::best());
let zeros = vec![b' '; 1 << 20];
for _ in 0..1024 {
z.write_all(&zeros).unwrap();
}
let bomb = z.finish().unwrap();
let mut doc = base_doc(b"");
let page = *doc.get_pages().values().next().unwrap();
let c = doc.add_object(Stream::new(dictionary! {"Filter" => "FlateDecode"}, bomb).with_compression(false));
doc.get_dictionary_mut(page).unwrap().set("Contents", c);
out.push(("content stream that inflates to 1 GiB", save(doc)));
}
// Malformed fonts.
out.push(("TrueType font of garbage", font_doc("FontFile2", (0..4096u32).map(|i| (i * 7919 % 251) as u8).collect())));
out.push(("TrueType claiming 65535 tables", font_doc("FontFile2", [&[0, 1, 0, 0, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0][..], &[0x41; 64]].concat())));
out.push(("truncated Type 1 font", font_doc("FontFile", b"%!PS-AdobeFont-1.0: Broken\n/FontName /Broken def\neexec\x00\x01".to_vec())));
// Encryption with a handler that does not exist.
out.push(("unknown security handler", replace(&valid(), b"/Root 5 0 R", b"/Root 5 0 R /Encrypt << /Filter /Bogus /V 9 /R 9 >>")));
out
}
fn fetched() -> Vec<(String, Vec<u8>)> {
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/fetched");
let Ok(rd) = std::fs::read_dir(&dir) else { return Vec::new() };
let mut v: Vec<(String, Vec<u8>)> = rd
.filter_map(|e| e.ok())
.filter(|e| e.path().extension().is_some_and(|x| x.eq_ignore_ascii_case("pdf")))
.map(|e| (e.file_name().to_string_lossy().into_owned(), std::fs::read(e.path()).unwrap()))
.collect();
v.sort();
v
}
#[derive(Default, Debug)]
struct Tally {
ok: usize,
typed_error: usize,
timed_out: usize,
out_of_memory: usize,
crashed: usize,
}
fn run(w: &mut Worker, tally: &mut Tally, name: &str, op: &str, args: serde_json::Value) {
let start = Instant::now();
let r = w.call(op, args, CAP);
let took = start.elapsed();
assert!(took < CAP + Duration::from_secs(5), "{name}: {op} took {took:?}, past its cap");
let outcome = match &r {
Ok(_) => {
tally.ok += 1;
"ok".to_string()
}
Err(WorkerError::Op(e)) => {
assert!(!e.message.is_empty() && !e.message.contains("panicked"), "{name}: unclear message {e:?}");
tally.typed_error += 1;
format!("{} ({})", e.kind, e.message)
}
Err(WorkerError::TimedOut(_)) => {
tally.timed_out += 1;
"timed out".into()
}
Err(WorkerError::OutOfMemory) => {
tally.out_of_memory += 1;
"out of memory".into()
}
Err(WorkerError::Crashed(m)) => {
tally.crashed += 1;
format!("crashed: {m}")
}
Err(WorkerError::Spawn(e)) => panic!("worker would not start: {e}"),
};
println!("{name:40} {op:10} {took:>8.2?} {outcome}");
}
#[test]
fn hostile_pdfs_fail_cleanly_and_never_take_the_tray_down() {
let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap();
let mut w = worker();
let mut tally = Tally::default();
let mut all: Vec<(String, Vec<u8>)> = fixtures().into_iter().map(|(n, b)| (n.to_string(), b)).collect();
all.extend(fetched());
let annotation = json!({"annotations": [{"page": 0, "kind": "highlight", "rects": [{"x": 10, "y": 10, "w": 50, "h": 10}]}]});
for (i, (name, bytes)) in all.iter().enumerate() {
let path = dir.path().join(format!("f{i}.pdf"));
std::fs::write(&path, bytes).unwrap();
let p = path.to_string_lossy().to_string();
let start = Instant::now();
let opened = w.call("pdf.open", json!({"path": p}), CAP);
let took = start.elapsed();
let doc = match &opened {
Ok(v) => {
tally.ok += 1;
println!("{name:40} {:10} {took:>8.2?} ok, {} pages", "open", v["info"]["pages"].as_array().map(|a| a.len()).unwrap_or(0));
v["doc"].as_u64()
}
Err(e) => {
match e {
WorkerError::Op(_) => tally.typed_error += 1,
WorkerError::TimedOut(_) => tally.timed_out += 1,
WorkerError::OutOfMemory => tally.out_of_memory += 1,
WorkerError::Crashed(_) => tally.crashed += 1,
WorkerError::Spawn(e) => panic!("{e}"),
}
println!("{name:40} {:10} {took:>8.2?} {} ({e})", "open", e.kind());
None
}
};
if let Some(doc) = doc {
run(&mut w, &mut tally, name, "pdf.render", json!({"doc": doc, "page": 0, "width": 800}));
if w.take_restarted() {
continue;
}
run(&mut w, &mut tally, name, "pdf.text", json!({"doc": doc}));
if w.take_restarted() {
continue;
}
let out = dir.path().join(format!("f{i}-edited.pdf")).to_string_lossy().to_string();
run(&mut w, &mut tally, name, "pdf.save", json!({"doc": doc, "edits": annotation, "output": out, "mode": "new"}));
}
run(&mut w, &mut tally, name, "meta.read", json!({"path": p}));
w.take_restarted();
// The tray carries on: a normal request right after works.
let good = dir.path().join("good.pdf");
std::fs::write(&good, valid()).unwrap();
let r = w.call("pdf.open", json!({"path": good.to_string_lossy()}), CAP).expect("a good PDF after a bad one");
w.call("pdf.close", json!({"doc": r["doc"]}), CAP).unwrap();
}
println!("{} fixtures: {tally:?}", all.len());
assert!(all.len() >= 21);
assert_eq!(tally.timed_out, 0, "a fixture hung");
assert_eq!(tally.crashed, 0, "a worker died without a known cause");
}
#[test]
fn the_client_survives_crash_hang_and_memory_blowup() {
let mut w = worker();
let crash = w.call("debug.crash", json!({}), CAP);
assert!(matches!(crash, Err(WorkerError::Crashed(_))), "{crash:?}");
assert!(w.take_restarted());
let start = Instant::now();
let hang = w.call("debug.sleep", json!({"secs": 120}), Duration::from_secs(2));
assert!(matches!(hang, Err(WorkerError::TimedOut(_))), "{hang:?}");
assert!(start.elapsed() < Duration::from_secs(10));
let oom = w.call("debug.alloc", json!({"mb": 3000}), CAP);
// try_reserve fails cleanly under the cap (a typed error); a hard allocation would be OutOfMemory.
assert!(matches!(&oom, Err(WorkerError::OutOfMemory) | Err(WorkerError::Op(_))), "the 1 GB memory cap did not hold: {oom:?}");
// And it works again.
let ok = w.call("image.heif_support", json!({}), CAP).unwrap();
assert!(ok["support"].is_string());
}
#[test]
fn unknown_operations_and_bad_arguments_are_typed_errors() {
let mut w = worker();
for (op, args) in [("nope", json!({})), ("pdf.open", json!({"wrong": 1})), ("pdf.render", json!({"doc": 77, "page": 0, "width": 10}))] {
match w.call(op, args, CAP) {
Err(WorkerError::Op(e)) => assert!(["invalid", "not_open"].contains(&e.kind.as_str()), "{e:?}"),
other => panic!("{op}: {other:?}"),
}
}
let missing = w.call("pdf.open", json!({"path": "F:/definitely/not/here.pdf"}), CAP);
assert!(matches!(missing, Err(WorkerError::Op(ref e)) if e.kind == "io"), "{missing:?}");
}