//! Every case of `packages/core/__tests__/media/keys.test.ts`, plus the extra //! vectors computed by running the TypeScript itself (`npx tsx` in //! `packages/core`) so the two implementations are pinned to each other. use super::*; use cotton_store::file_identity::FileId; fn ws() -> FileId { FileId::for_tests(WS) } const WS: &str = "a11ce0de-5eed-4c0d-8e00-00000000feed"; /// A real-shaped digest — the message and avatar keys are content-addressed. const SHA: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; /// A second one, for the release whose two assets must both be reclaimed. const OTHER_SHA: &str = "5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9"; /// A repository's row id — what every repository key's folder is. const REPO: &str = "0f8fad5b-d9cb-469f-a165-70867728950e"; fn types(kind: MediaKind) -> &'static [&'static str] { media_limits(kind).content_types } // ── key shapes ─────────────────────────────────────────────────────────────── #[test] fn keeps_the_document_keys_byte_identical_to_the_storage_era() { assert_eq!( document_original_key(&ws(), "doc-1", "pdf"), format!("{WS}/doc-1/original.pdf") ); assert_eq!( document_original_key(&ws(), "doc-1", ""), format!("{WS}/doc-1/original") ); assert_eq!( document_unlocked_key(&ws(), "doc-1"), format!("{WS}/doc-1/unlocked.pdf") ); } /// Vectors computed by running `documentOriginalKey` in Node. #[test] fn document_original_key_matches_node_vectors() { for (ext, expected) in [ ("pdf", format!("{WS}/doc-1/original.pdf")), (".pdf", format!("{WS}/doc-1/original.pdf")), ("", format!("{WS}/doc-1/original")), (".", format!("{WS}/doc-1/original.")), (".PDF", format!("{WS}/doc-1/original.PDF")), ("tar.gz", format!("{WS}/doc-1/original.tar.gz")), ("p df", format!("{WS}/doc-1/original.p df")), ] { assert_eq!( document_original_key(&ws(), "doc-1", ext), expected, "ext {ext:?}" ); } } #[test] fn keeps_the_statement_key_byte_identical_too() { assert_eq!( statement_key(&ws(), "abc123", "July statement.pdf"), format!("{WS}/abc123-July-statement.pdf") ); } #[test] fn sanitises_a_statement_filename_rather_than_trusting_the_picker() { assert_eq!( statement_key(&ws(), "tok", "a/b c?.pdf"), format!("{WS}/tok-a-b-c-.pdf") ); assert_eq!( statement_key(&ws(), "tok", "../../etc/passwd"), format!("{WS}/tok-.-.-etc-passwd") ); } /// The `safeName` vectors, both callers, straight out of Node. The non-BMP /// case is the one that proves the port counts UTF-16 code units: `🎉` is two /// units and becomes two dashes. #[test] fn safe_name_matches_node_vectors() { let long_x = format!("{}-tail.pdf", "x".repeat(120)); let long_staged = format!("{}-tail.pdf", "x".repeat(71)); for (name, staged, statement) in [ ("Bill.pdf", "Bill.pdf".to_string(), "Bill.pdf".to_string()), ( "a/b c?.pdf", "a-b-c-.pdf".to_string(), "a-b-c-.pdf".to_string(), ), ( "../../etc/passwd", ".-.-etc-passwd".to_string(), ".-.-etc-passwd".to_string(), ), ( "report..pdf", "report.pdf".to_string(), "report.pdf".to_string(), ), ("..", ".".to_string(), ".".to_string()), (long_x.as_str(), long_staged.clone(), long_staged.clone()), ( "naïve café.pdf", "na-ve-caf-.pdf".to_string(), "na-ve-caf-.pdf".to_string(), ), ( "🎉party.pdf", "--party.pdf".to_string(), "--party.pdf".to_string(), ), ("...leading", ".leading".to_string(), ".leading".to_string()), ("a\\b.pdf", "a-b.pdf".to_string(), "a-b.pdf".to_string()), ("", String::new(), String::new()), ("Ünï.PDF", "-n-.PDF".to_string(), "-n-.PDF".to_string()), ] { assert_eq!( document_staging_key(&ws(), "deadbeef", name), format!("{WS}/_staging/deadbeef/{staged}"), "staging {name:?}" ); assert_eq!( statement_key(&ws(), "tok", name), format!("{WS}/tok-{statement}"), "statement {name:?}" ); } } #[test] fn never_builds_a_key_its_own_validator_would_refuse() { // The invariant that ties the two halves of this module together. let hostile = "../../etc/pass wd\\x?.pdf"; for key in [ document_original_key(&ws(), "d", "pdf"), document_unlocked_key(&ws(), "d"), document_staging_key(&ws(), "sha", hostile), statement_key(&ws(), "tok", hostile), meeting_full_key(&ws(), "m-1"), meeting_segment_key(&ws(), "m-1", 3), message_media_key(&ws(), "t-1", SHA, hostile), avatar_key(&ws(), "p-1", SHA, hostile), walkthrough_image_key(&ws(), SHA, hostile), photo_key(&ws(), SHA, hostile), video_key(&ws(), SHA, hostile), video_poster_key(&ws(), SHA), ] { assert!( is_key_in_workspace(Some(&key), &ws()), "refused its own key: {key}" ); } } #[test] fn puts_meeting_audio_under_the_workspace_prefix() { assert_eq!( meeting_full_key(&ws(), "m-1"), format!("{WS}/meetings/m-1/full.m4a") ); assert_eq!( meeting_segment_key(&ws(), "m-1", 7), format!("{WS}/meetings/m-1/segments/007.m4a") ); assert_eq!( meeting_segment_key(&ws(), "m-1", 120), format!("{WS}/meetings/m-1/segments/120.m4a") ); assert_eq!( meeting_segment_prefix(&ws(), "m-1"), format!("{WS}/meetings/m-1/") ); } /// `String(seq).padStart(3, "0")`, from Node. #[test] fn meeting_segment_key_matches_node_vectors() { for (seq, expected) in [ (0, "000"), (1, "001"), (7, "007"), (99, "099"), (120, "120"), (999, "999"), (1000, "1000"), (12345, "12345"), ] { assert_eq!( meeting_segment_key(&ws(), "m-1", seq), format!("{WS}/meetings/m-1/segments/{expected}.m4a"), "seq {seq}" ); } } #[test] fn stages_an_assistants_upload_under_its_own_sha() { assert_eq!( document_staging_key(&ws(), "deadbeef", "Bill.pdf"), format!("{WS}/_staging/deadbeef/Bill.pdf") ); } #[test] fn addresses_a_message_attachment_by_its_own_bytes() { assert_eq!( message_media_key(&ws(), "t-1", SHA, "jpg"), format!("{WS}/messages/t-1/{SHA}.jpg") ); // A re-import of the same archive must land on the same key. assert_eq!( message_media_key(&ws(), "t-1", SHA, ".JPG"), message_media_key(&ws(), "t-1", SHA, "jpg") ); assert_eq!( message_media_key(&ws(), "t-1", SHA, ""), format!("{WS}/messages/t-1/{SHA}") ); } #[test] fn addresses_a_persons_photo_the_same_way_under_their_own_folder() { assert_eq!( avatar_key(&ws(), "p-1", SHA, "heic"), format!("{WS}/people/p-1/{SHA}.heic") ); assert_eq!( avatar_key(&ws(), "p-1", SHA, ""), format!("{WS}/people/p-1/{SHA}") ); } #[test] fn addresses_a_captured_screen_by_its_bytes_alone_in_one_flat_folder() { assert_eq!( walkthrough_image_key(&ws(), SHA, "webp"), format!("{WS}/walkthroughs/{SHA}.webp") ); assert_eq!( walkthrough_image_key(&ws(), SHA, ".WEBP"), walkthrough_image_key(&ws(), SHA, "webp") ); assert_eq!( walkthrough_image_key(&ws(), SHA, ""), format!("{WS}/walkthroughs/{SHA}") ); } #[test] fn keys_a_session_messages_attachment_by_the_message_and_the_bytes() { assert_eq!( session_message_media_key(&ws(), "m-1", SHA, ".PNG"), format!("{WS}/session-messages/m-1/{SHA}.png") ); assert_eq!( session_message_media_key(&ws(), "m-1", SHA, "png"), session_message_media_key(&ws(), "m-1", SHA, "png") ); } #[test] fn drops_an_extension_it_cannot_spell_rather_than_building_a_refused_key() { assert_eq!( message_media_key(&ws(), "t-1", SHA, "jpg?v=2"), format!("{WS}/messages/t-1/{SHA}.jpgv2") ); assert_eq!( avatar_key(&ws(), "p-1", SHA, "../png"), format!("{WS}/people/p-1/{SHA}.png") ); } /// The `extSuffix` vectors, from Node. #[test] fn ext_suffix_matches_node_vectors() { for (ext, expected) in [ ("jpg", ".jpg"), (".JPG", ".jpg"), ("", ""), ("jpg?v=2", ".jpgv2"), ("../png", ".png"), (".", ""), ("---", ""), ("aVeryLongExtensionIndeed", ".averylongext"), ("é", ""), ("MP4", ".mp4"), ("..webp", ".webp"), ("9", ".9"), ("a.b", ".ab"), ] { assert_eq!( message_media_key(&ws(), "t-1", SHA, ext), format!("{WS}/messages/t-1/{SHA}{expected}"), "ext {ext:?}" ); } } /// RULE: A song's file is `/music/.`, one of the seven audio formats up to 1 GB, and its key reads back as a song, never a document. #[test] fn addresses_a_song_by_its_own_bytes_and_reads_it_back_as_a_song() { assert_eq!(song_key(&ws(), SHA, "flac"), format!("{WS}/music/{SHA}.flac")); assert_eq!(song_key(&ws(), SHA, ".MP3"), format!("{WS}/music/{SHA}.mp3")); assert_eq!(SONG_EXTENSIONS, ["mp3", "m4a", "flac", "ogg", "opus", "wav", "aiff"]); let limit = media_limits(MediaKind::Song); for ext in SONG_EXTENSIONS { assert_eq!(media_kind_for(&song_key(&ws(), SHA, ext), &ws()).unwrap(), MediaKind::Song); let kind = song_content_type(ext).expect("every song extension carries a type"); assert!(limit.content_types.contains(&kind), "{ext} -> {kind}"); } assert_eq!(song_content_type("epub"), None); assert_eq!(limit.max_bytes, 1024 * 1024 * 1024); assert!(!limit.content_types.contains(&"application/octet-stream")); assert!(media_kind_for(&format!("other/music/{SHA}.mp3"), &ws()).is_err(), "another file's song is outside this one"); } /// RULE: A film's files live in its record's folder, `/films//`: a whole MP4, M4V or MOV the phone plays as it is (`whole.`), the upload in any film container waiting for the Mac (`source.`) and the Mac's HLS master; every one reads back as a film, never a document, up to 20 GiB. #[test] fn addresses_a_film_in_its_records_folder_and_reads_it_back_as_a_film() { const FILM: &str = "f1lm-0001"; assert_eq!(film_whole_key(WS, FILM, "mp4"), format!("{WS}/films/{FILM}/whole.mp4")); assert_eq!(film_whole_key(WS, FILM, ".MOV"), format!("{WS}/films/{FILM}/whole.mov")); assert_eq!(film_source_key(WS, FILM, "mkv"), format!("{WS}/films/{FILM}/source.mkv")); assert_eq!(film_master_key(WS, FILM), format!("{WS}/films/{FILM}/master.m3u8")); let limit = media_limits(MediaKind::Film); assert_eq!(limit.max_bytes, 20 * 1024 * 1024 * 1024); for ext in FILM_WHOLE_EXTENSIONS { assert_eq!(media_kind_for(&film_whole_key(WS, FILM, ext), &ws()).unwrap(), MediaKind::Film); let kind = film_content_type(ext).expect("every whole film extension carries a type"); assert!(["video/mp4", "video/quicktime"].contains(&kind), "{ext} -> {kind}"); assert!(limit.content_types.contains(&kind), "{ext} -> {kind}"); } for ext in FILM_SOURCE_EXTENSIONS { assert_eq!(media_kind_for(&film_source_key(WS, FILM, ext), &ws()).unwrap(), MediaKind::Film); let kind = film_content_type(ext).expect("every film source extension carries a type"); assert_eq!(media_kind_of_verified_key(&film_source_key(WS, FILM, ext)).unwrap(), MediaKind::Film); assert!(limit.content_types.contains(&kind), "{ext} -> {kind}"); } for name in ["master.m3u8", "video/index.m3u8", "video/seg-00001.m4s", "sub-en.vtt", "poster.jpg"] { assert_eq!(media_kind_for(&format!("{WS}/films/{FILM}/{name}"), &ws()).unwrap(), MediaKind::Film, "{name}"); } assert!(limit.content_types.contains(&"application/octet-stream"), "an upload in a container no type names"); assert_eq!(film_content_type(".MKV"), Some("video/x-matroska")); assert_eq!(film_content_type("srt"), None); assert_eq!(film_content_type("epub"), None); assert!(media_kind_for(&format!("other/films/{FILM}/whole.mp4"), &ws()).is_err(), "another file's film is outside this one"); assert_eq!(MediaKind::Film.as_str(), "film"); assert!(MediaKind::ALL.contains(&MediaKind::Film)); } /// RULE: The film containers the media keys take are the ones the intake rules call film files (`crate::films`): every film file can go up as an upload for the Mac, and every whole one is a container the phone plays. #[test] fn the_film_extensions_are_the_intake_rules_own() { use std::collections::BTreeSet; let source: BTreeSet<&str> = FILM_SOURCE_EXTENSIONS.iter().copied().collect(); let video: BTreeSet<&str> = crate::films::VIDEO_EXTENSIONS.iter().copied().collect(); assert_eq!(source, video); let whole: BTreeSet<&str> = FILM_WHOLE_EXTENSIONS.iter().copied().collect(); let plays: BTreeSet<&str> = crate::films::WHOLE_EXTENSIONS.iter().copied().collect(); assert_eq!(whole, plays); } /// RULE: A book's file is `/books/.`, an EPUB or a PDF up to 500 MB, and its key reads back as a book, never a document. #[test] fn addresses_a_book_by_its_own_bytes_and_reads_it_back_as_a_book() { assert_eq!(book_key(&ws(), SHA, "epub"), format!("{WS}/books/{SHA}.epub")); assert_eq!(book_key(&ws(), SHA, ".PDF"), format!("{WS}/books/{SHA}.pdf")); for ext in BOOK_EXTENSIONS { assert_eq!(media_kind_for(&book_key(&ws(), SHA, ext), &ws()).unwrap(), MediaKind::Book); } let limit = media_limits(MediaKind::Book); assert_eq!(limit.max_bytes, 500 * 1024 * 1024); assert_eq!(limit.content_types, ["application/epub+zip", "application/pdf"]); assert!(!limit.content_types.contains(&"application/octet-stream")); assert!(media_kind_for(&format!("other/books/{SHA}.epub"), &ws()).is_err(), "another file's book is outside this one"); } #[test] fn addresses_a_kept_photo_and_video_by_their_own_bytes() { assert_eq!(photo_key(&ws(), SHA, "jpg"), format!("{WS}/photos/{SHA}.jpg")); assert_eq!( photo_key(&ws(), SHA, ".HEIC"), format!("{WS}/photos/{SHA}.heic") ); assert_eq!(video_key(&ws(), SHA, "mp4"), format!("{WS}/videos/{SHA}.mp4")); assert_eq!(video_key(&ws(), SHA, ""), format!("{WS}/videos/{SHA}")); } #[test] fn names_a_videos_poster_from_the_videos_hash_beside_the_video() { assert_eq!( video_poster_key(&ws(), SHA), format!("{WS}/videos/{SHA}.poster.jpg") ); assert_ne!(video_poster_key(&ws(), SHA), video_key(&ws(), SHA, "jpg")); } #[test] fn prefixes_the_workspace_with_a_trailing_slash_so_a_list_cannot_bleed() { assert_eq!(workspace_prefix(&ws()), format!("{WS}/")); } // ── assert_key_in_workspace ────────────────────────────────────────────────── #[test] fn accepts_a_key_under_this_workspace() { let key = format!("{WS}/doc-1/original.pdf"); assert_eq!(assert_key_in_workspace(Some(&key), &ws()), Ok(key.as_str())); } #[test] fn refuses_another_workspaces_key() { assert_eq!( assert_key_in_workspace(Some("other-ws/doc-1/original.pdf"), &ws()), Err(MediaKeyError::OutsideWorkspace) ); } #[test] fn refuses_another_workspaces_walkthrough_image() { // A share hands a slug to a client, and a client is the one caller who is // not the owner of the file — a reserved folder name must not become a way // to reach across the prefix. let other = "0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0"; let foreign = walkthrough_image_key(&FileId::for_tests(other), SHA, "webp"); assert!(assert_key_in_workspace(Some(&foreign), &ws()).is_err()); assert!(is_key_in_workspace( Some(&walkthrough_image_key(&ws(), SHA, "webp")), &ws() )); } #[test] fn refuses_traversal_rather_than_normalising_it() { assert!(assert_key_in_workspace(Some(&format!("{WS}/../other/x.pdf")), &ws()).is_err()); assert!(assert_key_in_workspace(Some(&format!("{WS}/a/../../b")), &ws()).is_err()); } #[test] fn refuses_a_prefix_that_merely_starts_the_same() { // "ws-1" must not open "ws-10/..." — the slash is the boundary. assert!(assert_key_in_workspace(Some("ws-10/doc/original.pdf"), &FileId::for_tests("ws-1")).is_err()); } #[test] fn refuses_empty_leading_slash_empty_segment_and_over_long_keys() { assert!(assert_key_in_workspace(Some(""), &ws()).is_err()); assert!(assert_key_in_workspace(Some(" "), &ws()).is_err()); assert!(assert_key_in_workspace(None, &ws()).is_err()); assert!(assert_key_in_workspace(Some(&format!("/{WS}/doc/original.pdf")), &ws()).is_err()); assert!(assert_key_in_workspace(Some(&format!("{WS}//original.pdf")), &ws()).is_err()); assert!(assert_key_in_workspace(Some(&format!("{WS}/doc/")), &ws()).is_err()); assert!(assert_key_in_workspace(Some(&format!("{WS}/{}", "a".repeat(600))), &ws()).is_err()); } #[test] fn refuses_control_characters_backslashes_and_newlines() { // A newline in a key is how a header injection reaches a presigned URL. assert!(assert_key_in_workspace(Some(&format!("{WS}/a\nb.pdf")), &ws()).is_err()); assert!(assert_key_in_workspace(Some(&format!("{WS}/a\\b.pdf")), &ws()).is_err()); assert!(assert_key_in_workspace(Some(&format!("{WS}/a\u{000a}b.pdf")), &ws()).is_err()); } #[test] fn is_key_in_workspace_answers_the_same_question_without_failing() { assert!(is_key_in_workspace( Some(&format!("{WS}/doc-1/original.pdf")), &ws() )); assert!(!is_key_in_workspace(Some("other/doc-1/original.pdf"), &ws())); } /// The whitespace class is ECMAScript's, not Rust's: `trim` and the `\s` /// refusal both have to see U+FEFF (which Rust's `char::is_whitespace` does /// not) and U+00A0 (which it does). #[test] fn uses_the_javascript_whitespace_class_on_both_sides() { let key = format!("{WS}/doc-1/original.pdf"); assert!(is_key_in_workspace(Some(&format!(" {key}\u{feff}")), &ws())); assert!(!is_key_in_workspace( Some(&format!("{WS}/a\u{00a0}b.pdf")), &ws() )); assert!(!is_key_in_workspace( Some(&format!("{WS}/a\u{feff}b.pdf")), &ws() )); // U+0085 (NEL) is Unicode White_Space but NOT ECMAScript `\s`, and its // code unit is 133 rather than a control one — so the TypeScript ACCEPTS // it (verified by running `isKeyInWorkspace` in Node) and so does this. // Rust's own `char::is_whitespace` would have refused it. assert!(is_key_in_workspace( Some(&format!("{WS}/a\u{0085}b.pdf")), &ws() )); } /// `.length` is UTF-16 code units, so the ceiling counts them. #[test] fn measures_the_ceiling_in_utf16_code_units() { // 512 units exactly, and one more. let head = format!("{WS}/"); let room = MAX_KEY_LENGTH - head.encode_utf16().count(); assert!(is_key_in_workspace( Some(&format!("{head}{}", "a".repeat(room))), &ws() )); assert!(!is_key_in_workspace( Some(&format!("{head}{}", "a".repeat(room + 1))), &ws() )); } // ── a held repository's objects ────────────────────────────────────────────── #[test] fn keeps_a_held_repositorys_keys_content_addressed_under_one_folder() { assert_eq!( repo_bundle_key(&ws(), REPO, SHA), format!("{WS}/repos/{REPO}/bundles/{SHA}.bundle") ); assert_eq!( repo_release_asset_key(&ws(), REPO, SHA, "gz"), format!("{WS}/repos/{REPO}/releases/{SHA}.gz") ); assert_eq!( repo_attachment_key(&ws(), REPO, SHA, "png"), format!("{WS}/repos/{REPO}/attachments/{SHA}.png") ); assert_eq!( repo_run_log_key(&ws(), REPO, SHA), format!("{WS}/repos/{REPO}/runs/{SHA}.log"), "a FINISHED job's log, filed so a standby holds it too — the live one is a file on the \ serving Mac and never a row" ); assert_eq!( repo_media_prefix(&ws(), REPO), format!("{WS}/repos/{REPO}/"), "the trailing slash is load-bearing: without it, a sweep of `repo-1` also takes `repo-10`" ); for key in [ repo_bundle_key(&ws(), REPO, SHA), repo_release_asset_key(&ws(), REPO, SHA, "gz"), repo_attachment_key(&ws(), REPO, SHA, "png"), repo_run_log_key(&ws(), REPO, SHA), ] { assert!( key.starts_with(&repo_media_prefix(&ws(), REPO)), "{key} is not under the prefix a delete sweeps" ); } } /// The extension goes through `ext_suffix`, which is JavaScript's own /// semantics — the same vectors the document and message keys are pinned to. #[test] fn a_release_assets_extension_is_cleaned_the_way_every_other_one_is() { for (ext, expected) in [ ("gz", format!("{WS}/repos/{REPO}/releases/{SHA}.gz")), (".gz", format!("{WS}/repos/{REPO}/releases/{SHA}.gz")), ("GZ", format!("{WS}/repos/{REPO}/releases/{SHA}.gz")), ("", format!("{WS}/repos/{REPO}/releases/{SHA}")), ("tar.gz", format!("{WS}/repos/{REPO}/releases/{SHA}.targz")), // A non-BMP character is TWO UTF-16 units and neither is alphanumeric, // so both are dropped and the key carries no suffix at all. ("🎉", format!("{WS}/repos/{REPO}/releases/{SHA}")), ( "averyveryverylongextension", format!("{WS}/repos/{REPO}/releases/{SHA}.averyveryver"), ), ] { assert_eq!(repo_release_asset_key(&ws(), REPO, SHA, ext), expected, "{ext}"); } } #[test] fn a_repositorys_keys_are_refused_outside_their_own_workspace() { // The wall, asked of the keys this module builds: the prefix is the only // thing standing where bucket RLS used to. assert!(is_key_in_workspace( Some(&repo_bundle_key(&ws(), REPO, SHA)), &ws() )); assert!(!is_key_in_workspace( Some(&repo_bundle_key(&ws(), REPO, SHA)), &FileId::for_tests("another-workspace") )); // Traversal is REFUSED, never normalised — a repository id is a row id the // server writes, but the check does not depend on that being true. assert!(!is_key_in_workspace( Some(&repo_bundle_key(&ws(), "../..", SHA)), &ws() )); assert!(media_kind_for(&format!("{WS}/repos/../secrets/x"), &ws()).is_err()); assert!(media_kind_for(&format!("other/repos/{REPO}/bundles/{SHA}.bundle"), &ws()).is_err()); // An empty segment — a repository id nobody set — is refused rather than // read as the repository folder itself. assert!(!is_key_in_workspace(Some(&repo_bundle_key(&ws(), "", SHA)), &ws())); } #[test] fn a_releases_asset_keys_are_read_off_the_column_and_nowhere_else() { let one = repo_release_asset_key(&ws(), REPO, SHA, "gz"); let two = repo_release_asset_key(&ws(), REPO, OTHER_SHA, "zip"); let assets = format!( r#"[{{"name":"notes.db.gz","key":"{one}","bytes":10,"contentType":"application/gzip"}}, {{"name":"src.zip","key":"{two}","bytes":20,"contentType":"application/zip"}}]"# ); assert_eq!( repo_release_asset_keys(&ws(), REPO, &assets), vec![one.clone(), two.clone()] ); // The same asset named twice is one object. assert_eq!( repo_release_asset_keys(&ws(), REPO, &format!( r#"[{{"key":"{one}"}},{{"key":"{one}"}},{{"key":"{two}"}}]"# )), vec![one.clone(), two] ); // Every way the column can be wrong answers NOTHING for that entry rather // than an error: this is asked on the DELETE path, and a release whose // column somebody hand-edited still has other assets to reclaim. assert_eq!(repo_release_asset_keys(&ws(), REPO, "[]"), Vec::::new()); assert_eq!(repo_release_asset_keys(&ws(), REPO, "not json"), Vec::::new()); assert_eq!(repo_release_asset_keys(&ws(), REPO, "{}"), Vec::::new()); assert_eq!( repo_release_asset_keys(&ws(), REPO, &format!( r#"[{{"name":"no key"}},"a string",null,{{"key":""}},{{"key":" "}},{{"key":"{one}"}}]"# )), vec![one.clone()], "an entry with no usable key is skipped and the rest are still reclaimed" ); // A KEY THAT IS NOT THIS REPOSITORY'S DOES NOT COME BACK. The column is // synced and any paired device can write it, and this answer is a DELETE // list — a key under another workspace or a sibling repository would be a // delete that reclaimed somebody else's bytes. let elsewhere = repo_release_asset_key( &FileId::for_tests("3c0f9e1a-7b2d-4c5e-8a6f-1b2c3d4e5f60"), REPO, SHA, "gz", ); let sibling = repo_release_asset_key(&ws(), "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d", SHA, "gz"); assert_eq!( repo_release_asset_keys( &ws(), REPO, &format!( r#"[{{"key":"{elsewhere}"}},{{"key":"{sibling}"}},{{"key":"{one}"}}]"# ) ), vec![one], "only the repository's own objects are reclaimed" ); } #[test] fn media_keys_and_repo_ids_take_the_file_id_not_the_namespace() { // A database made at the stop has a new id and the old file's id as its // namespace. Its records derive under the namespace so they keep their // ids; its BYTES must not, or it and the file it came from would share a // folder in the store and a clone on disk. Read off a real file, so the // two values are the ones a producer actually gets. use cotton_store::file_identity::read_file_identity; use cotton_store::meta::Meta; use cotton_store::protocol::derived_id::{derived_id, memory_project_id, repo_id}; use cotton_store::test_template::create_workspace_in_memory_for_test; use rusqlite::types::Value; const NEW_FILE: &str = "22222222-2222-4222-8222-222222222222"; const OLD_FILE: &str = "11111111-1111-4111-8111-111111111111"; const KEY: &str = "git.example.com/owner/name"; let db = create_workspace_in_memory_for_test(&Meta { workspace_id: NEW_FILE.to_string(), owner_id: "owner-1".to_string(), device_id: "device:test".to_string(), last_server_seq: 0, last_hlc: None, }) .expect("a file"); db.run( "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at, kind, namespace) \ VALUES (?, 'Cotton', 'owner-1', '2026-10-03T10:30:00.000Z', 'shared', ?)", &[Value::Text(NEW_FILE.to_string()), Value::Text(OLD_FILE.to_string())], ) .expect("the file's own row"); let file = read_file_identity(&db).expect("reads").expect("seeded"); assert_eq!(file.namespace().as_str(), OLD_FILE); assert_eq!( photo_key(file.id(), SHA, "jpg"), format!("{NEW_FILE}/photos/{SHA}.jpg") ); assert_eq!( repo_bundle_key(file.id(), REPO, SHA), format!("{NEW_FILE}/repos/{REPO}/bundles/{SHA}.bundle") ); assert!(is_key_in_workspace(Some(&photo_key(file.id(), SHA, "jpg")), file.id())); assert!(!is_key_in_workspace( Some(&format!("{OLD_FILE}/photos/{SHA}.jpg")), file.id() )); assert_eq!(repo_id(file.id(), KEY), derived_id("cotton_repos", &[NEW_FILE, KEY])); // And the record beside them does take the namespace. assert_eq!( memory_project_id(file.namespace(), "cotton"), derived_id("cotton_memory_projects", &[OLD_FILE, "cotton"]) ); } // ── media_kind_for ─────────────────────────────────────────────────────────── #[test] fn reads_a_meeting_key_by_its_meetings_segment() { assert_eq!( media_kind_for(&meeting_full_key(&ws(), "m-1"), &ws()), Ok(MediaKind::Meeting) ); assert_eq!( media_kind_for(&meeting_segment_key(&ws(), "m-1", 2), &ws()), Ok(MediaKind::Meeting) ); } #[test] fn reads_a_two_segment_key_as_a_statement() { assert_eq!( media_kind_for(&statement_key(&ws(), "tok", "s.pdf"), &ws()), Ok(MediaKind::Statement) ); } #[test] fn reads_everything_else_under_the_workspace_as_a_document() { assert_eq!( media_kind_for(&document_original_key(&ws(), "d", "pdf"), &ws()), Ok(MediaKind::Document) ); assert_eq!( media_kind_for(&document_unlocked_key(&ws(), "d"), &ws()), Ok(MediaKind::Document) ); assert_eq!( media_kind_for(&document_staging_key(&ws(), "sha", "n.pdf"), &ws()), Ok(MediaKind::Document) ); // The server's own legacy staging shape, still in the store. assert_eq!( media_kind_for(&format!("{WS}/incoming/abc.pdf"), &ws()), Ok(MediaKind::Document) ); } #[test] fn reads_the_two_offline_first_prefixes_as_message_and_avatar() { assert_eq!( media_kind_for(&message_media_key(&ws(), "t-1", SHA, "mp4"), &ws()), Ok(MediaKind::Message) ); assert_eq!( media_kind_for(&avatar_key(&ws(), "p-1", SHA, "jpg"), &ws()), Ok(MediaKind::Avatar) ); } #[test] fn reads_the_walkthroughs_folder_as_a_walkthrough_never_a_document() { assert_eq!( media_kind_for(&walkthrough_image_key(&ws(), SHA, "webp"), &ws()), Ok(MediaKind::Walkthrough) ); assert_eq!( media_kind_for(&walkthrough_image_key(&ws(), SHA, ""), &ws()), Ok(MediaKind::Walkthrough) ); } #[test] fn reads_the_session_messages_folder_as_its_own_kind_never_a_document() { assert_eq!( media_kind_for(&session_message_media_key(&ws(), "m-1", SHA, "png"), &ws()), Ok(MediaKind::Session) ); assert_eq!( media_kind_for(&session_message_media_key(&ws(), "m-1", SHA, ""), &ws()), Ok(MediaKind::Session) ); } #[test] fn reads_the_photos_and_videos_folders_as_their_own_kinds_never_documents() { assert_eq!( media_kind_for(&photo_key(&ws(), SHA, "jpg"), &ws()), Ok(MediaKind::Photo) ); assert_eq!( media_kind_for(&photo_key(&ws(), SHA, ""), &ws()), Ok(MediaKind::Photo) ); assert_eq!( media_kind_for(&video_key(&ws(), SHA, "mp4"), &ws()), Ok(MediaKind::Video) ); } #[test] fn reads_a_videos_poster_as_kind_video() { assert_eq!( media_kind_for(&video_poster_key(&ws(), SHA), &ws()), Ok(MediaKind::Video) ); assert!(types(MediaKind::Video).contains(&"image/jpeg")); } #[test] fn reads_the_repos_folder_as_its_own_kind_although_it_is_four_segments_deep() { // The one reserved folder whose objects are DEEPER than the document shape, // so the fall-through would read a 371 MB bundle as a 100 MB document and // refuse the one content type it actually is. for key in [ repo_bundle_key(&ws(), REPO, SHA), repo_release_asset_key(&ws(), REPO, SHA, "gz"), repo_release_asset_key(&ws(), REPO, SHA, ""), repo_attachment_key(&ws(), REPO, SHA, "png"), // Phase 3 files a finished job's log under the same folder. repo_run_log_key(&ws(), REPO, SHA), ] { assert_eq!(media_kind_for(&key, &ws()), Ok(MediaKind::Repo), "{key}"); } assert!(types(MediaKind::Repo).contains(&"application/x-git-bundle")); assert_eq!(media_limits(MediaKind::Repo).max_bytes, 4_294_967_296); } #[test] fn a_repo_key_has_no_rendition_ladder_at_all() { // `derived_tier_keys`, `rendition_of` and `thumb_key_for` all gate on // `photos|videos`, so a repository's objects get `tier: None` and the // phone's eviction budget never reasons about one. That is the seam doing // the right thing by default, and this is the test that keeps it doing it: // a bundle given a thumbnail tier would be a 371 MB object the cache // thought it could re-fetch. for key in [ repo_bundle_key(&ws(), REPO, SHA), repo_release_asset_key(&ws(), REPO, SHA, "png"), repo_attachment_key(&ws(), REPO, SHA, "jpg"), ] { assert_eq!(derived_tier_keys(&key), Vec::::new(), "{key}"); assert_eq!(rendition_of(&key), None, "{key}"); assert_eq!(thumb_key_for(&key), None, "{key}"); } } #[test] fn refuses_a_key_outside_the_workspace_instead_of_guessing_a_kind() { assert!(media_kind_for("other/meetings/m/full.m4a", &ws()).is_err()); // The workspace id alone names no object — and is refused by the wall // first, since it does not carry the trailing slash. assert!(media_kind_for(WS, &ws()).is_err()); } // ── the limits ─────────────────────────────────────────────────────────────── #[test] fn carries_the_ceiling_each_bucket_enforced_per_kind() { assert_eq!(media_limits(MediaKind::Document).max_bytes, 104_857_600); assert_eq!(media_limits(MediaKind::Meeting).max_bytes, 524_288_000); assert_eq!(media_limits(MediaKind::Statement).max_bytes, 26_214_400); assert_eq!(media_limits(MediaKind::Message).max_bytes, 104_857_600); assert_eq!(media_limits(MediaKind::Avatar).max_bytes, 10_485_760); assert_eq!(media_limits(MediaKind::Walkthrough).max_bytes, 26_214_400); assert_eq!(media_limits(MediaKind::Session).max_bytes, 26_214_400); assert_eq!(media_limits(MediaKind::Photo).max_bytes, 52_428_800); assert_eq!(media_limits(MediaKind::Video).max_bytes, 524_288_000); for kind in ["application/pdf", "video/mp4", "application/octet-stream"] { assert!(!types(MediaKind::Session).contains(&kind)); } } #[test] fn takes_only_the_three_image_formats_a_screen_capture_is_written_in() { assert_eq!( types(MediaKind::Walkthrough), ["image/webp", "image/png", "image/jpeg"] ); for kind in [ "application/octet-stream", "image/heic", "video/mp4", "application/pdf", ] { assert!(!types(MediaKind::Walkthrough).contains(&kind)); } } #[test] fn takes_whatever_a_chat_archive_carries_and_only_images_for_a_face() { for kind in [ "image/jpeg", "image/gif", "image/heic", "video/mp4", "video/quicktime", "video/3gpp", "audio/ogg", "audio/opus", "application/pdf", "application/octet-stream", ] { assert!(types(MediaKind::Message).contains(&kind), "message {kind}"); } for kind in [ "image/jpeg", "image/png", "image/webp", "image/heic", "image/heif", ] { assert!(types(MediaKind::Avatar).contains(&kind), "avatar {kind}"); } assert!(!types(MediaKind::Avatar).contains(&"application/octet-stream")); assert!(!types(MediaKind::Avatar).contains(&"video/mp4")); } #[test] fn allows_the_content_types_each_tool_actually_produces() { assert!(types(MediaKind::Document).contains(&"application/pdf")); assert!(types(MediaKind::Document).contains(&"image/jpeg")); assert!(types(MediaKind::Meeting).contains(&"audio/mp4")); assert!(types(MediaKind::Meeting).contains(&"audio/mpeg")); assert!(types(MediaKind::Statement).contains(&"text/csv")); } #[test] fn accepts_a_statement_photographed_on_a_phone() { for kind in [ "image/heic", "image/heif", "image/jpeg", "image/png", "image/webp", ] { assert!( types(MediaKind::Statement).contains(&kind), "statement {kind}" ); } } #[test] fn accepts_every_csv_spelling_the_picker_asks_for() { for kind in ["text/csv", "application/csv", "text/comma-separated-values"] { assert!( types(MediaKind::Statement).contains(&kind), "statement {kind}" ); } } #[test] fn takes_camera_roll_image_formats_for_a_photo_and_no_catch_all() { assert_eq!( types(MediaKind::Photo), [ "image/jpeg", "image/png", "image/webp", "image/heic", "image/gif", ] ); for kind in ["application/octet-stream", "video/mp4", "application/pdf"] { assert!(!types(MediaKind::Photo).contains(&kind)); } } #[test] fn takes_the_two_movie_types_a_phone_writes_plus_the_posters_jpeg() { assert_eq!( types(MediaKind::Video), ["video/mp4", "video/quicktime", "image/jpeg"] ); for kind in ["image/png", "image/heic", "application/octet-stream"] { assert!(!types(MediaKind::Video).contains(&kind)); } } /// `MediaKind::ALL` and `as_str` are the Rust side of the TypeScript union; /// a kind added to one and not the other is a media route with no ceiling. /// RULE: Media kinds have unique names and bounded accepted content types, so every media route has an unambiguous upload limit. #[test] fn every_kind_names_itself_and_carries_a_limit() { let mut seen = std::collections::BTreeSet::new(); for kind in MediaKind::ALL { assert!(seen.insert(kind.as_str()), "duplicate kind {kind}"); assert!(media_limits(kind).max_bytes > 0); assert!(!media_limits(kind).content_types.is_empty()); } } // ── media_object_keys ──────────────────────────────────────────────────────── const KEY: &str = "ws-1/messages/th-1/aa.jpg"; const FORWARDED: &str = "ws-1/messages/th-2/aa.jpg"; const POSTER: &str = "ws-1/videos/aa.poster.jpg"; fn row(key: &str, poster: Option<&str>) -> MediaObjectRow { MediaObjectRow { key: key.to_string(), poster_key: poster.map(str::to_string), } } #[test] fn names_every_object_a_photo_owns() { assert_eq!( media_object_keys(&row(KEY, None), &[FORWARDED.to_string()]), [KEY, FORWARDED] ); } #[test] fn takes_a_videos_poster_too() { assert_eq!( media_object_keys(&row(KEY, Some(POSTER)), &[FORWARDED.to_string()]), [KEY, FORWARDED, POSTER] ); assert_eq!( media_object_keys(&row(KEY, Some(POSTER)), &[]), [KEY, POSTER] ); } #[test] fn says_each_object_once_key_first() { assert_eq!( media_object_keys( &row(KEY, None), &[ KEY.to_string(), FORWARDED.to_string(), FORWARDED.to_string() ] ), [KEY, FORWARDED] ); } #[test] fn answers_just_the_key_for_a_picture_that_lives_in_one_place() { assert_eq!(media_object_keys(&row(KEY, None), &[]), [KEY]); assert_eq!(media_object_keys(&row(KEY, None), &[]), [KEY]); assert_eq!( media_object_keys(&row(KEY, None), &[String::new(), KEY.to_string()]), [KEY] ); } // ── the rendition tiers ────────────────────────────────────────────────────── #[test] fn spells_the_two_renditions_off_the_originals_own_hash() { assert_eq!(photo_thumb_key(&FileId::for_tests("ws-1"), "aa"), "ws-1/photos/aa.t256.jpg"); assert_eq!(photo_display_key(&FileId::for_tests("ws-1"), "aa"), "ws-1/photos/aa.d1600.jpg"); assert_eq!(video_thumb_key(&FileId::for_tests("ws-1"), "bb"), "ws-1/videos/bb.t256.jpg"); assert_eq!(video_display_key(&FileId::for_tests("ws-1"), "bb"), "ws-1/videos/bb.d1600.jpg"); } #[test] fn reads_a_rendition_as_the_kind_of_the_folder_it_sits_in() { assert_eq!( media_kind_for(&photo_thumb_key(&FileId::for_tests("ws-1"), "aa"), &FileId::for_tests("ws-1")), Ok(MediaKind::Photo) ); assert_eq!( media_kind_for(&photo_display_key(&FileId::for_tests("ws-1"), "aa"), &FileId::for_tests("ws-1")), Ok(MediaKind::Photo) ); assert_eq!( media_kind_for(&video_thumb_key(&FileId::for_tests("ws-1"), "bb"), &FileId::for_tests("ws-1")), Ok(MediaKind::Video) ); // A jpeg is already an allowed type for both kinds, so a presign of a // rendition needs no new entry in either list. assert!(media_limits(MediaKind::Photo) .content_types .contains(&"image/jpeg")); assert!(media_limits(MediaKind::Video) .content_types .contains(&"image/jpeg")); } #[test] fn derives_both_renditions_from_an_original_whatever_its_extension() { assert_eq!( derived_tier_keys("ws-1/photos/aa.heic"), ["ws-1/photos/aa.t256.jpg", "ws-1/photos/aa.d1600.jpg"] ); assert_eq!( derived_tier_keys("ws-1/videos/bb.mov"), ["ws-1/videos/bb.t256.jpg", "ws-1/videos/bb.d1600.jpg"] ); } #[test] fn a_rendition_a_poster_and_anything_outside_the_two_folders_derives_nothing() { for key in [ "ws-1/photos/aa.t256.jpg", "ws-1/photos/aa.d1600.jpg", "ws-1/videos/bb.poster.jpg", "ws-1/messages/th-1/aa.jpg", "ws-1/people/p-1/aa.jpg", "ws-1/token-statement.pdf", "ws-1/photos/aa", "ws-1/photos/.heic", ] { assert_eq!(derived_tier_keys(key), Vec::::new(), "{key}"); } } #[test] fn deleting_a_photo_reclaims_its_thumbnail_and_its_display_rendition() { assert_eq!( media_object_keys(&row("ws-1/photos/aa.heic", None), &[]), [ "ws-1/photos/aa.heic", "ws-1/photos/aa.t256.jpg", "ws-1/photos/aa.d1600.jpg" ] ); } #[test] fn deleting_a_film_reclaims_its_poster_and_the_renditions_of_both() { assert_eq!( media_object_keys( &row( "ws-1/videos/bb.mov", Some("ws-1/videos/bb.poster.jpg") ), &[] ), [ "ws-1/videos/bb.mov", "ws-1/videos/bb.poster.jpg", "ws-1/videos/bb.t256.jpg", "ws-1/videos/bb.d1600.jpg" ] ); } // ───────────────────────────────────────────────────────────────────────────── // thumb_key_for — the read side, which a renderer asks per tile // ───────────────────────────────────────────────────────────────────────────── #[test] fn a_photo_and_a_film_and_a_films_poster_all_answer_the_same_thumbnail() { let sha = "a".repeat(64); assert_eq!( thumb_key_for(&photo_key(&ws(), &sha, "heic")).as_deref(), Some(photo_thumb_key(&ws(), &sha).as_str()) ); assert_eq!( thumb_key_for(&video_key(&ws(), &sha, "mp4")).as_deref(), Some(video_thumb_key(&ws(), &sha).as_str()) ); // THE POSTER TOO, and it is the case that matters: a grid tile for a film // is handed `cotton_videos.poster_key`, never the film's own object. assert_eq!( thumb_key_for(&video_poster_key(&ws(), &sha)).as_deref(), Some(video_thumb_key(&ws(), &sha).as_str()) ); } #[test] fn nothing_outside_photos_and_videos_has_a_thumbnail_tier() { let sha = "a".repeat(64); for key in [ document_original_key(&ws(), "doc-1", "pdf"), meeting_full_key(&ws(), "meeting-1"), avatar_key(&ws(), "person-1", &sha, "jpg"), walkthrough_image_key(&ws(), &sha, "webp"), ] { assert_eq!(thumb_key_for(&key), None, "{key} has no thumbnail tier"); } } /// RULE: a picture that arrived in a conversation has a 256 px thumbnail named off its own key, read back to that key with no lookup; the thumbnail is the thumb rung and the picture stays off the ladder; a thumbnail has no thumbnail. #[test] fn a_conversations_picture_has_a_thumbnail_named_off_its_own_key() { let sha = "a".repeat(64); let picture = message_media_key(&ws(), "thread-1", &sha, "jpg"); let thumb = thumb_key_for(&picture).expect("a chat's picture has a thumbnail"); assert_eq!(thumb, format!("{picture}{THUMB_SUFFIX}")); assert_eq!(message_thumb_key_for(&picture).as_deref(), Some(thumb.as_str())); assert_eq!(message_picture_of_thumb(&thumb), Some(picture.as_str())); assert_eq!(rendition_of(&thumb), Some(Tier::Thumb)); assert_eq!(rendition_of(&picture), None, "the picture itself is not a rung"); assert_eq!(thumb_key_for(&thumb), None, "a thumbnail has no thumbnail"); assert_eq!(display_key_for(&picture), None, "a chat's picture has no display rendition"); assert_eq!(message_picture_of_thumb(&photo_thumb_key(&ws(), &sha)), None); assert_eq!(message_picture_of_thumb(&picture), None); } // ───────────────────────────────────────────────────────────────────────────── // display_key_for — the rung a hero asks for // ───────────────────────────────────────────────────────────────────────────── #[test] fn a_photo_a_film_and_its_poster_all_answer_the_same_display_rendition() { let sha = "a".repeat(64); assert_eq!( display_key_for(&photo_key(&ws(), &sha, "heic")).as_deref(), Some(photo_display_key(&ws(), &sha).as_str()) ); assert_eq!( display_key_for(&video_key(&ws(), &sha, "mp4")).as_deref(), Some(video_display_key(&ws(), &sha).as_str()) ); assert_eq!( display_key_for(&video_poster_key(&ws(), &sha)).as_deref(), Some(video_display_key(&ws(), &sha).as_str()) ); } #[test] fn nothing_outside_photos_and_videos_has_a_display_tier_and_a_rendition_has_none() { let sha = "a".repeat(64); for key in [ document_original_key(&ws(), "doc-1", "pdf"), avatar_key(&ws(), "person-1", &sha, "jpg"), walkthrough_image_key(&ws(), &sha, "png"), photo_thumb_key(&ws(), &sha), photo_display_key(&ws(), &sha), ] { assert_eq!(display_key_for(&key), None, "{key} has no display tier"); } } #[test] fn a_rendition_has_no_rendition_of_its_own() { let sha = "a".repeat(64); assert_eq!(thumb_key_for(&photo_thumb_key(&ws(), &sha)), None); assert_eq!(thumb_key_for(&photo_display_key(&ws(), &sha)), None); assert_eq!(thumb_key_for(&video_thumb_key(&ws(), &sha)), None); assert_eq!(thumb_key_for(&video_display_key(&ws(), &sha)), None); } #[test] fn a_key_with_no_file_name_answers_nothing_rather_than_a_folder() { assert_eq!(thumb_key_for(&format!("{WS}/photos/")), None); assert_eq!(thumb_key_for(&format!("{WS}/photos/.heic")), None); assert_eq!(thumb_key_for(&format!("{WS}/photos/no-dot")), None); assert_eq!(thumb_key_for(WS), None); } // ───────────────────────────────────────────────────────────────────────────── // rendition_of — which rung of the ladder a key names, for the ledger's `tier` // ───────────────────────────────────────────────────────────────────────────── #[test] fn a_photo_and_a_film_and_their_two_renditions_each_name_their_own_rung() { use cotton_store::media_holdings::Tier; let sha = "a".repeat(64); assert_eq!( rendition_of(&photo_key(&ws(), &sha, "heic")), Some(Tier::Original) ); assert_eq!( rendition_of(&video_key(&ws(), &sha, "mp4")), Some(Tier::Original) ); assert_eq!( rendition_of(&photo_thumb_key(&ws(), &sha)), Some(Tier::Thumb) ); assert_eq!( rendition_of(&video_thumb_key(&ws(), &sha)), Some(Tier::Thumb) ); assert_eq!( rendition_of(&photo_display_key(&ws(), &sha)), Some(Tier::Display) ); assert_eq!( rendition_of(&video_display_key(&ws(), &sha)), Some(Tier::Display) ); } #[test] fn nothing_with_no_tier_ladder_is_given_one() { // EVERY ONE OF THESE MUST BE `None`, and none of them may read as // `Original`: `_media.tier` is what the budgeted phone cache decides an // eviction from, and a document or a meeting's recording called an // original is a file the budget would be allowed to delete. let sha = "a".repeat(64); for key in [ document_original_key(&ws(), "doc-1", "pdf"), meeting_full_key(&ws(), "meeting-1"), avatar_key(&ws(), "person-1", &sha, "jpg"), walkthrough_image_key(&ws(), &sha, "webp"), message_media_key(&ws(), "thread-1", &sha, "jpg"), // A film's POSTER is not a rung either: it is what every grid tile // draws and what the thumbnail is derived FROM, so naming it a tier // would make it evictable. video_poster_key(&ws(), &sha), ] { assert_eq!(rendition_of(&key), None, "{key} has no tier ladder"); } } #[test] fn a_key_with_no_file_name_names_no_rendition() { assert_eq!(rendition_of(&format!("{WS}/photos/")), None); assert_eq!(rendition_of(&format!("{WS}/photos/.heic")), None); assert_eq!(rendition_of(&format!("{WS}/photos/no-dot")), None); assert_eq!(rendition_of(WS), None); } #[test] fn a_photo_or_video_key_names_the_family_its_renditions_share() { for key in ["ws-1/photos/aa.heic", "ws-1/photos/aa.jpg", "ws-1/photos/aa.t256.jpg", "ws-1/photos/aa.d1600.jpg"] { assert_eq!(rendition_family(key).as_deref(), Some("ws-1/photos/aa."), "{key}"); } assert_eq!(rendition_family("ws-1/videos/bb.poster.jpg").as_deref(), Some("ws-1/videos/bb.")); for key in ["ws-1/documents/aa.pdf", "ws-1/photos/.heic", "ws-1/photos/aa", "ws-1/photos/x/aa.heic"] { assert_eq!(rendition_family(key), None, "{key}"); } assert!(is_derived_rendition("ws-1/photos/aa.t256.jpg")); assert!(is_derived_rendition("ws-1/videos/bb.d1600.jpg")); assert!(!is_derived_rendition("ws-1/photos/aa.heic")); assert!(!is_derived_rendition("ws-1/videos/bb.poster.jpg")); } /// RULE: cotton-store's id-built meeting keys (media_keys::meeting_derived_keys, which erasure reads) are every spelling meeting_full_key_of (each container) and meeting_segment_key build, so a meeting's erase names whatever its audio is stored under. #[test] fn the_stores_derived_meeting_keys_are_the_builders_spelling() { let segments = serde_json::json!([{ "seq": 0 }, { "seq": 1000 }, { "seq": 2, "path": "x" }, { "seq": 3, "lost": true }, { "seq": -1 }]); let derived = cotton_store::media_keys::meeting_derived_keys(&ws(), "m-1", Some(&segments)); let mut built: std::collections::BTreeSet = [0, 1000, -1] .into_iter() .map(|seq| meeting_segment_key(&ws(), "m-1", seq)) .collect(); built.insert(meeting_full_key(&ws(), "m-1")); built.extend( crate::media::meeting_audio::meeting_audio_extensions() .into_iter() .map(|ext| meeting_full_key_of(&ws(), "m-1", ext)), ); assert!(built.contains(&meeting_full_key_of(&ws(), "m-1", "opus"))); assert_eq!(derived, built); } /// RULE: A WhatsApp profile picture's key is the only avatar or group-picture key that reads as WhatsApp's; the key every other avatar writer makes never does, and both WhatsApp keys stay in their workspace and read as an avatar and a message picture. #[test] fn only_a_whatsapp_picture_key_reads_as_whatsapps() { let person = whatsapp_avatar_key(&ws(), "p-1", SHA, "jpg"); let group = whatsapp_group_picture_key(&ws(), "t-1", SHA, "jpg"); assert_eq!(person, format!("{WS}/people/p-1/whatsapp/{SHA}.jpg")); assert_eq!(group, format!("{WS}/messages/t-1/whatsapp/{SHA}.jpg")); assert!(is_whatsapp_picture_key(&person)); assert!(is_whatsapp_picture_key(&group)); assert!(!is_whatsapp_picture_key(&avatar_key(&ws(), "p-1", SHA, "jpg"))); assert!(!is_whatsapp_picture_key(&message_media_key(&ws(), "t-1", SHA, "jpg"))); assert!(!is_whatsapp_picture_key(&format!("{WS}/photos/whatsapp/{SHA}/x.jpg"))); assert_eq!(media_kind_for(&person, &ws()).unwrap(), MediaKind::Avatar); assert_eq!(media_kind_for(&group, &ws()).unwrap(), MediaKind::Message); } /// RULE (5 Nov 2026): a document that is a picture (`/documents/.`, what `put_document` keeps — a list's own picture set over Cotton MCP) has the thumbnail and display renditions a photo has, named off its own digest; the document itself stays off the tier ladder; a document of any other kind has none. #[test] fn a_document_that_is_a_picture_has_the_photo_renditions() { let sha = "b".repeat(64); let picture = format!("{}/documents/{sha}.png", ws()); let thumb = thumb_key_for(&picture).expect("a picture document has a thumbnail"); assert_eq!(thumb, format!("{}/documents/{sha}{THUMB_SUFFIX}", ws())); assert_eq!(display_key_for(&picture), Some(format!("{}/documents/{sha}{DISPLAY_SUFFIX}", ws()))); assert_eq!(rendition_of(&picture), None, "the document stays off the ladder"); assert_eq!(rendition_of(&thumb), Some(Tier::Thumb)); assert!(is_derived_rendition(&thumb)); assert_eq!(thumb_key_for(&thumb), None, "a thumbnail has no thumbnail"); for other in [format!("{}/documents/{sha}.pdf", ws()), format!("{}/documents/{sha}.csv", ws())] { assert_eq!((thumb_key_for(&other), display_key_for(&other), rendition_of(&other)), (None, None, None), "{other}"); } }