Files
leleka/control-plane/src/model.rs
T

475 lines
16 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, 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>>;
#[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());
}
}
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?;
eprintln!("verified {}", path.display());
}
Ok(())
}
pub async fn fetch(manifest: &Manifest, output: &Path) -> Result<()> {
fs::create_dir_all(output).await?;
preflight_space(manifest, output).await?;
// 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<_>, _>>()?;
let client = 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")))
{
attempt.follow()
} else {
attempt.error("refusing a non-HTTPS model redirect")
}
}))
.build()?;
for file in &manifest.files {
fetch_one(&client, file, output).await?;
}
Ok(())
}
async fn fetch_one(client: &Client, file: &ModelFile, output: &Path) -> Result<()> {
let destination = output.join(&file.name);
reject_symlink(&destination).await?;
match fs::metadata(&destination).await {
Ok(_) => {
verify_one(file, &destination).await?;
eprintln!("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 mut request = client.get(&file.url).header(ACCEPT_ENCODING, "identity");
if offset > 0 {
request = request.header(RANGE, format!("bytes={offset}-"));
}
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;
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);
}
writer.flush().await?;
writer.sync_all().await?;
drop(writer);
if received != file.size {
return Err(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?;
eprintln!("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)
}
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() };
(stats.f_bavail as u64)
.checked_mul(stats.f_frsize)
.ok_or_else(|| 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 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();
}
#[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/")
}));
}
}