//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). use super::*; use serde_json::json; use std::time::{SystemTime, UNIX_EPOCH}; use tokio::{net::TcpListener, time::timeout}; #[cfg(unix)] // model fetch is an offline tool that needs statvfs #[tokio::test] async fn insufficient_space_stops_before_network_or_partial_file() { let root = std::env::temp_dir().join(format!( "strata-space-test-{}-{}", std::process::id(), SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos() )); let manifest = Manifest { schema_version: 1, files: vec![ModelFile { name: "huge.gguf".into(), url: "https://example.invalid/huge.gguf".into(), size: u64::MAX, sha256: "0".repeat(64), }], }; let error = fetch(&manifest, &root).await.unwrap_err().to_string(); assert!(error.contains("insufficient disk space")); assert!(!root.join("huge.gguf.part").exists()); fs::remove_dir_all(root).await.unwrap(); } /// A scratch directory name that no other test or process uses. #[cfg(unix)] fn unique_dir(tag: &str) -> PathBuf { std::env::temp_dir().join(format!( "strata-{tag}-{}-{}", std::process::id(), SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos() )) } /// Accepts one connection and reads its request head; returns the socket and the head in lower case. #[cfg(unix)] async fn accept_request(listener: &TcpListener) -> (tokio::net::TcpStream, String) { let (mut socket, _) = listener.accept().await.unwrap(); let mut request = Vec::new(); let mut buffer = [0u8; 1024]; while !request.ends_with(b"\r\n\r\n") { let count = socket.read(&mut buffer).await.unwrap(); assert!(count > 0); request.extend_from_slice(&buffer[..count]); } let request = String::from_utf8(request).unwrap().to_ascii_lowercase(); (socket, request) } /// The tail `def` of `abcdef` as a partial response to `Range: bytes=3-`. #[cfg(unix)] const PARTIAL_TAIL: &[u8] = concat!( "HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\n", "Content-Range: bytes 3-5/6\r\nConnection: close\r\n\r\ndef" ) .as_bytes(); /// The manifest of the one six-byte file `sample.bin` (`abcdef`) served at `address`. #[cfg(unix)] fn sample_manifest_bytes(address: std::net::SocketAddr) -> Vec { serde_json::to_vec(&json!({ "schema_version": 1, "files": [{ "name": "sample.bin", "url": format!("http://{address}/sample.bin"), "size": 6, "sha256": hex::encode(Sha256::digest(b"abcdef")) }] })) .unwrap() } /// The same manifest, written to `manifest.json` in `base` and loaded from there. #[cfg(unix)] async fn load_sample_manifest(base: &Path, address: std::net::SocketAddr) -> Manifest { let manifest_path = base.join("manifest.json"); fs::write(&manifest_path, sample_manifest_bytes(address)) .await .unwrap(); Manifest::load(&manifest_path).await.unwrap() } /// The same manifest, built directly (without the validation of `Manifest::parse`). #[cfg(unix)] fn sample_manifest(address: std::net::SocketAddr) -> Manifest { Manifest { schema_version: 1, files: vec![ModelFile { name: "sample.bin".into(), url: format!("http://{address}/sample.bin"), size: 6, sha256: hex::encode(Sha256::digest(b"abcdef")), }], } } /// `fetch` that must finish within five seconds. #[cfg(unix)] async fn fetch_in_time(manifest: &Manifest, output: &Path) -> Result<()> { timeout(Duration::from_secs(5), fetch(manifest, output)) .await .unwrap() } #[cfg(unix)] // model fetch is an offline tool that needs statvfs #[tokio::test] async fn interrupted_download_resumes_and_verifies() { let base = unique_dir("model-test"); fs::create_dir_all(&base).await.unwrap(); let output = base.join("model"); fs::create_dir_all(&output).await.unwrap(); fs::write(output.join("sample.bin.part"), b"abc") .await .unwrap(); let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); let server = tokio::spawn(async move { let (mut socket, request) = accept_request(&listener).await; assert!(request.contains("range: bytes=3-")); socket.write_all(PARTIAL_TAIL).await.unwrap(); }); let manifest = load_sample_manifest(&base, address).await; fetch_in_time(&manifest, &output).await.unwrap(); server.await.unwrap(); verify(&manifest, &output).await.unwrap(); assert_eq!( fs::read(output.join("sample.bin")).await.unwrap(), b"abcdef" ); assert!(!output.join("sample.bin.part").exists()); fs::write(output.join("sample.bin"), b"xxxxxx") .await .unwrap(); assert!(verify(&manifest, &output).await.is_err()); fs::remove_dir_all(&base).await.unwrap(); } #[cfg(unix)] // model fetch is an offline tool that needs statvfs #[tokio::test] async fn checksum_mismatch_never_publishes_download() { let base = unique_dir("bad-download"); let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); let server = tokio::spawn(async move { let (mut socket, _) = accept_request(&listener).await; socket .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 6\r\nConnection: close\r\n\r\nxxxxxx") .await .unwrap(); }); let manifest = sample_manifest(address); let error = fetch_in_time(&manifest, &base).await.unwrap_err(); assert!(error.to_string().contains("SHA-256 mismatch")); server.await.unwrap(); assert!(!base.join("sample.bin").exists()); assert!(!base.join("sample.bin.part").exists()); // Also cover a full-length partial left by a prior interrupted process. fs::write(base.join("sample.bin.part"), b"xxxxxx") .await .unwrap(); let error = fetch_in_time(&manifest, &base).await.unwrap_err(); assert!(error.to_string().contains("size/SHA-256 verification")); assert!(!base.join("sample.bin").exists()); fs::remove_dir_all(base).await.unwrap(); } #[cfg(unix)] // model fetch is an offline tool that needs statvfs #[tokio::test] async fn transient_server_failure_retries_the_same_partial_download() { let base = unique_dir("retry-test"); fs::create_dir_all(&base).await.unwrap(); fs::write(base.join("sample.bin.part"), b"abc") .await .unwrap(); let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); let server = tokio::spawn(async move { for attempt in 0..2 { let (mut socket, request) = accept_request(&listener).await; assert!(request.contains("range: bytes=3-")); let reply: &[u8] = if attempt == 0 { b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" } else { PARTIAL_TAIL }; socket.write_all(reply).await.unwrap(); } }); let manifest = Manifest::parse(&sample_manifest_bytes(address)).unwrap(); fetch_in_time(&manifest, &base).await.unwrap(); server.await.unwrap(); assert_eq!(fs::read(base.join("sample.bin")).await.unwrap(), b"abcdef"); assert!(!base.join("sample.bin.part").exists()); fs::remove_dir_all(base).await.unwrap(); } #[cfg(unix)] // model fetch is an offline tool that needs statvfs #[tokio::test] async fn short_response_resumes_from_new_partial_offset() { let base = unique_dir("short-response-test"); fs::create_dir_all(&base).await.unwrap(); let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); let server = tokio::spawn(async move { for attempt in 0..2 { let (mut socket, request) = accept_request(&listener).await; let reply: &[u8] = if attempt == 0 { assert!(!request.contains("range:")); b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\nConnection: close\r\n\r\nabc" } else { assert!(request.contains("range: bytes=3-")); PARTIAL_TAIL }; socket.write_all(reply).await.unwrap(); } }); let manifest = Manifest::parse(&sample_manifest_bytes(address)).unwrap(); fetch_in_time(&manifest, &base).await.unwrap(); server.await.unwrap(); assert_eq!(fs::read(base.join("sample.bin")).await.unwrap(), b"abcdef"); assert!(!base.join("sample.bin.part").exists()); fs::remove_dir_all(base).await.unwrap(); } #[tokio::test] async fn manifest_rejects_path_traversal() { let path = std::env::temp_dir().join(format!("strata-bad-manifest-{}.json", std::process::id())); fs::write(&path, serde_json::to_vec(&json!({ "schema_version": 1, "files": [{"name": "../escape", "url": "https://example.com/file", "size": 1, "sha256": "a".repeat(64)}] })).unwrap()).await.unwrap(); assert!(Manifest::load(&path).await.is_err()); fs::remove_file(path).await.unwrap(); } fn secret_request(client: &Client, url: &str) -> reqwest::Request { let file = ModelFile { name: "model.gguf".into(), url: url.into(), size: 1, sha256: "0".repeat(64), }; model_request(client, &file, 3, Some("test-secret")) .unwrap() .build() .unwrap() } #[test] fn hub_token_is_only_attached_to_exact_https_host() { let client = Client::new(); for (url, expected_auth) in [ ( "https://huggingface.co/org/repo/resolve/commit/model.gguf", true, ), ("https://huggingface.co.evil.example/model.gguf", false), ("https://example.com/model.gguf", false), ("http://localhost/model.gguf", false), ] { let request = secret_request(&client, url); assert_eq!( request .headers() .get(reqwest::header::AUTHORIZATION) .is_some(), expected_auth, "{url}" ); assert_eq!(request.headers().get(RANGE).unwrap(), "bytes=3-"); } } #[test] fn manifest_rejects_url_credentials() { let bytes = serde_json::to_vec(&json!({ "schema_version": 1, "files": [{ "name": "model.gguf", "url": "https://alice:secret@huggingface.co/model.gguf", "size": 1, "sha256": "0".repeat(64) }] })) .unwrap(); assert!(Manifest::parse(&bytes).is_err()); } #[tokio::test] async fn builtin_profile_is_embedded_and_pinned() { let manifest = Manifest::from_spec("qwen-iq3-s").await.unwrap(); assert_eq!(manifest.files.len(), 2); assert_eq!( manifest.files[0].size + manifest.files[1].size, 83_617_662_656 ); assert!(manifest.files.iter().all(|file| { file.url .contains("/resolve/ed59f92082b1e93c0e96d60a8b11aab089b52f09/") })); }