1pub mod batch_verify;
2pub mod chachapoly;
3pub mod nip44;
4pub mod gate;
5pub mod gcm;
6pub mod guarded_key;
7pub mod sha256;
8pub mod stream;
9pub use chachapoly::{wipe, wipe_vec};
10pub use guarded_key::GuardedKey;
11
12mod signer;
13pub use signer::{GuardedSigner, WRAPS_PER_VAULT_READ};
14
15use argon2::Argon2;
16use chachapoly::{ChaCha20Poly1305, NONCE_LEN, TAG_LEN};
17use zeroize::Zeroize;
18
19#[derive(Clone, PartialEq, Eq)]
24pub enum Kdf {
25 Legacy,
26 V2 { salt: [u8; 16] },
28}
29
30impl std::fmt::Debug for Kdf {
31 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32 f.write_str(match self { Kdf::Legacy => "Kdf::Legacy", Kdf::V2 { .. } => "Kdf::V2" })
33 }
34}
35
36const KDF_V2_LABEL: &str = "argon2id-v2:";
37
38impl Kdf {
39 pub fn fresh() -> Kdf {
41 use rand::RngCore;
42 let mut salt = [0u8; 16];
43 rand::rngs::OsRng.fill_bytes(&mut salt);
44 Kdf::V2 { salt }
45 }
46
47 pub fn descriptor(&self) -> Option<String> {
49 match self {
50 Kdf::Legacy => None,
51 Kdf::V2 { salt } => Some(format!("{KDF_V2_LABEL}{}", crate::simd::hex::bytes_to_hex_string(salt))),
52 }
53 }
54
55 pub fn parse(stored: &str) -> Result<Kdf, String> {
56 let Some(hex) = stored.strip_prefix(KDF_V2_LABEL) else {
57 return Err("This account's key derivation is from a newer Vector; update to unlock it".to_string());
58 };
59 let salt = crate::simd::hex::hex_string_to_bytes_checked(hex)
60 .and_then(|b| <[u8; 16]>::try_from(b).ok())
61 .ok_or("This account's key derivation record is damaged")?;
62 Ok(Kdf::V2 { salt })
63 }
64
65 pub fn of_account() -> Result<Kdf, String> {
68 match crate::db::settings::get_sql_setting_strict("kdf")? {
69 None => Ok(Kdf::Legacy),
70 Some(stored) => Kdf::parse(&stored),
71 }
72 }
73
74 pub fn is_legacy(&self) -> bool {
75 matches!(self, Kdf::Legacy)
76 }
77}
78
79pub fn install_unlocked_key(key: &[u8; 32], kdf: &Kdf) -> Result<(), String> {
84 let _change = gate::key_change()?;
85 if Kdf::of_account()? != *kdf {
86 return Err("This account's encryption changed while unlocking; enter your PIN again".to_string());
87 }
88 if !crate::db::at_rest::key_matches_account(key) {
89 return Err("Incorrect password".to_string());
90 }
91 crate::state::ENCRYPTION_KEY.set(*key, &[]);
92 Ok(())
93}
94
95pub async fn derive_key(password: &str, kdf: &Kdf) -> [u8; 32] {
98 let password = zeroize::Zeroizing::new(password.to_string());
99 let kdf = kdf.clone();
100 crate::rt::spawn_blocking(move || {
101 let salt: &[u8] = match &kdf {
102 Kdf::Legacy => b"vectorvectovectvecvev",
103 Kdf::V2 { salt } => salt,
104 };
105 let mut output = [0u8; 32];
106 let params = argon2::Params::new(150_000, 10, 1, Some(32)).unwrap();
107 let argon2 = Argon2::new(argon2::Algorithm::Argon2id, argon2::Version::V0x13, params);
108 argon2.hash_password_into(password.as_bytes(), salt, &mut output).unwrap();
109 output
110 }).await.unwrap()
111}
112
113fn seal_framed(plaintext: &[u8], key: &[u8; 32]) -> Result<Vec<u8>, chachapoly::Error> {
115 seal_framed_with(&ChaCha20Poly1305::new(key), plaintext)
116}
117
118fn seal_framed_with(cipher: &ChaCha20Poly1305, plaintext: &[u8]) -> Result<Vec<u8>, chachapoly::Error> {
119 use rand::Rng;
120 let nonce: [u8; NONCE_LEN] = rand::thread_rng().gen();
121 let mut out = Vec::with_capacity(NONCE_LEN + plaintext.len() + TAG_LEN);
122 out.extend_from_slice(&nonce);
123 out.extend_from_slice(plaintext);
124 let tag = cipher.seal_in_place(&nonce, &[], &mut out[NONCE_LEN..])?;
125 out.extend_from_slice(&tag);
126 Ok(out)
127}
128
129fn open_framed(framed: Vec<u8>, key: &[u8; 32]) -> Option<Vec<u8>> {
131 open_framed_with(&ChaCha20Poly1305::new(key), framed)
132}
133
134fn open_framed_with(cipher: &ChaCha20Poly1305, mut framed: Vec<u8>) -> Option<Vec<u8>> {
135 let len = cipher.open_framed_in_place(&mut framed).ok()?.len();
136 framed.copy_within(NONCE_LEN..NONCE_LEN + len, 0);
137 framed.truncate(len);
138 Some(framed)
139}
140
141fn open_hex_previous(hex_data: &str) -> Option<String> {
144 crate::state::PREVIOUS_AT_REST_KEY.with_key(|key| open_hex(hex_data, key)).flatten()
145}
146
147#[cfg(not(test))]
149const PREVIOUS_GRACE: std::time::Duration = std::time::Duration::from_secs(5);
150#[cfg(test)]
151const PREVIOUS_GRACE: std::time::Duration = std::time::Duration::from_millis(200);
152static PREVIOUS_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
153
154pub(crate) fn hold_previous_key(old: &[u8; 32]) {
156 PREVIOUS_GENERATION.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
157 crate::state::PREVIOUS_AT_REST_KEY.set(*old, &[]);
158}
159
160pub(crate) fn forget_previous_key_later() {
162 let generation = PREVIOUS_GENERATION.load(std::sync::atomic::Ordering::SeqCst);
163 let forget = move || {
164 let _change = gate::key_change();
166 if PREVIOUS_GENERATION.load(std::sync::atomic::Ordering::SeqCst) == generation {
167 crate::state::PREVIOUS_AT_REST_KEY.clear(&[]);
168 }
169 };
170 #[cfg(not(target_arch = "wasm32"))]
171 std::thread::spawn(move || {
172 std::thread::sleep(PREVIOUS_GRACE);
173 forget();
174 });
175 #[cfg(target_arch = "wasm32")]
176 crate::rt::spawn(async move {
178 crate::rt::time::sleep(PREVIOUS_GRACE).await;
179 forget();
180 });
181}
182
183pub(crate) fn forget_previous_key() {
185 PREVIOUS_GENERATION.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
186 crate::state::PREVIOUS_AT_REST_KEY.clear(&[]);
187}
188
189fn open_blob_previous(stored: &[u8]) -> Option<Vec<u8>> {
190 crate::state::PREVIOUS_AT_REST_KEY.with_key(|key| decrypt_blob_with_key(stored, key).ok()).flatten()
191}
192
193fn open_hex(hex_data: &str, key: &[u8; 32]) -> Option<String> {
195 open_hex_with(&ChaCha20Poly1305::new(key), hex_data)
196}
197
198fn open_hex_with(cipher: &ChaCha20Poly1305, hex_data: &str) -> Option<String> {
199 let plaintext = open_framed_with(cipher, crate::simd::hex::hex_string_to_bytes(hex_data))?;
200 Some(unsafe { String::from_utf8_unchecked(plaintext) })
202}
203
204pub fn encrypt_with_key(plaintext: &str, key: &[u8; 32]) -> Result<String, String> {
206 let framed = seal_framed(plaintext.as_bytes(), key).map_err(|e| format!("Encryption failed: {}", e))?;
207 Ok(crate::simd::hex::bytes_to_hex_string(&framed))
208}
209
210pub fn decrypt_with_key(hex_data: &str, key: &[u8; 32]) -> Result<String, String> {
212 if hex_data.len() < 2 * NONCE_LEN {
213 return Err("Ciphertext too short".to_string());
214 }
215 open_hex(hex_data, key).ok_or_else(|| "Decryption failed (wrong key or corrupted data)".to_string())
216}
217
218pub fn is_encryption_enabled() -> bool {
226 crate::state::resolve_encryption_enabled_from_db()
227}
228
229mod hex {
231 pub fn encode(bytes: &[u8]) -> String {
232 crate::simd::hex::bytes_to_hex_string(bytes)
235 }
236
237 pub fn decode(hex: &str) -> Result<Vec<u8>, String> {
238 if !hex.len().is_multiple_of(2) {
239 return Err("Odd-length hex string".to_string());
240 }
241 crate::simd::hex::hex_string_to_bytes_checked(hex)
244 .ok_or_else(|| "Invalid hex character".to_string())
245 }
246}
247
248#[derive(Debug)]
254pub struct EncryptionParams {
255 pub key: String, pub nonce: String, }
258
259pub fn generate_encryption_params() -> EncryptionParams {
261 use rand::Rng;
262 let mut rng = rand::thread_rng();
263 let mut key: [u8; 32] = rng.gen();
264 let nonce: [u8; 16] = rng.gen();
265 let params = EncryptionParams {
266 key: hex::encode(&key),
267 nonce: hex::encode(&nonce),
268 };
269 key.iter_mut().for_each(|b| *b = 0); params
271}
272
273pub(crate) fn attachment_params(key_hex: &str, nonce_hex: &str, key_error: &str) -> Result<([u8; 32], [u8; 16]), String> {
276 let mut key_bytes = hex::decode(key_hex).map_err(|e| format!("Invalid key: {}", e))?;
277 let nonce_bytes = hex::decode(nonce_hex).map_err(|e| format!("Invalid nonce: {}", e))?;
278 let key: Result<[u8; 32], _> = key_bytes.as_slice().try_into();
279 key_bytes.zeroize();
280 let key = key.map_err(|_| key_error.to_string())?;
281 let nonce: [u8; 16] = nonce_bytes.try_into().map_err(|_| "Invalid nonce length".to_string())?;
282 Ok((key, nonce))
283}
284
285pub fn encrypt_data(data: &[u8], params: &EncryptionParams) -> Result<Vec<u8>, String> {
287 let (mut key, nonce) = attachment_params(¶ms.key, ¶ms.nonce, "Invalid encryption key")?;
288 let mut buffer = Vec::with_capacity(data.len() + gcm::TAG_LEN);
291 buffer.extend_from_slice(data);
292 let tag = gcm::seal(&key, &nonce, &mut buffer);
293 key.zeroize();
294 buffer.extend_from_slice(&tag);
295 Ok(buffer)
296}
297
298pub fn decrypt_data(encrypted_data: &[u8], key_hex: &str, nonce_hex: &str) -> Result<Vec<u8>, String> {
301 decrypt_data_owned(encrypted_data.to_vec(), key_hex, nonce_hex)
302}
303
304pub fn decrypt_data_owned(mut data: Vec<u8>, key_hex: &str, nonce_hex: &str) -> Result<Vec<u8>, String> {
307 if data.len() < gcm::TAG_LEN {
308 return Err(format!("Invalid Input: encrypted data too small ({} bytes, minimum 16 bytes required for authentication tag)", data.len()));
309 }
310 let (mut key, nonce) = attachment_params(key_hex, nonce_hex, "Invalid decryption key")?;
311 let body = data.len() - gcm::TAG_LEN;
312 let tag: [u8; gcm::TAG_LEN] = data[body..].try_into().unwrap();
313 data.truncate(body);
314 let opened = gcm::open(&key, &nonce, &mut data, &tag);
315 key.zeroize();
316 opened.map_err(|_| "aead::Error".to_string())?;
317 Ok(data)
318}
319
320pub fn sha256_hex(data: &[u8]) -> String {
322 hex::encode(&sha256::digest(data))
323}
324
325pub fn attachment_identity_basis(ox: Option<&str>, nonce: &str, url: &str) -> String {
335 match ox.filter(|h| !h.is_empty()) {
336 Some(h) => h.to_string(),
337 None => {
338 let mut buf = Vec::with_capacity(nonce.len() + 1 + url.len());
339 buf.extend_from_slice(nonce.as_bytes());
340 buf.push(0);
341 buf.extend_from_slice(url.as_bytes());
342 sha256_hex(&buf)
343 }
344 }
345}
346
347pub fn mime_from_extension(ext: &str) -> &'static str {
349 match ext.to_lowercase().as_str() {
350 "png" => "image/png",
351 "jpg" | "jpeg" => "image/jpeg",
352 "gif" => "image/gif",
353 "webp" => "image/webp",
354 "svg" => "image/svg+xml",
355 "bmp" => "image/bmp",
356 "ico" => "image/x-icon",
357 "tiff" | "tif" => "image/tiff",
358 "dng" => "image/x-adobe-dng",
359 "cr2" => "image/x-canon-cr2",
360 "nef" => "image/x-nikon-nef",
361 "arw" => "image/x-sony-arw",
362 "mp4" => "video/mp4",
363 "webm" => "video/webm",
364 "mov" => "video/quicktime",
365 "avi" => "video/x-msvideo",
366 "mkv" => "video/x-matroska",
367 "flv" => "video/x-flv",
368 "wmv" => "video/x-ms-wmv",
369 "mpg" | "mpeg" => "video/mpeg",
370 "3gp" => "video/3gpp",
371 "ogv" => "video/ogg",
372 "ts" => "video/mp2t",
373 "mp3" => "audio/mpeg",
374 "ogg" => "audio/ogg",
375 "wav" => "audio/wav",
376 "flac" => "audio/flac",
377 "m4a" => "audio/mp4",
378 "aac" => "audio/aac",
379 "wma" => "audio/x-ms-wma",
380 "opus" => "audio/opus",
381 "pdf" => "application/pdf",
382 "doc" => "application/msword",
383 "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
384 "xls" => "application/vnd.ms-excel",
385 "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
386 "ppt" => "application/vnd.ms-powerpoint",
387 "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
388 "odt" => "application/vnd.oasis.opendocument.text",
389 "ods" => "application/vnd.oasis.opendocument.spreadsheet",
390 "odp" => "application/vnd.oasis.opendocument.presentation",
391 "rtf" => "application/rtf",
392 "txt" => "text/plain",
393 "md" => "text/markdown",
394 "csv" => "text/csv",
395 "json" => "application/json",
396 "xml" => "application/xml",
397 "yaml" | "yml" => "application/x-yaml",
398 "toml" => "application/toml",
399 "sql" => "application/sql",
400 "zip" => "application/zip",
401 "rar" => "application/vnd.rar",
402 "7z" => "application/x-7z-compressed",
403 "tar" => "application/x-tar",
404 "gz" => "application/gzip",
405 "bz2" => "application/x-bzip2",
406 "xz" => "application/x-xz",
407 "iso" => "application/x-iso9660-image",
408 "dmg" => "application/x-apple-diskimage",
409 "apk" => "application/vnd.android.package-archive",
410 "jar" => "application/java-archive",
411 "xdc" => "application/vnd.webxdc+zip",
412 "obj" => "model/obj",
413 "gltf" => "model/gltf+json",
414 "glb" => "model/gltf-binary",
415 "stl" => "model/stl",
416 "dae" => "model/vnd.collada+xml",
417 "js" => "text/javascript",
418 "py" => "text/x-python",
419 "rs" => "text/x-rust",
420 "go" => "text/x-go",
421 "java" => "text/x-java",
422 "c" => "text/x-c",
423 "cpp" => "text/x-c++",
424 "cs" => "text/x-csharp",
425 "rb" => "text/x-ruby",
426 "php" => "text/x-php",
427 "swift" => "text/x-swift",
428 "html" | "htm" => "text/html",
429 "css" => "text/css",
430 "exe" => "application/x-msdownload",
431 "msi" => "application/x-msi",
432 "ttf" => "font/ttf",
433 "otf" => "font/otf",
434 "woff" => "font/woff",
435 "woff2" => "font/woff2",
436 _ => "application/octet-stream",
437 }
438}
439
440pub fn extension_from_mime(mime: &str) -> String {
443 match mime.trim().to_lowercase().as_str() {
444 "image/png" => "png",
446 "image/jpeg" | "image/jpg" => "jpg",
447 "image/gif" => "gif",
448 "image/webp" => "webp",
449 "image/svg+xml" => "svg",
450 "image/bmp" | "image/x-ms-bmp" => "bmp",
451 "image/x-icon" | "image/vnd.microsoft.icon" => "ico",
452 "image/tiff" => "tiff",
453 "image/x-adobe-dng" => "dng",
454 "image/x-canon-cr2" => "cr2",
455 "image/x-nikon-nef" => "nef",
456 "image/x-sony-arw" => "arw",
457 "audio/wav" | "audio/x-wav" | "audio/wave" => "wav",
459 "audio/mp3" | "audio/mpeg" => "mp3",
460 "audio/flac" => "flac",
461 "audio/ogg" => "ogg",
462 "audio/mp4" => "m4a",
463 "audio/aac" | "audio/x-aac" => "aac",
464 "audio/x-ms-wma" => "wma",
465 "audio/opus" => "opus",
466 "video/mp4" => "mp4",
468 "video/webm" => "webm",
469 "video/quicktime" => "mov",
470 "video/x-msvideo" => "avi",
471 "video/x-matroska" => "mkv",
472 "video/x-flv" => "flv",
473 "video/x-ms-wmv" => "wmv",
474 "video/mpeg" => "mpg",
475 "video/3gpp" => "3gp",
476 "video/ogg" => "ogv",
477 "video/mp2t" => "ts",
478 "application/pdf" => "pdf",
480 "application/msword" => "doc",
481 "application/vnd.openxmlformats-officedocument.wordprocessingml.document" => "docx",
482 "application/vnd.ms-excel" => "xls",
483 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => "xlsx",
484 "application/vnd.ms-powerpoint" => "ppt",
485 "application/vnd.openxmlformats-officedocument.presentationml.presentation" => "pptx",
486 "application/vnd.oasis.opendocument.text" => "odt",
487 "application/vnd.oasis.opendocument.spreadsheet" => "ods",
488 "application/vnd.oasis.opendocument.presentation" => "odp",
489 "application/rtf" => "rtf",
490 "text/plain" => "txt",
492 "text/markdown" => "md",
493 "text/csv" => "csv",
494 "application/json" => "json",
495 "application/xml" | "text/xml" => "xml",
496 "application/x-yaml" | "text/yaml" => "yaml",
497 "application/toml" => "toml",
498 "application/sql" => "sql",
499 "application/zip" => "zip",
501 "application/x-rar-compressed" | "application/vnd.rar" => "rar",
502 "application/x-7z-compressed" => "7z",
503 "application/x-tar" => "tar",
504 "application/gzip" => "gz",
505 "application/x-bzip2" => "bz2",
506 "application/x-xz" => "xz",
507 "application/x-iso9660-image" => "iso",
508 "application/x-apple-diskimage" => "dmg",
509 "application/vnd.android.package-archive" => "apk",
510 "application/java-archive" => "jar",
511 "application/vnd.webxdc+zip" => "xdc",
512 "model/obj" => "obj",
514 "model/gltf+json" => "gltf",
515 "model/gltf-binary" => "glb",
516 "model/stl" | "application/sla" => "stl",
517 "model/vnd.collada+xml" => "dae",
518 "text/javascript" | "application/javascript" => "js",
520 "text/typescript" | "application/typescript" => "ts",
521 "text/x-python" | "application/x-python" => "py",
522 "text/x-rust" => "rs",
523 "text/x-go" => "go",
524 "text/x-java" => "java",
525 "text/x-c" => "c",
526 "text/x-c++" => "cpp",
527 "text/x-csharp" => "cs",
528 "text/x-ruby" => "rb",
529 "text/x-php" => "php",
530 "text/x-swift" => "swift",
531 "text/html" => "html",
533 "text/css" => "css",
534 "application/x-msdownload" | "application/x-dosexec" => "exe",
536 "application/x-msi" => "msi",
537 "application/x-font-ttf" | "font/ttf" => "ttf",
538 "application/x-font-otf" | "font/otf" => "otf",
539 "font/woff" => "woff",
540 "font/woff2" => "woff2",
541 _ => {
544 let lower = mime.trim().to_lowercase();
545 let sub = lower.split('/').nth(1).unwrap_or("");
546 let safe = !sub.is_empty() && sub.len() <= 16 && sub.bytes().all(|b| b.is_ascii_alphanumeric());
547 return if safe { sub.to_string() } else { "bin".to_string() };
548 }
549 }.to_string()
550}
551
552pub fn sanitize_filename(name: &str) -> String {
555 let base = name.rsplit('/').next().unwrap_or(name);
556 let base = base.rsplit('\\').next().unwrap_or(base);
557
558 let sanitized: String = base.chars().filter(|c| {
559 !matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' | '\0')
560 }).collect();
561
562 let sanitized = sanitized.trim_matches(|c: char| c == '.' || c == ' ');
563
564 if sanitized.is_empty() {
565 return String::new();
566 }
567
568 if let Some(dot_pos) = sanitized.rfind('.') {
569 let stem = &sanitized[..dot_pos];
570 let ext = &sanitized[dot_pos..];
571 if stem.len() > 64 {
572 let truncated = &stem[..stem.floor_char_boundary(64)];
573 return format!("{}{}", truncated, ext);
574 }
575 } else if sanitized.len() > 64 {
576 let truncated = &sanitized[..sanitized.floor_char_boundary(64)];
577 return truncated.to_string();
578 }
579
580 sanitized.to_string()
581}
582
583pub fn resolve_unique_filename(dir: &std::path::Path, name: &str) -> std::path::PathBuf {
588 let candidate = dir.join(name);
589 if !candidate.exists() {
590 return candidate;
591 }
592
593 let stem = std::path::Path::new(name)
594 .file_stem()
595 .and_then(|s| s.to_str())
596 .unwrap_or(name);
597 let ext = std::path::Path::new(name)
598 .extension()
599 .and_then(|s| s.to_str())
600 .unwrap_or("");
601
602 let mut counter = 1u32;
603 loop {
604 let suffixed = if ext.is_empty() {
605 format!("{}-{}", stem, counter)
606 } else {
607 format!("{}-{}.{}", stem, counter, ext)
608 };
609 let candidate = dir.join(&suffixed);
610 if !candidate.exists() {
611 return candidate;
612 }
613 counter += 1;
614 }
615}
616
617pub fn format_bytes(bytes: u64) -> String {
619 const KB: f64 = 1024.0;
620 const MB: f64 = KB * 1024.0;
621 const GB: f64 = MB * 1024.0;
622
623 if bytes < KB as u64 {
624 format!("{} B", bytes)
625 } else if bytes < MB as u64 {
626 format!("{:.1} KB", bytes as f64 / KB)
627 } else if bytes < GB as u64 {
628 format!("{:.1} MB", bytes as f64 / MB)
629 } else {
630 format!("{:.1} GB", bytes as f64 / GB)
631 }
632}
633
634pub fn is_image_mime(mime: &str) -> bool {
636 mime.trim().starts_with("image/")
637}
638
639pub fn mime_from_extension_safe(extension: &str, image_only: bool) -> Result<String, String> {
641 let mime = mime_from_extension(extension).to_string();
642 if image_only && !is_image_mime(&mime) {
643 return Err(mime);
644 }
645 Ok(mime)
646}
647
648pub const RECOGNISED_MIMES: &[&str] = &[
657 "image/png",
658 "image/jpeg",
659 "image/gif",
660 "image/webp",
661 "image/tiff",
662 "image/x-icon",
663 "image/svg+xml",
664 "image/bmp",
665 "video/webm",
666 "video/x-matroska",
667 "video/quicktime",
668 "video/mp4",
669];
670
671pub fn animated_format(bytes: &[u8]) -> Option<&'static str> {
676 if bytes.len() >= 6 && (&bytes[..6] == b"GIF87a" || &bytes[..6] == b"GIF89a") {
678 return Some("gif");
679 }
680 if bytes.len() >= 16 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
683 let vp8x_anim = bytes.len() >= 21 && &bytes[12..16] == b"VP8X" && bytes[20] & 0x02 != 0;
684 let anim_chunk = bytes[..bytes.len().min(64)].windows(4).any(|w| w == b"ANIM");
685 if vp8x_anim || anim_chunk {
686 return Some("webp");
687 }
688 }
689 if bytes.len() >= 8 && &bytes[..8] == b"\x89PNG\r\n\x1a\n" && png_has_actl(bytes) {
691 return Some("png");
692 }
693 None
694}
695
696fn png_has_actl(bytes: &[u8]) -> bool {
699 let mut off = 8; while off + 8 <= bytes.len() {
701 let len = u32::from_be_bytes([bytes[off], bytes[off + 1], bytes[off + 2], bytes[off + 3]]) as usize;
702 match &bytes[off + 4..off + 8] {
703 b"acTL" => return true,
704 b"IDAT" => return false,
705 _ => {}
706 }
707 off = off.saturating_add(12).saturating_add(len); }
709 false
710}
711
712pub fn still_png(bytes: &[u8]) -> Result<Vec<u8>, String> {
715 use image::ImageEncoder;
716 let rgba = decode_image_bounded(bytes)?.into_rgba8();
717 let mut out = Vec::new();
718 image::codecs::png::PngEncoder::new_with_quality(&mut out, image::codecs::png::CompressionType::Fast, image::codecs::png::FilterType::Adaptive)
719 .write_image(&rgba, rgba.width(), rgba.height(), image::ExtendedColorType::Rgba8)
720 .map_err(|e| format!("still encode: {e}"))?;
721 Ok(out)
722}
723
724pub fn mime_from_magic_bytes(bytes: &[u8]) -> &'static str {
725 if bytes.len() < 4 {
726 return "application/octet-stream";
727 }
728 match bytes[0] {
729 0x89 if bytes[1..4] == [0x50, 0x4E, 0x47] => "image/png",
730 0xFF if bytes[1..3] == [0xD8, 0xFF] => "image/jpeg",
731 b'G' if bytes.len() >= 6 && (bytes[..6] == *b"GIF87a" || bytes[..6] == *b"GIF89a") => "image/gif",
732 b'R' if bytes.len() > 12 && bytes[..4] == *b"RIFF" && bytes[8..12] == *b"WEBP" => "image/webp",
733 0x49 if bytes[1..4] == [0x49, 0x2A, 0x00] => "image/tiff",
734 0x4D if bytes[1..4] == [0x4D, 0x00, 0x2A] => "image/tiff",
735 0x00 if bytes[1..4] == [0x00, 0x01, 0x00] => "image/x-icon",
736 b'<' if bytes.starts_with(b"<?xml") || bytes.starts_with(b"<svg") => "image/svg+xml",
737 b'B' if bytes[1] == b'M' => "image/bmp",
738 0x1A if bytes[1..4] == [0x45, 0xDF, 0xA3] => {
740 if bytes.len() >= 64 && bytes[..64].windows(4).any(|w| w == b"webm") {
741 "video/webm"
742 } else {
743 "video/x-matroska"
744 }
745 }
746 _ if bytes.len() >= 12 && bytes[4..8] == *b"ftyp" => match &bytes[8..12] {
748 b"qt " => "video/quicktime",
749 _ => "video/mp4",
750 },
751 _ => "application/octet-stream",
752 }
753}
754
755#[inline]
762pub fn looks_encrypted(s: &str) -> bool {
763 if s.len() < 56 { return false; }
764 is_all_lowercase_hex(s.as_bytes())
765}
766
767#[cfg(target_arch = "aarch64")]
769#[inline]
770fn is_all_lowercase_hex(bytes: &[u8]) -> bool {
771 use std::arch::aarch64::*;
772 unsafe {
773 let mut i = 0;
774 while i + 16 <= bytes.len() {
775 let chunk = vld1q_u8(bytes.as_ptr().add(i));
776 let is_digit = vandq_u8(vcgeq_u8(chunk, vdupq_n_u8(b'0')),
777 vcleq_u8(chunk, vdupq_n_u8(b'9')));
778 let is_af = vandq_u8(vcgeq_u8(chunk, vdupq_n_u8(b'a')),
779 vcleq_u8(chunk, vdupq_n_u8(b'f')));
780 if vminvq_u8(vorrq_u8(is_digit, is_af)) == 0 { return false; }
781 i += 16;
782 }
783 while i < bytes.len() {
784 let b = bytes[i];
785 if !matches!(b, b'0'..=b'9' | b'a'..=b'f') { return false; }
786 i += 1;
787 }
788 }
789 true
790}
791
792#[cfg(target_arch = "x86_64")]
794#[inline]
795fn is_all_lowercase_hex(bytes: &[u8]) -> bool {
796 use std::arch::x86_64::*;
797 unsafe {
798 let mut i = 0;
799 while i + 16 <= bytes.len() {
800 let chunk = _mm_loadu_si128(bytes.as_ptr().add(i) as *const __m128i);
801 let is_digit = _mm_cmpeq_epi8(
802 _mm_subs_epu8(_mm_sub_epi8(chunk, _mm_set1_epi8(b'0' as i8)), _mm_set1_epi8(9)),
803 _mm_setzero_si128());
804 let is_af = _mm_cmpeq_epi8(
805 _mm_subs_epu8(_mm_sub_epi8(chunk, _mm_set1_epi8(b'a' as i8)), _mm_set1_epi8(5)),
806 _mm_setzero_si128());
807 if _mm_movemask_epi8(_mm_or_si128(is_digit, is_af)) != 0xFFFF { return false; }
808 i += 16;
809 }
810 while i < bytes.len() {
811 let b = bytes[i];
812 if !matches!(b, b'0'..=b'9' | b'a'..=b'f') { return false; }
813 i += 1;
814 }
815 }
816 true
817}
818
819#[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))]
821#[inline]
822fn is_all_lowercase_hex(bytes: &[u8]) -> bool {
823 const IS_LOWER_HEX: [bool; 256] = {
824 let mut t = [false; 256];
825 t[b'0' as usize] = true; t[b'1' as usize] = true; t[b'2' as usize] = true;
826 t[b'3' as usize] = true; t[b'4' as usize] = true; t[b'5' as usize] = true;
827 t[b'6' as usize] = true; t[b'7' as usize] = true; t[b'8' as usize] = true;
828 t[b'9' as usize] = true; t[b'a' as usize] = true; t[b'b' as usize] = true;
829 t[b'c' as usize] = true; t[b'd' as usize] = true; t[b'e' as usize] = true;
830 t[b'f' as usize] = true;
831 t
832 };
833 bytes.iter().all(|&b| IS_LOWER_HEX[b as usize])
834}
835
836pub async fn maybe_decrypt_inner(ciphertext: String, password: Option<String>) -> Result<String, ()> {
839 let opened = if let Some(pass) = password {
840 let Ok(kdf) = Kdf::of_account() else { return Err(()) };
841 let mut key = derive_key(&pass, &kdf).await;
842 let opened = open_hex(&ciphertext, &key);
843 key.zeroize();
844 opened
845 } else {
846 crate::state::ENCRYPTION_KEY.with_key(|key| open_hex(&ciphertext, key)).ok_or(())?
847 };
848 opened.or_else(|| open_hex_previous(&ciphertext)).ok_or(())
849}
850
851pub async fn maybe_decrypt(input: String) -> Result<String, ()> {
854 if !looks_encrypted(&input) {
857 return Ok(input);
858 }
859 if let Some(plaintext) = open_with_vault(&input) {
860 return Ok(plaintext);
861 }
862 if crate::state::is_encryption_enabled_fast() { Err(()) } else { Ok(input) }
863}
864
865fn open_with_vault(hex_data: &str) -> Option<String> {
866 let opened = crate::state::ENCRYPTION_KEY.with_key(|key| open_hex(hex_data, key)).flatten();
867 opened.or_else(|| open_hex_previous(hex_data))
868}
869
870pub fn open_batch<R>(f: impl FnOnce(&mut AtRestOpener) -> R) -> R {
874 f(&mut AtRestOpener { cipher: None, loaded: false })
875}
876
877pub struct AtRestOpener {
880 cipher: Option<ChaCha20Poly1305>,
881 loaded: bool,
882}
883
884impl AtRestOpener {
885 fn cipher(&mut self) -> Option<&ChaCha20Poly1305> {
886 if !self.loaded {
887 self.loaded = true;
888 crate::state::ENCRYPTION_KEY.with_key(|key| self.cipher = Some(ChaCha20Poly1305::new(key)));
889 }
890 self.cipher.as_ref()
891 }
892
893 pub fn open_or_keep(&mut self, input: String) -> String {
896 if !looks_encrypted(&input) {
897 return input;
898 }
899 self.cipher().and_then(|c| open_hex_with(c, &input)).or_else(|| open_with_vault(&input)).unwrap_or(input)
900 }
901
902 pub fn open_blob_or_keep(&mut self, stored: &[u8]) -> Vec<u8> {
904 if stored.len() == 32 {
905 return stored.to_vec();
906 }
907 if stored.len() >= NONCE_LEN + TAG_LEN {
908 if let Some(opened) = self.cipher().and_then(|c| open_framed_with(c, stored.to_vec())) {
909 return opened;
910 }
911 }
912 maybe_decrypt_blob(stored)
913 }
914
915 #[allow(clippy::result_unit_err)] pub fn open(&mut self, input: String) -> Result<String, ()> {
918 if !looks_encrypted(&input) {
919 return Ok(input);
920 }
921 if let Some(plaintext) = self.cipher().and_then(|c| open_hex_with(c, &input)).or_else(|| open_with_vault(&input)) {
924 return Ok(plaintext);
925 }
926 if crate::state::is_encryption_enabled_fast() { Err(()) } else { Ok(input) }
927 }
928}
929
930pub fn seal_batch<R>(f: impl FnOnce(&mut AtRestSealer) -> R) -> R {
933 gate::require_held("seal_batch");
934 f(&mut AtRestSealer { cipher: None })
935}
936
937pub struct AtRestSealer {
939 cipher: Option<Option<ChaCha20Poly1305>>,
941}
942
943impl AtRestSealer {
944 pub fn seal(&mut self, plaintext: &str) -> Result<String, String> {
946 if self.cipher.is_none() {
947 gate::with_sealing_key(|key| self.cipher = Some(key.map(ChaCha20Poly1305::new)))?;
948 }
949 let Some(Some(cipher)) = self.cipher.as_ref() else {
950 return Ok(plaintext.to_string());
951 };
952 let framed = seal_framed_with(cipher, plaintext.as_bytes()).map_err(|e| format!("Encryption failed: {e}"))?;
953 Ok(crate::simd::hex::bytes_to_hex_string(&framed))
954 }
955
956 pub fn seal_blob(&mut self, plaintext: &[u8]) -> Result<Vec<u8>, String> {
958 if self.cipher.is_none() {
959 gate::with_sealing_key(|key| self.cipher = Some(key.map(ChaCha20Poly1305::new)))?;
960 }
961 let Some(Some(cipher)) = self.cipher.as_ref() else {
962 return Ok(plaintext.to_vec());
963 };
964 seal_framed_with(cipher, plaintext).map_err(|e| format!("blob encryption failed: {e}"))
965 }
966
967 pub fn seal_set(&mut self, plaintext: &str) -> Result<String, String> {
969 if plaintext.is_empty() { Ok(String::new()) } else { self.seal(plaintext) }
970 }
971}
972
973pub fn encrypt_blob_with_key(plaintext: &[u8], key: &[u8; 32]) -> Result<Vec<u8>, String> {
986 seal_framed(plaintext, key).map_err(|e| format!("blob encryption failed: {}", e))
987}
988
989pub fn decrypt_blob_with_key(stored: &[u8], key: &[u8; 32]) -> Result<Vec<u8>, String> {
991 if stored.len() < NONCE_LEN + TAG_LEN {
992 return Err("blob too short to be ciphertext".to_string());
993 }
994 open_framed(stored.to_vec(), key).ok_or_else(|| "blob decryption failed (wrong key or corrupted)".to_string())
995}
996
997pub fn maybe_encrypt_blob(plaintext: &[u8]) -> Result<Vec<u8>, String> {
1000 gate::require_held("maybe_encrypt_blob");
1001 gate::with_sealing_key(|key| match key {
1002 Some(key) => encrypt_blob_with_key(plaintext, key),
1003 None => Ok(plaintext.to_vec()),
1004 })?
1005}
1006
1007pub fn maybe_decrypt_blob(stored: &[u8]) -> Vec<u8> {
1011 if stored.len() == 32 {
1013 return stored.to_vec();
1014 }
1015 let opened = crate::state::ENCRYPTION_KEY.with_key(|key| decrypt_blob_with_key(stored, key).ok()).flatten();
1016 opened.or_else(|| open_blob_previous(stored)).unwrap_or_else(|| stored.to_vec())
1017}
1018
1019pub fn maybe_encrypt_text(plaintext: &str) -> Result<String, String> {
1022 gate::require_held("maybe_encrypt_text");
1023 gate::with_sealing_key(|key| match key {
1024 Some(key) => encrypt_with_key(plaintext, key),
1025 None => Ok(plaintext.to_string()),
1026 })?
1027}
1028
1029pub fn maybe_decrypt_text(stored: &str) -> String {
1032 if !looks_encrypted(stored) {
1033 return stored.to_string();
1034 }
1035 open_with_vault(stored).unwrap_or_else(|| stored.to_string())
1036}
1037
1038#[cfg(test)]
1039mod at_rest_batch_tests {
1040 use super::*;
1041
1042 fn with_vault<R>(key: Option<[u8; 32]>, enabled: bool, f: impl FnOnce() -> R) -> R {
1044 let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1045 match key {
1046 Some(k) => crate::state::ENCRYPTION_KEY.set(k, &[]),
1047 None => crate::state::ENCRYPTION_KEY.clear(&[]),
1048 }
1049 crate::state::set_encryption_enabled(enabled);
1050 let out = f();
1051 crate::state::set_encryption_enabled(false);
1052 crate::state::ENCRYPTION_KEY.clear(&[]);
1053 out
1054 }
1055
1056 fn rows(key: &[u8; 32]) -> Vec<String> {
1057 vec![
1058 encrypt_with_key("first", key).unwrap(),
1059 "plain row".to_string(),
1060 encrypt_with_key("", key).unwrap(),
1061 encrypt_with_key(&"long ".repeat(300), key).unwrap(),
1062 encrypt_with_key("wrong key", &[9u8; 32]).unwrap(),
1063 "cafe".repeat(20),
1064 ]
1065 }
1066
1067 #[test]
1068 fn a_batch_answers_every_row_as_maybe_decrypt_does() {
1069 use futures_util::FutureExt;
1070 let key = [0x55u8; 32];
1071 let rows = rows(&key);
1072 for enabled in [true, false] {
1073 with_vault(Some(key), enabled, || {
1074 let expected: Vec<_> = rows.iter().map(|r| maybe_decrypt(r.clone()).now_or_never().unwrap()).collect();
1076 let batched = open_batch(|at_rest| rows.iter().map(|r| at_rest.open(r.clone())).collect::<Vec<_>>());
1077 assert_eq!(batched, expected, "encryption enabled: {enabled}");
1078 });
1079 }
1080 }
1081
1082 #[test]
1083 fn a_batch_answers_every_blob_as_maybe_decrypt_blob_does() {
1084 let key = [0x55u8; 32];
1085 let blobs = vec![
1086 encrypt_blob_with_key(&[1u8; 32], &key).unwrap(),
1087 vec![2u8; 32],
1088 encrypt_blob_with_key(&[3u8; 32], &[9u8; 32]).unwrap(),
1089 vec![4u8; 10],
1090 encrypt_blob_with_key(b"", &key).unwrap(),
1091 ];
1092 for vault in [Some(key), None] {
1093 with_vault(vault, true, || {
1094 let expected: Vec<_> = blobs.iter().map(|b| maybe_decrypt_blob(b)).collect();
1095 let batched = open_batch(|at_rest| blobs.iter().map(|b| at_rest.open_blob_or_keep(b)).collect::<Vec<_>>());
1096 assert_eq!(batched, expected, "vault holds the key: {}", vault.is_some());
1097 });
1098 }
1099 }
1100
1101 #[test]
1102 fn a_batch_opens_rows_still_under_the_key_a_pin_change_replaced() {
1103 let (old, new) = ([0x31u8; 32], [0x32u8; 32]);
1104 let text = encrypt_with_key("sealed before the change", &old).unwrap();
1105 let blob = encrypt_blob_with_key(&[7u8; 32], &old).unwrap();
1106 let (batched, single) = with_vault(Some(new), true, || {
1107 hold_previous_key(&old);
1108 let batched = open_batch(|at_rest| {
1109 (at_rest.open_or_keep(text.clone()), at_rest.open_blob_or_keep(&blob), at_rest.open(text.clone()))
1110 });
1111 let single = (maybe_decrypt_text(&text), maybe_decrypt_blob(&blob));
1112 crate::state::PREVIOUS_AT_REST_KEY.clear(&[]);
1113 (batched, single)
1114 });
1115 assert_eq!(batched.0, "sealed before the change");
1116 assert_eq!(batched.1, vec![7u8; 32]);
1117 assert_eq!(batched.2, Ok("sealed before the change".to_string()));
1118 assert_eq!((batched.0, batched.1), single, "the batch answers as the single-row opens do");
1119 }
1120
1121 #[test]
1122 fn plaintext_rows_never_need_the_key() {
1123 let got = with_vault(None, true, || open_batch(|at_rest| vec![at_rest.open("hello".into()), at_rest.open("a b c".into())]));
1124 assert_eq!(got, vec![Ok("hello".to_string()), Ok("a b c".to_string())]);
1125 }
1126
1127 #[test]
1128 fn a_ciphertext_with_no_key_in_the_vault_is_refused_while_encryption_is_on() {
1129 let sealed = encrypt_with_key("secret", &[0x55u8; 32]).unwrap();
1130 let on = with_vault(None, true, || open_batch(|at_rest| at_rest.open(sealed.clone())));
1131 assert_eq!(on, Err(()));
1132 let off = with_vault(None, false, || open_batch(|at_rest| at_rest.open(sealed.clone())));
1133 assert_eq!(off, Ok(sealed), "encryption off: an undecryptable row reads through as-is");
1134 }
1135}
1136
1137#[cfg(test)]
1138mod attachment_cipher_tests {
1139 use super::*;
1140
1141 const PINNED: [(usize, &str); 6] = [
1143 (0, "022f841c702b66b0bec8111f67de221d"),
1144 (1, "292017643f9281af327f9487e3df3e3d7c"),
1145 (15, "29a932a407ebe042f8dc56e1ba4ae84d9c12aa8198954368a48d9deebb7ab9"),
1146 (16, "29a932a407ebe042f8dc56e1ba4ae8fc890ce0e3fa7321a07ba4f5bedc8e26e7"),
1147 (17, "29a932a407ebe042f8dc56e1ba4ae8fcf1bed63597cf6053bc96b53c32185e0ecd"),
1148 (100, "29a932a407ebe042f8dc56e1ba4ae8fcf13fc2f1f1a2cc0856a0d376defbf35bef7b179b6ad5b2a9f52b19922f7cf2bc4960c60abb73d0a56dabe7c406cb1555ca5427dad72a529c7f8f0c592ce2d0c49b46f9f9011bda808e760db92ad6ecc171a88a1ce072e4f68ec1b5cc3a5e23c37c645be7"),
1149 ];
1150
1151 #[test]
1152 fn attachment_cipher_matches_pinned_vectors() {
1153 let params = EncryptionParams {
1154 key: "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f".to_string(),
1155 nonce: "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf".to_string(),
1156 };
1157 for (len, want) in PINNED {
1158 let pt: Vec<u8> = (0..len).map(|i| (i * 7 + 3) as u8).collect();
1159 let sealed = encrypt_data(&pt, ¶ms).unwrap();
1160 assert_eq!(hex::encode(&sealed), want, "seal len={len}");
1161 let ct = hex::decode(want).unwrap();
1162 assert_eq!(decrypt_data(&ct, ¶ms.key, ¶ms.nonce).unwrap(), pt, "open len={len}");
1163 }
1164 }
1165}
1166
1167#[cfg(test)]
1168mod at_rest_tests {
1169 use super::*;
1170
1171 #[test]
1172 fn blob_roundtrip_with_explicit_key() {
1173 let key = [7u8; 32];
1174 let secret = [0x42u8; 32];
1175 let ct = encrypt_blob_with_key(&secret, &key).unwrap();
1176 assert_eq!(ct.len(), 12 + 32 + 16, "nonce + ciphertext + tag");
1177 assert_ne!(&ct[12..44], &secret[..], "ciphertext must not equal plaintext");
1178 assert_eq!(decrypt_blob_with_key(&ct, &key).unwrap(), secret.to_vec());
1179 }
1180
1181 #[test]
1182 fn blob_wrong_key_fails() {
1183 let ct = encrypt_blob_with_key(&[1u8; 32], &[7u8; 32]).unwrap();
1184 assert!(decrypt_blob_with_key(&ct, &[9u8; 32]).is_err());
1185 }
1186
1187 #[test]
1188 fn encrypted_text_is_always_detected_as_encrypted() {
1189 let key = [3u8; 32];
1192 for s in ["", "[]", "{}", "a"] {
1193 let ct = encrypt_with_key(s, &key).unwrap();
1194 assert!(looks_encrypted(&ct), "ciphertext for {:?} must look encrypted", s);
1195 assert_eq!(decrypt_with_key(&ct, &key).unwrap(), s);
1196 }
1197 }
1198}
1199
1200pub use crate::simd::image::nearest_neighbor_downsample_rgba;
1206
1207pub fn generate_thumbhash_from_rgba(pixels: &[u8], width: u32, height: u32) -> Option<String> {
1212 use fast_thumbhash::{rgba_to_thumb_hash, base91_encode};
1213
1214 const MAX_DIM: u32 = 100;
1215
1216 let (thumb_w, thumb_h) = if width <= MAX_DIM && height <= MAX_DIM {
1217 (width, height)
1218 } else if width > height {
1219 (MAX_DIM, (MAX_DIM * height / width).max(1))
1220 } else {
1221 ((MAX_DIM * width / height).max(1), MAX_DIM)
1222 };
1223
1224 let thumbnail = if thumb_w == width && thumb_h == height {
1225 pixels.to_vec()
1226 } else {
1227 nearest_neighbor_downsample_rgba(pixels, width, height, thumb_w, thumb_h)
1228 };
1229
1230 let hash = rgba_to_thumb_hash(thumb_w as usize, thumb_h as usize, &thumbnail);
1231 Some(base91_encode(&hash))
1232}
1233
1234pub fn decode_image_bounded(bytes: &[u8]) -> Result<image::DynamicImage, String> {
1244 use image::ImageDecoder;
1245 let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes))
1246 .with_guessed_format()
1247 .map_err(|e| format!("image format: {e}"))?;
1248 reader.limits(bounded_image_limits());
1249 let mut decoder = reader.into_decoder().map_err(|e| format!("image decode: {e}"))?;
1250 let orientation = decoder.orientation().map_err(|e| format!("image orientation: {e}"))?;
1252 let mut img = image::DynamicImage::from_decoder(decoder)
1253 .map_err(|e| format!("image decode: {e}"))?;
1254 img.apply_orientation(orientation);
1255 Ok(img)
1256}
1257
1258pub fn bounded_image_limits() -> image::Limits {
1261 let mut limits = image::Limits::default();
1262 limits.max_image_width = Some(16_384);
1263 limits.max_image_height = Some(16_384);
1264 limits.max_alloc = Some(256 * 1024 * 1024);
1265 limits
1266}
1267
1268pub fn generate_image_metadata(file_bytes: &[u8]) -> Option<crate::types::ImageMetadata> {
1273 let img = decode_image_bounded(file_bytes).ok()?;
1274 let width = img.width();
1275 let height = img.height();
1276
1277 let small = if width > 100 || height > 100 { img.thumbnail(100, 100) } else { img };
1280 let rgba = small.to_rgba8();
1281 let thumbhash = generate_thumbhash_from_rgba(rgba.as_raw(), rgba.width(), rgba.height())?;
1282
1283 Some(crate::types::ImageMetadata {
1284 thumbhash,
1285 width,
1286 height,
1287 })
1288}
1289
1290#[cfg(test)]
1291mod tests {
1292 #[test]
1293 fn a_senders_mime_can_only_name_a_plain_extension() {
1294 use super::extension_from_mime;
1295 assert_eq!(extension_from_mime("image/png"), "png");
1296 assert_eq!(extension_from_mime("application/x-bittorrent"), "bin");
1297 assert_eq!(extension_from_mime("audio/opus"), "opus");
1298 assert_eq!(extension_from_mime("x/.\\..\\..\\AppData\\Startup\\a.bat"), "bin");
1299 assert_eq!(extension_from_mime("x/../../etc"), "bin");
1300 assert_eq!(extension_from_mime("nothing"), "bin");
1301 }
1302
1303 use super::*;
1304
1305 #[test]
1309 fn magic_bytes_name_video_and_bitmaps() {
1310 let mut mp4 = vec![0u8, 0, 0, 0x20];
1311 mp4.extend_from_slice(b"ftypisom");
1312 assert_eq!(mime_from_magic_bytes(&mp4), "video/mp4");
1313
1314 let mut mov = vec![0u8, 0, 0, 0x14];
1315 mov.extend_from_slice(b"ftypqt ");
1316 assert_eq!(mime_from_magic_bytes(&mov), "video/quicktime");
1317
1318 let mut webm = vec![0x1A, 0x45, 0xDF, 0xA3];
1319 webm.extend_from_slice(&[0u8; 20]);
1320 webm.extend_from_slice(b"webm");
1321 webm.extend_from_slice(&[0u8; 40]);
1322 assert_eq!(mime_from_magic_bytes(&webm), "video/webm");
1323
1324 let mut mkv = vec![0x1A, 0x45, 0xDF, 0xA3];
1325 mkv.extend_from_slice(&[0u8; 64]);
1326 assert_eq!(mime_from_magic_bytes(&mkv), "video/x-matroska");
1327
1328 let mut bmp = b"BM".to_vec();
1329 bmp.extend_from_slice(&[0u8; 20]);
1330 assert_eq!(mime_from_magic_bytes(&bmp), "image/bmp");
1331 }
1332
1333 #[test]
1336 fn every_recognised_mime_is_reachable_from_some_bytes() {
1337 let mut webm = vec![0x1A, 0x45, 0xDF, 0xA3];
1338 webm.extend_from_slice(&[0u8; 20]);
1339 webm.extend_from_slice(b"webm");
1340 webm.resize(80, 0);
1341 let mut mkv = vec![0x1A, 0x45, 0xDF, 0xA3];
1342 mkv.resize(80, 0);
1343 let mut webp = b"RIFF".to_vec();
1344 webp.extend_from_slice(&[0u8; 4]);
1345 webp.extend_from_slice(b"WEBP____");
1346
1347 let samples: Vec<Vec<u8>> = vec![
1348 vec![0x89, b'P', b'N', b'G'],
1349 vec![0xFF, 0xD8, 0xFF, 0xE0],
1350 b"GIF89a__".to_vec(),
1351 webp,
1352 vec![0x49, 0x49, 0x2A, 0x00],
1353 vec![0x00, 0x00, 0x01, 0x00],
1354 b"<svg xmlns".to_vec(),
1355 b"BM______".to_vec(),
1356 webm,
1357 mkv,
1358 b"\0\0\0\x14ftypqt ".to_vec(),
1359 b"\0\0\0\x20ftypisom".to_vec(),
1360 ];
1361 let reachable: std::collections::HashSet<&str> =
1362 samples.iter().map(|b| mime_from_magic_bytes(b)).collect();
1363 for m in RECOGNISED_MIMES {
1364 assert!(reachable.contains(m), "{m} is listed but no bytes produce it");
1365 }
1366 assert_eq!(reachable.len(), RECOGNISED_MIMES.len(), "and nothing is produced that is not listed");
1367 }
1368
1369 #[test]
1371 fn magic_bytes_still_name_the_image_types() {
1372 assert_eq!(mime_from_magic_bytes(&[0x89, b'P', b'N', b'G']), "image/png");
1373 assert_eq!(mime_from_magic_bytes(&[0xFF, 0xD8, 0xFF, 0xE0]), "image/jpeg");
1374 assert_eq!(mime_from_magic_bytes(b"GIF89a__"), "image/gif");
1375 let mut webp = b"RIFF".to_vec();
1376 webp.extend_from_slice(&[0u8; 4]);
1377 webp.extend_from_slice(b"WEBP____");
1378 assert_eq!(mime_from_magic_bytes(&webp), "image/webp");
1379 assert_eq!(mime_from_magic_bytes(b"<svg xmlns"), "image/svg+xml");
1380 assert_eq!(mime_from_magic_bytes(&[0xDE, 0xAD, 0xBE, 0xEF]), "application/octet-stream");
1381 assert_eq!(mime_from_magic_bytes(&[]), "application/octet-stream", "a short read is not a type");
1382 assert_eq!(mime_from_magic_bytes(b"Bm"), "application/octet-stream", "and BMP is case-sensitive");
1383 }
1384
1385 fn test_key() -> [u8; 32] {
1390 [0x42u8; 32]
1391 }
1392
1393 fn alt_key() -> [u8; 32] {
1394 [0x99u8; 32]
1395 }
1396
1397 #[test]
1398 fn encrypt_decrypt_roundtrip_simple() {
1399 let key = test_key();
1400 let plaintext = "hello world";
1401 let encrypted = encrypt_with_key(plaintext, &key).expect("encryption should succeed");
1402 let decrypted = decrypt_with_key(&encrypted, &key).expect("decryption should succeed");
1403 assert_eq!(decrypted, plaintext, "roundtrip should preserve plaintext");
1404 }
1405
1406 #[test]
1407 fn encrypt_decrypt_100_random_strings() {
1408 use rand::Rng;
1409 let key = test_key();
1410 let mut rng = rand::thread_rng();
1411 for i in 0..100 {
1412 let len = rng.gen_range(1..=200);
1413 let s: String = (0..len).map(|_| rng.gen_range(0x20u8..0x7f) as char).collect();
1414 let enc = encrypt_with_key(&s, &key)
1415 .unwrap_or_else(|e| panic!("encryption failed on iteration {}: {}", i, e));
1416 let dec = decrypt_with_key(&enc, &key)
1417 .unwrap_or_else(|e| panic!("decryption failed on iteration {}: {}", i, e));
1418 assert_eq!(dec, s, "roundtrip failed on iteration {}", i);
1419 }
1420 }
1421
1422 #[test]
1423 fn encrypt_decrypt_empty_string() {
1424 let key = test_key();
1425 let encrypted = encrypt_with_key("", &key).expect("encrypting empty string should succeed");
1426 let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting empty string should succeed");
1427 assert_eq!(decrypted, "", "empty string roundtrip should produce empty string");
1428 }
1429
1430 #[test]
1431 fn encrypt_decrypt_large_string() {
1432 let key = test_key();
1433 let plaintext = "A".repeat(10 * 1024); let encrypted = encrypt_with_key(&plaintext, &key).expect("encrypting 10KB should succeed");
1435 let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting 10KB should succeed");
1436 assert_eq!(decrypted, plaintext, "10KB roundtrip should preserve content");
1437 }
1438
1439 #[test]
1440 fn decrypt_with_wrong_key_fails() {
1441 let key = test_key();
1442 let wrong_key = alt_key();
1443 let encrypted = encrypt_with_key("secret data", &key).expect("encryption should succeed");
1444 let result = decrypt_with_key(&encrypted, &wrong_key);
1445 assert!(result.is_err(), "decryption with wrong key should fail");
1446 }
1447
1448 #[test]
1449 fn decrypt_corrupted_ciphertext_fails() {
1450 let key = test_key();
1451 let mut encrypted = encrypt_with_key("secret data", &key).expect("encryption should succeed");
1452 let bytes: Vec<u8> = encrypted.bytes().collect();
1454 if bytes.len() > 30 {
1455 let mut chars: Vec<char> = encrypted.chars().collect();
1456 chars[30] = if chars[30] == '0' { 'f' } else { '0' };
1458 encrypted = chars.into_iter().collect();
1459 }
1460 let result = decrypt_with_key(&encrypted, &key);
1461 assert!(result.is_err(), "decryption of corrupted ciphertext should fail");
1462 }
1463
1464 #[test]
1465 fn different_keys_produce_different_ciphertext() {
1466 let key1 = test_key();
1467 let key2 = alt_key();
1468 let plaintext = "same plaintext";
1469 let enc1 = encrypt_with_key(plaintext, &key1).expect("enc1 should succeed");
1470 let enc2 = encrypt_with_key(plaintext, &key2).expect("enc2 should succeed");
1471 assert_ne!(enc1, enc2, "different keys should produce different ciphertext");
1473 }
1474
1475 #[test]
1476 fn nonce_is_always_different() {
1477 let key = test_key();
1478 let plaintext = "same string encrypted twice";
1479 let enc1 = encrypt_with_key(plaintext, &key).expect("enc1 should succeed");
1480 let enc2 = encrypt_with_key(plaintext, &key).expect("enc2 should succeed");
1481 let nonce1 = &enc1[..24];
1483 let nonce2 = &enc2[..24];
1484 assert_ne!(nonce1, nonce2, "nonces should differ between encryptions of the same plaintext");
1485 }
1486
1487 #[test]
1488 fn unicode_content_preserved() {
1489 let key = test_key();
1490 let plaintext = "Hello \u{1F600} \u{1F4A9} \u{1F30D} \u{00E9}\u{00E0}\u{00FC} \u{4E16}\u{754C} \u{0410}\u{0411}\u{0412}";
1491 let encrypted = encrypt_with_key(plaintext, &key).expect("encrypting unicode should succeed");
1492 let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting unicode should succeed");
1493 assert_eq!(decrypted, plaintext, "unicode content should be preserved through encrypt/decrypt");
1494 }
1495
1496 #[test]
1497 fn decrypt_too_short_ciphertext_fails() {
1498 let key = test_key();
1499 let result = decrypt_with_key("abcdef", &key);
1500 assert!(result.is_err(), "ciphertext shorter than 24 hex chars should fail");
1501 assert!(result.unwrap_err().contains("too short"), "error should mention too short");
1502 }
1503
1504 #[test]
1505 fn encrypt_output_is_hex_encoded() {
1506 let key = test_key();
1507 let encrypted = encrypt_with_key("test", &key).expect("encryption should succeed");
1508 assert!(encrypted.chars().all(|c| c.is_ascii_hexdigit()),
1509 "encrypted output should be entirely hex characters");
1510 }
1511
1512 #[test]
1513 fn encrypt_output_has_correct_structure() {
1514 let key = test_key();
1515 let encrypted = encrypt_with_key("test", &key).expect("encryption should succeed");
1516 assert!(encrypted.len() > 24,
1518 "encrypted output should have nonce (24 hex chars) plus ciphertext");
1519 assert_eq!(encrypted.len() % 2, 0,
1521 "encrypted output length should be even (hex pairs)");
1522 }
1523
1524 #[test]
1525 fn encrypt_decrypt_special_characters() {
1526 let key = test_key();
1527 let plaintext = r#"!@#$%^&*()_+-=[]{}|;':",.<>?/\`~"#;
1528 let encrypted = encrypt_with_key(plaintext, &key).expect("encrypting special chars should succeed");
1529 let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting special chars should succeed");
1530 assert_eq!(decrypted, plaintext, "special characters should survive roundtrip");
1531 }
1532
1533 #[test]
1534 fn encrypt_decrypt_newlines_and_whitespace() {
1535 let key = test_key();
1536 let plaintext = "line1\nline2\r\nline3\ttab\0null";
1537 let encrypted = encrypt_with_key(plaintext, &key).expect("encrypting whitespace should succeed");
1538 let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting whitespace should succeed");
1539 assert_eq!(decrypted, plaintext, "whitespace and control chars should survive roundtrip");
1540 }
1541
1542 #[test]
1543 fn decrypt_invalid_hex_in_nonce_fails() {
1544 let key = test_key();
1545 let bad = "zzzzzzzzzzzzzzzzzzzzzzzz0000000000000000";
1547 let result = decrypt_with_key(bad, &key);
1548 assert!(result.is_err(), "invalid hex in nonce should fail");
1549 }
1550
1551 #[test]
1552 fn decrypt_invalid_hex_in_ciphertext_fails() {
1553 let key = test_key();
1554 let bad = "000000000000000000000000gggggggg";
1556 let result = decrypt_with_key(bad, &key);
1557 assert!(result.is_err(), "invalid hex in ciphertext should fail");
1558 }
1559
1560 #[test]
1565 fn hex_encode_decode_roundtrip() {
1566 let data = vec![0x00, 0x01, 0xff, 0x80, 0x7f];
1567 let encoded = hex::encode(&data);
1568 let decoded = hex::decode(&encoded).expect("decode should succeed");
1569 assert_eq!(decoded, data, "hex encode/decode roundtrip should preserve bytes");
1570 }
1571
1572 #[test]
1573 fn hex_decode_odd_length_error() {
1574 let result = hex::decode("abc");
1575 assert!(result.is_err(), "odd-length hex string should fail");
1576 assert!(result.unwrap_err().contains("Odd-length"), "error should mention odd-length");
1577 }
1578
1579 #[test]
1580 fn hex_decode_invalid_hex_error() {
1581 let result = hex::decode("zzzz");
1582 assert!(result.is_err(), "invalid hex characters should fail");
1583 }
1584
1585 #[test]
1586 fn hex_encode_empty() {
1587 assert_eq!(hex::encode(&[]), "", "encoding empty bytes should produce empty string");
1588 }
1589
1590 #[test]
1591 fn hex_decode_empty() {
1592 let decoded = hex::decode("").expect("decoding empty string should succeed");
1593 assert!(decoded.is_empty(), "decoding empty string should produce empty vec");
1594 }
1595
1596 #[tokio::test]
1603 async fn the_legacy_derivation_is_unchanged() {
1604 let key = derive_key("legacy-check", &Kdf::Legacy).await;
1605 assert_eq!(
1606 crate::simd::hex::bytes_to_hex_string(&key),
1607 "3be43f3aae893d0a07de2d1820ebdb9908ce98e07f50dab5cbfaded6fd8a5dcf"
1608 );
1609 }
1610
1611 #[tokio::test]
1612 async fn a_salt_makes_the_same_pin_a_different_key() {
1613 let (a, b) = (Kdf::fresh(), Kdf::fresh());
1614 assert_ne!(a, b, "every credential gets its own salt");
1615 let ka = derive_key("123456", &a).await;
1616 assert_eq!(ka, derive_key("123456", &a).await, "deterministic for one salt");
1617 assert_ne!(ka, derive_key("123456", &b).await);
1618 assert_ne!(ka, derive_key("123456", &Kdf::Legacy).await);
1619 }
1620
1621 #[test]
1622 fn the_stored_derivation_round_trips_and_refuses_what_it_does_not_know() {
1623 let kdf = Kdf::fresh();
1624 let stored = kdf.descriptor().unwrap();
1625 assert!(stored.starts_with("argon2id-v2:"));
1626 assert_eq!(Kdf::parse(&stored).unwrap(), kdf);
1627 assert_eq!(Kdf::Legacy.descriptor(), None, "legacy is stored as no row");
1628 for bad in ["argon2id-v3:00", "argon2id-v2:abcd", "argon2id-v2:zz", "", "legacy"] {
1629 assert!(Kdf::parse(bad).is_err(), "{bad:?} must not parse");
1630 }
1631 }
1632
1633 #[test]
1634 fn generate_thumbhash_from_bytes_basic() {
1635 let pixels: Vec<u8> = vec![
1637 255, 0, 0, 255, 255, 0, 0, 255,
1638 255, 0, 0, 255, 255, 0, 0, 255,
1639 ];
1640 let result = super::generate_thumbhash_from_rgba(&pixels, 2, 2);
1641 assert!(result.is_some());
1642 assert!(!result.unwrap().is_empty());
1643 }
1644
1645 #[test]
1646 fn generate_image_metadata_from_bytes() {
1647 let img = image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 0, 255, 255]));
1649 let mut buf = Vec::new();
1650 let mut cursor = std::io::Cursor::new(&mut buf);
1651 img.write_to(&mut cursor, image::ImageFormat::Png).unwrap();
1652
1653 let meta = super::generate_image_metadata(&buf);
1654 assert!(meta.is_some());
1655 let meta = meta.unwrap();
1656 assert_eq!(meta.width, 4);
1657 assert_eq!(meta.height, 4);
1658 assert!(!meta.thumbhash.is_empty());
1659 }
1660
1661 #[test]
1662 fn generate_image_metadata_non_image() {
1663 let text_bytes = b"this is not an image";
1664 let meta = super::generate_image_metadata(text_bytes);
1665 assert!(meta.is_none());
1666 }
1667}