A boot pass re-sniffs attachments whose mime froze generic
Browse files at this commit18a5e7bd0ee6295a545bbb8c919c82e95b42ee87Parent: 1c39e3410 changed files +728 -155
- Cargo.lock +1 -0
- Cargo.toml +1 -0
- crates/izlek-core/Cargo.toml +1 -1
- crates/izlek-core/src/store/mod.rs +2 -0
- crates/izlek-core/src/store/sniff.rs +366 -0
- crates/izlek-core/src/store/turso_store.rs +104 -2
- crates/izlek-core/tests/store.rs +250 -0
- crates/izlek-web/Cargo.toml +1 -1
- crates/izlek-web/src/files.rs +1 -150
- crates/izlek-web/src/photo.rs +1 -1
Cargo.lockmodified+1 -0
| @@ -1795,6 +1795,7 @@ dependencies = [ | |||
| 1795 | "toml", | 1795 | "toml", |
| 1796 | "turso", | 1796 | "turso", |
| 1797 | "ulid", | 1797 | "ulid", |
| 1798 | + "zip", | ||
| 1798 | ] | 1799 | ] |
| 1799 | 1800 | ||
| 1800 | [[package]] | 1801 | [[package]] |
Cargo.tomlmodified+1 -0
| @@ -24,6 +24,7 @@ subtle = "2.6.1" | |||
| 24 | chacha20poly1305 = "0.10.1" | 24 | chacha20poly1305 = "0.10.1" |
| 25 | base64 = "0.22.1" | 25 | base64 = "0.22.1" |
| 26 | toml = "1" | 26 | toml = "1" |
| 27 | +zip = { version = "8.6.0", default-features = false, features = ["deflate"] } | ||
| 27 | 28 | ||
| 28 | [profile.release] | 29 | [profile.release] |
| 29 | codegen-units = 1 | 30 | codegen-units = 1 |
crates/izlek-core/Cargo.tomlmodified+1 -1
| @@ -45,4 +45,4 @@ ulid = { workspace = true, optional = true } | |||
| 45 | async-trait = "0.1.92" | 45 | async-trait = "0.1.92" |
| 46 | serde_json.workspace = true | 46 | serde_json.workspace = true |
| 47 | tokio = { workspace = true } | 47 | tokio = { workspace = true } |
| 48 | -turso = { workspace = true } | 48 | +zip.workspace = true |
crates/izlek-core/src/store/mod.rsmodified+2 -0
| @@ -17,6 +17,8 @@ pub mod secret; | |||
| 17 | #[cfg(feature = "server")] | 17 | #[cfg(feature = "server")] |
| 18 | pub mod reconcile; | 18 | pub mod reconcile; |
| 19 | #[cfg(feature = "server")] | 19 | #[cfg(feature = "server")] |
| 20 | +pub mod sniff; | ||
| 21 | +#[cfg(feature = "server")] | ||
| 20 | pub mod schema; | 22 | pub mod schema; |
| 21 | pub mod turso_store; | 23 | pub mod turso_store; |
| 22 | 24 | ||
crates/izlek-core/src/store/sniff.rsadded+366 -0
| @@ -0,0 +1,366 @@ | |||
| 1 | +//! What uploaded bytes are, decided from the bytes themselves — never from a | ||
| 2 | +//! part's `content_type()`, which is whatever the browser felt like sending. | ||
| 3 | +//! | ||
| 4 | +//! Pure `bytes -> mime`, with no I/O and nothing browser-shaped in it, living | ||
| 5 | +//! behind the same `server` gate as the store it serves. The upload path | ||
| 6 | +//! sniffs a file once when it arrives; [`TursoStore::open`] additionally runs | ||
| 7 | +//! [`refine`] over rows whose stored type is one of the [`GENERIC_MIME_TYPES`] | ||
| 8 | +//! buckets, so attachments written before the sniffer could name OOXML files | ||
| 9 | +//! come out of the next restart carrying their real type. One definition | ||
| 10 | +//! serves both callers: the store cannot reach the web crate, and a second | ||
| 11 | +//! sniffer would drift. | ||
| 12 | + | ||
| 13 | +/// The mime types the upload path can store that name nothing: a zip that is | ||
| 14 | +/// not an office document, bytes no magic matched, and an OLE container with | ||
| 15 | +/// no stream name to narrow it. The boot pass reads only rows wearing one of | ||
| 16 | +/// these; `text/plain` is deliberately absent — no window of a text file can | ||
| 17 | +/// ever refine it, so sweeping it would read every text blob on every boot | ||
| 18 | +/// for a guaranteed no-op. | ||
| 19 | +pub const GENERIC_MIME_TYPES: &[&str] = &[ | ||
| 20 | + "application/zip", | ||
| 21 | + "application/octet-stream", | ||
| 22 | + "application/x-ole-storage", | ||
| 23 | +]; | ||
| 24 | + | ||
| 25 | +/// Head bytes read per generic row: every prefix-magic format this sniffer | ||
| 26 | +/// knows decides from the first bytes, an OpenDocument file's `mimetype` | ||
| 27 | +/// entry is required to be the first thing in the file, and an OLE | ||
| 28 | +/// container's directory sectors precede its stream data. | ||
| 29 | +pub const HEAD_WINDOW: i64 = 64 * 1024; | ||
| 30 | +/// Tail bytes read per generic row. A zip ends with its end-of-central- | ||
| 31 | +/// directory record, which — comment included — can sit at most | ||
| 32 | +/// 22 + 65535 bytes from the end of the file, so a tail this wide can never | ||
| 33 | +/// miss it, and it usually holds much of the central directory besides. | ||
| 34 | +pub const TAIL_WINDOW: i64 = 128 * 1024; | ||
| 35 | +/// A central directory larger than this — tens of thousands of entries — is | ||
| 36 | +/// left unread and the row left exactly as stored. | ||
| 37 | +pub const DIRECTORY_CAP: i64 = 4 * 1024 * 1024; | ||
| 38 | + | ||
| 39 | +pub fn sniff(bytes: &[u8]) -> &'static str { | ||
| 40 | + if bytes.starts_with(&[0x89, 0x50, 0x4E, 0x47]) { | ||
| 41 | + "image/png" | ||
| 42 | + } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { | ||
| 43 | + "image/jpeg" | ||
| 44 | + } else if bytes.starts_with(b"GIF8") { | ||
| 45 | + "image/gif" | ||
| 46 | + } else if bytes.starts_with(b"%PDF-") { | ||
| 47 | + "application/pdf" | ||
| 48 | + } else if bytes.starts_with(b"PK\x03\x04") { | ||
| 49 | + // Every OOXML and OpenDocument file is a zip; what kind it is lives in | ||
| 50 | + // the entry names, which a zip stores uncompressed. `xl/workbook.xml` | ||
| 51 | + // is the one part an xlsx cannot be without, an ods declares its | ||
| 52 | + // type in the `mimetype` entry the format requires be stored first, | ||
| 53 | + // and `ppt/presentation.xml` is the one part a pptx cannot be | ||
| 54 | + // without. | ||
| 55 | + zip_mime(bytes) | ||
| 56 | + } else if bytes.starts_with(&[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]) { | ||
| 57 | + // The pre-2007 OLE compound file .xls, .doc and .ppt all share. Its | ||
| 58 | + // directory holds stream names in UTF-16, and only a workbook carries | ||
| 59 | + // one called `Workbook` — a .doc or .ppt stays an unnamed container. | ||
| 60 | + if contains(bytes, b"W\0o\0r\0k\0b\0o\0o\0k\0") { | ||
| 61 | + "application/vnd.ms-excel" | ||
| 62 | + } else { | ||
| 63 | + "application/x-ole-storage" | ||
| 64 | + } | ||
| 65 | + } else if bytes.starts_with(&[0x1F, 0x8B]) { | ||
| 66 | + "application/gzip" | ||
| 67 | + } else if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" && &bytes[8..12] == b"avif" { | ||
| 68 | + "image/avif" | ||
| 69 | + } else if bytes.len() >= 12 | ||
| 70 | + && &bytes[4..8] == b"ftyp" | ||
| 71 | + && matches!( | ||
| 72 | + &bytes[8..12], | ||
| 73 | + b"heic" | b"heix" | b"hevc" | b"heif" | b"mif1" | b"msf1" | ||
| 74 | + ) | ||
| 75 | + { | ||
| 76 | + // Apple's HEIC container reuses the ISO-BMFF `ftyp` box video shares; | ||
| 77 | + // the brand at bytes 8..12 is what tells a photo from a video apart. | ||
| 78 | + "image/heic" | ||
| 79 | + } else if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" && &bytes[8..12] == b"qt " { | ||
| 80 | + "video/quicktime" | ||
| 81 | + } else if bytes.len() >= 8 && &bytes[4..8] == b"ftyp" { | ||
| 82 | + "video/mp4" | ||
| 83 | + } else if bytes.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) { | ||
| 84 | + "video/webm" | ||
| 85 | + } else if bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP" { | ||
| 86 | + "image/webp" | ||
| 87 | + } else if bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WAVE" { | ||
| 88 | + "audio/wav" | ||
| 89 | + } else if bytes.starts_with(b"fLaC") { | ||
| 90 | + "audio/flac" | ||
| 91 | + } else if bytes.starts_with(b"OggS") { | ||
| 92 | + "audio/ogg" | ||
| 93 | + } else if bytes.starts_with(b"ID3") | ||
| 94 | + || bytes.starts_with(&[0xFF, 0xFB]) | ||
| 95 | + || bytes.starts_with(&[0xFF, 0xF3]) | ||
| 96 | + || bytes.starts_with(&[0xFF, 0xF2]) | ||
| 97 | + { | ||
| 98 | + "audio/mpeg" | ||
| 99 | + } else if std::str::from_utf8(bytes).is_ok() { | ||
| 100 | + "text/plain" | ||
| 101 | + } else { | ||
| 102 | + "application/octet-stream" | ||
| 103 | + } | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +/// Which office document a zip's bytes declare, decided the way every reader | ||
| 107 | +/// of the format does: by the entry names a zip stores uncompressed. Ends in | ||
| 108 | +/// [`GENERIC_MIME_TYPES`]' zip bucket when the names name nothing. | ||
| 109 | +fn zip_mime(bytes: &[u8]) -> &'static str { | ||
| 110 | + if contains(bytes, b"xl/workbook.xml") { | ||
| 111 | + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" | ||
| 112 | + } else if contains(bytes, b"opendocument.spreadsheet") { | ||
| 113 | + "application/vnd.oasis.opendocument.spreadsheet" | ||
| 114 | + } else if contains(bytes, b"ppt/presentation.xml") { | ||
| 115 | + "application/vnd.openxmlformats-officedocument.presentationml.presentation" | ||
| 116 | + } else { | ||
| 117 | + "application/zip" | ||
| 118 | + } | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +/// Whether `haystack` holds `needle` anywhere in it. Used on zip bytes, where | ||
| 122 | +/// the entry names sit in the clear even when the entries themselves do not. | ||
| 123 | +fn contains(haystack: &[u8], needle: &[u8]) -> bool { | ||
| 124 | + haystack | ||
| 125 | + .windows(needle.len()) | ||
| 126 | + .any(|window| window == needle) | ||
| 127 | +} | ||
| 128 | + | ||
| 129 | +/// The office mime declared by the zip entry names in `bytes` — the central | ||
| 130 | +/// directory's vocabulary, where every entry a file holds is listed. An | ||
| 131 | +/// OpenDocument file is deliberately absent: its marker is the *content* of | ||
| 132 | +/// the `mimetype` entry the format requires be stored first, not an entry | ||
| 133 | +/// name, so it is decided from the head window and could never be found here. | ||
| 134 | +pub(crate) fn office_entry_mime(bytes: &[u8]) -> Option<&'static str> { | ||
| 135 | + if contains(bytes, b"xl/workbook.xml") { | ||
| 136 | + Some("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") | ||
| 137 | + } else if contains(bytes, b"ppt/presentation.xml") { | ||
| 138 | + Some("application/vnd.openxmlformats-officedocument.presentationml.presentation") | ||
| 139 | + } else { | ||
| 140 | + None | ||
| 141 | + } | ||
| 142 | +} | ||
| 143 | + | ||
| 144 | +/// What one generic row's byte windows decided. | ||
| 145 | +#[derive(Debug)] | ||
| 146 | +pub(crate) enum Verdict { | ||
| 147 | + /// Nothing left to read. `Some` is a candidate more specific than the | ||
| 148 | + /// stored bucket (subject to [`refinement`]), `None` means the windows | ||
| 149 | + /// could not improve on what is stored — and, for a zip, never will: | ||
| 150 | + /// whatever the central directory says, the search already covered it. | ||
| 151 | + Settle(Option<&'static str>), | ||
| 152 | + /// A zip whose windows name no office part. `offset`/`size` locate the | ||
| 153 | + /// central directory as the end record states them; reading it is the | ||
| 154 | + /// last word, because every entry name the file has is listed there. | ||
| 155 | + ReadDirectory { offset: u64, size: u64 }, | ||
| 156 | +} | ||
| 157 | + | ||
| 158 | +/// Decides a generic row from its head and tail windows alone. When the | ||
| 159 | +/// windows themselves hold a verdict it settles; only a zip with no office | ||
| 160 | +/// marker in either window asks for the central directory. | ||
| 161 | +pub(crate) fn refine(stored: &str, head: &[u8], tail: &[u8]) -> Verdict { | ||
| 162 | + let mut windows = Vec::with_capacity(head.len() + tail.len()); | ||
| 163 | + windows.extend_from_slice(head); | ||
| 164 | + windows.extend_from_slice(tail); | ||
| 165 | + match sniff(&windows) { | ||
| 166 | + "application/zip" => match end_of_central_directory(tail) { | ||
| 167 | + Some((offset, size)) => Verdict::ReadDirectory { offset, size }, | ||
| 168 | + None => Verdict::Settle(None), | ||
| 169 | + }, | ||
| 170 | + candidate => Verdict::Settle(refinement(stored, Some(candidate))), | ||
| 171 | + } | ||
| 172 | +} | ||
| 173 | + | ||
| 174 | +/// Whether `candidate` may replace `stored`: something specific, something | ||
| 175 | +/// other than what is stored, and never `text/plain` — a window cannot prove | ||
| 176 | +/// a whole blob is UTF-8, so a text verdict out of windows is unverifiable, | ||
| 177 | +/// and a text row would gain nothing from the sweep anyway. Everything else | ||
| 178 | +/// the sniffer names is either a prefix-magic fact (true of the whole blob | ||
| 179 | +/// when true of its head) or an office marker, both safe to act on. | ||
| 180 | +pub(crate) fn refinement(stored: &str, candidate: Option<&'static str>) -> Option<&'static str> { | ||
| 181 | + let candidate = candidate?; | ||
| 182 | + if candidate == stored | ||
| 183 | + || candidate == "text/plain" | ||
| 184 | + || GENERIC_MIME_TYPES.contains(&candidate) | ||
| 185 | + { | ||
| 186 | + return None; | ||
| 187 | + } | ||
| 188 | + Some(candidate) | ||
| 189 | +} | ||
| 190 | + | ||
| 191 | +/// The end-of-central-directory record every zip ends with: `PK\x05\x06`, | ||
| 192 | +/// then the directory's size (12..16) and offset (16..20), then a comment | ||
| 193 | +/// whose declared length must land exactly at the end of the bytes. Scanning | ||
| 194 | +/// from the end, the first signature satisfying that anchor is the record. | ||
| 195 | +/// `None` when there is none to trust: no record at all, or a zip64 one — | ||
| 196 | +/// the `u32::MAX` sentinels say the real numbers live in a zip64 locator | ||
| 197 | +/// this pass declines to parse, and a row it declines stays as stored. | ||
| 198 | +pub(crate) fn end_of_central_directory(tail: &[u8]) -> Option<(u64, u64)> { | ||
| 199 | + if tail.len() < 22 { | ||
| 200 | + return None; | ||
| 201 | + } | ||
| 202 | + for i in (0..=tail.len() - 22).rev() { | ||
| 203 | + if &tail[i..i + 4] != b"PK\x05\x06" { | ||
| 204 | + continue; | ||
| 205 | + } | ||
| 206 | + let comment = u16::from_le_bytes([tail[i + 20], tail[i + 21]]) as usize; | ||
| 207 | + if i + 22 + comment != tail.len() { | ||
| 208 | + continue; | ||
| 209 | + } | ||
| 210 | + let size = u32::from_le_bytes(tail[i + 12..i + 16].try_into().ok()?) as u64; | ||
| 211 | + let offset = u32::from_le_bytes(tail[i + 16..i + 20].try_into().ok()?) as u64; | ||
| 212 | + if offset == u32::MAX as u64 || size == u32::MAX as u64 { | ||
| 213 | + return None; | ||
| 214 | + } | ||
| 215 | + return Some((offset, size)); | ||
| 216 | + } | ||
| 217 | + None | ||
| 218 | +} | ||
| 219 | + | ||
| 220 | +#[cfg(test)] | ||
| 221 | +mod tests { | ||
| 222 | + use super::*; | ||
| 223 | + | ||
| 224 | + #[test] | ||
| 225 | + fn sniffs_the_magic_numbers() { | ||
| 226 | + assert_eq!(sniff(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A]), "image/png"); | ||
| 227 | + assert_eq!(sniff(&[0xFF, 0xD8, 0xFF, 0xE0]), "image/jpeg"); | ||
| 228 | + assert_eq!(sniff(b"hello, this is plainly text"), "text/plain"); | ||
| 229 | + assert_eq!( | ||
| 230 | + sniff(&[0x00, 0x01, 0xFE, 0xFF, 0x02]), | ||
| 231 | + "application/octet-stream" | ||
| 232 | + ); | ||
| 233 | + } | ||
| 234 | + | ||
| 235 | + #[test] | ||
| 236 | + fn sniffs_the_media_types() { | ||
| 237 | + assert_eq!( | ||
| 238 | + sniff(b"\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00"), | ||
| 239 | + "video/mp4" | ||
| 240 | + ); | ||
| 241 | + assert_eq!( | ||
| 242 | + sniff(b"\x00\x00\x00\x18ftypavif\x00\x00\x00\x00"), | ||
| 243 | + "image/avif" | ||
| 244 | + ); | ||
| 245 | + assert_eq!( | ||
| 246 | + sniff(b"\x00\x00\x00\x18ftypheic\x00\x00\x00\x00"), | ||
| 247 | + "image/heic" | ||
| 248 | + ); | ||
| 249 | + assert_eq!( | ||
| 250 | + sniff(b"\x00\x00\x00\x18ftypmif1\x00\x00\x00\x00"), | ||
| 251 | + "image/heic" | ||
| 252 | + ); | ||
| 253 | + assert_eq!( | ||
| 254 | + sniff(b"\x00\x00\x00\x14ftypqt \x00\x00\x00\x00"), | ||
| 255 | + "video/quicktime" | ||
| 256 | + ); | ||
| 257 | + assert_eq!(sniff(&[0x1A, 0x45, 0xDF, 0xA3, 0x00, 0x00]), "video/webm"); | ||
| 258 | + assert_eq!(sniff(b"RIFF\x00\x00\x00\x00WEBPVP8 "), "image/webp"); | ||
| 259 | + assert_eq!(sniff(b"RIFF\x00\x00\x00\x00WAVEfmt "), "audio/wav"); | ||
| 260 | + assert_eq!(sniff(b"fLaC\x00\x00\x00\x00"), "audio/flac"); | ||
| 261 | + assert_eq!(sniff(b"OggS\x00\x00\x00\x00"), "audio/ogg"); | ||
| 262 | + assert_eq!(sniff(b"ID3\x03\x00\x00\x00"), "audio/mpeg"); | ||
| 263 | + assert_eq!(sniff(&[0xFF, 0xFB, 0x90, 0x00]), "audio/mpeg"); | ||
| 264 | + } | ||
| 265 | + | ||
| 266 | + /// A zip of the named entries, bytes inside irrelevant: the sniff reads | ||
| 267 | + /// the entry names a zip stores uncompressed. | ||
| 268 | + fn zip_with(names: &[&str]) -> Vec<u8> { | ||
| 269 | + use std::io::Write as _; | ||
| 270 | + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); | ||
| 271 | + for name in names { | ||
| 272 | + zip.start_file(*name, zip::write::SimpleFileOptions::default()) | ||
| 273 | + .unwrap(); | ||
| 274 | + zip.write_all(b"<xml/>").unwrap(); | ||
| 275 | + } | ||
| 276 | + zip.finish().unwrap().into_inner() | ||
| 277 | + } | ||
| 278 | + | ||
| 279 | + #[test] | ||
| 280 | + fn a_presentation_sniffs_its_presentation_mime_and_a_plain_zip_stays_a_zip() { | ||
| 281 | + let pptx = zip_with(&["ppt/presentation.xml", "ppt/slides/slide1.xml"]); | ||
| 282 | + assert_eq!( | ||
| 283 | + sniff(&pptx), | ||
| 284 | + "application/vnd.openxmlformats-officedocument.presentationml.presentation" | ||
| 285 | + ); | ||
| 286 | + assert_eq!(sniff(&zip_with(&["notes.txt"])), "application/zip"); | ||
| 287 | + } | ||
| 288 | + | ||
| 289 | + #[test] | ||
| 290 | + fn a_workbook_declared_only_in_its_central_directory_is_found_by_the_directory_search() { | ||
| 291 | + let bytes = zip_with(&["ppt/presentation.xml", "ppt/slides/slide1.xml"]); | ||
| 292 | + let head = &bytes[..bytes.len() / 2]; | ||
| 293 | + // Both windows of a cut in half hold the marker, so the windows alone | ||
| 294 | + // settle a small file. | ||
| 295 | + assert!(contains(head, b"ppt/presentation.xml")); | ||
| 296 | + match refine("application/zip", head, &bytes[bytes.len() / 2..]) { | ||
| 297 | + Verdict::Settle(Some( | ||
| 298 | + "application/vnd.openxmlformats-officedocument.presentationml.presentation", | ||
| 299 | + )) => {} | ||
| 300 | + other => panic!("expected a settled presentation, got {other:?}"), | ||
| 301 | + } | ||
| 302 | + // The real end record survives its move into the synthetic tail. | ||
| 303 | + let (offset, size) = end_of_central_directory(&bytes).expect("a real zip has an EOCD"); | ||
| 304 | + let directory = &bytes[offset as usize..(offset + size) as usize]; | ||
| 305 | + assert_eq!( | ||
| 306 | + office_entry_mime(directory), | ||
| 307 | + Some("application/vnd.openxmlformats-officedocument.presentationml.presentation") | ||
| 308 | + ); | ||
| 309 | + } | ||
| 310 | + | ||
| 311 | + #[test] | ||
| 312 | + fn an_eocd_is_found_by_its_anchor_and_declined_when_zip64_or_absent() { | ||
| 313 | + // A hand-built record: signature, the two disk fields, two entry | ||
| 314 | + // counts, size, offset, a one-byte comment. | ||
| 315 | + let mut tail = Vec::new(); | ||
| 316 | + tail.extend_from_slice(b"PK\x05\x06"); | ||
| 317 | + tail.extend_from_slice(&[0, 0, 0, 0]); // disk numbers | ||
| 318 | + tail.extend_from_slice(&[1, 0, 1, 0]); // entry counts | ||
| 319 | + tail.extend_from_slice(&0x1122_3344u32.to_le_bytes()); // size | ||
| 320 | + tail.extend_from_slice(&0x5566_7788u32.to_le_bytes()); // offset | ||
| 321 | + tail.extend_from_slice(&1u16.to_le_bytes()); // comment length | ||
| 322 | + tail.push(b'!'); | ||
| 323 | + assert_eq!( | ||
| 324 | + end_of_central_directory(&tail), | ||
| 325 | + Some((0x5566_7788, 0x1122_3344)) | ||
| 326 | + ); | ||
| 327 | + // A lie about the comment length leaves the record unanchored. | ||
| 328 | + let mut drifting = tail.clone(); | ||
| 329 | + *drifting.last_mut().unwrap() = b'?'; | ||
| 330 | + drifting.push(b'!'); | ||
| 331 | + assert_eq!(end_of_central_directory(&drifting), None); | ||
| 332 | + // zip64 sentinels are declined rather than mis-read. | ||
| 333 | + let mut zip64 = tail.clone(); | ||
| 334 | + zip64[16..20].copy_from_slice(&u32::MAX.to_le_bytes()); | ||
| 335 | + assert_eq!(end_of_central_directory(&zip64), None); | ||
| 336 | + // No record, no verdict. | ||
| 337 | + assert_eq!(end_of_central_directory(b"PK\x03\x04 not a tail"), None); | ||
| 338 | + assert_eq!(end_of_central_directory(&[]), None); | ||
| 339 | + } | ||
| 340 | + | ||
| 341 | + #[test] | ||
| 342 | + fn a_refinement_must_be_specific_different_and_never_text() { | ||
| 343 | + assert_eq!(refinement("application/zip", Some("image/png")), Some("image/png")); | ||
| 344 | + assert_eq!(refinement("image/png", Some("image/png")), None, "no rewrite of the same value"); | ||
| 345 | + assert_eq!(refinement("application/zip", Some("text/plain")), None, "windows cannot prove text"); | ||
| 346 | + assert_eq!(refinement("application/zip", Some("application/zip")), None, "never narrowed"); | ||
| 347 | + assert_eq!(refinement("application/zip", Some("application/octet-stream")), None); | ||
| 348 | + assert_eq!(refinement("application/zip", None), None); | ||
| 349 | + } | ||
| 350 | + | ||
| 351 | + #[test] | ||
| 352 | + fn an_opendocument_file_is_decided_from_the_head_window_alone() { | ||
| 353 | + // The format requires the `mimetype` entry first, stored | ||
| 354 | + // uncompressed: its marker is the first thing in the file. | ||
| 355 | + let head = b"PK\x03\x04\x08\x00\x00\x00mimetypeapplication/vnd.oasis.opendocument.spreadsheet"; | ||
| 356 | + match refine("application/zip", head, b"") { | ||
| 357 | + Verdict::Settle(Some( | ||
| 358 | + "application/vnd.oasis.opendocument.spreadsheet", | ||
| 359 | + )) => {} | ||
| 360 | + other => panic!("expected a settled spreadsheet, got {other:?}"), | ||
| 361 | + } | ||
| 362 | + // And the directory search, which reads entry names only, never | ||
| 363 | + // claims one — the marker is entry content, not an entry name. | ||
| 364 | + assert_eq!(office_entry_mime(head), None); | ||
| 365 | + } | ||
| 366 | +} | ||
crates/izlek-core/src/store/turso_store.rsmodified+104 -2
| @@ -10,7 +10,7 @@ use rand::Rng; | |||
| 10 | use time::{Duration, OffsetDateTime}; | 10 | use time::{Duration, OffsetDateTime}; |
| 11 | use time::format_description::well_known::Rfc3339; | 11 | use time::format_description::well_known::Rfc3339; |
| 12 | use turso::transaction::{Transaction, TransactionBehavior}; | 12 | use turso::transaction::{Transaction, TransactionBehavior}; |
| 13 | -use turso::{Builder, Connection, Row, Value, params}; | 13 | +use turso::{Builder, Connection, Row, Value, params, params_from_iter}; |
| 14 | use ulid::Ulid; | 14 | use ulid::Ulid; |
| 15 | 15 | ||
| 16 | use super::secret; | 16 | use super::secret; |
| @@ -21,7 +21,7 @@ use super::{ | |||
| 21 | SenderCheck, SenderTest, Session, SigninLink, Store, StoreError, Tag, TaskCreated, Trigger, | 21 | SenderCheck, SenderTest, Session, SigninLink, Store, StoreError, Tag, TaskCreated, Trigger, |
| 22 | User, UserStats, Workspace, LinkKind, | 22 | User, UserStats, Workspace, LinkKind, |
| 23 | }; | 23 | }; |
| 24 | -use super::{reconcile, ReconcileOptions, schema}; | 24 | +use super::{reconcile, ReconcileOptions, schema, sniff}; |
| 25 | use crate::Role; | 25 | use crate::Role; |
| 26 | use crate::board::{BoardMeta, BoardReads, Column, Moved, Person, TagChip, TaskRow, Transition}; | 26 | use crate::board::{BoardMeta, BoardReads, Column, Moved, Person, TagChip, TaskRow, Transition}; |
| 27 | use crate::detail::{ | 27 | use crate::detail::{ |
| @@ -124,6 +124,7 @@ impl TursoStore { | |||
| 124 | }; | 124 | }; |
| 125 | store.migrate(path).await?; | 125 | store.migrate(path).await?; |
| 126 | store.encrypt_plaintext_passwords().await?; | 126 | store.encrypt_plaintext_passwords().await?; |
| 127 | + store.resniff_generic_attachments().await?; | ||
| 127 | // The file may have been rebuilt from a backup; its permissions and | 128 | // The file may have been rebuilt from a backup; its permissions and |
| 128 | // any transient WAL/SHM siblings should still be private. | 129 | // any transient WAL/SHM siblings should still be private. |
| 129 | if path != ":memory:" { | 130 | if path != ":memory:" { |
| @@ -172,6 +173,107 @@ impl TursoStore { | |||
| 172 | Ok(()) | 173 | Ok(()) |
| 173 | } | 174 | } |
| 174 | 175 | ||
| 176 | + /// Re-decides the stored type of attachments whose `mime_type` is one of | ||
| 177 | + /// [`sniff::GENERIC_MIME_TYPES`] — rows written before the sniffer could | ||
| 178 | + /// name OOXML files, which a file chip then renders as a plain download | ||
| 179 | + /// because the viewer routes on the stored type alone. It runs here, once | ||
| 180 | + /// per boot, for the same reason the password-sealing pass above does: it | ||
| 181 | + /// is a data repair no migration can express, and a boot is the one moment | ||
| 182 | + /// the store may rewrite what uploads wrote. It is idempotent by | ||
| 183 | + /// construction — a row the pass refines leaves the generic buckets and is | ||
| 184 | + /// never read again, and a row the bytes cannot settle is left exactly as | ||
| 185 | + /// stored. Nothing is ever narrowed: the only verdicts written back are | ||
| 186 | + /// specific mime types that differ from what is stored. | ||
| 187 | + /// | ||
| 188 | + /// Cheap by design. The pass opens with a count of generic rows and, when | ||
| 189 | + /// there are none — every database after one pass, and every database | ||
| 190 | + /// whose uploads all postdate the sniffer — reads no blob bytes at all. | ||
| 191 | + /// Otherwise each such row donates two windows, the first | ||
| 192 | + /// [`sniff::HEAD_WINDOW`] and last [`sniff::TAIL_WINDOW`] bytes, and only | ||
| 193 | + /// when the windows find a zip with no office marker in them does the row | ||
| 194 | + /// give up its central directory: the complete entry list, in which every | ||
| 195 | + /// entry name the file has appears, so a pptx or xlsx cannot hide its | ||
| 196 | + /// `ppt/presentation.xml` or `xl/workbook.xml` from the sweep. A window | ||
| 197 | + /// verdict is never trusted for `text/plain` — a window cannot prove a | ||
| 198 | + /// whole blob is UTF-8 — and a directory the end record locates beyond | ||
| 199 | + /// [`sniff::DIRECTORY_CAP`], or a zip64 one, is left unread and the row | ||
| 200 | + /// left alone. | ||
| 201 | + async fn resniff_generic_attachments(&self) -> Result<()> { | ||
| 202 | + let buckets = sniff::GENERIC_MIME_TYPES; | ||
| 203 | + let marks = (1..=buckets.len()) | ||
| 204 | + .map(|i| format!("?{i}")) | ||
| 205 | + .collect::<Vec<_>>() | ||
| 206 | + .join(", "); | ||
| 207 | + let conn = self.conn.lock().await; | ||
| 208 | + | ||
| 209 | + // The existence probe the whole pass hangs off: one count of a short | ||
| 210 | + // text column, no blob reads, and the common case is done here. | ||
| 211 | + let mut rows = conn | ||
| 212 | + .query( | ||
| 213 | + &format!("SELECT COUNT(*) FROM attachment WHERE mime_type IN ({marks})"), | ||
| 214 | + params_from_iter(buckets.iter().copied()), | ||
| 215 | + ) | ||
| 216 | + .await | ||
| 217 | + .map_err(backend)?; | ||
| 218 | + let count = match rows.next().await.map_err(backend)? { | ||
| 219 | + Some(row) => row.get::<i64>(0).map_err(backend)?, | ||
| 220 | + None => 0, | ||
| 221 | + }; | ||
| 222 | + if count == 0 { | ||
| 223 | + return Ok(()); | ||
| 224 | + } | ||
| 225 | + | ||
| 226 | + let mut rows = conn | ||
| 227 | + .query( | ||
| 228 | + &format!( | ||
| 229 | + "SELECT id, mime_type, substr(bytes, 1, {head}), substr(bytes, -{tail}) \ | ||
| 230 | + FROM attachment WHERE mime_type IN ({marks})", | ||
| 231 | + head = sniff::HEAD_WINDOW, | ||
| 232 | + tail = sniff::TAIL_WINDOW, | ||
| 233 | + marks = marks, | ||
| 234 | + ), | ||
| 235 | + params_from_iter(buckets.iter().copied()), | ||
| 236 | + ) | ||
| 237 | + .await | ||
| 238 | + .map_err(backend)?; | ||
| 239 | + let mut pending = Vec::new(); | ||
| 240 | + while let Some(row) = rows.next().await.map_err(backend)? { | ||
| 241 | + let id = text(&row, 0)?; | ||
| 242 | + let stored = text(&row, 1)?; | ||
| 243 | + let head: Vec<u8> = row.get(2).map_err(backend)?; | ||
| 244 | + let tail: Vec<u8> = row.get(3).map_err(backend)?; | ||
| 245 | + let candidate = match sniff::refine(&stored, &head, &tail) { | ||
| 246 | + sniff::Verdict::Settle(candidate) => candidate, | ||
| 247 | + sniff::Verdict::ReadDirectory { offset, size } => { | ||
| 248 | + let len = size.min(sniff::DIRECTORY_CAP as u64) as i64; | ||
| 249 | + let mut directory = conn | ||
| 250 | + .query( | ||
| 251 | + "SELECT substr(bytes, ?1, ?2) FROM attachment WHERE id = ?3", | ||
| 252 | + params![offset as i64 + 1, len, id.clone()], | ||
| 253 | + ) | ||
| 254 | + .await | ||
| 255 | + .map_err(backend)?; | ||
| 256 | + match directory.next().await.map_err(backend)? { | ||
| 257 | + Some(row) => sniff::office_entry_mime(&row.get::<Vec<u8>>(0).map_err(backend)?), | ||
| 258 | + None => None, | ||
| 259 | + } | ||
| 260 | + } | ||
| 261 | + }; | ||
| 262 | + if let Some(mime) = sniff::refinement(&stored, candidate) { | ||
| 263 | + pending.push((mime, id)); | ||
| 264 | + } | ||
| 265 | + } | ||
| 266 | + for (mime, id) in pending { | ||
| 267 | + conn.execute( | ||
| 268 | + "UPDATE attachment SET mime_type = ?1 WHERE id = ?2", | ||
| 269 | + params![mime, id], | ||
| 270 | + ) | ||
| 271 | + .await | ||
| 272 | + .map_err(backend)?; | ||
| 273 | + } | ||
| 274 | + Ok(()) | ||
| 275 | + } | ||
| 276 | + | ||
| 175 | /// Brings the database to the declared schema. | 277 | /// Brings the database to the declared schema. |
| 176 | /// | 278 | /// |
| 177 | /// - An empty database is created from `migrations/0001_init.sql`. | 279 | /// - An empty database is created from `migrations/0001_init.sql`. |
crates/izlek-core/tests/store.rsmodified+250 -0
| @@ -9522,3 +9522,253 @@ async fn reconcile_backfills_watches_from_history_exactly_once() { | |||
| 9522 | 9522 | ||
| 9523 | let _ = std::fs::remove_dir_all(&dir); | 9523 | let _ = std::fs::remove_dir_all(&dir); |
| 9524 | } | 9524 | } |
| 9525 | + | ||
| 9526 | +// --------------------------------------------------------------------------- | ||
| 9527 | +// Boot-time re-sniff — attachments uploaded before the sniffer could name | ||
| 9528 | +// OOXML files froze on a generic bucket, and the viewer routes on the stored | ||
| 9529 | +// type alone, so an old .pptx used to render as a plain download. Opening a | ||
| 9530 | +// store runs the pass: these tests plant old-style rows, then open, then read | ||
| 9531 | +// back what the rows became. | ||
| 9532 | +// --------------------------------------------------------------------------- | ||
| 9533 | + | ||
| 9534 | +/// A zip of the named entries, contents irrelevant: the sniffer reads the | ||
| 9535 | +/// entry names a zip stores uncompressed. | ||
| 9536 | +fn zip_with(names: &[&str]) -> Vec<u8> { | ||
| 9537 | + use std::io::Write as _; | ||
| 9538 | + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); | ||
| 9539 | + for name in names { | ||
| 9540 | + zip.start_file(*name, zip::write::SimpleFileOptions::default()) | ||
| 9541 | + .unwrap(); | ||
| 9542 | + zip.write_all(b"<xml/>").unwrap(); | ||
| 9543 | + } | ||
| 9544 | + zip.finish().unwrap().into_inner() | ||
| 9545 | +} | ||
| 9546 | + | ||
| 9547 | +/// A zip whose only office marker sits in its central directory, beyond both | ||
| 9548 | +/// boot windows: the filler entries before the marked one push its local | ||
| 9549 | +/// header past the head window, and the filler entries after it push its | ||
| 9550 | +/// directory record past the tail window — the shape only the directory | ||
| 9551 | +/// read can settle. | ||
| 9552 | +fn deep_zip(before: usize, after: usize) -> Vec<u8> { | ||
| 9553 | + use std::io::Write as _; | ||
| 9554 | + let mut names: Vec<String> = (0..before).map(|i| format!("head/filler{i}.bin")).collect(); | ||
| 9555 | + names.push("ppt/presentation.xml".into()); | ||
| 9556 | + names.extend((0..after).map(|i| format!("tail/filler{i}.bin"))); | ||
| 9557 | + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); | ||
| 9558 | + for name in &names { | ||
| 9559 | + zip.start_file(name.as_str(), zip::write::SimpleFileOptions::default()) | ||
| 9560 | + .unwrap(); | ||
| 9561 | + zip.write_all(&[b'x'; 64]).unwrap(); | ||
| 9562 | + } | ||
| 9563 | + zip.finish().unwrap().into_inner() | ||
| 9564 | +} | ||
| 9565 | + | ||
| 9566 | +/// Whether the boot windows of `bytes` hold `marker` — the premise the deep | ||
| 9567 | +/// zip's test stands on, checked rather than assumed. | ||
| 9568 | +fn windows_hold(bytes: &[u8], marker: &[u8]) -> bool { | ||
| 9569 | + let head = &bytes[..bytes.len().min(izlek_core::store::sniff::HEAD_WINDOW as usize)]; | ||
| 9570 | + let tail = &bytes[bytes.len().saturating_sub(izlek_core::store::sniff::TAIL_WINDOW as usize)..]; | ||
| 9571 | + head.windows(marker.len()).any(|w| w == marker) | ||
| 9572 | + || tail.windows(marker.len()).any(|w| w == marker) | ||
| 9573 | +} | ||
| 9574 | + | ||
| 9575 | +/// OLE container bytes: the compound-file magic, then optionally the UTF-16 | ||
| 9576 | +/// `Workbook` stream name an .xls directory carries. | ||
| 9577 | +fn ole_bytes(with_workbook: bool) -> Vec<u8> { | ||
| 9578 | + let mut bytes = vec![0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]; | ||
| 9579 | + bytes.extend_from_slice(&[0; 512]); | ||
| 9580 | + if with_workbook { | ||
| 9581 | + bytes.extend_from_slice(b"W\0o\0r\0k\0b\0o\0o\0k\0"); | ||
| 9582 | + } | ||
| 9583 | + bytes | ||
| 9584 | +} | ||
| 9585 | + | ||
| 9586 | +/// A scratch database carrying old-style attachment rows: real bytes under | ||
| 9587 | +/// the generic mime a pre-sniffer upload froze on. The first open creates | ||
| 9588 | +/// the schema and finds nothing to do; the rows go in through a raw | ||
| 9589 | +/// connection; the caller then opens the store again, which runs the pass. | ||
| 9590 | +struct Planted { | ||
| 9591 | + dir: PathBuf, | ||
| 9592 | + path: String, | ||
| 9593 | +} | ||
| 9594 | + | ||
| 9595 | +impl Planted { | ||
| 9596 | + async fn plant(rows: &[(&str, &str, Vec<u8>)]) -> Self { | ||
| 9597 | + let dir = std::env::temp_dir().join(format!("izlek-resniff-{}", Ulid::new())); | ||
| 9598 | + std::fs::create_dir_all(&dir).unwrap(); | ||
| 9599 | + let path = dir.join("izlek.db").to_str().unwrap().to_string(); | ||
| 9600 | + drop(TursoStore::open(&path).await.unwrap()); | ||
| 9601 | + let db = turso::Builder::new_local(&path).build().await.unwrap(); | ||
| 9602 | + let conn = db.connect().unwrap(); | ||
| 9603 | + for (id, mime, bytes) in rows { | ||
| 9604 | + conn.execute( | ||
| 9605 | + "INSERT INTO attachment (id, task_id, file_name, mime_type, size_bytes, \ | ||
| 9606 | + bytes, uploaded_by, created_at) \ | ||
| 9607 | + VALUES (?1, 'T1', 'old.bin', ?2, ?3, ?4, 'U1', '2026-08-01T00:00:00Z')", | ||
| 9608 | + turso::params![id, mime, bytes.len() as i64, bytes.clone()], | ||
| 9609 | + ) | ||
| 9610 | + .await | ||
| 9611 | + .unwrap(); | ||
| 9612 | + } | ||
| 9613 | + drop(conn); | ||
| 9614 | + drop(db); | ||
| 9615 | + Self { dir, path } | ||
| 9616 | + } | ||
| 9617 | + | ||
| 9618 | + fn path(&self) -> &str { | ||
| 9619 | + &self.path | ||
| 9620 | + } | ||
| 9621 | + | ||
| 9622 | + async fn open(&self) -> TursoStore { | ||
| 9623 | + TursoStore::open(self.path()).await.unwrap() | ||
| 9624 | + } | ||
| 9625 | +} | ||
| 9626 | + | ||
| 9627 | +impl Drop for Planted { | ||
| 9628 | + fn drop(&mut self) { | ||
| 9629 | + let _ = std::fs::remove_dir_all(&self.dir); | ||
| 9630 | + } | ||
| 9631 | +} | ||
| 9632 | + | ||
| 9633 | +#[tokio::test] | ||
| 9634 | +async fn a_zip_mime_presentation_becomes_the_slides_mime_on_the_next_boot() { | ||
| 9635 | + let planted = Planted::plant(&[( | ||
| 9636 | + "FA", | ||
| 9637 | + "application/zip", | ||
| 9638 | + zip_with(&["ppt/presentation.xml", "ppt/slides/slide1.xml"]), | ||
| 9639 | + )]) | ||
| 9640 | + .await; | ||
| 9641 | + let store = planted.open().await; | ||
| 9642 | + assert_eq!( | ||
| 9643 | + store.attachment("FA").await.unwrap().unwrap().mime_type, | ||
| 9644 | + "application/vnd.openxmlformats-officedocument.presentationml.presentation", | ||
| 9645 | + "the mime `viewer_kind` routes to the Slides overlay" | ||
| 9646 | + ); | ||
| 9647 | +} | ||
| 9648 | + | ||
| 9649 | +#[tokio::test] | ||
| 9650 | +async fn a_zip_mime_workbook_becomes_the_sheet_mime_on_the_next_boot() { | ||
| 9651 | + let planted = Planted::plant(&[( | ||
| 9652 | + "FB", | ||
| 9653 | + "application/zip", | ||
| 9654 | + zip_with(&["xl/workbook.xml", "xl/worksheets/sheet1.xml"]), | ||
| 9655 | + )]) | ||
| 9656 | + .await; | ||
| 9657 | + let store = planted.open().await; | ||
| 9658 | + assert_eq!( | ||
| 9659 | + store.attachment("FB").await.unwrap().unwrap().mime_type, | ||
| 9660 | + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", | ||
| 9661 | + "the mime `is_spreadsheet` routes to the Sheet overlay" | ||
| 9662 | + ); | ||
| 9663 | +} | ||
| 9664 | + | ||
| 9665 | +#[tokio::test] | ||
| 9666 | +async fn an_ole_container_without_a_workbook_stream_stays_as_stored() { | ||
| 9667 | + let planted = Planted::plant(&[( | ||
| 9668 | + "FC", | ||
| 9669 | + "application/x-ole-storage", | ||
| 9670 | + ole_bytes(false), | ||
| 9671 | + )]) | ||
| 9672 | + .await; | ||
| 9673 | + let store = planted.open().await; | ||
| 9674 | + assert_eq!( | ||
| 9675 | + store.attachment("FC").await.unwrap().unwrap().mime_type, | ||
| 9676 | + "application/x-ole-storage" | ||
| 9677 | + ); | ||
| 9678 | +} | ||
| 9679 | + | ||
| 9680 | +#[tokio::test] | ||
| 9681 | +async fn an_ole_container_with_a_workbook_stream_becomes_ms_excel() { | ||
| 9682 | + let planted = Planted::plant(&[( | ||
| 9683 | + "FD", | ||
| 9684 | + "application/x-ole-storage", | ||
| 9685 | + ole_bytes(true), | ||
| 9686 | + )]) | ||
| 9687 | + .await; | ||
| 9688 | + let store = planted.open().await; | ||
| 9689 | + assert_eq!( | ||
| 9690 | + store.attachment("FD").await.unwrap().unwrap().mime_type, | ||
| 9691 | + "application/vnd.ms-excel" | ||
| 9692 | + ); | ||
| 9693 | +} | ||
| 9694 | + | ||
| 9695 | +/// Every stored type the pass could touch but never should: specific rows | ||
| 9696 | +/// wear no generic bucket, so the probe finds nothing and no blob moves — | ||
| 9697 | +/// which is also why there is nothing here to un-write on the next boot. | ||
| 9698 | +#[tokio::test] | ||
| 9699 | +async fn specific_mimes_survive_a_boot_pass_that_has_nothing_to_do() { | ||
| 9700 | + let png = { | ||
| 9701 | + let mut bytes = vec![0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; | ||
| 9702 | + bytes.extend_from_slice(&[0; 64]); | ||
| 9703 | + bytes | ||
| 9704 | + }; | ||
| 9705 | + let planted = Planted::plant(&[ | ||
| 9706 | + ("FE", "image/png", png), | ||
| 9707 | + ("FF", "application/pdf", b"%PDF-1.4 nothing to see".to_vec()), | ||
| 9708 | + ("FG", "text/plain", b"plainly text".to_vec()), | ||
| 9709 | + ]) | ||
| 9710 | + .await; | ||
| 9711 | + let store = planted.open().await; | ||
| 9712 | + assert_eq!(store.attachment("FE").await.unwrap().unwrap().mime_type, "image/png"); | ||
| 9713 | + assert_eq!(store.attachment("FF").await.unwrap().unwrap().mime_type, "application/pdf"); | ||
| 9714 | + assert_eq!(store.attachment("FG").await.unwrap().unwrap().mime_type, "text/plain"); | ||
| 9715 | +} | ||
| 9716 | + | ||
| 9717 | +#[tokio::test] | ||
| 9718 | +async fn a_plain_zip_stays_a_plain_zip_across_the_boot_pass() { | ||
| 9719 | + let planted = Planted::plant(&[( | ||
| 9720 | + "FH", | ||
| 9721 | + "application/zip", | ||
| 9722 | + zip_with(&["notes.txt", "data/blob.bin"]), | ||
| 9723 | + )]) | ||
| 9724 | + .await; | ||
| 9725 | + let store = planted.open().await; | ||
| 9726 | + assert_eq!( | ||
| 9727 | + store.attachment("FH").await.unwrap().unwrap().mime_type, | ||
| 9728 | + "application/zip" | ||
| 9729 | + ); | ||
| 9730 | +} | ||
| 9731 | + | ||
| 9732 | +#[tokio::test] | ||
| 9733 | +async fn a_presentation_hidden_beyond_both_windows_is_found_in_its_central_directory() { | ||
| 9734 | + let bytes = deep_zip(2000, 3000); | ||
| 9735 | + assert!( | ||
| 9736 | + !windows_hold(&bytes, b"ppt/presentation.xml"), | ||
| 9737 | + "the test's premise broke: the marker fell inside a boot window" | ||
| 9738 | + ); | ||
| 9739 | + let planted = Planted::plant(&[("FI", "application/zip", bytes)]).await; | ||
| 9740 | + let store = planted.open().await; | ||
| 9741 | + assert_eq!( | ||
| 9742 | + store.attachment("FI").await.unwrap().unwrap().mime_type, | ||
| 9743 | + "application/vnd.openxmlformats-officedocument.presentationml.presentation" | ||
| 9744 | + ); | ||
| 9745 | +} | ||
| 9746 | + | ||
| 9747 | +#[tokio::test] | ||
| 9748 | +async fn an_octet_stream_row_wearing_office_bytes_is_refined_too() { | ||
| 9749 | + let planted = Planted::plant(&[( | ||
| 9750 | + "FJ", | ||
| 9751 | + "application/octet-stream", | ||
| 9752 | + zip_with(&["ppt/presentation.xml", "ppt/slides/slide1.xml"]), | ||
| 9753 | + )]) | ||
| 9754 | + .await; | ||
| 9755 | + let store = planted.open().await; | ||
| 9756 | + assert_eq!( | ||
| 9757 | + store.attachment("FJ").await.unwrap().unwrap().mime_type, | ||
| 9758 | + "application/vnd.openxmlformats-officedocument.presentationml.presentation" | ||
| 9759 | + ); | ||
| 9760 | +} | ||
| 9761 | + | ||
| 9762 | +/// A window cannot prove a whole blob is UTF-8: an octet-stream row whose | ||
| 9763 | +/// head reads as text but whose tail is binary stays exactly what it is. | ||
| 9764 | +#[tokio::test] | ||
| 9765 | +async fn a_window_that_cannot_prove_text_keeps_the_octet_stream_bucket() { | ||
| 9766 | + let mut bytes = b"this front half is plainly text, ".to_vec(); | ||
| 9767 | + bytes.extend_from_slice(&[0x00, 0xFF, 0xFE, 0x80]); | ||
| 9768 | + let planted = Planted::plant(&[("FK", "application/octet-stream", bytes)]).await; | ||
| 9769 | + let store = planted.open().await; | ||
| 9770 | + assert_eq!( | ||
| 9771 | + store.attachment("FK").await.unwrap().unwrap().mime_type, | ||
| 9772 | + "application/octet-stream" | ||
| 9773 | + ); | ||
| 9774 | +} | ||
crates/izlek-web/Cargo.tomlmodified+1 -1
| @@ -44,7 +44,7 @@ calamine = { version = "0.36.1", default-features = false } | |||
| 44 | # the same zip calamine opens for a workbook, read with the XML parser | 44 | # the same zip calamine opens for a workbook, read with the XML parser |
| 45 | # already in the tree — both crates ride the lockfile as it stands. | 45 | # already in the tree — both crates ride the lockfile as it stands. |
| 46 | quick-xml = { version = "0.41.0", default-features = false } | 46 | quick-xml = { version = "0.41.0", default-features = false } |
| 47 | -zip = { version = "8.6.0", default-features = false, features = ["deflate"] } | 47 | +zip.workspace = true |
| 48 | # Hashes the compiled stylesheet against the bundle's bytes at boot, so a | 48 | # Hashes the compiled stylesheet against the bundle's bytes at boot, so a |
| 49 | # bundle from another generation refuses the boot instead of serving under | 49 | # bundle from another generation refuses the boot instead of serving under |
| 50 | # this binary (see `server.rs`'s `stylesheet_guard`). | 50 | # this binary (see `server.rs`'s `stylesheet_guard`). |
crates/izlek-web/src/files.rsmodified+1 -150
| @@ -14,6 +14,7 @@ use topcoat::router::{ | |||
| 14 | HeaderMap, HeaderValue, StatusCode, header, path_param, query_params, route, | 14 | HeaderMap, HeaderValue, StatusCode, header, path_param, query_params, route, |
| 15 | }; | 15 | }; |
| 16 | 16 | ||
| 17 | +use izlek_core::store::sniff::sniff; | ||
| 17 | use izlek_core::store::{NewAttachment, Store, User}; | 18 | use izlek_core::store::{NewAttachment, Store, User}; |
| 18 | 19 | ||
| 19 | use crate::server::{Refusal, accounts, require_user}; | 20 | use crate::server::{Refusal, accounts, require_user}; |
| @@ -115,91 +116,6 @@ fn mime_of_extension(ext: &str) -> Option<&'static str> { | |||
| 115 | } | 116 | } |
| 116 | } | 117 | } |
| 117 | 118 | ||
| 118 | -/// What the bytes are, decided from the bytes themselves — never from the | ||
| 119 | -/// part's `content_type()`, which is whatever the browser felt like sending. | ||
| 120 | -pub(crate) fn sniff(bytes: &[u8]) -> &'static str { | ||
| 121 | - if bytes.starts_with(&[0x89, 0x50, 0x4E, 0x47]) { | ||
| 122 | - "image/png" | ||
| 123 | - } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { | ||
| 124 | - "image/jpeg" | ||
| 125 | - } else if bytes.starts_with(b"GIF8") { | ||
| 126 | - "image/gif" | ||
| 127 | - } else if bytes.starts_with(b"%PDF-") { | ||
| 128 | - "application/pdf" | ||
| 129 | - } else if bytes.starts_with(b"PK\x03\x04") { | ||
| 130 | - // Every OOXML and OpenDocument file is a zip; what kind it is lives in | ||
| 131 | - // the entry names, which a zip stores uncompressed. `xl/workbook.xml` | ||
| 132 | - // is the one part an xlsx cannot be without, an ods declares its | ||
| 133 | - // type in the `mimetype` entry the format requires be stored first, | ||
| 134 | - // and `ppt/presentation.xml` is the one part a pptx cannot be | ||
| 135 | - // without. | ||
| 136 | - if contains(bytes, b"xl/workbook.xml") { | ||
| 137 | - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" | ||
| 138 | - } else if contains(bytes, b"opendocument.spreadsheet") { | ||
| 139 | - "application/vnd.oasis.opendocument.spreadsheet" | ||
| 140 | - } else if contains(bytes, b"ppt/presentation.xml") { | ||
| 141 | - "application/vnd.openxmlformats-officedocument.presentationml.presentation" | ||
| 142 | - } else { | ||
| 143 | - "application/zip" | ||
| 144 | - } | ||
| 145 | - } else if bytes.starts_with(&[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]) { | ||
| 146 | - // The pre-2007 OLE compound file .xls, .doc and .ppt all share. Its | ||
| 147 | - // directory holds stream names in UTF-16, and only a workbook carries | ||
| 148 | - // one called `Workbook` — a .doc or .ppt stays an unnamed container. | ||
| 149 | - if contains(bytes, b"W\0o\0r\0k\0b\0o\0o\0k\0") { | ||
| 150 | - "application/vnd.ms-excel" | ||
| 151 | - } else { | ||
| 152 | - "application/x-ole-storage" | ||
| 153 | - } | ||
| 154 | - } else if bytes.starts_with(&[0x1F, 0x8B]) { | ||
| 155 | - "application/gzip" | ||
| 156 | - } else if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" && &bytes[8..12] == b"avif" { | ||
| 157 | - "image/avif" | ||
| 158 | - } else if bytes.len() >= 12 | ||
| 159 | - && &bytes[4..8] == b"ftyp" | ||
| 160 | - && matches!( | ||
| 161 | - &bytes[8..12], | ||
| 162 | - b"heic" | b"heix" | b"hevc" | b"heif" | b"mif1" | b"msf1" | ||
| 163 | - ) | ||
| 164 | - { | ||
| 165 | - // Apple's HEIC container reuses the ISO-BMFF `ftyp` box video shares; | ||
| 166 | - // the brand at bytes 8..12 is what tells a photo from a video apart. | ||
| 167 | - "image/heic" | ||
| 168 | - } else if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" && &bytes[8..12] == b"qt " { | ||
| 169 | - "video/quicktime" | ||
| 170 | - } else if bytes.len() >= 8 && &bytes[4..8] == b"ftyp" { | ||
| 171 | - "video/mp4" | ||
| 172 | - } else if bytes.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) { | ||
| 173 | - "video/webm" | ||
| 174 | - } else if bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP" { | ||
| 175 | - "image/webp" | ||
| 176 | - } else if bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WAVE" { | ||
| 177 | - "audio/wav" | ||
| 178 | - } else if bytes.starts_with(b"fLaC") { | ||
| 179 | - "audio/flac" | ||
| 180 | - } else if bytes.starts_with(b"OggS") { | ||
| 181 | - "audio/ogg" | ||
| 182 | - } else if bytes.starts_with(b"ID3") | ||
| 183 | - || bytes.starts_with(&[0xFF, 0xFB]) | ||
| 184 | - || bytes.starts_with(&[0xFF, 0xF3]) | ||
| 185 | - || bytes.starts_with(&[0xFF, 0xF2]) | ||
| 186 | - { | ||
| 187 | - "audio/mpeg" | ||
| 188 | - } else if std::str::from_utf8(bytes).is_ok() { | ||
| 189 | - "text/plain" | ||
| 190 | - } else { | ||
| 191 | - "application/octet-stream" | ||
| 192 | - } | ||
| 193 | -} | ||
| 194 | - | ||
| 195 | -/// Whether `haystack` holds `needle` anywhere in it. Used on zip bytes, where | ||
| 196 | -/// the entry names sit in the clear even when the entries themselves do not. | ||
| 197 | -fn contains(haystack: &[u8], needle: &[u8]) -> bool { | ||
| 198 | - haystack | ||
| 199 | - .windows(needle.len()) | ||
| 200 | - .any(|window| window == needle) | ||
| 201 | -} | ||
| 202 | - | ||
| 203 | /// The `Content-Disposition` header for one download. `inline` is only ever | 119 | /// The `Content-Disposition` header for one download. `inline` is only ever |
| 204 | /// true for a mime type a browser renders on its own ([`renders_inline`]) and | 120 | /// true for a mime type a browser renders on its own ([`renders_inline`]) and |
| 205 | /// the caller did not ask for a forced download (`?dl=1`) — an uploaded HTML | 121 | /// 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<u8>)> | |||
| 579 | mod tests { | 495 | mod tests { |
| 580 | use super::*; | 496 | use super::*; |
| 581 | 497 | ||
| 582 | - #[test] | ||
| 583 | - fn sniffs_the_magic_numbers() { | ||
| 584 | - assert_eq!(sniff(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A]), "image/png"); | ||
| 585 | - assert_eq!(sniff(&[0xFF, 0xD8, 0xFF, 0xE0]), "image/jpeg"); | ||
| 586 | - assert_eq!(sniff(b"hello, this is plainly text"), "text/plain"); | ||
| 587 | - assert_eq!( | ||
| 588 | - sniff(&[0x00, 0x01, 0xFE, 0xFF, 0x02]), | ||
| 589 | - "application/octet-stream" | ||
| 590 | - ); | ||
| 591 | - } | ||
| 592 | - | ||
| 593 | - #[test] | ||
| 594 | - fn sniffs_the_media_types() { | ||
| 595 | - assert_eq!( | ||
| 596 | - sniff(b"\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00"), | ||
| 597 | - "video/mp4" | ||
| 598 | - ); | ||
| 599 | - assert_eq!( | ||
| 600 | - sniff(b"\x00\x00\x00\x18ftypavif\x00\x00\x00\x00"), | ||
| 601 | - "image/avif" | ||
| 602 | - ); | ||
| 603 | - assert_eq!( | ||
| 604 | - sniff(b"\x00\x00\x00\x18ftypheic\x00\x00\x00\x00"), | ||
| 605 | - "image/heic" | ||
| 606 | - ); | ||
| 607 | - assert_eq!( | ||
| 608 | - sniff(b"\x00\x00\x00\x18ftypmif1\x00\x00\x00\x00"), | ||
| 609 | - "image/heic" | ||
| 610 | - ); | ||
| 611 | - assert_eq!( | ||
| 612 | - sniff(b"\x00\x00\x00\x14ftypqt \x00\x00\x00\x00"), | ||
| 613 | - "video/quicktime" | ||
| 614 | - ); | ||
| 615 | - assert_eq!(sniff(&[0x1A, 0x45, 0xDF, 0xA3, 0x00, 0x00]), "video/webm"); | ||
| 616 | - assert_eq!(sniff(b"RIFF\x00\x00\x00\x00WEBPVP8 "), "image/webp"); | ||
| 617 | - assert_eq!(sniff(b"RIFF\x00\x00\x00\x00WAVEfmt "), "audio/wav"); | ||
| 618 | - assert_eq!(sniff(b"fLaC\x00\x00\x00\x00"), "audio/flac"); | ||
| 619 | - assert_eq!(sniff(b"OggS\x00\x00\x00\x00"), "audio/ogg"); | ||
| 620 | - assert_eq!(sniff(b"ID3\x03\x00\x00\x00"), "audio/mpeg"); | ||
| 621 | - assert_eq!(sniff(&[0xFF, 0xFB, 0x90, 0x00]), "audio/mpeg"); | ||
| 622 | - } | ||
| 623 | - | ||
| 624 | #[test] | 498 | #[test] |
| 625 | fn labels_strip_the_path_and_the_control_characters() { | 499 | fn labels_strip_the_path_and_the_control_characters() { |
| 626 | assert_eq!(label_of("../../etc/passwd"), "passwd"); | 500 | assert_eq!(label_of("../../etc/passwd"), "passwd"); |
| @@ -737,29 +611,6 @@ mod tests { | |||
| 737 | assert_eq!(accept_attribute(&[]), "", "no list, no attribute"); | 611 | assert_eq!(accept_attribute(&[]), "", "no list, no attribute"); |
| 738 | } | 612 | } |
| 739 | 613 | ||
| 740 | - /// A zip of the named entries, bytes inside irrelevant: the sniff reads | ||
| 741 | - /// the entry names a zip stores uncompressed. | ||
| 742 | - fn zip_with(names: &[&str]) -> Vec<u8> { | ||
| 743 | - use std::io::Write as _; | ||
| 744 | - let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); | ||
| 745 | - for name in names { | ||
| 746 | - zip.start_file(*name, zip::write::SimpleFileOptions::default()) | ||
| 747 | - .unwrap(); | ||
| 748 | - zip.write_all(b"<xml/>").unwrap(); | ||
| 749 | - } | ||
| 750 | - zip.finish().unwrap().into_inner() | ||
| 751 | - } | ||
| 752 | - | ||
| 753 | - #[test] | ||
| 754 | - fn a_presentation_sniffs_its_presentation_mime_and_a_plain_zip_stays_a_zip() { | ||
| 755 | - let pptx = zip_with(&["ppt/presentation.xml", "ppt/slides/slide1.xml"]); | ||
| 756 | - assert_eq!( | ||
| 757 | - sniff(&pptx), | ||
| 758 | - "application/vnd.openxmlformats-officedocument.presentationml.presentation" | ||
| 759 | - ); | ||
| 760 | - assert_eq!(sniff(&zip_with(&["notes.txt"])), "application/zip"); | ||
| 761 | - } | ||
| 762 | - | ||
| 763 | #[test] | 614 | #[test] |
| 764 | fn an_ole_presentation_stays_download_only() { | 615 | fn an_ole_presentation_stays_download_only() { |
| 765 | // The pre-2007 .ppt shares the OLE container magic with .doc and | 616 | // The pre-2007 .ppt shares the OLE container magic with .doc and |
crates/izlek-web/src/photo.rsmodified+1 -1
| @@ -10,7 +10,7 @@ use topcoat::router::content::multipart::Multipart; | |||
| 10 | use topcoat::router::request::headers as request_headers; | 10 | use topcoat::router::request::headers as request_headers; |
| 11 | use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, path_param, route}; | 11 | use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, path_param, route}; |
| 12 | 12 | ||
| 13 | -use crate::files::sniff; | 13 | +use izlek_core::store::sniff::sniff; |
| 14 | use crate::server::{Refusal, accounts, require_user}; | 14 | use crate::server::{Refusal, accounts, require_user}; |
| 15 | use crate::settings::saved_or_refused; | 15 | use crate::settings::saved_or_refused; |
| 16 | 16 | ||