From 18a5e7bd0ee6295a545bbb8c919c82e95b42ee87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Sep 2026 14:33:59 +0300 Subject: [PATCH] A boot pass re-sniffs attachments whose mime froze generic MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The mime an attachment wears is written at upload, so a deck or workbook uploaded before its viewer existed kept application/zip forever and its chip stayed a download link. At open the store now re-reads a head and tail window of every generically-typed row, follows the zip central directory when the windows cannot settle it, and rewrites only rows the bytes prove more specific — a plain zip, an OLE container, or anything uncertain is left exactly as stored. Sniff moves into izlek-core for this; the web upload and photo handlers share the one definition. --- Cargo.lock | 1 + Cargo.toml | 1 + crates/izlek-core/Cargo.toml | 2 +- crates/izlek-core/src/store/mod.rs | 2 + crates/izlek-core/src/store/sniff.rs | 366 +++++++++++++++++++++ crates/izlek-core/src/store/turso_store.rs | 106 +++++- crates/izlek-core/tests/store.rs | 250 ++++++++++++++ crates/izlek-web/Cargo.toml | 2 +- crates/izlek-web/src/files.rs | 151 +-------- crates/izlek-web/src/photo.rs | 2 +- 10 files changed, 728 insertions(+), 155 deletions(-) create mode 100644 crates/izlek-core/src/store/sniff.rs diff --git a/Cargo.lock b/Cargo.lock index 2fca663..8b4e509 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1795,6 +1795,7 @@ dependencies = [ "toml", "turso", "ulid", + "zip", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index df2414e..4bd9b08 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,7 @@ subtle = "2.6.1" chacha20poly1305 = "0.10.1" base64 = "0.22.1" toml = "1" +zip = { version = "8.6.0", default-features = false, features = ["deflate"] } [profile.release] codegen-units = 1 diff --git a/crates/izlek-core/Cargo.toml b/crates/izlek-core/Cargo.toml index d1c316f..a7bc960 100644 --- a/crates/izlek-core/Cargo.toml +++ b/crates/izlek-core/Cargo.toml @@ -45,4 +45,4 @@ ulid = { workspace = true, optional = true } async-trait = "0.1.92" serde_json.workspace = true tokio = { workspace = true } -turso = { workspace = true } +zip.workspace = true diff --git a/crates/izlek-core/src/store/mod.rs b/crates/izlek-core/src/store/mod.rs index 2eb37c9..899547b 100644 --- a/crates/izlek-core/src/store/mod.rs +++ b/crates/izlek-core/src/store/mod.rs @@ -17,6 +17,8 @@ pub mod secret; #[cfg(feature = "server")] pub mod reconcile; #[cfg(feature = "server")] +pub mod sniff; +#[cfg(feature = "server")] pub mod schema; pub mod turso_store; diff --git a/crates/izlek-core/src/store/sniff.rs b/crates/izlek-core/src/store/sniff.rs new file mode 100644 index 0000000..d83a465 --- /dev/null +++ b/crates/izlek-core/src/store/sniff.rs @@ -0,0 +1,366 @@ +//! What uploaded bytes are, decided from the bytes themselves — never from a +//! part's `content_type()`, which is whatever the browser felt like sending. +//! +//! Pure `bytes -> mime`, with no I/O and nothing browser-shaped in it, living +//! behind the same `server` gate as the store it serves. The upload path +//! sniffs a file once when it arrives; [`TursoStore::open`] additionally runs +//! [`refine`] over rows whose stored type is one of the [`GENERIC_MIME_TYPES`] +//! buckets, so attachments written before the sniffer could name OOXML files +//! come out of the next restart carrying their real type. One definition +//! serves both callers: the store cannot reach the web crate, and a second +//! sniffer would drift. + +/// The mime types the upload path can store that name nothing: a zip that is +/// not an office document, bytes no magic matched, and an OLE container with +/// no stream name to narrow it. The boot pass reads only rows wearing one of +/// these; `text/plain` is deliberately absent — no window of a text file can +/// ever refine it, so sweeping it would read every text blob on every boot +/// for a guaranteed no-op. +pub const GENERIC_MIME_TYPES: &[&str] = &[ + "application/zip", + "application/octet-stream", + "application/x-ole-storage", +]; + +/// Head bytes read per generic row: every prefix-magic format this sniffer +/// knows decides from the first bytes, an OpenDocument file's `mimetype` +/// entry is required to be the first thing in the file, and an OLE +/// container's directory sectors precede its stream data. +pub const HEAD_WINDOW: i64 = 64 * 1024; +/// Tail bytes read per generic row. A zip ends with its end-of-central- +/// directory record, which — comment included — can sit at most +/// 22 + 65535 bytes from the end of the file, so a tail this wide can never +/// miss it, and it usually holds much of the central directory besides. +pub const TAIL_WINDOW: i64 = 128 * 1024; +/// A central directory larger than this — tens of thousands of entries — is +/// left unread and the row left exactly as stored. +pub const DIRECTORY_CAP: i64 = 4 * 1024 * 1024; + +pub fn sniff(bytes: &[u8]) -> &'static str { + if bytes.starts_with(&[0x89, 0x50, 0x4E, 0x47]) { + "image/png" + } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { + "image/jpeg" + } else if bytes.starts_with(b"GIF8") { + "image/gif" + } else if bytes.starts_with(b"%PDF-") { + "application/pdf" + } else if bytes.starts_with(b"PK\x03\x04") { + // Every OOXML and OpenDocument file is a zip; what kind it is lives in + // the entry names, which a zip stores uncompressed. `xl/workbook.xml` + // is the one part an xlsx cannot be without, an ods declares its + // type in the `mimetype` entry the format requires be stored first, + // and `ppt/presentation.xml` is the one part a pptx cannot be + // without. + zip_mime(bytes) + } else if bytes.starts_with(&[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]) { + // The pre-2007 OLE compound file .xls, .doc and .ppt all share. Its + // directory holds stream names in UTF-16, and only a workbook carries + // one called `Workbook` — a .doc or .ppt stays an unnamed container. + if contains(bytes, b"W\0o\0r\0k\0b\0o\0o\0k\0") { + "application/vnd.ms-excel" + } else { + "application/x-ole-storage" + } + } else if bytes.starts_with(&[0x1F, 0x8B]) { + "application/gzip" + } else if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" && &bytes[8..12] == b"avif" { + "image/avif" + } else if bytes.len() >= 12 + && &bytes[4..8] == b"ftyp" + && matches!( + &bytes[8..12], + b"heic" | b"heix" | b"hevc" | b"heif" | b"mif1" | b"msf1" + ) + { + // Apple's HEIC container reuses the ISO-BMFF `ftyp` box video shares; + // the brand at bytes 8..12 is what tells a photo from a video apart. + "image/heic" + } else if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" && &bytes[8..12] == b"qt " { + "video/quicktime" + } else if bytes.len() >= 8 && &bytes[4..8] == b"ftyp" { + "video/mp4" + } else if bytes.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) { + "video/webm" + } else if bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP" { + "image/webp" + } else if bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WAVE" { + "audio/wav" + } else if bytes.starts_with(b"fLaC") { + "audio/flac" + } else if bytes.starts_with(b"OggS") { + "audio/ogg" + } else if bytes.starts_with(b"ID3") + || bytes.starts_with(&[0xFF, 0xFB]) + || bytes.starts_with(&[0xFF, 0xF3]) + || bytes.starts_with(&[0xFF, 0xF2]) + { + "audio/mpeg" + } else if std::str::from_utf8(bytes).is_ok() { + "text/plain" + } else { + "application/octet-stream" + } +} + +/// Which office document a zip's bytes declare, decided the way every reader +/// of the format does: by the entry names a zip stores uncompressed. Ends in +/// [`GENERIC_MIME_TYPES`]' zip bucket when the names name nothing. +fn zip_mime(bytes: &[u8]) -> &'static str { + if contains(bytes, b"xl/workbook.xml") { + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + } else if contains(bytes, b"opendocument.spreadsheet") { + "application/vnd.oasis.opendocument.spreadsheet" + } else if contains(bytes, b"ppt/presentation.xml") { + "application/vnd.openxmlformats-officedocument.presentationml.presentation" + } else { + "application/zip" + } +} + +/// Whether `haystack` holds `needle` anywhere in it. Used on zip bytes, where +/// the entry names sit in the clear even when the entries themselves do not. +fn contains(haystack: &[u8], needle: &[u8]) -> bool { + haystack + .windows(needle.len()) + .any(|window| window == needle) +} + +/// The office mime declared by the zip entry names in `bytes` — the central +/// directory's vocabulary, where every entry a file holds is listed. An +/// OpenDocument file is deliberately absent: its marker is the *content* of +/// the `mimetype` entry the format requires be stored first, not an entry +/// name, so it is decided from the head window and could never be found here. +pub(crate) fn office_entry_mime(bytes: &[u8]) -> Option<&'static str> { + if contains(bytes, b"xl/workbook.xml") { + Some("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") + } else if contains(bytes, b"ppt/presentation.xml") { + Some("application/vnd.openxmlformats-officedocument.presentationml.presentation") + } else { + None + } +} + +/// What one generic row's byte windows decided. +#[derive(Debug)] +pub(crate) enum Verdict { + /// Nothing left to read. `Some` is a candidate more specific than the + /// stored bucket (subject to [`refinement`]), `None` means the windows + /// could not improve on what is stored — and, for a zip, never will: + /// whatever the central directory says, the search already covered it. + Settle(Option<&'static str>), + /// A zip whose windows name no office part. `offset`/`size` locate the + /// central directory as the end record states them; reading it is the + /// last word, because every entry name the file has is listed there. + ReadDirectory { offset: u64, size: u64 }, +} + +/// Decides a generic row from its head and tail windows alone. When the +/// windows themselves hold a verdict it settles; only a zip with no office +/// marker in either window asks for the central directory. +pub(crate) fn refine(stored: &str, head: &[u8], tail: &[u8]) -> Verdict { + let mut windows = Vec::with_capacity(head.len() + tail.len()); + windows.extend_from_slice(head); + windows.extend_from_slice(tail); + match sniff(&windows) { + "application/zip" => match end_of_central_directory(tail) { + Some((offset, size)) => Verdict::ReadDirectory { offset, size }, + None => Verdict::Settle(None), + }, + candidate => Verdict::Settle(refinement(stored, Some(candidate))), + } +} + +/// Whether `candidate` may replace `stored`: something specific, something +/// other than what is stored, and never `text/plain` — a window cannot prove +/// a whole blob is UTF-8, so a text verdict out of windows is unverifiable, +/// and a text row would gain nothing from the sweep anyway. Everything else +/// the sniffer names is either a prefix-magic fact (true of the whole blob +/// when true of its head) or an office marker, both safe to act on. +pub(crate) fn refinement(stored: &str, candidate: Option<&'static str>) -> Option<&'static str> { + let candidate = candidate?; + if candidate == stored + || candidate == "text/plain" + || GENERIC_MIME_TYPES.contains(&candidate) + { + return None; + } + Some(candidate) +} + +/// The end-of-central-directory record every zip ends with: `PK\x05\x06`, +/// then the directory's size (12..16) and offset (16..20), then a comment +/// whose declared length must land exactly at the end of the bytes. Scanning +/// from the end, the first signature satisfying that anchor is the record. +/// `None` when there is none to trust: no record at all, or a zip64 one — +/// the `u32::MAX` sentinels say the real numbers live in a zip64 locator +/// this pass declines to parse, and a row it declines stays as stored. +pub(crate) fn end_of_central_directory(tail: &[u8]) -> Option<(u64, u64)> { + if tail.len() < 22 { + return None; + } + for i in (0..=tail.len() - 22).rev() { + if &tail[i..i + 4] != b"PK\x05\x06" { + continue; + } + let comment = u16::from_le_bytes([tail[i + 20], tail[i + 21]]) as usize; + if i + 22 + comment != tail.len() { + continue; + } + let size = u32::from_le_bytes(tail[i + 12..i + 16].try_into().ok()?) as u64; + let offset = u32::from_le_bytes(tail[i + 16..i + 20].try_into().ok()?) as u64; + if offset == u32::MAX as u64 || size == u32::MAX as u64 { + return None; + } + return Some((offset, size)); + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sniffs_the_magic_numbers() { + assert_eq!(sniff(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A]), "image/png"); + assert_eq!(sniff(&[0xFF, 0xD8, 0xFF, 0xE0]), "image/jpeg"); + assert_eq!(sniff(b"hello, this is plainly text"), "text/plain"); + assert_eq!( + sniff(&[0x00, 0x01, 0xFE, 0xFF, 0x02]), + "application/octet-stream" + ); + } + + #[test] + fn sniffs_the_media_types() { + assert_eq!( + sniff(b"\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00"), + "video/mp4" + ); + assert_eq!( + sniff(b"\x00\x00\x00\x18ftypavif\x00\x00\x00\x00"), + "image/avif" + ); + assert_eq!( + sniff(b"\x00\x00\x00\x18ftypheic\x00\x00\x00\x00"), + "image/heic" + ); + assert_eq!( + sniff(b"\x00\x00\x00\x18ftypmif1\x00\x00\x00\x00"), + "image/heic" + ); + assert_eq!( + sniff(b"\x00\x00\x00\x14ftypqt \x00\x00\x00\x00"), + "video/quicktime" + ); + assert_eq!(sniff(&[0x1A, 0x45, 0xDF, 0xA3, 0x00, 0x00]), "video/webm"); + assert_eq!(sniff(b"RIFF\x00\x00\x00\x00WEBPVP8 "), "image/webp"); + assert_eq!(sniff(b"RIFF\x00\x00\x00\x00WAVEfmt "), "audio/wav"); + assert_eq!(sniff(b"fLaC\x00\x00\x00\x00"), "audio/flac"); + assert_eq!(sniff(b"OggS\x00\x00\x00\x00"), "audio/ogg"); + assert_eq!(sniff(b"ID3\x03\x00\x00\x00"), "audio/mpeg"); + assert_eq!(sniff(&[0xFF, 0xFB, 0x90, 0x00]), "audio/mpeg"); + } + + /// A zip of the named entries, bytes inside irrelevant: the sniff reads + /// the entry names a zip stores uncompressed. + fn zip_with(names: &[&str]) -> Vec { + use std::io::Write as _; + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for name in names { + zip.start_file(*name, zip::write::SimpleFileOptions::default()) + .unwrap(); + zip.write_all(b"").unwrap(); + } + zip.finish().unwrap().into_inner() + } + + #[test] + fn a_presentation_sniffs_its_presentation_mime_and_a_plain_zip_stays_a_zip() { + let pptx = zip_with(&["ppt/presentation.xml", "ppt/slides/slide1.xml"]); + assert_eq!( + sniff(&pptx), + "application/vnd.openxmlformats-officedocument.presentationml.presentation" + ); + assert_eq!(sniff(&zip_with(&["notes.txt"])), "application/zip"); + } + + #[test] + fn a_workbook_declared_only_in_its_central_directory_is_found_by_the_directory_search() { + let bytes = zip_with(&["ppt/presentation.xml", "ppt/slides/slide1.xml"]); + let head = &bytes[..bytes.len() / 2]; + // Both windows of a cut in half hold the marker, so the windows alone + // settle a small file. + assert!(contains(head, b"ppt/presentation.xml")); + match refine("application/zip", head, &bytes[bytes.len() / 2..]) { + Verdict::Settle(Some( + "application/vnd.openxmlformats-officedocument.presentationml.presentation", + )) => {} + other => panic!("expected a settled presentation, got {other:?}"), + } + // The real end record survives its move into the synthetic tail. + let (offset, size) = end_of_central_directory(&bytes).expect("a real zip has an EOCD"); + let directory = &bytes[offset as usize..(offset + size) as usize]; + assert_eq!( + office_entry_mime(directory), + Some("application/vnd.openxmlformats-officedocument.presentationml.presentation") + ); + } + + #[test] + fn an_eocd_is_found_by_its_anchor_and_declined_when_zip64_or_absent() { + // A hand-built record: signature, the two disk fields, two entry + // counts, size, offset, a one-byte comment. + let mut tail = Vec::new(); + tail.extend_from_slice(b"PK\x05\x06"); + tail.extend_from_slice(&[0, 0, 0, 0]); // disk numbers + tail.extend_from_slice(&[1, 0, 1, 0]); // entry counts + tail.extend_from_slice(&0x1122_3344u32.to_le_bytes()); // size + tail.extend_from_slice(&0x5566_7788u32.to_le_bytes()); // offset + tail.extend_from_slice(&1u16.to_le_bytes()); // comment length + tail.push(b'!'); + assert_eq!( + end_of_central_directory(&tail), + Some((0x5566_7788, 0x1122_3344)) + ); + // A lie about the comment length leaves the record unanchored. + let mut drifting = tail.clone(); + *drifting.last_mut().unwrap() = b'?'; + drifting.push(b'!'); + assert_eq!(end_of_central_directory(&drifting), None); + // zip64 sentinels are declined rather than mis-read. + let mut zip64 = tail.clone(); + zip64[16..20].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(end_of_central_directory(&zip64), None); + // No record, no verdict. + assert_eq!(end_of_central_directory(b"PK\x03\x04 not a tail"), None); + assert_eq!(end_of_central_directory(&[]), None); + } + + #[test] + fn a_refinement_must_be_specific_different_and_never_text() { + assert_eq!(refinement("application/zip", Some("image/png")), Some("image/png")); + assert_eq!(refinement("image/png", Some("image/png")), None, "no rewrite of the same value"); + assert_eq!(refinement("application/zip", Some("text/plain")), None, "windows cannot prove text"); + assert_eq!(refinement("application/zip", Some("application/zip")), None, "never narrowed"); + assert_eq!(refinement("application/zip", Some("application/octet-stream")), None); + assert_eq!(refinement("application/zip", None), None); + } + + #[test] + fn an_opendocument_file_is_decided_from_the_head_window_alone() { + // The format requires the `mimetype` entry first, stored + // uncompressed: its marker is the first thing in the file. + let head = b"PK\x03\x04\x08\x00\x00\x00mimetypeapplication/vnd.oasis.opendocument.spreadsheet"; + match refine("application/zip", head, b"") { + Verdict::Settle(Some( + "application/vnd.oasis.opendocument.spreadsheet", + )) => {} + other => panic!("expected a settled spreadsheet, got {other:?}"), + } + // And the directory search, which reads entry names only, never + // claims one — the marker is entry content, not an entry name. + assert_eq!(office_entry_mime(head), None); + } +} diff --git a/crates/izlek-core/src/store/turso_store.rs b/crates/izlek-core/src/store/turso_store.rs index 63962db..6347b92 100644 --- a/crates/izlek-core/src/store/turso_store.rs +++ b/crates/izlek-core/src/store/turso_store.rs @@ -10,7 +10,7 @@ use rand::Rng; use time::{Duration, OffsetDateTime}; use time::format_description::well_known::Rfc3339; use turso::transaction::{Transaction, TransactionBehavior}; -use turso::{Builder, Connection, Row, Value, params}; +use turso::{Builder, Connection, Row, Value, params, params_from_iter}; use ulid::Ulid; use super::secret; @@ -21,7 +21,7 @@ use super::{ SenderCheck, SenderTest, Session, SigninLink, Store, StoreError, Tag, TaskCreated, Trigger, User, UserStats, Workspace, LinkKind, }; -use super::{reconcile, ReconcileOptions, schema}; +use super::{reconcile, ReconcileOptions, schema, sniff}; use crate::Role; use crate::board::{BoardMeta, BoardReads, Column, Moved, Person, TagChip, TaskRow, Transition}; use crate::detail::{ @@ -124,6 +124,7 @@ impl TursoStore { }; store.migrate(path).await?; store.encrypt_plaintext_passwords().await?; + store.resniff_generic_attachments().await?; // The file may have been rebuilt from a backup; its permissions and // any transient WAL/SHM siblings should still be private. if path != ":memory:" { @@ -172,6 +173,107 @@ impl TursoStore { Ok(()) } + /// Re-decides the stored type of attachments whose `mime_type` is one of + /// [`sniff::GENERIC_MIME_TYPES`] — rows written before the sniffer could + /// name OOXML files, which a file chip then renders as a plain download + /// because the viewer routes on the stored type alone. It runs here, once + /// per boot, for the same reason the password-sealing pass above does: it + /// is a data repair no migration can express, and a boot is the one moment + /// the store may rewrite what uploads wrote. It is idempotent by + /// construction — a row the pass refines leaves the generic buckets and is + /// never read again, and a row the bytes cannot settle is left exactly as + /// stored. Nothing is ever narrowed: the only verdicts written back are + /// specific mime types that differ from what is stored. + /// + /// Cheap by design. The pass opens with a count of generic rows and, when + /// there are none — every database after one pass, and every database + /// whose uploads all postdate the sniffer — reads no blob bytes at all. + /// Otherwise each such row donates two windows, the first + /// [`sniff::HEAD_WINDOW`] and last [`sniff::TAIL_WINDOW`] bytes, and only + /// when the windows find a zip with no office marker in them does the row + /// give up its central directory: the complete entry list, in which every + /// entry name the file has appears, so a pptx or xlsx cannot hide its + /// `ppt/presentation.xml` or `xl/workbook.xml` from the sweep. A window + /// verdict is never trusted for `text/plain` — a window cannot prove a + /// whole blob is UTF-8 — and a directory the end record locates beyond + /// [`sniff::DIRECTORY_CAP`], or a zip64 one, is left unread and the row + /// left alone. + async fn resniff_generic_attachments(&self) -> Result<()> { + let buckets = sniff::GENERIC_MIME_TYPES; + let marks = (1..=buckets.len()) + .map(|i| format!("?{i}")) + .collect::>() + .join(", "); + let conn = self.conn.lock().await; + + // The existence probe the whole pass hangs off: one count of a short + // text column, no blob reads, and the common case is done here. + let mut rows = conn + .query( + &format!("SELECT COUNT(*) FROM attachment WHERE mime_type IN ({marks})"), + params_from_iter(buckets.iter().copied()), + ) + .await + .map_err(backend)?; + let count = match rows.next().await.map_err(backend)? { + Some(row) => row.get::(0).map_err(backend)?, + None => 0, + }; + if count == 0 { + return Ok(()); + } + + let mut rows = conn + .query( + &format!( + "SELECT id, mime_type, substr(bytes, 1, {head}), substr(bytes, -{tail}) \ + FROM attachment WHERE mime_type IN ({marks})", + head = sniff::HEAD_WINDOW, + tail = sniff::TAIL_WINDOW, + marks = marks, + ), + params_from_iter(buckets.iter().copied()), + ) + .await + .map_err(backend)?; + let mut pending = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + let id = text(&row, 0)?; + let stored = text(&row, 1)?; + let head: Vec = row.get(2).map_err(backend)?; + let tail: Vec = row.get(3).map_err(backend)?; + let candidate = match sniff::refine(&stored, &head, &tail) { + sniff::Verdict::Settle(candidate) => candidate, + sniff::Verdict::ReadDirectory { offset, size } => { + let len = size.min(sniff::DIRECTORY_CAP as u64) as i64; + let mut directory = conn + .query( + "SELECT substr(bytes, ?1, ?2) FROM attachment WHERE id = ?3", + params![offset as i64 + 1, len, id.clone()], + ) + .await + .map_err(backend)?; + match directory.next().await.map_err(backend)? { + Some(row) => sniff::office_entry_mime(&row.get::>(0).map_err(backend)?), + None => None, + } + } + }; + if let Some(mime) = sniff::refinement(&stored, candidate) { + pending.push((mime, id)); + } + } + for (mime, id) in pending { + conn.execute( + "UPDATE attachment SET mime_type = ?1 WHERE id = ?2", + params![mime, id], + ) + .await + .map_err(backend)?; + } + Ok(()) + } + /// Brings the database to the declared schema. /// /// - An empty database is created from `migrations/0001_init.sql`. diff --git a/crates/izlek-core/tests/store.rs b/crates/izlek-core/tests/store.rs index c56b2e8..4073e26 100644 --- a/crates/izlek-core/tests/store.rs +++ b/crates/izlek-core/tests/store.rs @@ -9522,3 +9522,253 @@ async fn reconcile_backfills_watches_from_history_exactly_once() { let _ = std::fs::remove_dir_all(&dir); } + +// --------------------------------------------------------------------------- +// Boot-time re-sniff — attachments uploaded before the sniffer could name +// OOXML files froze on a generic bucket, and the viewer routes on the stored +// type alone, so an old .pptx used to render as a plain download. Opening a +// store runs the pass: these tests plant old-style rows, then open, then read +// back what the rows became. +// --------------------------------------------------------------------------- + +/// A zip of the named entries, contents irrelevant: the sniffer reads the +/// entry names a zip stores uncompressed. +fn zip_with(names: &[&str]) -> Vec { + use std::io::Write as _; + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for name in names { + zip.start_file(*name, zip::write::SimpleFileOptions::default()) + .unwrap(); + zip.write_all(b"").unwrap(); + } + zip.finish().unwrap().into_inner() +} + +/// A zip whose only office marker sits in its central directory, beyond both +/// boot windows: the filler entries before the marked one push its local +/// header past the head window, and the filler entries after it push its +/// directory record past the tail window — the shape only the directory +/// read can settle. +fn deep_zip(before: usize, after: usize) -> Vec { + use std::io::Write as _; + let mut names: Vec = (0..before).map(|i| format!("head/filler{i}.bin")).collect(); + names.push("ppt/presentation.xml".into()); + names.extend((0..after).map(|i| format!("tail/filler{i}.bin"))); + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for name in &names { + zip.start_file(name.as_str(), zip::write::SimpleFileOptions::default()) + .unwrap(); + zip.write_all(&[b'x'; 64]).unwrap(); + } + zip.finish().unwrap().into_inner() +} + +/// Whether the boot windows of `bytes` hold `marker` — the premise the deep +/// zip's test stands on, checked rather than assumed. +fn windows_hold(bytes: &[u8], marker: &[u8]) -> bool { + let head = &bytes[..bytes.len().min(izlek_core::store::sniff::HEAD_WINDOW as usize)]; + let tail = &bytes[bytes.len().saturating_sub(izlek_core::store::sniff::TAIL_WINDOW as usize)..]; + head.windows(marker.len()).any(|w| w == marker) + || tail.windows(marker.len()).any(|w| w == marker) +} + +/// OLE container bytes: the compound-file magic, then optionally the UTF-16 +/// `Workbook` stream name an .xls directory carries. +fn ole_bytes(with_workbook: bool) -> Vec { + let mut bytes = vec![0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]; + bytes.extend_from_slice(&[0; 512]); + if with_workbook { + bytes.extend_from_slice(b"W\0o\0r\0k\0b\0o\0o\0k\0"); + } + bytes +} + +/// A scratch database carrying old-style attachment rows: real bytes under +/// the generic mime a pre-sniffer upload froze on. The first open creates +/// the schema and finds nothing to do; the rows go in through a raw +/// connection; the caller then opens the store again, which runs the pass. +struct Planted { + dir: PathBuf, + path: String, +} + +impl Planted { + async fn plant(rows: &[(&str, &str, Vec)]) -> Self { + let dir = std::env::temp_dir().join(format!("izlek-resniff-{}", Ulid::new())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("izlek.db").to_str().unwrap().to_string(); + drop(TursoStore::open(&path).await.unwrap()); + let db = turso::Builder::new_local(&path).build().await.unwrap(); + let conn = db.connect().unwrap(); + for (id, mime, bytes) in rows { + conn.execute( + "INSERT INTO attachment (id, task_id, file_name, mime_type, size_bytes, \ + bytes, uploaded_by, created_at) \ + VALUES (?1, 'T1', 'old.bin', ?2, ?3, ?4, 'U1', '2026-08-01T00:00:00Z')", + turso::params![id, mime, bytes.len() as i64, bytes.clone()], + ) + .await + .unwrap(); + } + drop(conn); + drop(db); + Self { dir, path } + } + + fn path(&self) -> &str { + &self.path + } + + async fn open(&self) -> TursoStore { + TursoStore::open(self.path()).await.unwrap() + } +} + +impl Drop for Planted { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +#[tokio::test] +async fn a_zip_mime_presentation_becomes_the_slides_mime_on_the_next_boot() { + let planted = Planted::plant(&[( + "FA", + "application/zip", + zip_with(&["ppt/presentation.xml", "ppt/slides/slide1.xml"]), + )]) + .await; + let store = planted.open().await; + assert_eq!( + store.attachment("FA").await.unwrap().unwrap().mime_type, + "application/vnd.openxmlformats-officedocument.presentationml.presentation", + "the mime `viewer_kind` routes to the Slides overlay" + ); +} + +#[tokio::test] +async fn a_zip_mime_workbook_becomes_the_sheet_mime_on_the_next_boot() { + let planted = Planted::plant(&[( + "FB", + "application/zip", + zip_with(&["xl/workbook.xml", "xl/worksheets/sheet1.xml"]), + )]) + .await; + let store = planted.open().await; + assert_eq!( + store.attachment("FB").await.unwrap().unwrap().mime_type, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "the mime `is_spreadsheet` routes to the Sheet overlay" + ); +} + +#[tokio::test] +async fn an_ole_container_without_a_workbook_stream_stays_as_stored() { + let planted = Planted::plant(&[( + "FC", + "application/x-ole-storage", + ole_bytes(false), + )]) + .await; + let store = planted.open().await; + assert_eq!( + store.attachment("FC").await.unwrap().unwrap().mime_type, + "application/x-ole-storage" + ); +} + +#[tokio::test] +async fn an_ole_container_with_a_workbook_stream_becomes_ms_excel() { + let planted = Planted::plant(&[( + "FD", + "application/x-ole-storage", + ole_bytes(true), + )]) + .await; + let store = planted.open().await; + assert_eq!( + store.attachment("FD").await.unwrap().unwrap().mime_type, + "application/vnd.ms-excel" + ); +} + +/// Every stored type the pass could touch but never should: specific rows +/// wear no generic bucket, so the probe finds nothing and no blob moves — +/// which is also why there is nothing here to un-write on the next boot. +#[tokio::test] +async fn specific_mimes_survive_a_boot_pass_that_has_nothing_to_do() { + let png = { + let mut bytes = vec![0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; + bytes.extend_from_slice(&[0; 64]); + bytes + }; + let planted = Planted::plant(&[ + ("FE", "image/png", png), + ("FF", "application/pdf", b"%PDF-1.4 nothing to see".to_vec()), + ("FG", "text/plain", b"plainly text".to_vec()), + ]) + .await; + let store = planted.open().await; + assert_eq!(store.attachment("FE").await.unwrap().unwrap().mime_type, "image/png"); + assert_eq!(store.attachment("FF").await.unwrap().unwrap().mime_type, "application/pdf"); + assert_eq!(store.attachment("FG").await.unwrap().unwrap().mime_type, "text/plain"); +} + +#[tokio::test] +async fn a_plain_zip_stays_a_plain_zip_across_the_boot_pass() { + let planted = Planted::plant(&[( + "FH", + "application/zip", + zip_with(&["notes.txt", "data/blob.bin"]), + )]) + .await; + let store = planted.open().await; + assert_eq!( + store.attachment("FH").await.unwrap().unwrap().mime_type, + "application/zip" + ); +} + +#[tokio::test] +async fn a_presentation_hidden_beyond_both_windows_is_found_in_its_central_directory() { + let bytes = deep_zip(2000, 3000); + assert!( + !windows_hold(&bytes, b"ppt/presentation.xml"), + "the test's premise broke: the marker fell inside a boot window" + ); + let planted = Planted::plant(&[("FI", "application/zip", bytes)]).await; + let store = planted.open().await; + assert_eq!( + store.attachment("FI").await.unwrap().unwrap().mime_type, + "application/vnd.openxmlformats-officedocument.presentationml.presentation" + ); +} + +#[tokio::test] +async fn an_octet_stream_row_wearing_office_bytes_is_refined_too() { + let planted = Planted::plant(&[( + "FJ", + "application/octet-stream", + zip_with(&["ppt/presentation.xml", "ppt/slides/slide1.xml"]), + )]) + .await; + let store = planted.open().await; + assert_eq!( + store.attachment("FJ").await.unwrap().unwrap().mime_type, + "application/vnd.openxmlformats-officedocument.presentationml.presentation" + ); +} + +/// A window cannot prove a whole blob is UTF-8: an octet-stream row whose +/// head reads as text but whose tail is binary stays exactly what it is. +#[tokio::test] +async fn a_window_that_cannot_prove_text_keeps_the_octet_stream_bucket() { + let mut bytes = b"this front half is plainly text, ".to_vec(); + bytes.extend_from_slice(&[0x00, 0xFF, 0xFE, 0x80]); + let planted = Planted::plant(&[("FK", "application/octet-stream", bytes)]).await; + let store = planted.open().await; + assert_eq!( + store.attachment("FK").await.unwrap().unwrap().mime_type, + "application/octet-stream" + ); +} diff --git a/crates/izlek-web/Cargo.toml b/crates/izlek-web/Cargo.toml index 5cc334c..25bce65 100644 --- a/crates/izlek-web/Cargo.toml +++ b/crates/izlek-web/Cargo.toml @@ -44,7 +44,7 @@ calamine = { version = "0.36.1", default-features = false } # the same zip calamine opens for a workbook, read with the XML parser # already in the tree — both crates ride the lockfile as it stands. quick-xml = { version = "0.41.0", default-features = false } -zip = { version = "8.6.0", default-features = false, features = ["deflate"] } +zip.workspace = true # Hashes the compiled stylesheet against the bundle's bytes at boot, so a # bundle from another generation refuses the boot instead of serving under # this binary (see `server.rs`'s `stylesheet_guard`). diff --git a/crates/izlek-web/src/files.rs b/crates/izlek-web/src/files.rs index 76e837f..6e01978 100644 --- a/crates/izlek-web/src/files.rs +++ b/crates/izlek-web/src/files.rs @@ -14,6 +14,7 @@ use topcoat::router::{ HeaderMap, HeaderValue, StatusCode, header, path_param, query_params, route, }; +use izlek_core::store::sniff::sniff; use izlek_core::store::{NewAttachment, Store, User}; use crate::server::{Refusal, accounts, require_user}; @@ -115,91 +116,6 @@ fn mime_of_extension(ext: &str) -> Option<&'static str> { } } -/// What the bytes are, decided from the bytes themselves — never from the -/// part's `content_type()`, which is whatever the browser felt like sending. -pub(crate) fn sniff(bytes: &[u8]) -> &'static str { - if bytes.starts_with(&[0x89, 0x50, 0x4E, 0x47]) { - "image/png" - } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { - "image/jpeg" - } else if bytes.starts_with(b"GIF8") { - "image/gif" - } else if bytes.starts_with(b"%PDF-") { - "application/pdf" - } else if bytes.starts_with(b"PK\x03\x04") { - // Every OOXML and OpenDocument file is a zip; what kind it is lives in - // the entry names, which a zip stores uncompressed. `xl/workbook.xml` - // is the one part an xlsx cannot be without, an ods declares its - // type in the `mimetype` entry the format requires be stored first, - // and `ppt/presentation.xml` is the one part a pptx cannot be - // without. - if contains(bytes, b"xl/workbook.xml") { - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" - } else if contains(bytes, b"opendocument.spreadsheet") { - "application/vnd.oasis.opendocument.spreadsheet" - } else if contains(bytes, b"ppt/presentation.xml") { - "application/vnd.openxmlformats-officedocument.presentationml.presentation" - } else { - "application/zip" - } - } else if bytes.starts_with(&[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]) { - // The pre-2007 OLE compound file .xls, .doc and .ppt all share. Its - // directory holds stream names in UTF-16, and only a workbook carries - // one called `Workbook` — a .doc or .ppt stays an unnamed container. - if contains(bytes, b"W\0o\0r\0k\0b\0o\0o\0k\0") { - "application/vnd.ms-excel" - } else { - "application/x-ole-storage" - } - } else if bytes.starts_with(&[0x1F, 0x8B]) { - "application/gzip" - } else if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" && &bytes[8..12] == b"avif" { - "image/avif" - } else if bytes.len() >= 12 - && &bytes[4..8] == b"ftyp" - && matches!( - &bytes[8..12], - b"heic" | b"heix" | b"hevc" | b"heif" | b"mif1" | b"msf1" - ) - { - // Apple's HEIC container reuses the ISO-BMFF `ftyp` box video shares; - // the brand at bytes 8..12 is what tells a photo from a video apart. - "image/heic" - } else if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" && &bytes[8..12] == b"qt " { - "video/quicktime" - } else if bytes.len() >= 8 && &bytes[4..8] == b"ftyp" { - "video/mp4" - } else if bytes.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) { - "video/webm" - } else if bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP" { - "image/webp" - } else if bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WAVE" { - "audio/wav" - } else if bytes.starts_with(b"fLaC") { - "audio/flac" - } else if bytes.starts_with(b"OggS") { - "audio/ogg" - } else if bytes.starts_with(b"ID3") - || bytes.starts_with(&[0xFF, 0xFB]) - || bytes.starts_with(&[0xFF, 0xF3]) - || bytes.starts_with(&[0xFF, 0xF2]) - { - "audio/mpeg" - } else if std::str::from_utf8(bytes).is_ok() { - "text/plain" - } else { - "application/octet-stream" - } -} - -/// Whether `haystack` holds `needle` anywhere in it. Used on zip bytes, where -/// the entry names sit in the clear even when the entries themselves do not. -fn contains(haystack: &[u8], needle: &[u8]) -> bool { - haystack - .windows(needle.len()) - .any(|window| window == needle) -} - /// The `Content-Disposition` header for one download. `inline` is only ever /// true for a mime type a browser renders on its own ([`renders_inline`]) and /// the caller did not ask for a forced download (`?dl=1`) — an uploaded HTML @@ -579,48 +495,6 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> mod tests { use super::*; - #[test] - fn sniffs_the_magic_numbers() { - assert_eq!(sniff(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A]), "image/png"); - assert_eq!(sniff(&[0xFF, 0xD8, 0xFF, 0xE0]), "image/jpeg"); - assert_eq!(sniff(b"hello, this is plainly text"), "text/plain"); - assert_eq!( - sniff(&[0x00, 0x01, 0xFE, 0xFF, 0x02]), - "application/octet-stream" - ); - } - - #[test] - fn sniffs_the_media_types() { - assert_eq!( - sniff(b"\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00"), - "video/mp4" - ); - assert_eq!( - sniff(b"\x00\x00\x00\x18ftypavif\x00\x00\x00\x00"), - "image/avif" - ); - assert_eq!( - sniff(b"\x00\x00\x00\x18ftypheic\x00\x00\x00\x00"), - "image/heic" - ); - assert_eq!( - sniff(b"\x00\x00\x00\x18ftypmif1\x00\x00\x00\x00"), - "image/heic" - ); - assert_eq!( - sniff(b"\x00\x00\x00\x14ftypqt \x00\x00\x00\x00"), - "video/quicktime" - ); - assert_eq!(sniff(&[0x1A, 0x45, 0xDF, 0xA3, 0x00, 0x00]), "video/webm"); - assert_eq!(sniff(b"RIFF\x00\x00\x00\x00WEBPVP8 "), "image/webp"); - assert_eq!(sniff(b"RIFF\x00\x00\x00\x00WAVEfmt "), "audio/wav"); - assert_eq!(sniff(b"fLaC\x00\x00\x00\x00"), "audio/flac"); - assert_eq!(sniff(b"OggS\x00\x00\x00\x00"), "audio/ogg"); - assert_eq!(sniff(b"ID3\x03\x00\x00\x00"), "audio/mpeg"); - assert_eq!(sniff(&[0xFF, 0xFB, 0x90, 0x00]), "audio/mpeg"); - } - #[test] fn labels_strip_the_path_and_the_control_characters() { assert_eq!(label_of("../../etc/passwd"), "passwd"); @@ -737,29 +611,6 @@ mod tests { assert_eq!(accept_attribute(&[]), "", "no list, no attribute"); } - /// A zip of the named entries, bytes inside irrelevant: the sniff reads - /// the entry names a zip stores uncompressed. - fn zip_with(names: &[&str]) -> Vec { - use std::io::Write as _; - let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); - for name in names { - zip.start_file(*name, zip::write::SimpleFileOptions::default()) - .unwrap(); - zip.write_all(b"").unwrap(); - } - zip.finish().unwrap().into_inner() - } - - #[test] - fn a_presentation_sniffs_its_presentation_mime_and_a_plain_zip_stays_a_zip() { - let pptx = zip_with(&["ppt/presentation.xml", "ppt/slides/slide1.xml"]); - assert_eq!( - sniff(&pptx), - "application/vnd.openxmlformats-officedocument.presentationml.presentation" - ); - assert_eq!(sniff(&zip_with(&["notes.txt"])), "application/zip"); - } - #[test] fn an_ole_presentation_stays_download_only() { // The pre-2007 .ppt shares the OLE container magic with .doc and diff --git a/crates/izlek-web/src/photo.rs b/crates/izlek-web/src/photo.rs index 1c4bbc7..6cdc3be 100644 --- a/crates/izlek-web/src/photo.rs +++ b/crates/izlek-web/src/photo.rs @@ -10,7 +10,7 @@ use topcoat::router::content::multipart::Multipart; use topcoat::router::request::headers as request_headers; use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, path_param, route}; -use crate::files::sniff; +use izlek_core::store::sniff::sniff; use crate::server::{Refusal, accounts, require_user}; use crate::settings::saved_or_refused;