Files
leleka/control-plane/src/model.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 e74376430f fix(control-plane): a failing log sink can no longer kill the worker supervisor mid-request
eprintln! panics when stderr is unwritable (consumer gone: EPIPE, disk full:
ENOSPC). worker.rs logged before it marked the worker Failed, so with a dead log
consumer the supervisor task died, readiness stayed true and later requests hit a
dead worker (charter M1 / Gate A). All diagnostics now go through the
non-panicking elog! macro.

tests/log_failure_sse.rs starts the real strata-next binary with a scripted
engine, drops the stderr consumer after startup and provokes a protocol failure
inside a streamed Responses request: the stream must end with response.failed and
readiness must drop (the control case with a live sink passes before and after;
the dead-sink case failed before). A source scan keeps eprintln! out of the crate.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-16 01:59:26 +02:00

823 lines
29 KiB
Rust

//! Manifest-pinned model acquisition. Finished files are never accepted by name alone.
use std::{
error::Error,
io,
path::{Component, Path, PathBuf},
time::Duration,
};
#[cfg(unix)]
use std::ffi::CString;
use reqwest::{
Client, RequestBuilder, StatusCode,
header::{ACCEPT_ENCODING, CONTENT_RANGE, RANGE},
};
use serde::Deserialize;
use sha2::{Digest, Sha256};
use tokio::{
fs::{self, File, OpenOptions},
io::{AsyncReadExt, AsyncWriteExt},
};
type Result<T> = std::result::Result<T, Box<dyn Error>>;
const FETCH_ATTEMPTS: usize = 4;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Manifest {
pub schema_version: u32,
pub files: Vec<ModelFile>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ModelFile {
pub name: String,
pub url: String,
pub size: u64,
pub sha256: String,
}
impl Manifest {
pub async fn load(path: &Path) -> Result<Self> {
Self::parse(&fs::read(path).await?)
}
pub async fn from_spec(spec: &str) -> Result<Self> {
if spec == "qwen-iq3-s" {
Self::parse(include_bytes!(
"../../manifests/qwen3.8-flash-next-iq3-s.json"
))
} else {
Self::load(Path::new(spec)).await
}
}
fn parse(bytes: &[u8]) -> Result<Self> {
let manifest: Self = serde_json::from_slice(bytes)?;
if manifest.schema_version != 1 || manifest.files.is_empty() {
return Err("model manifest needs schema_version 1 and at least one file".into());
}
let mut names = std::collections::HashSet::new();
for file in &manifest.files {
let path = Path::new(&file.name);
if path.components().count() != 1
|| !matches!(path.components().next(), Some(Component::Normal(_)))
|| !names.insert(&file.name)
|| file.size == 0
|| file.sha256.len() != 64
|| !file.sha256.bytes().all(|byte| byte.is_ascii_hexdigit())
{
return Err(format!("invalid model file entry: {}", file.name).into());
}
let url = reqwest::Url::parse(&file.url)?;
if url.scheme() != "https"
&& !(url.scheme() == "http"
&& matches!(url.host_str(), Some("127.0.0.1" | "localhost")))
{
return Err(format!("model URL must use HTTPS: {}", file.name).into());
}
if !url.username().is_empty() || url.password().is_some() {
return Err(
format!("model URL must not contain credentials: {}", file.name).into(),
);
}
}
Ok(manifest)
}
}
pub async fn verify(manifest: &Manifest, output: &Path) -> Result<()> {
for file in &manifest.files {
let path = output.join(&file.name);
verify_one(file, &path).await?;
crate::elog!("verified {}", path.display());
}
Ok(())
}
/// The HTTP client every acquisition path uses: HTTPS with the bundled root set, loopback HTTP for local mirrors and
/// tests, no redirects to other schemes or with credentials.
pub(crate) fn http_client() -> Result<Client> {
// A scratch image and a standalone musl binary may have no host CA store.
// Keep certificate and hostname verification, with a root set in the binary.
let roots = webpki_root_certs::TLS_SERVER_ROOT_CERTS
.iter()
.map(|der| reqwest::Certificate::from_der(der.as_ref()))
.collect::<std::result::Result<Vec<_>, _>>()?;
Ok(Client::builder()
.tls_certs_only(roots)
.connect_timeout(Duration::from_secs(30))
.read_timeout(Duration::from_secs(120))
.redirect(reqwest::redirect::Policy::custom(|attempt| {
let url = attempt.url();
if attempt.previous().len() >= 10 {
attempt.error("too many redirects")
} else if url.scheme() == "https"
|| (url.scheme() == "http"
&& matches!(url.host_str(), Some("127.0.0.1" | "localhost")))
{
if url.username().is_empty() && url.password().is_none() {
attempt.follow()
} else {
attempt.error("refusing a model redirect containing credentials")
}
} else {
attempt.error("refusing a non-HTTPS model redirect")
}
}))
.build()?)
}
pub async fn fetch(manifest: &Manifest, output: &Path) -> Result<()> {
fs::create_dir_all(output).await?;
preflight_space(manifest, output).await?;
let client = http_client()?;
let hub_token = match std::env::var("HF_TOKEN") {
Ok(token) if token.is_empty() => None,
Ok(token) if token.chars().any(char::is_whitespace) => {
return Err("HF_TOKEN must not contain whitespace".into());
}
Ok(token) => Some(token),
Err(std::env::VarError::NotPresent) => None,
Err(std::env::VarError::NotUnicode(_)) => {
return Err("HF_TOKEN must contain valid UTF-8".into());
}
};
for file in &manifest.files {
fetch_one_with_retry(&client, file, output, hub_token.as_deref()).await?;
}
Ok(())
}
async fn fetch_one_with_retry(
client: &Client,
file: &ModelFile,
output: &Path,
hub_token: Option<&str>,
) -> Result<()> {
for attempt in 1..=FETCH_ATTEMPTS {
match fetch_one(client, file, output, hub_token).await {
Ok(()) => return Ok(()),
Err(error) if attempt < FETCH_ATTEMPTS && retryable_fetch_error(error.as_ref()) => {
let delay = Duration::from_secs(1 << (attempt - 1));
crate::elog!(
"temporary download failure for {} (attempt {attempt}/{FETCH_ATTEMPTS}): {error}; retrying in {}s",
file.name,
delay.as_secs()
);
tokio::time::sleep(delay).await;
}
Err(error) => return Err(error),
}
}
unreachable!("the final fetch attempt returns directly")
}
fn retryable_fetch_error(error: &(dyn Error + 'static)) -> bool {
if let Some(network) = error.downcast_ref::<reqwest::Error>() {
return network.is_connect()
|| network.is_timeout()
|| network.is_body()
|| network.status().is_some_and(|status| {
status.is_server_error()
|| status == StatusCode::TOO_MANY_REQUESTS
|| status == StatusCode::REQUEST_TIMEOUT
});
}
error
.downcast_ref::<io::Error>()
.is_some_and(|local| local.kind() == io::ErrorKind::UnexpectedEof)
}
fn model_request(
client: &Client,
file: &ModelFile,
offset: u64,
hub_token: Option<&str>,
) -> Result<RequestBuilder> {
let url = reqwest::Url::parse(&file.url)?;
let mut request = client.get(url.clone()).header(ACCEPT_ENCODING, "identity");
if is_hugging_face_url(&url)
&& let Some(token) = hub_token
{
request = request.bearer_auth(token);
}
if offset > 0 {
request = request.header(RANGE, format!("bytes={offset}-"));
}
Ok(request)
}
fn is_hugging_face_url(url: &reqwest::Url) -> bool {
url.scheme() == "https" && url.host_str() == Some("huggingface.co")
}
async fn fetch_one(
client: &Client,
file: &ModelFile,
output: &Path,
hub_token: Option<&str>,
) -> Result<()> {
let destination = output.join(&file.name);
reject_symlink(&destination).await?;
match fs::metadata(&destination).await {
Ok(_) => {
verify_one(file, &destination).await?;
crate::elog!("already verified {}", destination.display());
return Ok(());
}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}
let partial = part_path(&destination);
reject_symlink(&partial).await?;
let mut offset = match fs::metadata(&partial).await {
Ok(metadata) => metadata.len(),
Err(error) if error.kind() == io::ErrorKind::NotFound => 0,
Err(error) => return Err(error.into()),
};
if offset > file.size {
return Err(format!("partial file is larger than manifest size: {}", file.name).into());
}
if offset == file.size {
verify_one(file, &partial).await?;
fs::rename(&partial, &destination).await?;
return Ok(());
}
let request = model_request(client, file, offset, hub_token)?;
let mut response = request.send().await?.error_for_status()?;
match response.status() {
StatusCode::PARTIAL_CONTENT => {
let expected = format!("bytes {offset}-{}/{}", file.size - 1, file.size);
let actual = response
.headers()
.get(CONTENT_RANGE)
.and_then(|value| value.to_str().ok());
if actual != Some(expected.as_str()) {
return Err(
format!("unexpected Content-Range for {}: {actual:?}", file.name).into(),
);
}
}
StatusCode::OK => offset = 0,
status => return Err(format!("unexpected HTTP {status} for {}", file.name).into()),
}
require_space(
destination
.parent()
.ok_or("model destination has no parent")?,
file.size - offset,
)?;
let mut hasher = Sha256::new();
if offset > 0 {
let (size, prefix_hash) = hash_file(&partial).await?;
if size != offset {
return Err("partial file changed during resume".into());
}
hasher = prefix_hash;
}
let mut writer = OpenOptions::new()
.create(true)
.write(true)
.append(offset > 0)
.truncate(offset == 0)
.open(&partial)
.await?;
let mut received = offset;
let mut progress_at = tokio::time::Instant::now();
crate::elog!("fetching {}: {received}/{} bytes", file.name, file.size);
while let Some(chunk) = response.chunk().await? {
received = received
.checked_add(chunk.len() as u64)
.ok_or("download length overflow")?;
if received > file.size {
return Err(format!("download exceeded manifest size: {}", file.name).into());
}
writer.write_all(&chunk).await?;
hasher.update(&chunk);
if progress_at.elapsed() >= Duration::from_secs(10) {
crate::elog!(
"fetching {}: {received}/{} bytes ({:.1}%)",
file.name,
file.size,
received as f64 * 100.0 / file.size as f64
);
progress_at = tokio::time::Instant::now();
}
}
writer.flush().await?;
writer.sync_all().await?;
drop(writer);
if received != file.size {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
format!(
"incomplete download for {}: {received}/{}",
file.name, file.size
),
)
.into());
}
let digest = hex::encode(hasher.finalize());
if !digest.eq_ignore_ascii_case(&file.sha256) {
fs::remove_file(&partial).await?;
return Err(format!("SHA-256 mismatch for {}", file.name).into());
}
fs::rename(&partial, &destination).await?;
crate::elog!("downloaded {}", destination.display());
Ok(())
}
async fn preflight_space(manifest: &Manifest, output: &Path) -> Result<()> {
let mut needed = 0u64;
for entry in &manifest.files {
let destination = output.join(&entry.name);
reject_symlink(&destination).await?;
let remaining = match fs::metadata(&destination).await {
Ok(metadata) if metadata.len() == entry.size => 0,
Ok(_) => {
return Err(
format!("existing model file has unexpected size: {}", entry.name).into(),
);
}
Err(error) if error.kind() == io::ErrorKind::NotFound => {
let partial = part_path(&destination);
reject_symlink(&partial).await?;
let offset = match fs::metadata(&partial).await {
Ok(metadata) => metadata.len(),
Err(error) if error.kind() == io::ErrorKind::NotFound => 0,
Err(error) => return Err(error.into()),
};
entry
.size
.checked_sub(offset)
.ok_or("partial file exceeds manifest size")?
}
Err(error) => return Err(error.into()),
};
needed = needed
.checked_add(remaining)
.ok_or("model disk-space requirement overflow")?;
}
require_space(output, needed)
}
pub(crate) fn require_space(directory: &Path, needed: u64) -> Result<()> {
let available = available_bytes(directory)?;
if available < needed {
return Err(format!(
"insufficient disk space: need {needed} additional bytes, have {available} available bytes in {}",
directory.display()
).into());
}
Ok(())
}
#[cfg(unix)]
fn available_bytes(directory: &Path) -> io::Result<u64> {
use std::{mem::MaybeUninit, os::unix::ffi::OsStrExt};
let path = CString::new(directory.as_os_str().as_bytes())
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "directory contains NUL"))?;
let mut stats = MaybeUninit::<libc::statvfs>::uninit();
// SAFETY: path is NUL-terminated and stats points to writable statvfs storage.
if unsafe { libc::statvfs(path.as_ptr(), stats.as_mut_ptr()) } != 0 {
return Err(io::Error::last_os_error());
}
// SAFETY: a successful statvfs call initialized every field of stats.
let stats = unsafe { stats.assume_init() };
// statvfs counters have different widths on macOS and Linux. Widen both
// before multiplying, then check the byte count at the public u64 bound.
u64::try_from(u128::from(stats.f_bavail) * u128::from(stats.f_frsize))
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "available space overflow"))
}
#[cfg(not(unix))]
fn available_bytes(_directory: &Path) -> io::Result<u64> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"model fetch needs a Unix filesystem",
))
}
async fn verify_one(file: &ModelFile, path: &Path) -> Result<()> {
reject_symlink(path).await?;
let (size, hasher) = hash_file(path).await?;
if size != file.size || !hex::encode(hasher.finalize()).eq_ignore_ascii_case(&file.sha256) {
return Err(format!(
"model file failed size/SHA-256 verification: {}",
path.display()
)
.into());
}
Ok(())
}
async fn hash_file(path: &Path) -> Result<(u64, Sha256)> {
let mut reader = File::open(path).await?;
let mut hasher = Sha256::new();
let mut size = 0u64;
let mut buffer = vec![0u8; 1024 * 1024];
loop {
let read = reader.read(&mut buffer).await?;
if read == 0 {
break;
}
size = size
.checked_add(read as u64)
.ok_or("file length overflow")?;
hasher.update(&buffer[..read]);
}
Ok((size, hasher))
}
async fn reject_symlink(path: &Path) -> Result<()> {
match fs::symlink_metadata(path).await {
Ok(metadata) if metadata.file_type().is_symlink() => {
Err(format!("refusing symlink: {}", path.display()).into())
}
Ok(_) => Ok(()),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error.into()),
}
}
fn part_path(destination: &Path) -> PathBuf {
destination.with_file_name(format!(
"{}.part",
destination.file_name().unwrap().to_string_lossy()
))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::{net::TcpListener, time::timeout};
#[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();
}
#[tokio::test]
async fn interrupted_download_resumes_and_verifies() {
let base = std::env::temp_dir().join(format!(
"strata-model-test-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
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, _) = 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();
assert!(request.to_ascii_lowercase().contains("range: bytes=3-"));
socket
.write_all(b"HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\nContent-Range: bytes 3-5/6\r\nConnection: close\r\n\r\ndef")
.await
.unwrap();
});
let manifest_path = base.join("manifest.json");
fs::write(
&manifest_path,
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(),
)
.await
.unwrap();
let manifest = Manifest::load(&manifest_path).await.unwrap();
timeout(Duration::from_secs(5), fetch(&manifest, &output))
.await
.unwrap()
.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();
}
#[tokio::test]
async fn checksum_mismatch_never_publishes_download() {
let base = std::env::temp_dir().join(format!(
"strata-bad-download-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
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, _) = 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]);
}
socket
.write_all(
b"HTTP/1.1 200 OK\r\nContent-Length: 6\r\nConnection: close\r\n\r\nxxxxxx",
)
.await
.unwrap();
});
let 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")),
}],
};
let error = timeout(Duration::from_secs(5), fetch(&manifest, &base))
.await
.unwrap()
.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 = timeout(Duration::from_secs(5), fetch(&manifest, &base))
.await
.unwrap()
.unwrap_err();
assert!(error.to_string().contains("size/SHA-256 verification"));
assert!(!base.join("sample.bin").exists());
fs::remove_dir_all(base).await.unwrap();
}
#[tokio::test]
async fn transient_server_failure_retries_the_same_partial_download() {
let base = std::env::temp_dir().join(format!(
"strata-retry-test-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
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, _) = 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]);
}
assert!(
String::from_utf8(request)
.unwrap()
.to_ascii_lowercase()
.contains("range: bytes=3-")
);
if attempt == 0 {
socket
.write_all(
b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
)
.await
.unwrap();
} else {
socket
.write_all(b"HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\nContent-Range: bytes 3-5/6\r\nConnection: close\r\n\r\ndef")
.await
.unwrap();
}
}
});
let manifest = Manifest::parse(
&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(),
)
.unwrap();
timeout(Duration::from_secs(5), fetch(&manifest, &base))
.await
.unwrap()
.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 short_response_resumes_from_new_partial_offset() {
let base = std::env::temp_dir().join(format!(
"strata-short-response-test-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
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, _) = 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();
if attempt == 0 {
assert!(!request.contains("range:"));
socket
.write_all(
b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\nConnection: close\r\n\r\nabc",
)
.await
.unwrap();
} else {
assert!(request.contains("range: bytes=3-"));
socket
.write_all(b"HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\nContent-Range: bytes 3-5/6\r\nConnection: close\r\n\r\ndef")
.await
.unwrap();
}
}
});
let manifest = Manifest::parse(
&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(),
)
.unwrap();
timeout(Duration::from_secs(5), fetch(&manifest, &base))
.await
.unwrap()
.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();
}
#[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 file = ModelFile {
name: "model.gguf".into(),
url: url.into(),
size: 1,
sha256: "0".repeat(64),
};
let request = model_request(&client, &file, 3, Some("test-secret"))
.unwrap()
.build()
.unwrap();
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/")
}));
}
}