//! A person's files on this Mac (e2e rulings R6): the film and fetch //! importers' sealed uploads, opening a file a phone sent, and re-sealing //! what an object still stores in the clear. Synthetic bytes only, against an //! object inside the test. mod support; use std::sync::Arc; use cotton_client::media::sealed::PersonFiles; use cotton_client::seal::{DataKeyStore, HeldDataKeys}; use cotton_core::seal::DataKey; use cotton_mac::copy::{Copy, SealDoor}; use cotton_mac::files::{fetch_listed, fetch_opened, held_keys, playlist_names, put_listed, put_listed_patiently, put_listed_telling, report, reseal, Fetch, Item, ResealOptions}; use cotton_mac::ids::sha256_hex; use cotton_mac::object::ObjectClient; use cotton_mac::patience::Patience; use serde_json::json; use support::object::{kit_table, FakeObject}; const DB: &str = "00000000-0000-4000-8000-0000000000f1"; fn tables() -> Vec { ["photo", "song", "film", "book"].map(kit_table).to_vec() } /// This Mac as a device holding the data key `byte` names. fn device(object: &FakeObject, dir: &std::path::Path, byte: u8) -> (ObjectClient, Arc) { let keys = HeldDataKeys::new(); keys.hold(DB, &DataKey::from_bytes([byte; 32])); let store: Arc = keys; let copy = Arc::new(Copy::open(&dir.join("copy.db"), DB, store.clone()).unwrap()); let files = Arc::new(PersonFiles::new(DB, store)); (ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap().sealing_with(SealDoor::over(copy)).sealing_files(files.clone()), files) } fn opened(files: &PersonFiles, key: &str, sealed: &[u8]) -> Vec { let mut plain = Vec::new(); cotton_core::seal::file::open_file(&files.file_key(key).unwrap(), key, &mut &sealed[..], &mut plain).unwrap(); plain } const MASTER: &str = "#EXTM3U\n#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"a\",NAME=\"English\",URI=\"audio-1/index.m3u8\"\n#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=\"s\",NAME=\"English\",URI=\"sub-en.m3u8\"\n#EXT-X-STREAM-INF:BANDWIDTH=800000,AUDIO=\"a\"\nvideo/index.m3u8\n"; const VIDEO: &str = "#EXTM3U\n#EXT-X-MAP:URI=\"init.mp4\"\n#EXTINF:6.0,\nseg00000.m4s\n#EXTINF:6.0,\nseg00001.m4s\n#EXT-X-ENDLIST\n"; const AUDIO: &str = "#EXTM3U\n#EXT-X-MAP:URI=\"init.mp4\"\n#EXTINF:6.0,\nseg00000.m4s\n#EXT-X-ENDLIST\n"; const SUBS: &str = "#EXTM3U\n#EXTINF:12.0,\nsub-en.vtt\n#EXT-X-ENDLIST\n"; /// A film's HLS folder, as `film:import` lays it: (name, bytes). fn hls() -> Vec<(&'static str, Vec)> { vec![ ("video/init.mp4", b"\0\0\0\x18ftypiso5 video init".to_vec()), ("video/seg00000.m4s", b"moof video zero quokka".to_vec()), ("video/seg00001.m4s", b"moof video one".to_vec()), ("video/index.m3u8", VIDEO.as_bytes().to_vec()), ("audio-1/init.mp4", b"\0\0\0\x18ftypiso5 audio init".to_vec()), ("audio-1/seg00000.m4s", b"moof audio zero".to_vec()), ("audio-1/index.m3u8", AUDIO.as_bytes().to_vec()), ("sub-en.vtt", b"WEBVTT\n\n00:00.000 --> 00:02.000\nThe lantern keeper\n".to_vec()), ("sub-en.m3u8", SUBS.as_bytes().to_vec()), ("master.m3u8", MASTER.as_bytes().to_vec()), ] } #[test] fn a_playlist_names_its_files_and_nothing_outside_its_folder() { assert_eq!(playlist_names(MASTER), vec!["audio-1/index.m3u8", "sub-en.m3u8", "video/index.m3u8"]); assert_eq!(playlist_names(VIDEO), vec!["init.mp4", "seg00000.m4s", "seg00001.m4s"]); assert!(playlist_names("#EXT-X-KEY:URI=\"https://elsewhere.example/k\"\n../other/seg.m4s\n/abs.m4s\n").is_empty()); } /// RULE (e2e rulings R6): a film's HLS folder leaves this Mac sealed file by file: the master, every playlist, init section, segment and subtitle is its own f1 file under its own key, and no playlist line or subtitle word reaches the object. A phone holding the data key opens each to the bytes the Mac read. #[test] fn a_films_hls_folder_goes_up_sealed_file_by_file_and_opens_with_the_data_key() { let object = FakeObject::start(DB, "+15550100001", tables()); let dir = tempfile::tempdir().unwrap(); let (client, files) = device(&object, dir.path(), 7); let items: Vec = hls() .into_iter() .map(|(name, bytes)| { let path = dir.path().join(name.replace('/', "_")); std::fs::write(&path, bytes).unwrap(); Item { key: format!("{DB}/films/film-1/{name}"), path, content_type: None, replace: false } }) .collect(); let outcomes = put_listed(&client, &items, 3); assert_eq!(outcomes.len(), 10); assert!(outcomes.iter().all(|o| o.state == "sent"), "{outcomes:?}"); { let state = object.state.lock().unwrap(); assert_eq!(state.media.len(), 10); for (name, bytes) in hls() { let key = format!("{DB}/films/film-1/{name}"); assert_eq!(state.media_types[&key], "application/vnd.cotton.f1", "{name}"); assert!(state.media[&key].starts_with(b"CTF1"), "{name}"); assert_eq!(opened(&files, &key, &state.media[&key]), bytes, "{name} opens to what the Mac read"); } // One segment's bytes under another's key open nothing: a file cannot be moved. let moved = &state.media[&format!("{DB}/films/film-1/video/seg00000.m4s")]; let other = format!("{DB}/films/film-1/video/seg00001.m4s"); assert!(cotton_core::seal::file::open_file(&files.file_key(&other).unwrap(), &other, &mut &moved[..], &mut Vec::new()).is_err()); } let heard = object.everything(); for word in ["EXTM3U", "EXTINF", "lantern keeper", "quokka", "ftyp"] { assert!(!heard.contains(word), "{word} reached the object"); } // Sent again, nothing moves: every file is held sealed. let again = put_listed(&client, &items, 2); assert!(again.iter().all(|o| o.state == "held"), "{again:?}"); // The film's row names the master; the folder's files are found through its playlists. client.upsert("film", "film-1", &json!({ "title": "Synthetic", "file": format!("{DB}/films/film-1/master.m3u8") })).unwrap(); let keys = held_keys(&client, DB, &["films".to_string()]).unwrap(); assert_eq!(keys.len(), 10, "{keys:?}"); // A key that is not a person's is refused, never sent open. let stray = put_listed(&client, &[Item { key: format!("{DB}/documents/x.pdf"), path: items[0].path.clone(), content_type: None, replace: false }], 1); assert_eq!(stray[0].state, "failed"); assert!(!object.state.lock().unwrap().media.contains_key(&format!("{DB}/documents/x.pdf"))); } /// Three small files of a film, on disk, to send. fn three_pieces(dir: &std::path::Path) -> Vec { (0..3) .map(|n| { let path = dir.join(format!("piece{n}")); std::fs::write(&path, format!("synthetic piece {n}")).unwrap(); Item { key: format!("{DB}/films/film-away/video/seg0000{n}.m4s"), path, content_type: None, replace: false } }) .collect() } fn quick() -> Patience { Patience::new(std::time::Duration::from_millis(1), std::time::Duration::from_millis(5), std::time::Duration::from_secs(30)) } /// RULE (owner, 18 Nov 2026): an object answering 500 for a while fails no file: the send waits and every file lands. #[test] fn a_send_waits_out_an_object_that_answers_500_for_a_while() { let object = FakeObject::start(DB, "+15550100001", tables()); let dir = tempfile::tempdir().unwrap(); let (client, _) = device(&object, dir.path(), 7); let items = three_pieces(dir.path()); object.state.lock().unwrap().away_for = 40; let outcomes = put_listed_patiently(&client, &items, 2, &quick()); assert!(outcomes.iter().all(|o| o.state == "sent"), "{outcomes:?}"); assert_eq!(object.state.lock().unwrap().media.len(), 3); } /// RULE (owner, 18 Nov 2026): only a long time with no answer at all ends a send, and each file then says why. #[test] fn a_send_gives_up_only_when_the_object_has_said_nothing_for_the_whole_time() { let object = FakeObject::start(DB, "+15550100001", tables()); let dir = tempfile::tempdir().unwrap(); let (client, _) = device(&object, dir.path(), 7); let items = three_pieces(dir.path()); object.state.lock().unwrap().away_for = usize::MAX; let patience = Patience::new(std::time::Duration::from_millis(1), std::time::Duration::from_millis(3), std::time::Duration::from_millis(40)); let outcomes = put_listed_patiently(&client, &items, 2, &patience); assert!(outcomes.iter().all(|o| o.state == "failed" && o.why.as_deref().is_some_and(|why| why.contains("500"))), "{outcomes:?}"); } /// RULE: a refusal is the object's answer about this file: it is said at once, never waited on. #[test] fn a_refused_file_fails_at_once_and_is_not_sent_again() { let object = FakeObject::start(DB, "+15550100001", tables()); let dir = tempfile::tempdir().unwrap(); let (client, _) = device(&object, dir.path(), 7); let items = three_pieces(dir.path()); { let mut state = object.state.lock().unwrap(); state.away_for = usize::MAX; state.away_status = 413; } let outcomes = put_listed_patiently(&client, &items[..1], 1, &quick()); assert_eq!(outcomes[0].state, "failed"); // One question about what is held, and one try at the file. assert_eq!(object.server.requests().len(), 2); } /// RULE (owner, 18 Nov 2026): a send says each file as it finishes, so a landing can say how far it is. #[test] fn a_send_tells_each_file_as_it_finishes() { let object = FakeObject::start(DB, "+15550100001", tables()); let dir = tempfile::tempdir().unwrap(); let (client, _) = device(&object, dir.path(), 7); let items = three_pieces(dir.path()); let told = std::sync::Mutex::new(Vec::new()); let outcomes = put_listed_telling(&client, &items, 2, &quick(), &|outcome| told.lock().unwrap().push(outcome.key.clone())); let mut told = told.into_inner().unwrap(); told.sort(); assert_eq!(told, outcomes.iter().map(|o| o.key.clone()).collect::>()); } /// RULE (owner, 18 Nov 2026): a landing started again sends nothing the object stores sealed, and asks about the files together, not one call each. #[test] fn a_landing_started_again_sends_only_what_the_object_does_not_hold() { let object = FakeObject::start(DB, "+15550100001", tables()); let dir = tempfile::tempdir().unwrap(); let (client, _) = device(&object, dir.path(), 7); let items = three_pieces(dir.path()); assert!(put_listed(&client, &items[..2], 2).iter().all(|o| o.state == "sent")); let before = object.server.requests().len(); let outcomes = put_listed(&client, &items, 2); assert_eq!(outcomes.iter().map(|o| o.state).collect::>(), ["held", "held", "sent"]); let asked: Vec<_> = object.server.requests().into_iter().skip(before).map(|r| (r.method, r.path)).collect(); let on_media = asked.iter().filter(|(_, path)| path.contains("seg00000") || path.contains("seg00001")).count(); assert_eq!(on_media, 0, "{asked:?}"); assert_eq!(asked.iter().filter(|(_, path)| path == "/v1/media/missing").count(), 1, "{asked:?}"); } /// RULE (e2e rulings R6): a file a phone sent sealed (a film's `source.*` for this Mac to convert) opens here with the key the data key derives; under another person's key it opens nothing. #[test] fn a_file_a_phone_sent_sealed_opens_on_this_mac() { let object = FakeObject::start(DB, "+15550100001", tables()); let dir = tempfile::tempdir().unwrap(); let (client, _) = device(&object, dir.path(), 7); let key = format!("{DB}/films/film-2/source.mkv"); let source = dir.path().join("in.mkv"); std::fs::write(&source, vec![42u8; 200_000]).unwrap(); assert_eq!(put_listed(&client, &[Item { key: key.clone(), path: source, content_type: None, replace: false }], 1)[0].state, "sent"); let out = dir.path().join("out.mkv"); assert_eq!(fetch_opened(&client, &key, &out).unwrap(), 200_000); assert_eq!(std::fs::read(&out).unwrap(), vec![42u8; 200_000]); let other = tempfile::tempdir().unwrap(); let (stranger, _) = device(&object, other.path(), 9); assert!(fetch_opened(&stranger, &key, &other.path().join("out.mkv")).is_err()); assert!(!other.path().join("out.mkv").exists(), "nothing is left where a file did not open"); } /// Lay a person's clear files as an object held them before R6, with the rows that name them. fn clear_object() -> (FakeObject, Vec<(String, Vec)>) { let object = FakeObject::start(DB, "+15550100001", tables()); let photo = b"\xFF\xD8\xFF\xE0 a clear picture".to_vec(); let song = b"fLaC a clear song".to_vec(); let book = b"PK\x03\x04 a clear book".to_vec(); let photo_key = format!("{DB}/photos/{}.jpg", sha256_hex(&photo)); let thumb_key = format!("{DB}/photos/{}.t256.jpg", sha256_hex(&photo)); let song_key = format!("{DB}/music/{}.flac", sha256_hex(&song)); let book_key = format!("{DB}/books/{}.epub", sha256_hex(&book)); let whole_key = format!("{DB}/films/film-9/whole.mp4"); let held = vec![ (photo_key.clone(), photo), (thumb_key, b"\xFF\xD8\xFF\xE0 thumb".to_vec()), (song_key.clone(), song), (book_key.clone(), book), (whole_key.clone(), b"\0\0\0\x18ftypmp42 a clear film".to_vec()), ]; { let mut state = object.state.lock().unwrap(); for (key, bytes) in &held { state.media.insert(key.clone(), bytes.clone()); state.media_types.insert(key.clone(), "application/octet-stream".into()); } } object.put_row("photo", "p1", json!({ "key": photo_key, "sha256": "x" })); object.put_row("song", "s1", json!({ "title": "Morning", "file": song_key })); object.put_row("book", "b1", json!({ "title": "A book", "file": book_key })); object.put_row("film", "f1", json!({ "title": "A film", "file": whole_key })); // A row naming a file the object never got, and one of another kind. object.put_row("photo", "p2", json!({ "key": format!("{DB}/photos/{}.jpg", "0".repeat(64)) })); object.put_row("film", "f2", json!({ "title": "Elsewhere", "file": format!("{DB}/documents/not-a-persons-kind.pdf") })); (object, held) } /// RULE (step 4): the re-seal's dry run only counts: it says how many files of each kind are stored in the clear and how many bytes, and fetches, writes and sends nothing. #[test] fn a_dry_run_counts_what_is_clear_and_touches_nothing() { let (object, held) = clear_object(); let dir = tempfile::tempdir().unwrap(); let (client, _) = device(&object, dir.path(), 7); let kinds: Vec = ["photos", "videos", "books", "music", "films"].map(String::from).to_vec(); let keys = held_keys(&client, DB, &kinds).unwrap(); assert_eq!(keys.len(), 9, "five held (one a rendition), the other rendition, and the missing picture with its two: {keys:?}"); let keep = dir.path().join("keep"); let options = ResealOptions { dry_run: true, keep: keep.clone(), keep_clear: false, progress: None, limit: None, threads: 1 }; let outcomes = reseal(&client, &keys, &options, &mut |_| {}).unwrap(); let summary = report(&outcomes, true); assert_eq!(summary["kinds"]["photos"]["clear"]["files"], 2); assert_eq!(summary["kinds"]["photos"]["missing"]["files"], 4); assert_eq!(summary["kinds"]["music"]["clear"]["bytes"], held[2].1.len()); assert_eq!(summary["left"], 5); assert!(!keep.exists(), "a dry run writes nothing here"); assert!(object.server.requests().iter().all(|r| r.method != "PUT" && !(r.method == "GET" && r.path.starts_with("/v1/media/"))), "and nothing is fetched or sent"); let state = object.state.lock().unwrap(); assert!(held.iter().all(|(key, bytes)| &state.media[key] == bytes)); } /// RULE (step 4): a file stored in the clear is fetched, checked against the sha256 its key names, stored again sealed under the same key, read back and opened, and only then is its clear copy on this Mac deleted. Stopped part way, the next run starts where it stopped; run again when done, it moves nothing. Stored bytes that are not the ones the key names are left alone and said. #[test] fn clear_files_are_re_sealed_in_place_verified_and_a_stopped_run_resumes() { let (object, held) = clear_object(); // One stored file is not the bytes its key names. let bad_key = format!("{DB}/music/{}.mp3", "a".repeat(64)); { let mut state = object.state.lock().unwrap(); state.media.insert(bad_key.clone(), b"ID3 other bytes".to_vec()); state.media_types.insert(bad_key.clone(), "audio/mpeg".into()); } object.put_row("song", "s2", json!({ "title": "Wrong", "file": bad_key })); let dir = tempfile::tempdir().unwrap(); let (client, files) = device(&object, dir.path(), 7); let kinds: Vec = ["photos", "videos", "books", "music", "films"].map(String::from).to_vec(); let keys = held_keys(&client, DB, &kinds).unwrap(); let keep = dir.path().join("keep"); let progress = dir.path().join("progress.txt"); let options = |limit, threads| ResealOptions { dry_run: false, keep: keep.clone(), keep_clear: false, progress: Some(progress.clone()), limit, threads }; // A run stopped after two files. let first = reseal(&client, &keys, &options(Some(2), 1), &mut |_| {}).unwrap(); assert_eq!(first.iter().filter(|o| o.state == "sealed").count(), 2); let sealed_after_first = object.state.lock().unwrap().media.values().filter(|bytes| bytes.starts_with(b"CTF1")).count(); assert_eq!(sealed_after_first, 2); // The next run finishes it, several files at once. let second = reseal(&client, &keys, &options(None, 4), &mut |_| {}).unwrap(); assert_eq!(second.iter().filter(|o| o.state == "sealed").count(), 3); assert_eq!(second.iter().filter(|o| o.state == "held").count(), 2, "what the first run sealed is left"); let summary = report(&second, false); assert_eq!(summary["left"], 1, "{summary}"); assert_eq!(summary["failed"][0]["state"], "corrupt"); { let state = object.state.lock().unwrap(); for (key, bytes) in &held { assert_eq!(state.media_types[key], "application/vnd.cotton.f1", "{key}"); assert_eq!(&opened(&files, key, &state.media[key]), bytes, "{key} opens to the bytes that were stored"); } assert_eq!(state.media[&bad_key], b"ID3 other bytes", "a file that is not what its key names is left as it was"); } // Every verified clear copy is gone from this Mac. let left: Vec<_> = walk(&keep); assert!(left.is_empty(), "{left:?}"); assert_eq!(std::fs::read_to_string(&progress).unwrap().lines().count(), 5); // Done: a third run sends nothing. let before = object.server.requests().len(); let third = reseal(&client, &keys, &options(None, 4), &mut |_| {}).unwrap(); assert!(third.iter().all(|o| o.state != "sealed")); assert!(object.server.requests()[before..].iter().all(|r| r.method != "PUT")); } /// RULE (e2e rulings R2): with no data key on this Mac the re-seal touches nothing: no file is fetched and none replaced. #[test] fn a_re_seal_with_no_data_key_touches_nothing() { let (object, held) = clear_object(); let dir = tempfile::tempdir().unwrap(); let keys: Vec = held.iter().map(|(key, _)| key.clone()).collect(); let client = ObjectClient::new(object.server.url.clone(), Some("device".into())).unwrap(); let options = ResealOptions { dry_run: false, keep: dir.path().join("keep"), keep_clear: false, progress: None, limit: None, threads: 1 }; let error = reseal(&client, &keys, &options, &mut |_| {}).unwrap_err(); assert!(error.contains("seal_key_missing"), "{error}"); assert!(object.server.requests().is_empty()); } fn walk(dir: &std::path::Path) -> Vec { let mut out = Vec::new(); for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() { if entry.path().is_dir() { out.extend(walk(&entry.path())); } else { out.push(entry.path()); } } out } /// RULE (owner, 17 Nov 2026: a film switches quality by itself): a film's master is named afresh when its ladder is added, sealed over the old one in one write and only when asked (`replace`); unasked, a held master is left as it was, so a rerun never undoes the ladder or sends it twice. #[test] fn a_films_master_is_put_again_sealed_only_when_asked() { let object = FakeObject::start(DB, "+15550100001", tables()); let dir = tempfile::tempdir().unwrap(); let (client, files) = device(&object, dir.path(), 7); let key = format!("{DB}/films/film-3/master.m3u8"); let one = dir.path().join("one.m3u8"); let three = dir.path().join("three.m3u8"); std::fs::write(&one, "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1\nvideo/index.m3u8\n").unwrap(); std::fs::write(&three, "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1\nvideo-720/index.m3u8\n#EXT-X-STREAM-INF:BANDWIDTH=2\nvideo/index.m3u8\n").unwrap(); let item = |path: &std::path::Path, replace: bool| Item { key: key.clone(), path: path.to_path_buf(), content_type: None, replace }; assert_eq!(put_listed(&client, &[item(&one, false)], 1)[0].state, "sent"); assert_eq!(put_listed(&client, &[item(&three, false)], 1)[0].state, "held"); let stored = |object: &FakeObject| object.state.lock().unwrap().media[&key].clone(); assert_eq!(opened(&files, &key, &stored(&object)), std::fs::read(&one).unwrap(), "unasked, the held master stays"); assert_eq!(put_listed(&client, &[item(&three, true)], 1)[0].state, "sent"); assert_eq!(object.state.lock().unwrap().media_types[&key], "application/vnd.cotton.f1"); assert_eq!(opened(&files, &key, &stored(&object)), std::fs::read(&three).unwrap(), "asked, the master is the new one, sealed"); assert!(!object.everything().contains("video-720"), "the new master reached the object sealed"); } /// `film:open`'s pieces: many files brought down opened under one client, a /// file already whole left (a stopped run starts again where it stopped), each /// landing under `.part` and renamed, and one the object does not hold /// `failed` with nothing left where it would land. #[test] fn a_list_of_files_comes_down_opened_and_a_run_again_takes_what_is_whole() { let object = FakeObject::start(DB, "+15550100001", tables()); let dir = tempfile::tempdir().unwrap(); let (client, _) = device(&object, dir.path(), 7); let folder = format!("{DB}/films/film-open-1"); let pieces: Vec<(String, Vec)> = (0..6).map(|n| (format!("{folder}/video/seg{n:05}.m4s"), format!("moof piece {n} of a synthetic film").into_bytes())).collect(); let items: Vec = pieces .iter() .enumerate() .map(|(n, (key, bytes))| { let path = dir.path().join(format!("src-{n}")); std::fs::write(&path, bytes).unwrap(); Item { key: key.clone(), path, content_type: None, replace: false } }) .collect(); assert!(put_listed(&client, &items, 2).iter().all(|o| o.state == "sent")); let out = dir.path().join("pieces"); std::fs::create_dir_all(&out).unwrap(); let fetches: Vec = pieces.iter().enumerate().map(|(n, (key, _))| Fetch { key: key.clone(), out: out.join(format!("{n}.m4s")) }).collect(); // A run stopped after two: those two are whole, the rest come now. std::fs::write(out.join("0.m4s"), &pieces[0].1).unwrap(); std::fs::write(out.join("1.m4s"), &pieces[1].1).unwrap(); let told = std::sync::Mutex::new(Vec::new()); let outcomes = fetch_listed(&client, &fetches, 3, 2, std::time::Duration::from_millis(10), &|o| told.lock().unwrap().push(o.state)); assert_eq!(outcomes.iter().map(|o| o.state).collect::>(), ["had", "had", "got", "got", "got", "got"]); assert_eq!(told.lock().unwrap().len(), 6, "each told as it finished"); for (n, (_, bytes)) in pieces.iter().enumerate() { assert_eq!(&std::fs::read(out.join(format!("{n}.m4s"))).unwrap(), bytes); } let stray: Vec<_> = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).filter(|n| !n.ends_with(".m4s")).collect(); assert!(stray.is_empty(), "no .part left: {stray:?}"); let absent = [Fetch { key: format!("{folder}/video/seg09999.m4s"), out: out.join("absent.m4s") }]; let outcomes = fetch_listed(&client, &absent, 1, 3, std::time::Duration::from_millis(10), &|_| {}); assert_eq!(outcomes[0].state, "failed"); assert!(outcomes[0].why.as_deref().unwrap_or_default().contains("no such file"), "{:?}", outcomes[0].why); assert!(!out.join("absent.m4s").exists() && !out.join("absent.m4s.part").exists()); } /// RULE (AVATAR SEAL, MEDIA SEAL FINDINGS (1), 27 Nov 2026): faces the object holds plain are re-sealed from this Mac under /// the person table's files root: the ones a person row names and the ones the object lists plain that no row names (a /// WhatsApp picture). While the object holds faces back for a device on an app from before, a dry run counts (reads only) /// and names the devices, and a real run touches no face; once it has updated, every plain face is sealed in place and /// opens to the bytes it replaced, and a face already sealed is left. #[test] fn faces_are_re_sealed_under_the_person_files_root_and_held_back_while_an_older_app_reads_them() { use cotton_mac::files::reseal_plan; let object = FakeObject::start(DB, "+15550100001", ["photo", "person"].map(kit_table).to_vec()); let (named, orphan, already) = (b"\xFF\xD8\xFF\xE0 an invented face".to_vec(), b"\xFF\xD8\xFF\xE0 an invented WhatsApp face".to_vec(), b"CTF1 sealed by a phone".to_vec()); let named_key = format!("{DB}/people/p-1/{}.jpg", sha256_hex(&named)); let orphan_key = format!("{DB}/people/p-2/whatsapp/{}.jpg", sha256_hex(&orphan)); let already_key = format!("{DB}/people/p-3/{}.jpg", "a".repeat(64)); { let mut state = object.state.lock().unwrap(); for (key, bytes, kind) in [(&named_key, &named, "image/jpeg"), (&orphan_key, &orphan, "image/jpeg"), (&already_key, &already, "application/vnd.cotton.f1")] { state.media.insert(key.clone(), bytes.clone()); state.media_types.insert(key.clone(), kind.into()); } state.plain_waiting.insert("people".into(), vec!["Old Comms".into()]); } object.put_row("person", "p-1", json!({ "full_name": "Invented Person", "avatar_key": named_key })); let dir = tempfile::tempdir().unwrap(); let (client, files) = device(&object, dir.path(), 7); let people = vec!["people".to_string()]; // Held back: the dry run counts what a row names and says who waits; a real run takes nothing. let counted = reseal_plan(&client, DB, &people, true).unwrap(); assert_eq!(counted.keys, [named_key.clone()]); assert_eq!(counted.held_back.get("people").map(Vec::as_slice), Some(["Old Comms".to_string()].as_slice())); let summary = report(&reseal(&client, &counted.keys, &ResealOptions { dry_run: true, keep: dir.path().join("keep"), keep_clear: false, progress: None, limit: None, threads: 1 }, &mut |_| {}).unwrap(), true); assert_eq!(summary["kinds"]["people"]["clear"]["files"], 1); assert!(object.server.requests().iter().all(|r| r.method != "PUT"), "a dry run sends nothing"); assert!(reseal_plan(&client, DB, &people, false).unwrap().keys.is_empty(), "a real run touches no face while held back"); // Updated: both plain faces, the row's and the orphan, sealed in place; the sealed one left. object.state.lock().unwrap().plain_waiting.clear(); let plan = reseal_plan(&client, DB, &people, false).unwrap(); assert!(plan.held_back.is_empty()); assert_eq!(plan.keys, { let mut k = vec![named_key.clone(), orphan_key.clone()]; k.sort(); k }); let outcomes = reseal(&client, &plan.keys, &ResealOptions { dry_run: false, keep: dir.path().join("keep"), keep_clear: false, progress: None, limit: None, threads: 2 }, &mut |_| {}).unwrap(); assert!(outcomes.iter().all(|o| o.state == "sealed"), "{outcomes:?}"); let state = object.state.lock().unwrap(); let root = cotton_core::seal::keys::table_file_root(&DataKey::from_bytes([7; 32]), DB, "person").unwrap(); for (key, plain) in [(&named_key, &named), (&orphan_key, &orphan)] { assert_eq!(state.media_types[key], "application/vnd.cotton.f1"); assert_eq!(&opened(&files, key, &state.media[key]), plain, "nothing lost"); let mut under_person = Vec::new(); cotton_core::seal::file::open_file(&cotton_core::seal::file::person_file_key(&root, key), key, &mut &state.media[key][..], &mut under_person).expect("sealed under the person table's files root"); } assert_eq!(state.media[&already_key], already, "a face already sealed is left"); }