use cotton_core::seal::file::{FileKey, OpeningReader, SealingReader, PART};usesuper::*;const KEY: &str = "db-synthetic/films/film-1/whole.mp4";fn sealed_film(plain: &[u8]) -> Vec<u8> {letmut out = Vec::new();SealingReader::new(&FileKey::from_bytes([2; 32]), KEY, std::io::Cursor::new(plain.to_vec()), plain.len() as u64).read_to_end(&mut out).unwrap(); out}fn get(url: &str, range: Option<&str>, method: &str) -> (String, Vec<u8>) {let rest = url.strip_prefix("http://").unwrap();let (host, path) = rest.split_once('/').unwrap();letmut stream = std::net::TcpStream::connect(host).unwrap();let range = range.map(|r| format!("Range: {r}\r\n")).unwrap_or_default(); write!(stream, "{method} /{path} HTTP/1.1\r\nHost: {host}\r\n{range}\r\n").unwrap();letmut all = Vec::new(); stream.read_to_end(&mut all).unwrap();let split = all.windows(4).position(|w| w == b"\r\n\r\n").unwrap(); (String::from_utf8(all[..split].to_vec()).unwrap(), all[split + 4..].to_vec())}fn offered(door: &Loopback, sealed: Vec<u8>, key: &'static str) -> String { door.offer("film.mp4", "video/mp4", Arc::new(move || {let len = sealed.len() as u64;OpeningReader::new(&FileKey::from_bytes([2; 32]), key, std::io::Cursor::new(sealed.clone()), len) .map(|reader| Box::new(reader) asBox<dynPlainSource>) .map_err(|error| error.to_string()) }))}/// RULE (R6): the player's door answers a sealed film's plaintext whole and any range of it (206, Content-Range),/// past the end 416, and nothing at a path it did not offer; it listens on 127.0.0.1 alone.#[test]fn the_door_answers_a_sealed_films_plaintext_and_any_range() {let film: Vec<u8> = (0..(3 * PART + 1234)).map(|i| (i % 211) as u8).collect();let door = Loopback::start().unwrap();let url = offered(&door, sealed_film(&film), KEY); assert!(url.starts_with(&format!("http://127.0.0.1:{}/", door.port())), "{url}");let (head, body) = get(&url, None, "GET"); assert!(head.starts_with("HTTP/1.1 200"), "{head}"); assert!(head.contains("Content-Type: video/mp4"), "{head}"); assert_eq!(body, film);let (head, body) = get(&url, Some(&format!("bytes={}-{}", PART - 10, 2 * PART + 5)), "GET"); assert!(head.starts_with("HTTP/1.1 206"), "{head}"); assert!(head.contains(&format!("Content-Range: bytes {}-{}/{}", PART - 10, 2 * PART + 5, film.len())), "{head}"); assert_eq!(body, film[PART - 10..=2 * PART + 5]);let (head, body) = get(&url, Some("bytes=-100"), "GET"); assert!(head.starts_with("HTTP/1.1 206"), "{head}"); assert_eq!(body, film[film.len() - 100..]);let (head, _) = get(&url, Some(&format!("bytes={}-", film.len())), "GET"); assert!(head.starts_with("HTTP/1.1 416"), "{head}");let (head, body) = get(&url, None, "HEAD"); assert!(head.contains(&format!("Content-Length: {}", film.len())), "{head}"); assert!(body.is_empty());let elsewhere = format!("http://127.0.0.1:{}/{}/film.mp4", door.port(), "0".repeat(32)); assert!(get(&elsewhere, None, "GET").0.starts_with("HTTP/1.1 404")); door.withdraw_all(); assert!(get(&url, None, "GET").0.starts_with("HTTP/1.1 404"), "withdrawn, the path answers nothing");}/// RULE (R6): a tampered part never reaches the player: the answer stops short before it, and a request for a range/// in it sends no byte of it.#[test]fn a_tampered_part_never_reaches_the_player() {let film: Vec<u8> = (0..(3 * PART)).map(|i| (i % 7) as u8).collect();letmut sealed = sealed_film(&film);let at = (cotton_core::seal::file::HEAD + cotton_core::seal::file::SEALED_PART + 3) as usize; sealed[at] ^= 1;let door = Loopback::start().unwrap();let url = offered(&door, sealed, KEY);let (_, body) = get(&url, None, "GET"); assert_eq!(body, film[..PART], "only the part before the tampered one");let (_, body) = get(&url, Some(&format!("bytes={}-{}", PART + 10, PART + 20)), "GET"); assert!(body.is_empty(), "{} bytes of a part that did not open", body.len());}#[test]fn ranges_read_as_rfc_9110_says() { assert_eq!(range_of(None, 10), Ok(None)); assert_eq!(range_of(Some("bytes=2-4"), 10), Ok(Some((2, 3)))); assert_eq!(range_of(Some("bytes=8-"), 10), Ok(Some((8, 2)))); assert_eq!(range_of(Some("bytes=-3"), 10), Ok(Some((7, 3)))); assert_eq!(range_of(Some("bytes=5-100"), 10), Ok(Some((5, 5)))); assert_eq!(range_of(Some("bytes=10-"), 10), Err(())); assert_eq!(range_of(Some("bytes=1-2,4-5"), 10), Ok(None)); assert_eq!(range_of(Some("items=1-2"), 10), Ok(None));}#[test]fn a_door_that_no_longer_answers_is_opened_again() {let first = Loopback::shared().unwrap();let url = offered(&first, sealed_film(b"a film"), KEY); assert!(first.answers() && stands(&url)); assert_eq!(Loopback::shared().unwrap().port(), first.port(), "a door that stands is the one door");// The system took the listener back (an iPhone does, of a suspended app). first.close();for _ in0..50 {if !stands(&url) {break; } std::thread::sleep(std::time::Duration::from_millis(20)); } assert!(!first.answers() && !stands(&url), "nothing answers at a closed door");let second = Loopback::shared().unwrap(); assert_ne!(second.port(), first.port());let again = offered(&second, sealed_film(b"a film"), KEY); assert!(stands(&again)); assert_eq!(get(&again, None, "GET").1, b"a film"); assert!(stands("https://cotton.example.test/v1/stream/tok/x"), "the object's address is not this door's to say");}/// RULE (R6): a film laid as an HLS folder, every file sealed under its own key, plays through the door: the player asks for the master, then each playlist and segment by the relative path the playlists name, and each request opens that one file. A path that climbs out of the folder, or names nothing, answers 404; no file is opened for it.#[test]fn the_door_answers_a_sealed_folder_file_by_file() {const FOLDER: &str = "db-synthetic/films/film-2";let files: std::collections::BTreeMap<&str, Vec<u8>> = [ ("master.m3u8", b"#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1\nvideo/index.m3u8\n".to_vec()), ("video/index.m3u8", b"#EXTM3U\n#EXT-X-MAP:URI=\"init.mp4\"\n#EXTINF:6,\nseg00000.m4s\n".to_vec()), ("video/init.mp4", vec![7u8; 900]), ("video/seg00000.m4s", (0..(PART + 77)).map(|i| (i % 199) as u8).collect()), ("sub-en.vtt", b"WEBVTT\n".to_vec()), ] .into_iter() .collect();// Each file sealed under its own key: the key of its own object key.let fk = |key: &str| cotton_core::seal::file::person_file_key(&zeroize::Zeroizing::new([5u8; 32]), key);let stored: std::collections::BTreeMap<String, Vec<u8>> = files .iter() .map(|(name, plain)| {let key = format!("{FOLDER}/{name}");letmut sealed = Vec::new();SealingReader::new(&fk(&key), &key, std::io::Cursor::new(plain.clone()), plain.len() as u64).read_to_end(&mut sealed).unwrap(); (key, sealed) }) .collect();let asked: Arc<Mutex<Vec<String>>> = Arc::default();let heard = Arc::clone(&asked);let door = Loopback::start().unwrap();let url = door.offer_folder("master.m3u8", Arc::new(move |inner| { heard.lock().unwrap().push(inner.to_string());let key = format!("{FOLDER}/{inner}");let sealed = stored.get(&key).ok_or("no such file")?.clone();let len = sealed.len() as u64;let reader = OpeningReader::new(&fk(&key), &key, std::io::Cursor::new(sealed), len).map_err(|error| error.to_string())?;Ok((hls_type(inner).to_string(), Box::new(reader) asBox<dynPlainSource>)) })); assert!(url.ends_with("/master.m3u8"), "{url}");let base = url.strip_suffix("master.m3u8").unwrap().to_string();let (head, body) = get(&url, None, "GET"); assert!(head.starts_with("HTTP/1.1 200") && head.contains("Content-Type: application/vnd.apple.mpegurl"), "{head}"); assert_eq!(body, files["master.m3u8"]);let (head, body) = get(&format!("{base}video/index.m3u8"), None, "GET"); assert!(head.starts_with("HTTP/1.1 200"), "{head}"); assert_eq!(body, files["video/index.m3u8"]);let (head, body) = get(&format!("{base}video/init.mp4"), None, "GET"); assert!(head.contains("Content-Type: video/mp4"), "{head}"); assert_eq!(body, files["video/init.mp4"]);let (head, body) = get(&format!("{base}video/seg00000.m4s"), Some(&format!("bytes={}-", PART - 5)), "GET"); assert!(head.starts_with("HTTP/1.1 206") && head.contains("Content-Type: video/iso.segment"), "{head}"); assert_eq!(body, files["video/seg00000.m4s"][PART - 5..]); assert_eq!(get(&format!("{base}sub-en.vtt?x=1"), None, "GET").1, files["sub-en.vtt"]);let before = asked.lock().unwrap().len();for stray in ["../film-1/whole.mp4", "video/../../x", "video//seg.m4s", "", "video/%2e%2e/x"] { assert!(get(&format!("{base}{stray}"), None, "GET").0.starts_with("HTTP/1.1 404"), "{stray}"); } assert_eq!(asked.lock().unwrap().len(), before, "nothing is opened for a path outside the folder"); assert!(get(&format!("{base}video/seg00009.m4s"), None, "GET").0.starts_with("HTTP/1.1 502"), "a file the folder lacks is not answered");// A segment's sealed bytes under another file's name open nothing. assert_eq!(folder_path("video/seg00000.m4s").as_deref(), Some("video/seg00000.m4s")); assert_eq!(folder_path("a/../b"), None);}