Repository navigation
Expand file tree
/
Copy pathvalidation.rs
More file actions
2808 lines (2610 loc) · 112 KB
/
Copy pathvalidation.rs
File metadata and controls
2808 lines (2610 loc) · 112 KB
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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Content validation — magic bytes, allowlist, size, image bomb protection, video metadata.
use std::io::{BufReader, Seek, SeekFrom};
use std::path::Path;
use crate::config::MediaConfig;
use crate::error::MediaError;
/// Accepted MIME types for the image upload path.
///
/// `video/mp4` is intentionally excluded — video uploads use a separate pipeline
/// (`process_video_upload`) with its own magic-byte check. If an MP4 is uploaded
/// through the image path (Content-Type spoofing), `infer::get()` detects
/// `video/mp4` and `validate_content()` rejects it here.
const ALLOWED_MIME_TYPES: &[&str] = &["image/jpeg", "image/png", "image/gif", "image/webp"];
const MP4_BRANDS: &[[u8; 4]] = &[
*b"isom", *b"iso2", *b"iso3", *b"iso4", *b"iso5", *b"iso6", *b"iso7", *b"iso8", *b"iso9",
*b"mp41", *b"mp42", *b"avc1", *b"dash", *b"M4V ",
];
fn iso_bmff_ftyp_payload(bytes: &[u8]) -> Option<&[u8]> {
if bytes.len() < 16 || &bytes[4..8] != b"ftyp" {
return None;
}
let compact = u32::from_be_bytes(bytes[..4].try_into().ok()?) as u64;
let (declared_size, header_size) = if compact == 1 {
if bytes.len() < 24 {
return None;
}
(u64::from_be_bytes(bytes[8..16].try_into().ok()?), 16usize)
} else if compact == 0 {
(bytes.len() as u64, 8usize)
} else {
(compact, 8usize)
};
if declared_size < (header_size + 8) as u64 {
return None;
}
let available_end = usize::try_from(declared_size)
.unwrap_or(usize::MAX)
.min(bytes.len());
(available_end >= header_size + 8).then_some(&bytes[header_size..available_end])
}
/// Return whether the leading bytes contain a structurally valid ISO-BMFF
/// `ftyp` box, independent of the request MIME type or `infer`'s brand list.
pub fn looks_like_iso_bmff(bytes: &[u8]) -> bool {
iso_bmff_ftyp_payload(bytes).is_some()
}
pub(crate) fn looks_like_mp4_iso_bmff(bytes: &[u8]) -> bool {
let Some(payload) = iso_bmff_ftyp_payload(bytes) else {
return false;
};
let major = payload[..4].try_into().ok();
major.is_some_and(|brand| MP4_BRANDS.contains(&brand))
|| payload[8..]
.as_chunks::<4>()
.0
.iter()
.any(|brand| MP4_BRANDS.contains(brand))
}
/// MIME types blocked from the generic file-upload path.
///
/// These are the formats a browser (or the desktop webview) will *execute* or
/// *render as active content* if it ever reaches them with the wrong response
/// headers. We serve generic files with `Content-Disposition: attachment` +
/// `X-Content-Type-Options: nosniff` + `CSP: default-src 'none'`, which already
/// neutralises them — this allowlist-of-denials is defence in depth, so a future
/// header regression can't turn an uploaded blob into a stored-XSS vector.
///
/// JS and SVG are the classic stored-XSS carriers. Native executables are
/// blocked because there's no legitimate reason to host them inline in chat and
/// they're a malware-distribution risk.
///
/// HTML is intentionally *not* blocked: it is accepted as an inert download
/// (`serve_inline` returns false for `text/html`, so it is served with
/// `Content-Disposition: attachment` + `nosniff` + `CSP: default-src 'none'`,
/// and the desktop renderer never navigates a webview to a generic
/// attachment). The old sniff-based block only caught the well-formed HTML
/// `infer` recognises anyway — HTML that evades the sniff already uploaded as
/// `application/octet-stream` and served as a download, so blocking canonical
/// HTML was inconsistent rather than a real control. `application/xhtml+xml`
/// stays listed as dormant defence in depth: `infer` has no XHTML matcher, so
/// it is unreachable through sniffing, but the entry costs nothing and guards
/// against a future detector that does classify it.
const BLOCKED_FILE_MIME_TYPES: &[&str] = &[
// Active web content — stored-XSS vectors.
"application/xhtml+xml",
"image/svg+xml",
"application/javascript",
"text/javascript",
// Native executables / installers.
"application/x-msdownload", // .exe / .dll
"application/x-executable", // ELF
"application/vnd.microsoft.portable-executable",
"application/x-mach-binary", // Mach-O
"application/x-sharedlib",
"application/x-elf",
"application/x-msi",
"application/vnd.android.package-archive", // .apk
"application/x-apple-diskimage", // .dmg
];
/// Map a sniffed MIME type to a file extension for the generic file path.
///
/// Covers the common document, archive, audio, and data formats `infer`
/// recognises. Returns `None` for MIME types we don't have a canonical
/// extension for — the caller falls back to `bin`.
fn file_mime_to_ext(mime: &str) -> Option<&'static str> {
let ext = match mime {
// Documents
"application/pdf" => "pdf",
"application/msword" => "doc",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document" => "docx",
"application/vnd.ms-excel" => "xls",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => "xlsx",
"application/vnd.ms-powerpoint" => "ppt",
"application/vnd.openxmlformats-officedocument.presentationml.presentation" => "pptx",
"application/vnd.oasis.opendocument.text" => "odt",
"application/vnd.oasis.opendocument.spreadsheet" => "ods",
"application/vnd.oasis.opendocument.presentation" => "odp",
"application/rtf" => "rtf",
"application/epub+zip" => "epub",
// Archives
"application/zip" => "zip",
"application/gzip" => "gz",
"application/x-tar" => "tar",
"application/x-7z-compressed" => "7z",
"application/x-rar-compressed" | "application/vnd.rar" => "rar",
"application/x-bzip2" => "bz2",
"application/x-xz" => "xz",
"application/zstd" => "zst",
// Audio
"audio/mpeg" => "mp3",
"audio/mp4" | "audio/m4a" | "audio/x-m4a" => "m4a",
"audio/flac" | "audio/x-flac" => "flac",
"audio/wav" | "audio/x-wav" => "wav",
"audio/ogg" => "ogg",
"audio/aac" => "aac",
"audio/opus" => "opus",
// Other media containers (served as downloads, not transcoded)
"video/quicktime" => "mov",
"video/webm" => "webm",
"video/x-matroska" => "mkv",
// Data / text
"application/json" => "json",
"text/csv" => "csv",
"text/html" => "html",
"text/plain" => "txt",
_ => return None,
};
Some(ext)
}
/// Validate uploaded bytes for the **generic file** upload path.
///
/// This is the catch-all path for non-media attachments (documents, archives,
/// text, data). It enforces three things:
/// 1. A size cap (`config.max_file_bytes`).
/// 2. A *deny* list — known active-content and executable MIME types are
/// rejected even though safe headers already neutralise them.
/// 3. Magic-byte sniffing where possible.
///
/// Files with no detectable signature (plain text, CSV, source code, JSON —
/// none of which have magic bytes) are accepted as `application/octet-stream`.
/// They are always served as downloads, so an un-sniffable file can never
/// execute in the app.
///
/// Returns `(mime, ext)`.
pub fn validate_file_content(
bytes: &[u8],
config: &MediaConfig,
) -> Result<(String, String), MediaError> {
// 1. Size cap.
if bytes.len() as u64 > config.max_file_bytes {
return Err(MediaError::FileTooLarge {
size: bytes.len() as u64,
max: config.max_file_bytes,
});
}
// ISO-BMFF permits arbitrary major brands, so `infer` cannot enumerate all
// valid MP4 signatures. Never let an `ftyp` container fall through as an
// opaque attachment merely because its brand is unfamiliar.
if looks_like_iso_bmff(bytes) {
let mime = infer::get(bytes)
.map(|kind| kind.mime_type().to_string())
.unwrap_or_else(|| "application/iso-bmff".to_string());
return Err(MediaError::DisallowedContentType(mime));
}
// 2. Sniff. `None` means no magic signature (text/csv/json/source) — that's
// fine for the generic path; treat as opaque binary served as a download.
match infer::get(bytes) {
Some(kind) => {
let mime = kind.mime_type().to_string();
// Recognized media must never fall through exact-byte attachment
// storage. Images and video use their canonical media validators;
// audio is rejected until Buzz has an explicit sanitizer and
// location-metadata validator for its container.
if mime.starts_with("image/")
|| mime.starts_with("video/")
|| mime.starts_with("audio/")
{
return Err(MediaError::DisallowedContentType(mime));
}
// 3. Deny dangerous active-content / executable types.
if BLOCKED_FILE_MIME_TYPES.contains(&mime.as_str()) {
return Err(MediaError::DisallowedContentType(mime));
}
let ext = file_mime_to_ext(&mime)
.map(str::to_string)
.unwrap_or_else(|| kind.extension().to_string());
Ok((mime, ext))
}
None => Ok(("application/octet-stream".to_string(), "bin".to_string())),
}
}
/// Whether a stored blob should be served inline (rendered in the client) or as
/// an attachment (forced download).
///
/// Images and video are previewed inline by the renderer; everything else is a
/// generic file card with a download action, so it serves as an attachment.
/// PDF is intentionally *not* inline yet — inline PDF preview is a planned
/// fast-follow; until the renderer handles it, force download like any other file.
pub fn serve_inline(mime: &str) -> bool {
mime.starts_with("image/") || mime.starts_with("video/")
}
/// Metadata extracted from a validated MP4 file.
#[derive(Debug, Clone)]
pub struct VideoMeta {
/// Duration in seconds (from mvhd timescale — not edit lists).
pub duration_secs: f64,
/// Width of the first video track in pixels.
pub width: u32,
/// Height of the first video track in pixels.
pub height: u32,
/// Whether the file contains at least one audio track.
pub has_audio: bool,
}
/// Validate uploaded bytes for the **image** upload path.
///
/// Checks magic bytes, MIME allowlist (images only), size, and pixel dimensions.
/// Rejects `video/mp4` — video uploads must use [`process_video_upload`] which
/// has its own magic-byte check and full MP4 validation pipeline.
pub fn validate_content(bytes: &[u8], config: &MediaConfig) -> Result<String, MediaError> {
// 1. Magic bytes — never trust Content-Type header
let mime = infer::get(bytes)
.map(|t| t.mime_type().to_string())
.ok_or(MediaError::UnknownContentType)?;
// 2. Allowlist (SVG, PDF, executables all rejected)
if !ALLOWED_MIME_TYPES.contains(&mime.as_str()) {
return Err(MediaError::DisallowedContentType(mime));
}
// 3. Size cap (images only — video uses its own size enforcement in the streaming pipeline)
let max = if mime == "image/gif" {
config.max_gif_bytes
} else {
config.max_image_bytes
};
if bytes.len() as u64 > max {
return Err(MediaError::FileTooLarge {
size: bytes.len() as u64,
max,
});
}
// 4. Reject metadata-bearing or non-canonical container structures.
validate_image_metadata_free(bytes, &mime)?;
// 5. Image bomb — check pixel dimensions before full decode.
check_image_pixels(bytes)?;
Ok(mime)
}
/// Reject an image over 25 megapixels (100MB max RGBA decode) before any full
/// decode. Fails closed: imagesize supports JPEG, PNG, GIF, WebP, and an image
/// whose dimensions can't be parsed never reaches the decoder.
pub(crate) fn check_image_pixels(bytes: &[u8]) -> Result<(), MediaError> {
const MAX_PIXELS: u64 = 25_000_000;
let size = imagesize::blob_size(bytes).map_err(|_| MediaError::InvalidImage)?;
if (size.width as u64) * (size.height as u64) > MAX_PIXELS {
return Err(MediaError::ImageTooLarge);
}
Ok(())
}
/// Validate an MP4 file on disk.
///
/// Checks:
/// - Container is MP4 (ftyp brand is not QuickTime `qt `)
/// - Exactly one video track using `avc1` (H.264 only — rejects HEVC, VP9, AV1)
/// - At most one audio track, using `mp4a` (AAC)
/// - Duration ≤ 600 seconds (from mvhd timescale, not edit lists)
/// - Resolution: short edge ≤ 2160 and long edge ≤ 3840 (portrait or landscape)
/// - moov atom precedes mdat (fast-start / web-optimised)
///
/// Returns [`VideoMeta`] on success.
pub fn validate_video_file(path: &Path, config: &MediaConfig) -> Result<VideoMeta, MediaError> {
// --- moov-before-mdat check (raw byte scan) ---
// We scan the top-level atom sequence before handing off to the mp4 crate,
// because the mp4 crate parses the whole file regardless of atom order.
check_moov_before_mdat(path)?;
let file = std::fs::File::open(path).map_err(|e| MediaError::Io(e.to_string()))?;
let size = file
.metadata()
.map_err(|e| MediaError::Io(e.to_string()))?
.len();
// Size guard (belt-and-suspenders — the streaming layer also enforces this).
if size > config.max_video_bytes {
return Err(MediaError::FileTooLarge {
size,
max: config.max_video_bytes,
});
}
validate_mp4_metadata_free(path)?;
let reader = BufReader::new(file);
let mp4 = mp4::Mp4Reader::read_header(reader, size).map_err(|_| MediaError::InvalidVideo)?;
// --- Container check ---
// QuickTime (MOV) uses brand "qt ". We reject it — only ISO-base MP4.
// The mp4 crate exposes the ftyp major brand via mp4.major_brand().
let brand = mp4.major_brand();
let qt_brand = mp4::FourCC::from(*b"qt ");
if *brand == qt_brand {
return Err(MediaError::UnsupportedContainer);
}
// --- Track inspection ---
let mut video_meta: Option<VideoMeta> = None;
let mut has_audio = false;
for track in mp4.tracks().values() {
match track.track_type().map_err(|_| MediaError::InvalidVideo)? {
mp4::TrackType::Video => {
if video_meta.is_some() {
// Alternate video tracks can carry telemetry or other content
// that the client did not intend to publish. Canonical uploads
// contain exactly one video track.
return Err(MediaError::MetadataForbidden);
}
// Codec check: only H.264 (avc1).
// media_type() reads the handler type and sample entry box type.
let media_type = track.media_type().map_err(|_| MediaError::WrongCodec)?;
if media_type != mp4::MediaType::H264 {
return Err(MediaError::WrongCodec);
}
// Duration from mvhd timescale (track duration / timescale).
// Reject zero/negative (malformed) and >600s (too long).
// Must match imeta validation which requires duration > 0.0.
// Guard: timescale=0 causes division-by-zero in the mp4 crate's
// duration() method. Fail fast before it panics.
if track.timescale() == 0 {
return Err(MediaError::InvalidVideo);
}
let duration_ms = track.duration().as_millis();
let duration_secs = duration_ms as f64 / 1000.0;
if duration_secs <= 0.0 {
return Err(MediaError::InvalidVideo);
}
if duration_secs > 600.0 {
return Err(MediaError::DurationTooLong);
}
// Resolution check. Apply the 2160×3840 envelope independent
// of orientation so equivalent portrait and landscape videos
// receive the same treatment.
let width = track.width() as u32;
let height = track.height() as u32;
let short_edge = width.min(height);
let long_edge = width.max(height);
if short_edge > 2160 || long_edge > 3840 {
return Err(MediaError::ResolutionTooHigh);
}
video_meta = Some(VideoMeta {
duration_secs,
width,
height,
has_audio: false, // filled in after audio scan
});
}
mp4::TrackType::Audio => {
if has_audio {
// Reject alternate audio tracks for the same reason as
// alternate video tracks: only the canonical primary stream
// produced by the client sanitizer is permitted.
return Err(MediaError::MetadataForbidden);
}
let media_type = track.media_type().map_err(|_| MediaError::WrongCodec)?;
if media_type != mp4::MediaType::AAC {
return Err(MediaError::WrongCodec);
}
has_audio = true;
}
_ => return Err(MediaError::MetadataForbidden),
}
}
let mut meta = video_meta.ok_or_else(|| {
if has_audio {
MediaError::DisallowedContentType("audio/mp4".to_string())
} else {
MediaError::InvalidVideo
}
})?;
meta.has_audio = has_audio;
Ok(meta)
}
/// Scan the top-level atom sequence to verify moov appears before mdat.
///
/// Reads only the 8-byte atom headers (size + fourcc) — never loads atom bodies.
/// Extended-size atoms (size==1) are handled by reading the 64-bit size field.
/// Iteration is capped to prevent DoS from crafted files with millions of tiny atoms.
fn check_moov_before_mdat(path: &Path) -> Result<(), MediaError> {
use std::io::Read;
/// Maximum top-level atoms to scan before giving up.
/// A normal MP4 has < 20 top-level atoms. 1024 is generous but bounded.
const MAX_ATOMS: u32 = 1024;
let mut file = std::fs::File::open(path).map_err(|e| MediaError::Io(e.to_string()))?;
let file_size = file
.metadata()
.map_err(|e| MediaError::Io(e.to_string()))?
.len();
let mut offset: u64 = 0;
let mut moov_seen = false;
let mut atoms_scanned: u32 = 0;
while offset < file_size {
atoms_scanned += 1;
if atoms_scanned > MAX_ATOMS {
// Fail closed: too many top-level atoms is abnormal. A crafted file
// could hide mdat after 1025 junk atoms to bypass the moov check.
return Err(MediaError::MoovNotAtFront);
}
file.seek(SeekFrom::Start(offset))
.map_err(|e| MediaError::Io(e.to_string()))?;
let mut header = [0u8; 8];
match file.read_exact(&mut header) {
Ok(_) => {}
Err(_) => break, // truncated file — mp4 parser will catch it
}
let compact_size = u32::from_be_bytes([header[0], header[1], header[2], header[3]]) as u64;
let fourcc = &header[4..8];
// Resolve actual atom size.
let atom_size = if compact_size == 1 {
// Extended size: next 8 bytes are the real 64-bit size (includes the 16-byte header).
let mut ext = [0u8; 8];
match file.read_exact(&mut ext) {
Ok(_) => {}
Err(_) => break, // truncated — mp4 parser will catch it
}
let extended = u64::from_be_bytes(ext);
if extended < 16 {
break; // malformed extended size — mp4 parser will reject
}
extended
} else if compact_size == 0 {
// atom_size == 0 means "extends to EOF" — this is the last atom.
// Check fourcc before stopping: mdat-at-EOF without prior moov is an error.
if fourcc == b"mdat" && !moov_seen {
return Err(MediaError::MoovNotAtFront);
}
break;
} else if compact_size < 8 {
break; // malformed — mp4 parser will reject
} else {
compact_size
};
match fourcc {
b"moov" => {
moov_seen = true;
}
b"mdat" if !moov_seen => {
return Err(MediaError::MoovNotAtFront);
}
_ => {}
}
offset += atom_size;
}
Ok(())
}
/// Reject metadata-bearing image structures without decoding pixel data.
///
/// This is deliberately a structural allowlist rather than an EXIF-tag denylist:
/// location can also live in XMP, comments, PNG text, ICC descriptions, or
/// private chunks. Client encoders remove these before upload.
fn validate_image_metadata_free(bytes: &[u8], mime: &str) -> Result<(), MediaError> {
match mime {
"image/jpeg" => validate_jpeg_metadata_free(bytes),
"image/png" => validate_png_metadata_free(bytes),
"image/webp" => validate_webp_metadata_free(bytes),
"image/gif" => validate_gif_metadata_free(bytes),
_ => Ok(()),
}
}
fn validate_jpeg_metadata_free(bytes: &[u8]) -> Result<(), MediaError> {
if !bytes.starts_with(&[0xff, 0xd8]) {
return Err(MediaError::InvalidImage);
}
let mut i = 2usize;
let mut in_scan = false;
while i < bytes.len() {
if bytes[i] != 0xff {
if in_scan {
i += 1;
continue;
}
return Err(MediaError::InvalidImage);
}
while i < bytes.len() && bytes[i] == 0xff {
i += 1;
}
if i >= bytes.len() {
return Err(MediaError::InvalidImage);
}
let marker = bytes[i];
i += 1;
if in_scan && marker == 0x00 {
continue;
}
if (0xd0..=0xd7).contains(&marker) || marker == 0x01 {
continue;
}
if marker == 0xd9 {
return (i == bytes.len())
.then_some(())
.ok_or(MediaError::MetadataForbidden);
}
if marker == 0xd8 {
return Err(MediaError::InvalidImage);
}
if i + 2 > bytes.len() {
return Err(MediaError::InvalidImage);
}
let len = u16::from_be_bytes([bytes[i], bytes[i + 1]]) as usize;
if len < 2 {
return Err(MediaError::InvalidImage);
}
let end = i
.checked_add(len)
.filter(|&end| end <= bytes.len())
.ok_or(MediaError::InvalidImage)?;
// Only canonical JFIF/Adobe colour headers are allowed. Their lengths and
// identifiers are fixed; accepting arbitrary APP0/APP14 payloads would
// leave a metadata side channel.
if marker == 0xe0 {
let payload = &bytes[i + 2..end];
let canonical_jfif = payload.len() >= 14
&& &payload[..5] == b"JFIF\0"
&& payload.len() == 14 + 3 * payload[12] as usize * payload[13] as usize;
if !canonical_jfif {
return Err(MediaError::MetadataForbidden);
}
} else if marker == 0xee {
let payload = &bytes[i + 2..end];
if payload.len() != 12 || &payload[..5] != b"Adobe" {
return Err(MediaError::MetadataForbidden);
}
} else if (0xe1..=0xed).contains(&marker) || marker == 0xef || marker == 0xfe {
return Err(MediaError::MetadataForbidden);
}
i = end;
in_scan = marker == 0xda;
}
Err(MediaError::InvalidImage)
}
/// tEXt keywords that carry Buzz snapshot manifests (`.agent.png` /
/// `.team.png`). These are deliberate product payloads — agent/team sharing
/// embeds a manifest in a single tEXt chunk — so they are exempt from the
/// metadata ban. Exactly one snapshot chunk is permitted per file; every
/// other textual/metadata chunk remains forbidden.
const PNG_SNAPSHOT_KEYWORDS: [&[u8]; 2] = [b"buzz_agent_snapshot", b"buzz_team_snapshot"];
/// Returns true when a raw tEXt chunk payload is a Buzz snapshot manifest:
/// the payload must start with an allowlisted keyword followed by the
/// keyword/text NUL separator.
fn is_snapshot_text_chunk(payload: &[u8]) -> bool {
PNG_SNAPSHOT_KEYWORDS.iter().any(|keyword| {
payload.len() > keyword.len()
&& &payload[..keyword.len()] == *keyword
&& payload[keyword.len()] == 0
})
}
fn validate_png_metadata_free(bytes: &[u8]) -> Result<(), MediaError> {
const SIG: &[u8] = b"\x89PNG\r\n\x1a\n";
if !bytes.starts_with(SIG) {
return Err(MediaError::InvalidImage);
}
let mut i = SIG.len();
let mut saw_iend = false;
let mut saw_snapshot_chunk = false;
while i < bytes.len() {
if i + 12 > bytes.len() {
return Err(MediaError::InvalidImage);
}
let len = u32::from_be_bytes(bytes[i..i + 4].try_into().unwrap()) as usize;
let kind: [u8; 4] = bytes[i + 4..i + 8].try_into().unwrap();
let end = i
.checked_add(12)
.and_then(|v| v.checked_add(len))
.filter(|&v| v <= bytes.len())
.ok_or(MediaError::InvalidImage)?;
if &kind == b"tEXt" {
// Buzz agent/team snapshot manifests ride in a single tEXt chunk
// with an allowlisted keyword. Anything else — other keywords, or
// a second snapshot chunk — is a forbidden metadata channel.
let payload = &bytes[i + 8..end - 4];
if saw_snapshot_chunk || !is_snapshot_text_chunk(payload) {
return Err(MediaError::MetadataForbidden);
}
saw_snapshot_chunk = true;
i = end;
continue;
}
if matches!(&kind, b"eXIf" | b"zTXt" | b"iTXt" | b"iCCP") {
return Err(MediaError::MetadataForbidden);
}
// Unknown ancillary chunks are private metadata channels. Keep only
// rendering chunks that client encoders may legitimately emit; pHYs is
// deliberately excluded because arbitrary values are an identity channel.
let ancillary = kind[0] & 0x20 != 0;
let known_rendering = matches!(
&kind,
b"cHRM"
| b"gAMA"
| b"sBIT"
| b"sRGB"
| b"bKGD"
| b"hIST"
| b"tRNS"
| b"sPLT"
| b"acTL"
| b"fcTL"
| b"fdAT"
);
if ancillary && !known_rendering {
return Err(MediaError::MetadataForbidden);
}
i = end;
if &kind == b"IEND" {
saw_iend = true;
break;
}
}
if !saw_iend || i != bytes.len() {
return Err(MediaError::MetadataForbidden);
}
Ok(())
}
fn validate_webp_metadata_free(bytes: &[u8]) -> Result<(), MediaError> {
fn validate_frame_payload(payload: &[u8]) -> Result<(), MediaError> {
const FRAME_HEADER_LEN: usize = 16;
if payload.len() < FRAME_HEADER_LEN {
return Err(MediaError::InvalidImage);
}
let mut i = FRAME_HEADER_LEN;
let mut saw_alpha = false;
let mut saw_image = false;
while i < payload.len() {
if i + 8 > payload.len() {
return Err(MediaError::InvalidImage);
}
let kind: [u8; 4] = payload[i..i + 4].try_into().unwrap();
let len = u32::from_le_bytes(payload[i + 4..i + 8].try_into().unwrap()) as usize;
let padded = len.checked_add(len & 1).ok_or(MediaError::InvalidImage)?;
i = i
.checked_add(8)
.and_then(|start| start.checked_add(padded))
.filter(|&end| end <= payload.len())
.ok_or(MediaError::InvalidImage)?;
match &kind {
b"ALPH" if !saw_alpha && !saw_image => saw_alpha = true,
b"VP8 " if !saw_image => saw_image = true,
b"VP8L" if !saw_alpha && !saw_image => saw_image = true,
b"ALPH" | b"VP8 " | b"VP8L" => return Err(MediaError::InvalidImage),
_ => return Err(MediaError::MetadataForbidden),
}
}
saw_image.then_some(()).ok_or(MediaError::InvalidImage)
}
if bytes.len() < 12 || &bytes[..4] != b"RIFF" || &bytes[8..12] != b"WEBP" {
return Err(MediaError::InvalidImage);
}
let declared = u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize;
if declared.checked_add(8) != Some(bytes.len()) {
return Err(MediaError::MetadataForbidden);
}
let mut i = 12usize;
while i < bytes.len() {
if i + 8 > bytes.len() {
return Err(MediaError::InvalidImage);
}
let kind: [u8; 4] = bytes[i..i + 4].try_into().unwrap();
let len = u32::from_le_bytes(bytes[i + 4..i + 8].try_into().unwrap()) as usize;
let payload_start = i + 8;
let padded = len.checked_add(len & 1).ok_or(MediaError::InvalidImage)?;
i = payload_start
.checked_add(padded)
.filter(|&v| v <= bytes.len())
.ok_or(MediaError::InvalidImage)?;
if !matches!(
&kind,
b"VP8 " | b"VP8L" | b"VP8X" | b"ALPH" | b"ANIM" | b"ANMF"
) {
return Err(MediaError::MetadataForbidden);
}
if &kind == b"VP8X" {
let flags = *bytes.get(payload_start).ok_or(MediaError::InvalidImage)?;
// ICC, EXIF, and XMP presence flags are metadata even if a malformed
// file omits their corresponding chunks.
if flags & (0x20 | 0x08 | 0x04) != 0 {
return Err(MediaError::MetadataForbidden);
}
} else if &kind == b"ANMF" {
validate_frame_payload(&bytes[payload_start..payload_start + len])?;
}
}
Ok(())
}
fn validate_gif_metadata_free(bytes: &[u8]) -> Result<(), MediaError> {
if !(bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a")) || bytes.len() < 13 {
return Err(MediaError::InvalidImage);
}
fn skip_sub_blocks(bytes: &[u8], i: &mut usize) -> Result<(), MediaError> {
loop {
let len = *bytes.get(*i).ok_or(MediaError::InvalidImage)? as usize;
*i += 1;
if len == 0 {
return Ok(());
}
*i = i
.checked_add(len)
.filter(|&end| end <= bytes.len())
.ok_or(MediaError::InvalidImage)?;
}
}
let packed = bytes[10];
let mut i = 13usize;
if packed & 0x80 != 0 {
let table_len = 3usize << ((packed & 0x07) as usize + 1);
i = i
.checked_add(table_len)
.filter(|&end| end <= bytes.len())
.ok_or(MediaError::InvalidImage)?;
}
loop {
match *bytes.get(i).ok_or(MediaError::InvalidImage)? {
0x2c => {
// Image descriptor, optional local colour table, LZW code size,
// then length-prefixed image-data sub-blocks.
if i + 10 > bytes.len() {
return Err(MediaError::InvalidImage);
}
let image_packed = bytes[i + 9];
i += 10;
if image_packed & 0x80 != 0 {
let table_len = 3usize << ((image_packed & 0x07) as usize + 1);
i = i
.checked_add(table_len)
.filter(|&end| end <= bytes.len())
.ok_or(MediaError::InvalidImage)?;
}
i = i
.checked_add(1)
.filter(|&v| v <= bytes.len())
.ok_or(MediaError::InvalidImage)?;
skip_sub_blocks(bytes, &mut i)?;
}
0x21 => {
let label = *bytes.get(i + 1).ok_or(MediaError::InvalidImage)?;
i += 2;
match label {
// Graphic Control Extension carries rendering/animation state,
// not descriptive metadata. Its shape is fixed by the spec.
0xf9 => {
if bytes.get(i) != Some(&4) || i + 6 > bytes.len() || bytes[i + 5] != 0 {
return Err(MediaError::InvalidImage);
}
i += 6;
}
// Preserve only the standard looping application extensions.
// Other application, comment, and plain-text extensions are
// unrestricted metadata channels.
0xff => {
if bytes.get(i) != Some(&11) || i + 12 > bytes.len() {
return Err(MediaError::InvalidImage);
}
let app = &bytes[i + 1..i + 12];
if app != b"NETSCAPE2.0" && app != b"ANIMEXTS1.0" {
return Err(MediaError::MetadataForbidden);
}
i += 12;
if bytes.get(i) != Some(&3)
|| bytes.get(i + 1) != Some(&1)
|| bytes.get(i + 4) != Some(&0)
{
return Err(MediaError::MetadataForbidden);
}
i += 5;
}
_ => return Err(MediaError::MetadataForbidden),
}
}
0x3b => {
return (i + 1 == bytes.len())
.then_some(())
.ok_or(MediaError::MetadataForbidden);
}
_ => return Err(MediaError::InvalidImage),
}
}
}
fn validate_mp4_metadata_free(path: &Path) -> Result<(), MediaError> {
const MAX_BOXES: usize = 100_000;
const MAX_BOX_DEPTH: usize = 32;
const EMPTY_FFMPEG_UDTA: &[u8] = &[
0, 0, 0, 0x35, b'm', b'e', b't', b'a', 0, 0, 0, 0, 0, 0, 0, 0x21, b'h', b'd', b'l', b'r',
0, 0, 0, 0, 0, 0, 0, 0, b'm', b'd', b'i', b'r', b'a', b'p', b'p', b'l', 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 8, b'i', b'l', b's', b't',
];
const FORBIDDEN: &[[u8; 4]] = &[
*b"meta",
*b"ilst",
*b"keys",
*b"data",
*b"uuid",
*b"xml ",
*b"bxml",
*b"loci",
*b"\xa9xyz",
*b"name",
*b"chap",
];
const CONTAINERS: &[[u8; 4]] = &[
*b"moov", *b"trak", *b"mdia", *b"minf", *b"stbl", *b"edts", *b"dinf", *b"sinf", *b"schi",
];
// Constrained H.264/AAC MP4 produced by our client encoders. Unknown boxes
// are rejected rather than guessed safe because private boxes can carry GPS.
const ALLOWED: &[[u8; 4]] = &[
*b"ftyp", *b"moov", *b"mdat", *b"free", *b"skip", *b"wide", *b"trak", *b"mdia", *b"minf",
*b"stbl", *b"edts", *b"dinf", *b"sinf", *b"schi", *b"udta", *b"mvhd", *b"tkhd", *b"mdhd",
*b"hdlr", *b"vmhd", *b"smhd", *b"dref", *b"url ", *b"urn ", *b"stsd", *b"stts", *b"stss",
*b"ctts", *b"stsc", *b"stsz", *b"stco", *b"co64", *b"sgpd", *b"sbgp", *b"sdtp", *b"elst",
];
fn walk(
file: &mut std::fs::File,
start: u64,
end: u64,
count: &mut usize,
depth: usize,
) -> Result<(), MediaError> {
use std::io::{Read, Seek, SeekFrom};
if depth > MAX_BOX_DEPTH {
return Err(MediaError::InvalidVideo);
}
let mut off = start;
while off < end {
*count += 1;
if *count > MAX_BOXES || end - off < 8 {
return Err(MediaError::InvalidVideo);
}
file.seek(SeekFrom::Start(off))
.map_err(|e| MediaError::Io(e.to_string()))?;
let mut h = [0u8; 8];
file.read_exact(&mut h)
.map_err(|_| MediaError::InvalidVideo)?;
let compact = u32::from_be_bytes(h[..4].try_into().unwrap()) as u64;
let kind: [u8; 4] = h[4..8].try_into().unwrap();
let (size, header) = if compact == 1 {
let mut ext = [0u8; 8];
file.read_exact(&mut ext)
.map_err(|_| MediaError::InvalidVideo)?;
(u64::from_be_bytes(ext), 16)
} else if compact == 0 {
(end - off, 8)
} else {
(compact, 8)
};
if size < header || off.checked_add(size).filter(|&v| v <= end).is_none() {
return Err(MediaError::InvalidVideo);
}
if FORBIDDEN.contains(&kind) || !ALLOWED.contains(&kind) {
return Err(MediaError::MetadataForbidden);
}
if kind == *b"udta" {
if size != header + EMPTY_FFMPEG_UDTA.len() as u64 {
return Err(MediaError::MetadataForbidden);
}
let mut body = vec![0; EMPTY_FFMPEG_UDTA.len()];
file.read_exact(&mut body)
.map_err(|_| MediaError::InvalidVideo)?;
if body != EMPTY_FFMPEG_UDTA {
return Err(MediaError::MetadataForbidden);
}
} else if CONTAINERS.contains(&kind) {
walk(file, off + header, off + size, count, depth + 1)?;
}
off += size;
}
Ok(())
}
let mut file = std::fs::File::open(path).map_err(|e| MediaError::Io(e.to_string()))?;
let end = file
.metadata()
.map_err(|e| MediaError::Io(e.to_string()))?
.len();
let mut count = 0;
walk(&mut file, 0, end, &mut count, 0)
}
/// Map MIME type to file extension.
pub fn mime_to_ext(mime: &str) -> &'static str {
match mime {
"image/jpeg" => "jpg",
"image/png" => "png",
"image/gif" => "gif",
"image/webp" => "webp",
"video/mp4" => "mp4",
_ => "bin",
}
}
/// Return a minimal structurally-valid H.264/avc1 MP4 body (618 bytes).
///
/// Fast-start layout (ftyp + moov + mdat), single video track, 1 s, 320×240,
/// no audio. Generated from the same builder as the unit tests and verified to
/// pass `validate_video_file` with the default `MediaConfig`.
///
/// Exposed only under `#[cfg(test)]` so it has no runtime cost; placed at
/// module scope (not inside `mod tests`) so other test modules in this crate
/// can import it via `use crate::validation::minimal_valid_mp4;`.
#[cfg(test)]
pub(crate) fn minimal_valid_mp4() -> Vec<u8> {
// ftyp(isom) + moov + mdat — pre-computed; identical to
// build_mp4_bytes(true, b"avc1", 1_000, 320, 240, false).
vec![
0x00, 0x00, 0x00, 0x14, 0x66, 0x74, 0x79, 0x70, 0x69, 0x73, 0x6f, 0x6d, 0x00, 0x00, 0x00,
0x00, 0x69, 0x73, 0x6f, 0x6d, 0x00, 0x00, 0x02, 0x4e, 0x6d, 0x6f, 0x6f, 0x76, 0x00, 0x00,
0x00, 0x6c, 0x6d, 0x76, 0x68, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xe8, 0x00, 0x00, 0x03, 0xe8, 0x00, 0x01, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x01, 0xda, 0x74, 0x72, 0x61, 0x6b, 0x00, 0x00, 0x00, 0x5c, 0x74, 0x6b,
0x68, 0x64, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xe8, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40,
0x00, 0x00, 0x00, 0x01, 0x40, 0x00, 0x00, 0x00, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x01, 0x76,
0x6d, 0x64, 0x69, 0x61, 0x00, 0x00, 0x00, 0x20, 0x6d, 0x64, 0x68, 0x64, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xe8, 0x00, 0x00,
0x03, 0xe8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2d, 0x68, 0x64, 0x6c, 0x72, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x69, 0x64, 0x65, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61,
0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00, 0x00, 0x00, 0x01, 0x21, 0x6d, 0x69, 0x6e, 0x66, 0x00,
0x00, 0x00, 0x14, 0x76, 0x6d, 0x68, 0x64, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,