[meta] Metadata: read and strip EXIF/GPS/XMP/IPTC (JPEG, PNG, WebP, GIF, TIFF) and PDF info/XMP

This commit is contained in:
2026-11-16 13:27:47 +01:00
parent 2c1611b34a
commit ede068f7c9
17 changed files with 2914 additions and 88 deletions
+283
View File
@@ -0,0 +1,283 @@
//! Fixtures built in code: nothing binary lives in git.
#![allow(dead_code)]
use std::io::Cursor;
use exif::experimental::Writer;
use exif::{Field, In, Rational, Tag, Value};
use image::{ImageEncoder, RgbImage, RgbaImage};
pub const AUTHOR: &str = "Jan Novak Fixtureauthor";
pub const MAKE: &str = "Apple";
pub const MODEL: &str = "iPhone 15";
pub const SOFTWARE: &str = "PhotoEditor 17.1 Fixture";
pub const COMMENT: &str = "Holiday at the secret cottage";
pub const XMP_NS: &str = "http://ns.adobe.com/xap";
pub fn rgb(w: u32, h: u32) -> RgbImage {
RgbImage::from_fn(w, h, |x, y| image::Rgb([(x * 13 + y * 7) as u8, (x * 31) as u8 ^ (y * 5) as u8, (y * 17) as u8]))
}
pub fn rgba(w: u32, h: u32) -> RgbaImage {
RgbaImage::from_fn(w, h, |x, y| image::Rgba([(x * 29) as u8, (y * 41) as u8, (x ^ y) as u8 * 9, 128 + (x as u8)]))
}
pub fn ascii(tag: Tag, s: &str) -> Field {
Field { tag, ifd_num: In::PRIMARY, value: Value::Ascii(vec![s.as_bytes().to_vec()]) }
}
pub fn rationals(tag: Tag, v: &[(u32, u32)]) -> Field {
Field {
tag,
ifd_num: In::PRIMARY,
value: Value::Rational(v.iter().map(|&(num, denom)| Rational { num, denom }).collect()),
}
}
pub fn short(tag: Tag, v: &[u16]) -> Field {
Field { tag, ifd_num: In::PRIMARY, value: Value::Short(v.to_vec()) }
}
/// GPS 50.08 N, 14.42 E; Apple iPhone 15; software; artist; date taken; Orientation 6.
pub fn photo_fields() -> Vec<Field> {
vec![
ascii(Tag::Make, MAKE),
ascii(Tag::Model, MODEL),
ascii(Tag::Software, SOFTWARE),
ascii(Tag::Artist, AUTHOR),
ascii(Tag::DateTimeOriginal, "2024:05:01 10:20:30"),
short(Tag::Orientation, &[6]),
ascii(Tag::GPSLatitudeRef, "N"),
rationals(Tag::GPSLatitude, &[(50, 1), (4, 1), (48, 1)]),
ascii(Tag::GPSLongitudeRef, "E"),
rationals(Tag::GPSLongitude, &[(14, 1), (25, 1), (12, 1)]),
]
}
/// A raw EXIF block (TIFF header onwards).
pub fn exif_tiff(fields: &[Field]) -> Vec<u8> {
let mut w = Writer::new();
for f in fields {
w.push_field(f);
}
let mut c = Cursor::new(Vec::new());
w.write(&mut c, false).expect("exif writer");
c.into_inner()
}
pub fn xmp_packet() -> String {
format!(
r#"<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:xmp="{XMP_NS}/1.0/"
xmp:CreatorTool="{SOFTWARE}">
<dc:creator><rdf:Seq><rdf:li>{AUTHOR}</rdf:li></rdf:Seq></dc:creator>
</rdf:Description></rdf:RDF></x:xmpmeta>
<?xpacket end="w"?>"#
)
}
/// Photoshop 3.0 + 8BIM 0x0404 with an IPTC by-line (2:80).
pub fn photoshop_iptc() -> Vec<u8> {
let mut iim = vec![0x1C, 2, 80];
iim.extend_from_slice(&(AUTHOR.len() as u16).to_be_bytes());
iim.extend_from_slice(AUTHOR.as_bytes());
let mut p = b"Photoshop 3.0\0".to_vec();
p.extend_from_slice(b"8BIM");
p.extend_from_slice(&0x0404u16.to_be_bytes());
p.extend_from_slice(&[0, 0]); // empty name, padded
p.extend_from_slice(&(iim.len() as u32).to_be_bytes());
p.extend_from_slice(&iim);
if iim.len() % 2 == 1 {
p.push(0);
}
p
}
pub fn segment(marker: u8, payload: &[u8]) -> Vec<u8> {
let mut s = vec![0xFF, marker];
s.extend_from_slice(&((payload.len() + 2) as u16).to_be_bytes());
s.extend_from_slice(payload);
s
}
pub fn plain_jpeg() -> Vec<u8> {
let img = rgb(24, 16);
let mut out = Vec::new();
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 90)
.write_image(img.as_raw(), 24, 16, image::ExtendedColorType::Rgb8)
.expect("jpeg encode");
out
}
/// A JPEG with the given extra segments inserted right after SOI.
pub fn jpeg_with(segments: &[Vec<u8>]) -> Vec<u8> {
let plain = plain_jpeg();
let mut out = plain[..2].to_vec();
for s in segments {
out.extend_from_slice(s);
}
out.extend_from_slice(&plain[2..]);
out
}
pub fn exif_app1(raw: &[u8]) -> Vec<u8> {
let mut p = b"Exif\0\0".to_vec();
p.extend_from_slice(raw);
segment(0xE1, &p)
}
pub fn xmp_app1() -> Vec<u8> {
let mut p = b"http://ns.adobe.com/xap/1.0/\0".to_vec();
p.extend_from_slice(xmp_packet().as_bytes());
segment(0xE1, &p)
}
/// The full test photo: EXIF (GPS, camera, author, software, date, Orientation 6), XMP, IPTC, a comment.
pub fn photo_jpeg() -> Vec<u8> {
jpeg_with(&[
exif_app1(&exif_tiff(&photo_fields())),
xmp_app1(),
segment(0xED, &photoshop_iptc()),
segment(0xFE, COMMENT.as_bytes()),
])
}
pub fn plain_png() -> Vec<u8> {
let img = rgba(9, 7);
let mut out = Vec::new();
image::codecs::png::PngEncoder::new(&mut out)
.write_image(img.as_raw(), 9, 7, image::ExtendedColorType::Rgba8)
.expect("png encode");
out
}
/// PNG with eXIf, iTXt XMP, tEXt Author and Software, tIME.
pub fn photo_png() -> Vec<u8> {
use img_parts::Bytes;
use img_parts::png::{Png, PngChunk};
let mut png = Png::from_bytes(Bytes::from(plain_png())).expect("png parse");
let mut itxt = b"XML:com.adobe.xmp\0\0\0\0\0".to_vec();
itxt.extend_from_slice(xmp_packet().as_bytes());
let mut author = b"Author\0".to_vec();
author.extend_from_slice(AUTHOR.as_bytes());
let mut software = b"Software\0".to_vec();
software.extend_from_slice(SOFTWARE.as_bytes());
let chunks = [
PngChunk::new(*b"eXIf", Bytes::from(exif_tiff(&photo_fields()))),
PngChunk::new(*b"iTXt", Bytes::from(itxt)),
PngChunk::new(*b"tEXt", Bytes::from(author)),
PngChunk::new(*b"tEXt", Bytes::from(software)),
PngChunk::new(*b"tIME", Bytes::from_static(&[0x07, 0xE8, 5, 1, 10, 20, 30])),
];
for (i, c) in chunks.into_iter().enumerate() {
png.chunks_mut().insert(1 + i, c);
}
png.encoder().bytes().to_vec()
}
pub fn plain_webp() -> Vec<u8> {
let img = rgba(10, 6);
let mut out = Vec::new();
image::codecs::webp::WebPEncoder::new_lossless(&mut out)
.write_image(img.as_raw(), 10, 6, image::ExtendedColorType::Rgba8)
.expect("webp encode");
out
}
/// VP8X WebP with EXIF and XMP chunks (built with img-parts, which also sets the VP8X flags).
pub fn photo_webp() -> Vec<u8> {
use img_parts::riff::{RiffChunk, RiffContent};
use img_parts::webp::{CHUNK_XMP, WebP};
use img_parts::{Bytes, ImageEXIF};
let mut webp = WebP::from_bytes(Bytes::from(plain_webp())).expect("webp parse");
webp.chunks_mut().push(RiffChunk::new(CHUNK_XMP, RiffContent::Data(Bytes::from(xmp_packet().into_bytes()))));
webp.set_exif(Some(Bytes::from(exif_tiff(&photo_fields()))));
webp.encoder().bytes().to_vec()
}
/// A 5x4 RGB TIFF written by the EXIF writer, with Make, Model, Software and Artist tags.
pub fn photo_tiff() -> (Vec<u8>, RgbImage) {
let (w, h) = (5u32, 4u32);
let img = rgb(w, h);
let fields = vec![
Field { tag: Tag::ImageWidth, ifd_num: In::PRIMARY, value: Value::Long(vec![w]) },
Field { tag: Tag::ImageLength, ifd_num: In::PRIMARY, value: Value::Long(vec![h]) },
short(Tag::BitsPerSample, &[8, 8, 8]),
short(Tag::Compression, &[1]),
short(Tag::PhotometricInterpretation, &[2]),
short(Tag::SamplesPerPixel, &[3]),
Field { tag: Tag::RowsPerStrip, ifd_num: In::PRIMARY, value: Value::Long(vec![h]) },
short(Tag::PlanarConfiguration, &[1]),
ascii(Tag::Make, MAKE),
ascii(Tag::Model, MODEL),
ascii(Tag::Software, SOFTWARE),
ascii(Tag::Artist, AUTHOR),
];
let strip: &[u8] = img.as_raw();
let strips = [strip];
let mut wr = Writer::new();
for f in &fields {
wr.push_field(f);
}
wr.set_strips(&strips, In::PRIMARY);
let mut c = Cursor::new(Vec::new());
wr.write(&mut c, false).expect("tiff writer");
(c.into_inner(), img)
}
/// A two-frame looping GIF with a comment extension and an XMP application extension.
pub fn photo_gif() -> Vec<u8> {
use image::codecs::gif::{GifEncoder, Repeat};
use image::{Delay, Frame};
let mut out = Vec::new();
{
let mut enc = GifEncoder::new(&mut out);
enc.set_repeat(Repeat::Infinite).expect("repeat");
let a = RgbaImage::from_fn(6, 5, |x, y| {
if (x + y) % 2 == 0 { image::Rgba([255, 0, 0, 255]) } else { image::Rgba([0, 0, 255, 255]) }
});
let b = RgbaImage::from_fn(6, 5, |x, _| {
if x < 3 { image::Rgba([0, 255, 0, 255]) } else { image::Rgba([255, 255, 255, 255]) }
});
let d = Delay::from_numer_denom_ms(100, 1);
enc.encode_frames(vec![Frame::from_parts(a, 0, 0, d), Frame::from_parts(b, 0, 0, d)]).expect("gif encode");
}
assert_eq!(out.last(), Some(&0x3B));
out.pop();
// Comment extension.
out.extend_from_slice(&[0x21, 0xFE, COMMENT.len() as u8]);
out.extend_from_slice(COMMENT.as_bytes());
out.push(0);
// XMP application extension: raw packet plus the 258-byte magic trailer.
out.extend_from_slice(&[0x21, 0xFF, 11]);
out.extend_from_slice(b"XMP DataXMP");
out.extend_from_slice(xmp_packet().as_bytes());
out.push(1);
out.extend((0..=255u8).rev());
out.push(0);
out.push(0x3B);
out
}
pub fn contains(hay: &[u8], needle: &[u8]) -> bool {
hay.windows(needle.len()).any(|w| w == needle)
}
/// A deterministic xorshift generator.
pub struct XorShift(pub u64);
impl XorShift {
pub fn next(&mut self) -> u64 {
let mut x = self.0;
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
self.0 = x;
x
}
pub fn below(&mut self, n: usize) -> usize {
if n == 0 { 0 } else { (self.next() % n as u64) as usize }
}
}
+196
View File
@@ -0,0 +1,196 @@
mod common;
use common::*;
use pictor_meta::{Group, MetaError, read, strip};
fn malformed_exif_blocks() -> Vec<(&'static str, Vec<u8>)> {
let mut truncated_ifd = b"MM\0*\0\0\0\x08\0\x05".to_vec();
truncated_ifd.extend_from_slice(&[0x01, 0x12, 0x00, 0x03, 0x00, 0x00]); // half an entry
let offset_beyond = b"MM\0*\xFF\xFF\xFF\x00".to_vec();
let mut huge_count = b"II*\0\x08\0\0\0\xFF\xFF".to_vec();
huge_count.extend_from_slice(&[0x0F, 0x01, 0x02, 0x00, 0xFF, 0xFF, 0xFF, 0x7F, 0x10, 0x00, 0x00, 0x00]);
let mut value_beyond = b"MM\0*\0\0\0\x08\0\x01".to_vec();
value_beyond.extend_from_slice(&[0x01, 0x0F, 0x00, 0x02, 0x7F, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x10, 0x00]);
value_beyond.extend_from_slice(&[0, 0, 0, 0]);
vec![
("truncated IFD", truncated_ifd),
("IFD offset beyond the segment", offset_beyond),
("huge entry count", huge_count),
("value offset beyond the segment", value_beyond),
("not TIFF at all", b"garbage!".to_vec()),
("empty", Vec::new()),
]
}
#[test]
fn malformed_exif_is_reported_and_still_removed() {
let plain = image::load_from_memory(&plain_jpeg()).unwrap().to_rgb8();
for (what, block) in malformed_exif_blocks() {
let jpeg = jpeg_with(&[exif_app1(&block), segment(0xFE, COMMENT.as_bytes())]);
match read(&jpeg) {
Ok(r) => {
assert!(r.find(Group::Exif, "EXIF block").is_some(), "{what}");
assert!(!r.warnings.is_empty() || r.items.len() <= 3, "{what}: {:?}", r);
}
Err(e) => assert!(matches!(e, MetaError::Damaged(_)), "{what}: {e:?}"),
}
let s = strip(&jpeg).unwrap_or_else(|e| panic!("{what}: {e}"));
assert!(!contains(&s.bytes, b"Exif\0"), "{what}: EXIF block removed, no orientation kept");
assert!(!contains(&s.bytes, COMMENT.as_bytes()), "{what}");
assert!(s.removed.contains(&Group::Exif), "{what}");
assert_eq!(image::load_from_memory(&s.bytes).unwrap().to_rgb8(), plain, "{what}");
}
}
#[test]
fn truncated_jpeg_never_panics() {
let jpeg = photo_jpeg();
for cut in [3, 4, 5, 20, 100, 300, jpeg.len() / 2, jpeg.len() - 40, jpeg.len() - 2, jpeg.len() - 1] {
let b = &jpeg[..cut];
let _ = read(b);
match strip(b) {
Ok(s) => {
assert!(!contains(&s.bytes, AUTHOR.as_bytes()), "cut {cut}");
assert!(!contains(&s.bytes, b"Exif\0\0MM\0*\0\0\0\x08\0\x0b"), "cut {cut}");
}
Err(e) => assert!(matches!(e, MetaError::Damaged(_)), "cut {cut}: {e:?}"),
}
}
}
#[test]
fn truncated_png_never_panics() {
let png = photo_png();
for cut in [8, 9, 12, 20, 33, 60, png.len() / 2, png.len() - 4, png.len() - 1] {
let b = &png[..cut];
if let Ok(r) = read(b) {
assert!(!r.warnings.is_empty(), "cut {cut}: a truncated PNG gives a warning");
}
assert!(matches!(strip(b), Err(MetaError::Damaged(_))), "cut {cut}");
}
}
#[test]
fn png_chunk_with_impossible_length() {
let mut b = png::SIGNATURE.to_vec();
b.extend_from_slice(&[0xFF, 0xFF, 0xFF, 0xF0]);
b.extend_from_slice(b"tEXt");
b.extend_from_slice(&[0x41; 32]);
assert!(read(&b).is_err());
assert!(matches!(strip(&b), Err(MetaError::Damaged(_))));
// The same after a valid IHDR.
let mut good = plain_png();
good.truncate(33);
good.extend_from_slice(&b[8..]);
let r = read(&good).unwrap();
assert!(!r.warnings.is_empty());
assert!(matches!(strip(&good), Err(MetaError::Damaged(_))));
}
#[test]
fn hostile_container_lengths() {
// WebP: RIFF size and chunk size far beyond the data.
let mut webp = b"RIFF\xF0\xFF\xFF\xFFWEBPVP8X\xFF\xFF\xFF\x7F".to_vec();
webp.extend_from_slice(&[0; 10]);
let _ = read(&webp);
assert!(strip(&webp).is_err());
// GIF: a colour table flag with no table, then nothing.
assert!(strip(b"GIF89a\x01\0\x01\0\xF7\0\0").is_err());
let _ = read(b"GIF89a\x01\0\x01\0\xF7\0\0");
// GIF: an extension that never ends.
assert!(strip(b"GIF89a\x01\0\x01\0\0\0\0\x21\xFE\xFF\x41\x41").is_err());
// TIFF: IFD offset beyond the file, huge count.
for t in [&b"II*\0\xFF\xFF\xFF\xFF"[..], b"MM\0*\0\0\0\x08\xFF\xFF\0\0", b"II*\0\x08\0\0\0"] {
let _ = read(t);
assert!(strip(t).is_err());
}
// JPEG: a segment length below 2, a length past the end, garbage between segments.
for j in [&b"\xFF\xD8\xFF\xE1\x00\x01"[..], b"\xFF\xD8\xFF\xE1\xFF\xFFExif", b"\xFF\xD8\xFF\xE0\x00\x04ab\x13\x37"]
{
let _ = read(j);
assert!(matches!(strip(j), Err(MetaError::Damaged(_))));
}
}
#[test]
fn empty_and_random_bytes() {
assert_eq!(read(&[]), Err(MetaError::Empty));
assert_eq!(strip(&[]), Err(MetaError::Empty));
let mut rng = XorShift(0x9E37_79B9_7F4A_7C15);
let prefixes: [&[u8]; 7] =
[b"", b"\xFF\xD8\xFF", &png::SIGNATURE, b"RIFF\x40\0\0\0WEBP", b"II*\0", b"GIF89a", b"%PDF-1.7\n"];
for prefix in prefixes {
for len in [1usize, 7, 64, 4096] {
let mut b = prefix.to_vec();
b.extend((0..len).map(|_| rng.next() as u8));
let _ = read(&b);
let _ = strip(&b);
}
}
}
/// Mutates every fixture a few hundred times (deterministically) and runs read and strip on each.
#[test]
fn mutation_fuzz_never_panics() {
let (tiff, _) = photo_tiff();
let fixtures: Vec<(&str, Vec<u8>)> = vec![
("jpeg", photo_jpeg()),
("png", photo_png()),
("webp", photo_webp()),
("tiff", tiff),
("gif", photo_gif()),
("pdf", pdf_fixture()),
];
let mut rng = XorShift(0x2545_F491_4F6C_DD1D);
for (name, original) in &fixtures {
for round in 0..300 {
let mut b = original.clone();
for _ in 0..1 + rng.below(8) {
let at = rng.below(b.len());
match rng.below(4) {
0 => b[at] = 0xFF,
1 => b[at] = 0x00,
_ => b[at] = rng.next() as u8,
}
}
if rng.below(5) == 0 {
let keep = rng.below(b.len()).max(1);
b.truncate(keep);
}
if rng.below(8) == 0 && b.len() > 16 {
let at = rng.below(b.len() - 4);
b[at..at + 4].copy_from_slice(&[0xFF, 0xFF, 0xFF, 0xF0]);
}
let _ = read(&b);
if let Ok(s) = strip(&b) {
assert!(!s.bytes.is_empty(), "{name} round {round}");
}
}
}
}
/// A small PDF with /Info, built with lopdf.
fn pdf_fixture() -> Vec<u8> {
use lopdf::{Document, Object, Stream, dictionary};
let mut doc = Document::with_version("1.5");
let pages_id = doc.new_object_id();
let xmp = doc.add_object(Stream::new(dictionary! { "Type" => "Metadata" }, xmp_packet().into_bytes()));
let content = doc.add_object(Stream::new(dictionary! {}, b"0 0 m 10 10 l S".to_vec()));
let page = doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages_id, "Contents" => content });
doc.objects.insert(
pages_id,
Object::Dictionary(dictionary! { "Type" => "Pages", "Kids" => vec![page.into()], "Count" => 1 }),
);
let catalog = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id, "Metadata" => xmp });
let info = doc.add_object(dictionary! { "Author" => Object::string_literal(AUTHOR) });
doc.trailer.set("Root", catalog);
doc.trailer.set("Info", info);
let mut out = Vec::new();
doc.save_to(&mut out).unwrap();
out
}
mod png {
pub const SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
}
+219
View File
@@ -0,0 +1,219 @@
mod common;
use std::io::Cursor;
use common::*;
use pictor_meta::{Group, Kind, MetaError, read, strip};
fn values(r: &pictor_meta::Report, g: Group) -> Vec<String> {
r.items.iter().filter(|i| i.group == g).map(|i| i.value.clone()).collect()
}
/// What an exiftool-style reader still sees: all EXIF fields in the file, through kamadak-exif.
fn exif_fields(bytes: &[u8]) -> Vec<(exif::Tag, String)> {
match exif::Reader::new().read_from_container(&mut Cursor::new(bytes)) {
Ok(e) => e.fields().map(|f| (f.tag, f.display_value().to_string())).collect(),
Err(_) => Vec::new(),
}
}
fn assert_no_leaks(bytes: &[u8]) {
for needle in [XMP_NS, "Photoshop 3.0", AUTHOR, MODEL, SOFTWARE, COMMENT, "2024:05:01"] {
assert!(!contains(bytes, needle.as_bytes()), "stripped file still contains {needle:?}");
}
}
#[test]
fn jpeg_read_lists_gps_camera_author_software() {
let r = read(&photo_jpeg()).unwrap();
assert_eq!(r.kind, Kind::Jpeg);
assert_eq!(r.find(Group::Gps, "Location").unwrap().value, "50.08 N, 14.42 E");
assert_eq!(r.find(Group::Camera, "Camera").unwrap().value, "Apple iPhone 15");
assert!(values(&r, Group::Author).contains(&AUTHOR.to_string()));
assert!(values(&r, Group::Software).contains(&SOFTWARE.to_string()));
assert!(values(&r, Group::Iptc).contains(&AUTHOR.to_string()), "IPTC by-line: {:?}", r.items);
assert!(values(&r, Group::Xmp).contains(&AUTHOR.to_string()), "XMP dc:creator: {:?}", r.items);
assert!(values(&r, Group::Comment).contains(&COMMENT.to_string()));
assert!(r.find(Group::Exif, "Orientation").is_some());
assert!(!values(&r, Group::Dates).is_empty());
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
}
#[test]
fn jpeg_strip_keeps_only_orientation_and_pixels() {
let original = photo_jpeg();
let s = strip(&original).unwrap();
for g in [
Group::Gps,
Group::Camera,
Group::Author,
Group::Software,
Group::Dates,
Group::Xmp,
Group::Iptc,
Group::Comment,
] {
assert!(s.removed.contains(&g), "{g:?} not in removed {:?}", s.removed);
}
let fields = exif_fields(&s.bytes);
assert_eq!(fields.len(), 1, "only Orientation may remain: {fields:?}");
assert_eq!(fields[0].0, exif::Tag::Orientation);
let exif = exif::Reader::new().read_from_container(&mut Cursor::new(&s.bytes)).unwrap();
let o = exif.get_field(exif::Tag::Orientation, exif::In::PRIMARY).unwrap();
assert_eq!(o.value.get_uint(0), Some(6));
assert_no_leaks(&s.bytes);
assert!(!contains(&s.bytes, MAKE.as_bytes()));
let before = image::load_from_memory(&original).unwrap().to_rgb8();
let after = image::load_from_memory(&s.bytes).unwrap().to_rgb8();
assert_eq!(before, after);
// The stripped file reads clean, and stripping again changes nothing.
let r = read(&s.bytes).unwrap();
assert_eq!(r.groups(), vec![Group::Exif], "{:?}", r.items);
assert_eq!(strip(&s.bytes).unwrap().bytes, s.bytes);
}
#[test]
fn jpeg_without_orientation_gets_no_exif() {
let mut fields = photo_fields();
fields.retain(|f| f.tag != exif::Tag::Orientation);
let original = jpeg_with(&[exif_app1(&exif_tiff(&fields))]);
let s = strip(&original).unwrap();
assert!(!contains(&s.bytes, b"Exif\0"));
assert_eq!(s.bytes, plain_jpeg(), "an untouched JPEG body is byte-identical");
}
#[test]
fn jpeg_keeps_icc_and_adobe_drops_other_app_segments() {
let mut icc = b"ICC_PROFILE\0\x01\x01".to_vec();
icc.extend_from_slice(&[7u8; 40]);
let adobe = b"Adobe\0\x64\0\0\0\0\x01".to_vec();
let original = jpeg_with(&[
segment(0xE2, &icc),
segment(0xEE, &adobe),
segment(0xEC, b"Ducky\0\x01\x02"),
segment(0xE2, b"MPF\0II*\0"),
segment(0xEF, b"secret"),
]);
let r = read(&original).unwrap();
assert!(r.items.iter().any(|i| i.name.contains("Ducky")));
let s = strip(&original).unwrap();
assert!(contains(&s.bytes, &icc));
assert!(contains(&s.bytes, &adobe));
assert!(!contains(&s.bytes, b"Ducky") && !contains(&s.bytes, b"MPF\0") && !contains(&s.bytes, b"secret"));
assert_eq!(s.removed, vec![Group::Other]);
}
#[test]
fn jpeg_drops_data_after_end_of_image() {
let mut original = photo_jpeg();
original.extend_from_slice(b"\xFF\xD8 hidden second image with GPS");
let r = read(&original).unwrap();
assert!(r.find(Group::Other, "Data after the end of the image").is_some());
let s = strip(&original).unwrap();
assert!(s.bytes.ends_with(&[0xFF, 0xD9]));
assert!(!contains(&s.bytes, b"hidden"));
}
#[test]
fn png_strip_drops_text_exif_xmp_and_keeps_pixels() {
let original = photo_png();
let r = read(&original).unwrap();
assert_eq!(r.kind, Kind::Png);
assert_eq!(r.find(Group::Gps, "Location").unwrap().value, "50.08 N, 14.42 E");
assert_eq!(r.find(Group::Author, "Author").unwrap().value, AUTHOR);
assert_eq!(r.find(Group::Software, "Software").unwrap().value, SOFTWARE);
assert!(values(&r, Group::Xmp).contains(&AUTHOR.to_string()));
assert_eq!(r.find(Group::Dates, "Last modified").unwrap().value, "2024-05-01 10:20:30");
let s = strip(&original).unwrap();
assert_no_leaks(&s.bytes);
for chunk in [b"eXIf", b"tEXt", b"iTXt", b"tIME"] {
assert!(!contains(&s.bytes, chunk));
}
assert!(exif_fields(&s.bytes).is_empty());
assert!(read(&s.bytes).unwrap().items.is_empty());
assert_eq!(s.bytes, plain_png(), "the remaining chunks are copied byte for byte");
let before = image::load_from_memory(&original).unwrap().to_rgba8();
let after = image::load_from_memory(&s.bytes).unwrap().to_rgba8();
assert_eq!(before, after);
for g in [Group::Gps, Group::Camera, Group::Author, Group::Software, Group::Xmp, Group::Dates] {
assert!(s.removed.contains(&g), "{g:?}");
}
}
#[test]
fn webp_strip_drops_exif_xmp_and_fixes_flags() {
let original = photo_webp();
assert!(contains(&original, b"VP8X") && contains(&original, b"EXIF") && contains(&original, b"XMP "));
let r = read(&original).unwrap();
assert_eq!(r.kind, Kind::WebP);
assert_eq!(r.find(Group::Camera, "Camera").unwrap().value, "Apple iPhone 15");
assert!(values(&r, Group::Xmp).contains(&AUTHOR.to_string()));
let s = strip(&original).unwrap();
assert_no_leaks(&s.bytes);
assert!(!contains(&s.bytes, b"EXIF") && !contains(&s.bytes, b"XMP "));
let vp8x = s.bytes.windows(4).position(|w| w == b"VP8X").expect("VP8X kept");
let flags = s.bytes[vp8x + 8];
assert_eq!(flags & 0x0C, 0, "EXIF and XMP flags cleared");
let riff = u32::from_le_bytes(s.bytes[4..8].try_into().unwrap()) as usize;
assert_eq!(riff + 8, s.bytes.len());
let before = image::load_from_memory(&original).unwrap().to_rgba8();
let after = image::load_from_memory(&s.bytes).unwrap().to_rgba8();
assert_eq!(before, after);
assert_eq!(before, rgba(10, 6), "lossless fixture");
}
#[test]
fn tiff_strip_removes_tags_and_keeps_pixels() {
let (original, img) = photo_tiff();
let r = read(&original).unwrap();
assert_eq!(r.kind, Kind::Tiff);
assert_eq!(r.find(Group::Camera, "Camera").unwrap().value, "Apple iPhone 15");
assert!(values(&r, Group::Author).contains(&AUTHOR.to_string()));
assert!(values(&r, Group::Software).contains(&SOFTWARE.to_string()));
assert_eq!(image::load_from_memory(&original).unwrap().to_rgb8(), img);
let s = strip(&original).unwrap();
assert_no_leaks(&s.bytes);
assert!(!contains(&s.bytes, MAKE.as_bytes()));
assert_eq!(image::load_from_memory(&s.bytes).unwrap().to_rgb8(), img);
assert!(read(&s.bytes).unwrap().items.is_empty(), "{:?}", read(&s.bytes).unwrap().items);
for g in [Group::Camera, Group::Author, Group::Software] {
assert!(s.removed.contains(&g));
}
}
#[test]
fn gif_strip_keeps_every_frame() {
use image::AnimationDecoder;
use image::codecs::gif::GifDecoder;
let original = photo_gif();
let r = read(&original).unwrap();
assert_eq!(r.kind, Kind::Gif);
assert!(values(&r, Group::Comment).contains(&COMMENT.to_string()));
assert!(values(&r, Group::Xmp).contains(&AUTHOR.to_string()), "{:?}", r.items);
let s = strip(&original).unwrap();
assert_no_leaks(&s.bytes);
assert!(contains(&s.bytes, b"NETSCAPE2.0"), "looping kept");
let frames = |b: &[u8]| -> Vec<image::RgbaImage> {
let d = GifDecoder::new(Cursor::new(b.to_vec())).unwrap();
d.into_frames().collect_frames().unwrap().into_iter().map(|f| f.into_buffer()).collect()
};
let (a, b) = (frames(&original), frames(&s.bytes));
assert_eq!(a.len(), 2);
assert_eq!(a, b);
assert_eq!(s.removed, vec![Group::Xmp, Group::Comment]);
}
#[test]
fn unknown_and_empty_inputs_are_typed_errors() {
assert_eq!(read(&[]), Err(MetaError::Empty));
assert!(matches!(read(b"BM\0\0 not supported"), Err(MetaError::Unsupported(_))));
assert!(matches!(strip(b"hello world"), Err(MetaError::Unsupported(_))));
let small = pictor_meta::Limits { max_input_bytes: 10, ..Default::default() };
assert!(matches!(pictor_meta::read_with(&photo_jpeg(), &small), Err(MetaError::TooLarge { .. })));
}
+180
View File
@@ -0,0 +1,180 @@
mod common;
use common::*;
use lopdf::{Document, Object, Stream, StringFormat, dictionary};
use pictor_meta::{Group, Kind, MetaError, read, strip};
const PDF_AUTHOR: &str = "Jan Novák";
fn utf16be(s: &str) -> Vec<u8> {
let mut v = vec![0xFE, 0xFF];
s.encode_utf16().for_each(|u| v.extend_from_slice(&u.to_be_bytes()));
v
}
fn xmp_for_pdf() -> String {
xmp_packet().replace(AUTHOR, PDF_AUTHOR)
}
/// One page drawing one image XObject; /Info with a UTF-16BE author; XMP on the catalog and on the image;
/// /PieceInfo on the page.
fn build(modern: bool) -> Vec<u8> {
let mut doc = Document::with_version("1.5");
let pages_id = doc.new_object_id();
let meta = || dictionary! { "Type" => "Metadata", "Subtype" => "XML" };
let xmp_doc = doc.add_object(Stream::new(meta(), xmp_for_pdf().into_bytes()).with_compression(false));
let xmp_img = doc.add_object(Stream::new(meta(), xmp_for_pdf().into_bytes()).with_compression(false));
let img = doc.add_object(Stream::new(
dictionary! {
"Type" => "XObject", "Subtype" => "Image", "Width" => 2, "Height" => 2,
"ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8, "Metadata" => xmp_img,
},
vec![255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255],
));
let content = doc.add_object(Stream::new(dictionary! {}, b"q 100 0 0 100 50 50 cm /Im1 Do Q".to_vec()));
let page = doc.add_object(dictionary! {
"Type" => "Page", "Parent" => pages_id, "Contents" => content,
"Resources" => dictionary! { "XObject" => dictionary! { "Im1" => img } },
"MediaBox" => vec![0.into(), 0.into(), 200.into(), 200.into()],
"PieceInfo" => dictionary! { "Illustrator" => dictionary! { "Private" => Object::string_literal("secret private") } },
});
doc.objects.insert(
pages_id,
Object::Dictionary(dictionary! { "Type" => "Pages", "Kids" => vec![page.into()], "Count" => 1 }),
);
let catalog = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id, "Metadata" => xmp_doc });
let info = doc.add_object(dictionary! {
"Author" => Object::String(utf16be(PDF_AUTHOR), StringFormat::Hexadecimal),
"Producer" => Object::string_literal("Fixture Producer 1.0"),
"Creator" => Object::string_literal(SOFTWARE),
"Title" => Object::string_literal("Secret plans"),
"CreationDate" => Object::string_literal("D:20240501102030+02'00'"),
"Department" => Object::string_literal("Custom department"),
});
doc.trailer.set("Root", catalog);
doc.trailer.set("Info", info);
let mut out = Vec::new();
if modern {
doc.save_modern(&mut out).unwrap()
} else {
doc.save_to(&mut out).unwrap()
}
out
}
fn any_metadata_key(o: &Object) -> bool {
match o {
Object::Dictionary(d) => {
d.has(b"Metadata") || d.has(b"PieceInfo") || d.iter().any(|(_, v)| any_metadata_key(v))
}
Object::Stream(s) => {
s.dict.has(b"Metadata") || s.dict.has_type(b"Metadata") || s.dict.iter().any(|(_, v)| any_metadata_key(v))
}
Object::Array(a) => a.iter().any(any_metadata_key),
_ => false,
}
}
fn first_page_content(bytes: &[u8]) -> Vec<u8> {
let doc = Document::load_mem(bytes).unwrap();
let page = *doc.get_pages().values().next().unwrap();
doc.get_page_content(page)
}
fn assert_clean(bytes: &[u8]) {
let doc = Document::load_mem(bytes).unwrap();
assert!(!doc.trailer.has(b"Info"), "trailer /Info removed");
for (id, o) in &doc.objects {
assert!(!any_metadata_key(o), "object {id:?} still has metadata: {o:?}");
}
let lower = String::from_utf8_lossy(bytes).to_lowercase();
for needle in [
"Novák",
"Fixture Producer",
"Secret plans",
"Custom department",
"secret private",
XMP_NS,
"adobe:ns:meta",
SOFTWARE,
] {
assert!(!contains(bytes, needle.as_bytes()), "raw bytes still contain {needle:?}");
}
assert!(!contains(bytes, &utf16be("Jan")[2..]), "UTF-16 author");
assert!(!lower.contains("feff004a"), "hex UTF-16 author");
}
#[test]
fn pdf_read_lists_info_and_xmp() {
let original = build(false);
assert!(contains(&original, XMP_NS.as_bytes()), "fixture has XMP");
let r = read(&original).unwrap();
assert_eq!(r.kind, Kind::Pdf);
assert_eq!(r.find(Group::Author, "Author").unwrap().value, PDF_AUTHOR);
assert_eq!(r.find(Group::Software, "Producer").unwrap().value, "Fixture Producer 1.0");
assert_eq!(r.find(Group::Software, "Creator").unwrap().value, SOFTWARE);
assert_eq!(r.find(Group::PdfInfo, "Title").unwrap().value, "Secret plans");
assert_eq!(r.find(Group::PdfInfo, "Department").unwrap().value, "Custom department");
assert_eq!(r.find(Group::Dates, "CreationDate").unwrap().value, "2024-05-01 10:20:30 +02:00");
assert_eq!(r.find(Group::PdfXmp, "Creator (dc:creator)").unwrap().value, PDF_AUTHOR);
assert_eq!(r.find(Group::PdfXmp, "Creator tool (xmp:CreatorTool)").unwrap().value, SOFTWARE);
assert_eq!(r.find(Group::PdfXmp, "XMP on pages, images or other objects").unwrap().value, "1 objects");
assert!(r.find(Group::Other, "Private application data (PieceInfo)").is_some());
}
#[test]
fn pdf_strip_removes_info_and_every_xmp_stream() {
let original = build(false);
let s = strip(&original).unwrap();
assert_clean(&s.bytes);
assert_eq!(first_page_content(&original), first_page_content(&s.bytes));
let doc = Document::load_mem(&s.bytes).unwrap();
let images =
doc.objects.values().filter(|o| matches!(o, Object::Stream(st) if st.dict.has_type(b"XObject"))).count();
assert_eq!(images, 1, "the image is kept");
assert!(read(&s.bytes).unwrap().items.is_empty());
for g in [Group::Author, Group::Software, Group::Dates, Group::PdfInfo, Group::PdfXmp, Group::Other] {
assert!(s.removed.contains(&g), "{g:?}");
}
}
#[test]
fn pdf_with_object_streams_is_stripped_too() {
let original = build(true);
let r = read(&original).unwrap();
assert_eq!(r.find(Group::Author, "Author").unwrap().value, PDF_AUTHOR);
let s = strip(&original).unwrap();
assert_clean(&s.bytes);
assert_eq!(first_page_content(&original), first_page_content(&s.bytes));
}
#[test]
fn encrypted_pdf_is_refused() {
let mut doc = Document::load_mem(&build(false)).unwrap();
let enc = doc.add_object(dictionary! {
"Filter" => "Standard", "V" => 1, "R" => 2, "Length" => 40, "P" => -4,
"O" => Object::String(vec![0x11; 32], StringFormat::Hexadecimal),
"U" => Object::String(vec![0x22; 32], StringFormat::Hexadecimal),
});
doc.trailer.set("Encrypt", enc);
doc.trailer.set(
"ID",
vec![
Object::String(vec![1; 16], StringFormat::Hexadecimal),
Object::String(vec![1; 16], StringFormat::Hexadecimal),
],
);
let mut bytes = Vec::new();
doc.save_to(&mut bytes).unwrap();
assert_eq!(read(&bytes), Err(MetaError::Encrypted));
assert_eq!(strip(&bytes), Err(MetaError::Encrypted));
assert_eq!(MetaError::Encrypted.to_string(), "This PDF is password-protected. Unlock it first.");
}
#[test]
fn unparseable_pdf_is_a_typed_error() {
for bytes in [&b"%PDF-1.7\n1 0 obj << /Type /Catalog"[..], b"%PDF-", b"%PDF-1.4\n%%EOF\n"] {
assert!(matches!(read(bytes), Err(MetaError::Damaged(_))), "{:?}", read(bytes));
assert!(matches!(strip(bytes), Err(MetaError::Damaged(_))));
}
}