photoforge 0.1.0

Rights-aware Wikimedia Commons image discovery and verified photo archival
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
use std::fs::{self, File};
use std::io::{self, BufReader, Read};
use std::path::Path;

use ::image::{GenericImageView, ImageFormat, ImageReader, Limits};
use crc32fast::Hasher as Crc32;

use crate::{MAX_RETAINED_IMAGE_BYTES, PhotoForgeError, Result};

const PNG_SIGNATURE: &[u8; 8] = b"\x89PNG\r\n\x1a\n";
const MAX_DECODE_DIMENSION: u32 = 32_768;
const MAX_DECODE_PIXELS: u64 = 100_000_000;
const MAX_DECODE_ALLOCATION: u64 = 512 * 1024 * 1024;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PhotoFormat {
    Jpeg,
    Png,
}

impl PhotoFormat {
    pub(crate) fn from_mime(mime: &str) -> Result<Self> {
        match mime {
            "image/jpeg" => Ok(Self::Jpeg),
            "image/png" => Ok(Self::Png),
            _ => Err(PhotoForgeError::VerificationFailed {
                path: mime.to_string(),
                message: "unsupported photo MIME type in PhotoForge 0.1".to_string(),
            }),
        }
    }

    pub(crate) const fn extension(self) -> &'static str {
        match self {
            Self::Jpeg => "jpg",
            Self::Png => "png",
        }
    }

    pub(crate) fn relative_name(self) -> String {
        format!("photo.{}", self.extension())
    }
}

pub(crate) fn validate_image_file(
    path: &Path,
    mime: &str,
    expected_width: u32,
    expected_height: u32,
) -> Result<()> {
    let metadata = fs::symlink_metadata(path)?;
    if metadata.file_type().is_symlink() || !metadata.is_file() {
        return verification(path, "image is not a regular non-symlink file");
    }
    if metadata.len() == 0 {
        return verification(path, "image is empty");
    }
    if metadata.len() > MAX_RETAINED_IMAGE_BYTES {
        return verification(path, "image exceeds the hard retained-image limit");
    }
    if expected_width == 0
        || expected_height == 0
        || expected_width > MAX_DECODE_DIMENSION
        || expected_height > MAX_DECODE_DIMENSION
        || u64::from(expected_width)
            .checked_mul(u64::from(expected_height))
            .is_none_or(|pixels| pixels > MAX_DECODE_PIXELS)
    {
        return verification(path, "expected image dimensions exceed decode limits");
    }
    let format = PhotoFormat::from_mime(mime)?;
    match format {
        PhotoFormat::Jpeg => validate_jpeg(path, expected_width, expected_height),
        PhotoFormat::Png => validate_png(path, expected_width, expected_height),
    }?;
    fully_decode_image(path, format, expected_width, expected_height)
}

fn fully_decode_image(
    path: &Path,
    format: PhotoFormat,
    expected_width: u32,
    expected_height: u32,
) -> Result<()> {
    let expected_format = match format {
        PhotoFormat::Jpeg => ImageFormat::Jpeg,
        PhotoFormat::Png => ImageFormat::Png,
    };
    let mut reader = ImageReader::new(BufReader::new(File::open(path)?))
        .with_guessed_format()
        .map_err(|error| PhotoForgeError::VerificationFailed {
            path: path.display().to_string(),
            message: format!("image format detection failed: {error}"),
        })?;
    if reader.format() != Some(expected_format) {
        return verification(path, "decoder format does not match the declared MIME type");
    }
    let mut limits = Limits::default();
    limits.max_image_width = Some(MAX_DECODE_DIMENSION);
    limits.max_image_height = Some(MAX_DECODE_DIMENSION);
    limits.max_alloc = Some(MAX_DECODE_ALLOCATION);
    reader.limits(limits);
    let decoded = reader
        .decode()
        .map_err(|error| PhotoForgeError::VerificationFailed {
            path: path.display().to_string(),
            message: format!("full bounded image decode failed: {error}"),
        })?;
    let (width, height) = decoded.dimensions();
    if width != expected_width || height != expected_height {
        return verification(path, "decoded dimensions do not match Commons metadata");
    }
    Ok(())
}

fn validate_png(path: &Path, expected_width: u32, expected_height: u32) -> Result<()> {
    let file = File::open(path)?;
    let file_len = file.metadata()?.len();
    let mut reader = BufReader::new(file);
    let mut signature = [0_u8; 8];
    read_exact_image(&mut reader, &mut signature, path, "truncated PNG signature")?;
    if &signature != PNG_SIGNATURE {
        return verification(path, "PNG signature is invalid");
    }
    let mut position = 8_u64;
    let mut chunk_index = 0_u64;
    let mut saw_idat = false;
    let mut idat_ended = false;

    loop {
        if position == file_len {
            return verification(path, "PNG is missing IEND");
        }
        if file_len.saturating_sub(position) < 12 {
            return verification(path, "PNG has a truncated chunk header");
        }
        let mut header = [0_u8; 8];
        read_exact_image(&mut reader, &mut header, path, "truncated PNG chunk header")?;
        position = position.saturating_add(8);
        let length = u32::from_be_bytes(header[..4].try_into().expect("four-byte slice"));
        let chunk_type: [u8; 4] = header[4..].try_into().expect("four-byte slice");
        if !chunk_type.iter().all(u8::is_ascii_alphabetic) {
            return verification(path, "PNG chunk type is invalid");
        }
        let remaining = u64::from(length).checked_add(4).ok_or_else(|| {
            PhotoForgeError::VerificationFailed {
                path: path.display().to_string(),
                message: "PNG chunk length overflowed".to_string(),
            }
        })?;
        if remaining > file_len.saturating_sub(position) {
            return verification(path, "PNG chunk length exceeds the remaining file");
        }
        if chunk_index == 0 && (chunk_type != *b"IHDR" || length != 13) {
            return verification(path, "PNG IHDR must be the first 13-byte chunk");
        }
        if chunk_index != 0 && chunk_type == *b"IHDR" {
            return verification(path, "PNG contains more than one IHDR chunk");
        }
        if matches!(&chunk_type, b"acTL" | b"fcTL" | b"fdAT") {
            return verification(path, "APNG animation chunks are not accepted");
        }
        if chunk_type == *b"IDAT" {
            if idat_ended {
                return verification(path, "PNG IDAT chunks are not consecutive");
            }
            saw_idat = true;
        } else if saw_idat && chunk_type != *b"IEND" {
            idat_ended = true;
        }

        let mut crc = Crc32::new();
        crc.update(&chunk_type);
        let mut retained = Vec::new();
        let mut left = u64::from(length);
        let mut buffer = [0_u8; 64 * 1024];
        while left > 0 {
            let wanted = usize::try_from(left.min(buffer.len() as u64)).expect("bounded buffer");
            read_exact_image(
                &mut reader,
                &mut buffer[..wanted],
                path,
                "truncated PNG chunk data",
            )?;
            crc.update(&buffer[..wanted]);
            if chunk_type == *b"IHDR" {
                retained.extend_from_slice(&buffer[..wanted]);
            }
            left -= wanted as u64;
            position = position.saturating_add(wanted as u64);
        }
        let mut expected_crc = [0_u8; 4];
        read_exact_image(
            &mut reader,
            &mut expected_crc,
            path,
            "truncated PNG chunk CRC",
        )?;
        position = position.saturating_add(4);
        if crc.finalize() != u32::from_be_bytes(expected_crc) {
            return verification(path, "PNG chunk CRC does not match");
        }

        if chunk_type == *b"IHDR" {
            validate_ihdr(path, &retained, expected_width, expected_height)?;
        }
        if chunk_type == *b"IEND" {
            if length != 0 || !saw_idat {
                return verification(path, "PNG IEND is invalid or precedes IDAT");
            }
            if position != file_len {
                return verification(path, "PNG has trailing bytes after IEND");
            }
            return Ok(());
        }
        chunk_index = chunk_index.saturating_add(1);
    }
}

fn validate_ihdr(
    path: &Path,
    data: &[u8],
    expected_width: u32,
    expected_height: u32,
) -> Result<()> {
    if data.len() != 13 {
        return verification(path, "PNG IHDR length is not 13 bytes");
    }
    let width = u32::from_be_bytes(data[..4].try_into().expect("four-byte slice"));
    let height = u32::from_be_bytes(data[4..8].try_into().expect("four-byte slice"));
    let bit_depth = data[8];
    let color_type = data[9];
    let valid_depth = match color_type {
        0 => matches!(bit_depth, 1 | 2 | 4 | 8 | 16),
        2 | 4 | 6 => matches!(bit_depth, 8 | 16),
        3 => matches!(bit_depth, 1 | 2 | 4 | 8),
        _ => false,
    };
    if width == 0
        || height == 0
        || width != expected_width
        || height != expected_height
        || !valid_depth
        || data[10] != 0
        || data[11] != 0
        || !matches!(data[12], 0 | 1)
    {
        return verification(
            path,
            "PNG IHDR dimensions or encoding fields do not match metadata",
        );
    }
    Ok(())
}

fn validate_jpeg(path: &Path, expected_width: u32, expected_height: u32) -> Result<()> {
    let mut reader = BufReader::new(File::open(path)?);
    let mut soi = [0_u8; 2];
    read_exact_image(&mut reader, &mut soi, path, "truncated JPEG SOI")?;
    if soi != [0xff, 0xd8] {
        return verification(path, "JPEG does not begin with FF D8");
    }
    let prefix = read_byte(&mut reader, path, "JPEG ends after SOI")?;
    if prefix != 0xff {
        return verification(path, "JPEG does not begin with FF D8 FF");
    }
    let mut marker = marker_after_prefix(&mut reader, path)?;
    let mut saw_sof = false;
    let mut saw_sos = false;
    let mut scan_mode = false;

    loop {
        if marker == 0xd9 {
            if !saw_sof || !saw_sos {
                return verification(path, "JPEG EOI appears before a valid SOF and scan");
            }
            let mut trailing = [0_u8; 64 * 1024];
            loop {
                let count = reader.read(&mut trailing)?;
                if count == 0 {
                    return Ok(());
                }
                if trailing[..count]
                    .iter()
                    .any(|byte| !matches!(byte, 0x00 | 0xff))
                {
                    return verification(path, "JPEG has non-padding bytes after EOI");
                }
            }
        }
        if matches!(marker, 0xd8) {
            return verification(path, "JPEG contains an unexpected second SOI");
        }
        if matches!(marker, 0x01 | 0xd0..=0xd7) {
            marker = next_jpeg_marker(&mut reader, path, scan_mode)?;
            continue;
        }
        let mut length_bytes = [0_u8; 2];
        read_exact_image(
            &mut reader,
            &mut length_bytes,
            path,
            "truncated JPEG segment length",
        )?;
        let length = usize::from(u16::from_be_bytes(length_bytes));
        if length < 2 {
            return verification(path, "JPEG segment length is smaller than two");
        }
        let payload_len = length - 2;
        if is_sof_marker(marker) {
            if saw_sof {
                return verification(path, "JPEG contains multiple frame headers");
            }
            let mut payload = vec![0_u8; payload_len];
            read_exact_image(
                &mut reader,
                &mut payload,
                path,
                "truncated JPEG frame header",
            )?;
            validate_sof(path, &payload, expected_width, expected_height)?;
            saw_sof = true;
            scan_mode = false;
        } else if marker == 0xda {
            let mut payload = vec![0_u8; payload_len];
            read_exact_image(
                &mut reader,
                &mut payload,
                path,
                "truncated JPEG scan header",
            )?;
            validate_sos(path, &payload)?;
            if !saw_sof {
                return verification(path, "JPEG scan precedes its frame header");
            }
            saw_sos = true;
            scan_mode = true;
        } else {
            skip_exact(&mut reader, payload_len, path, "truncated JPEG segment")?;
            scan_mode = false;
        }
        marker = next_jpeg_marker(&mut reader, path, scan_mode)?;
        if !matches!(marker, 0xd0..=0xd7 | 0x01) {
            scan_mode = false;
        }
    }
}

fn validate_sof(
    path: &Path,
    payload: &[u8],
    expected_width: u32,
    expected_height: u32,
) -> Result<()> {
    if payload.len() < 6 {
        return verification(path, "JPEG frame header is too short");
    }
    let precision = payload[0];
    let height = u32::from(u16::from_be_bytes([payload[1], payload[2]]));
    let width = u32::from(u16::from_be_bytes([payload[3], payload[4]]));
    let components = usize::from(payload[5]);
    if !matches!(precision, 8 | 12)
        || width == 0
        || height == 0
        || width != expected_width
        || height != expected_height
        || !(1..=4).contains(&components)
        || payload.len() != 6 + components * 3
    {
        return verification(
            path,
            "JPEG frame dimensions or component structure do not match metadata",
        );
    }
    Ok(())
}

fn validate_sos(path: &Path, payload: &[u8]) -> Result<()> {
    let Some(&components) = payload.first() else {
        return verification(path, "JPEG scan header is empty");
    };
    let components = usize::from(components);
    if !(1..=4).contains(&components) || payload.len() != 1 + components * 2 + 3 {
        return verification(path, "JPEG scan header has an invalid component structure");
    }
    Ok(())
}

fn is_sof_marker(marker: u8) -> bool {
    matches!(
        marker,
        0xc0 | 0xc1 | 0xc2 | 0xc3 | 0xc5 | 0xc6 | 0xc7 | 0xc9 | 0xca | 0xcb | 0xcd | 0xce | 0xcf
    )
}

fn next_jpeg_marker<R: Read>(reader: &mut R, path: &Path, scan_mode: bool) -> Result<u8> {
    if !scan_mode {
        let prefix = read_byte(reader, path, "JPEG is missing a following marker")?;
        if prefix != 0xff {
            return verification(path, "JPEG segment is not followed by a marker");
        }
        return marker_after_prefix(reader, path);
    }
    loop {
        if read_byte(reader, path, "JPEG scan is truncated before EOI")? != 0xff {
            continue;
        }
        let marker = marker_after_prefix(reader, path)?;
        if marker == 0x00 || matches!(marker, 0xd0..=0xd7 | 0x01) {
            continue;
        }
        return Ok(marker);
    }
}

fn marker_after_prefix<R: Read>(reader: &mut R, path: &Path) -> Result<u8> {
    loop {
        let marker = read_byte(reader, path, "truncated JPEG marker")?;
        if marker == 0xff {
            continue;
        }
        return Ok(marker);
    }
}

fn read_byte<R: Read>(reader: &mut R, path: &Path, message: &str) -> Result<u8> {
    let mut byte = [0_u8; 1];
    read_exact_image(reader, &mut byte, path, message)?;
    Ok(byte[0])
}

fn read_exact_image<R: Read>(
    reader: &mut R,
    bytes: &mut [u8],
    path: &Path,
    message: &str,
) -> Result<()> {
    reader.read_exact(bytes).map_err(|error| {
        if error.kind() == io::ErrorKind::UnexpectedEof {
            PhotoForgeError::VerificationFailed {
                path: path.display().to_string(),
                message: message.to_string(),
            }
        } else {
            PhotoForgeError::Io(error)
        }
    })
}

fn skip_exact<R: Read>(reader: &mut R, mut count: usize, path: &Path, message: &str) -> Result<()> {
    let mut buffer = [0_u8; 64 * 1024];
    while count > 0 {
        let wanted = count.min(buffer.len());
        read_exact_image(reader, &mut buffer[..wanted], path, message)?;
        count -= wanted;
    }
    Ok(())
}

fn verification<T>(path: &Path, message: &str) -> Result<T> {
    Err(PhotoForgeError::VerificationFailed {
        path: path.display().to_string(),
        message: message.to_string(),
    })
}

#[cfg(test)]
pub(crate) fn test_png(width: u32, height: u32) -> Vec<u8> {
    use ::image::ImageEncoder;

    let pixels = vec![0x6a; width as usize * height as usize * 3];
    let mut bytes = Vec::new();
    ::image::codecs::png::PngEncoder::new(&mut bytes)
        .write_image(&pixels, width, height, ::image::ExtendedColorType::Rgb8)
        .expect("tiny generated PNG encodes");
    bytes
}

#[cfg(test)]
pub(crate) fn test_jpeg(width: u16, height: u16) -> Vec<u8> {
    let pixels = vec![0x79; width as usize * height as usize * 3];
    let mut bytes = Vec::new();
    ::image::codecs::jpeg::JpegEncoder::new_with_quality(&mut bytes, 90)
        .encode(
            &pixels,
            u32::from(width),
            u32::from(height),
            ::image::ExtendedColorType::Rgb8,
        )
        .expect("tiny generated JPEG encodes");
    bytes
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;

    fn write_fixture(bytes: &[u8]) -> (tempfile::TempDir, std::path::PathBuf) {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("image.bin");
        let mut file = File::create(&path).unwrap();
        file.write_all(bytes).unwrap();
        (temp, path)
    }

    fn corrupt_png_deflate_with_valid_crc(bytes: &mut [u8]) {
        let mut offset = PNG_SIGNATURE.len();
        while offset + 12 <= bytes.len() {
            let length = u32::from_be_bytes(bytes[offset..offset + 4].try_into().unwrap()) as usize;
            let kind_start = offset + 4;
            let data_start = offset + 8;
            let data_end = data_start + length;
            if &bytes[kind_start..kind_start + 4] == b"IDAT" {
                bytes[data_start] ^= 0x7f;
                let mut crc = Crc32::new();
                crc.update(&bytes[kind_start..data_end]);
                bytes[data_end..data_end + 4].copy_from_slice(&crc.finalize().to_be_bytes());
                return;
            }
            offset = data_end + 4;
        }
        panic!("generated PNG had no IDAT");
    }

    fn structurally_valid_but_undecodable_jpeg(width: u16, height: u16) -> Vec<u8> {
        let mut bytes = vec![0xff, 0xd8];
        let sof = [
            8,
            (height >> 8) as u8,
            height as u8,
            (width >> 8) as u8,
            width as u8,
            1,
            1,
            0x11,
            0,
        ];
        bytes.extend_from_slice(&[0xff, 0xc0]);
        bytes.extend_from_slice(&((sof.len() + 2) as u16).to_be_bytes());
        bytes.extend_from_slice(&sof);
        let sos = [1, 1, 0, 0, 63, 0];
        bytes.extend_from_slice(&[0xff, 0xda]);
        bytes.extend_from_slice(&((sos.len() + 2) as u16).to_be_bytes());
        bytes.extend_from_slice(&sos);
        bytes.extend_from_slice(&[0x12, 0xff, 0x00, 0x34, 0xff, 0xd9]);
        bytes
    }

    #[test]
    fn validates_generated_static_png_and_jpeg() {
        let (_temp, png) = write_fixture(&test_png(3, 2));
        validate_image_file(&png, "image/png", 3, 2).unwrap();
        let (_temp, jpeg) = write_fixture(&test_jpeg(3, 2));
        validate_image_file(&jpeg, "image/jpeg", 3, 2).unwrap();
    }

    #[test]
    fn png_rejects_bad_signature_crc_truncation_and_dimension_mismatch() {
        let mut bytes = test_png(3, 2);
        bytes[0] = 0;
        let (_temp, path) = write_fixture(&bytes);
        assert!(validate_image_file(&path, "image/png", 3, 2).is_err());

        let mut bytes = test_png(3, 2);
        bytes[29] ^= 1;
        let (_temp, path) = write_fixture(&bytes);
        assert!(validate_image_file(&path, "image/png", 3, 2).is_err());

        let mut bytes = test_png(3, 2);
        bytes.truncate(bytes.len() - 2);
        let (_temp, path) = write_fixture(&bytes);
        assert!(validate_image_file(&path, "image/png", 3, 2).is_err());

        let (_temp, path) = write_fixture(&test_png(3, 2));
        assert!(validate_image_file(&path, "image/png", 4, 2).is_err());
    }

    #[test]
    fn png_rejects_apng_and_trailing_data() {
        let mut bytes = test_png(1, 1);
        let iend = bytes.split_off(bytes.len() - 12);
        let data = [0_u8; 8];
        bytes.extend_from_slice(&(data.len() as u32).to_be_bytes());
        bytes.extend_from_slice(b"acTL");
        bytes.extend_from_slice(&data);
        let mut crc = Crc32::new();
        crc.update(b"acTL");
        crc.update(&data);
        bytes.extend_from_slice(&crc.finalize().to_be_bytes());
        bytes.extend_from_slice(&iend);
        let (_temp, path) = write_fixture(&bytes);
        assert!(validate_image_file(&path, "image/png", 1, 1).is_err());

        let mut bytes = test_png(1, 1);
        bytes.push(0);
        let (_temp, path) = write_fixture(&bytes);
        assert!(validate_image_file(&path, "image/png", 1, 1).is_err());
    }

    #[test]
    fn full_decode_rejects_malformed_png_deflate_and_jpeg_entropy_tables() {
        let mut png = test_png(2, 1);
        corrupt_png_deflate_with_valid_crc(&mut png);
        let (_temp, path) = write_fixture(&png);
        validate_png(&path, 2, 1).unwrap();
        assert!(validate_image_file(&path, "image/png", 2, 1).is_err());

        let jpeg = structurally_valid_but_undecodable_jpeg(2, 1);
        let (_temp, path) = write_fixture(&jpeg);
        validate_jpeg(&path, 2, 1).unwrap();
        assert!(validate_image_file(&path, "image/jpeg", 2, 1).is_err());
    }

    #[test]
    fn jpeg_rejects_bad_soi_segment_lengths_truncation_and_mismatch() {
        let mut bytes = test_jpeg(3, 2);
        bytes[1] = 0;
        let (_temp, path) = write_fixture(&bytes);
        assert!(validate_image_file(&path, "image/jpeg", 3, 2).is_err());

        let mut bytes = test_jpeg(3, 2);
        bytes[4] = 0;
        bytes[5] = 1;
        let (_temp, path) = write_fixture(&bytes);
        assert!(validate_image_file(&path, "image/jpeg", 3, 2).is_err());

        let mut bytes = test_jpeg(3, 2);
        bytes.truncate(bytes.len() - 1);
        let (_temp, path) = write_fixture(&bytes);
        assert!(validate_image_file(&path, "image/jpeg", 3, 2).is_err());

        let (_temp, path) = write_fixture(&test_jpeg(3, 2));
        assert!(validate_image_file(&path, "image/jpeg", 2, 2).is_err());
    }

    #[test]
    fn jpeg_requires_eoi_and_rejects_nonpadding_trailer() {
        let mut bytes = test_jpeg(1, 1);
        bytes.truncate(bytes.len() - 2);
        let (_temp, path) = write_fixture(&bytes);
        assert!(validate_image_file(&path, "image/jpeg", 1, 1).is_err());

        let mut bytes = test_jpeg(1, 1);
        bytes.extend_from_slice(&[0, 0xff]);
        let (_temp, path) = write_fixture(&bytes);
        validate_image_file(&path, "image/jpeg", 1, 1).unwrap();

        let mut bytes = test_jpeg(1, 1);
        bytes.push(1);
        let (_temp, path) = write_fixture(&bytes);
        assert!(validate_image_file(&path, "image/jpeg", 1, 1).is_err());
    }

    #[test]
    fn rejects_every_unsupported_initial_mime() {
        let (_temp, path) = write_fixture(b"GIF89a");
        for mime in [
            "image/gif",
            "image/svg+xml",
            "image/webp",
            "image/tiff",
            "image/avif",
            "image/bigtiff",
        ] {
            assert!(validate_image_file(&path, mime, 1, 1).is_err());
        }
    }

    #[test]
    fn hard_file_and_decode_dimension_limits_apply_before_allocation() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("oversized.png");
        let file = File::create(&path).unwrap();
        file.set_len(MAX_RETAINED_IMAGE_BYTES + 1).unwrap();
        assert!(validate_image_file(&path, "image/png", 1, 1).is_err());

        let (_temp, path) = write_fixture(&test_png(1, 1));
        assert!(validate_image_file(&path, "image/png", MAX_DECODE_DIMENSION + 1, 1).is_err());
    }
}