From 3bfc4a3f0300e80fc2bf8576d009552005e8c4df Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 20:31:25 +0200 Subject: [PATCH] feat(engine): verify GGUF artifacts through owned Rust file handles --- crates/model-format/README.md | 39 ++- crates/model-format/src/gguf.rs | 441 +++++++++++++++++++++++++++++++- crates/model-format/src/lib.rs | 4 +- 3 files changed, 475 insertions(+), 9 deletions(-) diff --git a/crates/model-format/README.md b/crates/model-format/README.md index dadde167..8dc5e721 100644 --- a/crates/model-format/README.md +++ b/crates/model-format/README.md @@ -7,7 +7,7 @@ Python dependency. The existing control plane reexports its `gguf` module, so preparation, inspection, tokenizer extraction and tensor-export consumers keep their public paths. -The parser and its tests were moved unchanged from `control-plane/src/gguf.rs`. +The original parser geometry and its three tests were moved unchanged from `control-plane/src/gguf.rs`. Tensor block geometry and the legacy Flash-Next metadata guard retain their upstream references; see [the provenance record](../../docs/upstream.md). Those helpers inspect metadata and byte layout, not tensor values or inference. @@ -27,9 +27,32 @@ Recognizing a quantization block size is not support for decoding or serving it. All preexisting bounds/rejections remain unchanged. Path-based functions reopen the source; callers must keep the verified file stable between inspection and reading. File length checks do not detect same-size replacement or mutation. -This crate does not yet provide an owned, immutable, digest-bound model-loader -handle. Full-artifact verification, descriptor/tensor/tokenizer binding, memory -admission, GPU allocation, readiness and real-model parity remain separate work. +`VerifiedGgufFile::open` is a separate owned-file API: it accepts a +`sha256:<64 hex digits>` artifact digest, opens one regular file, hashes the full +file with a buffer of at most 64 KiB, and parses the strict tensor index through +that same handle. The private file/index pair is retained; `index()` offers only +an immutable borrow. `stream_tensor` validates a requested tensor number and +byte range before delivering at most 64 KiB per callback, and `tensor_sha256` +hashes the indexed payload through that stream. Neither tensor operation reopens +the pathname or allocates the full tensor. A consumer may explicitly collect +chunks or return an I/O error to abort. Empty ranges at the tensor end are valid. + +Renaming or replacing the original pathname after opening does not redirect this +handle to a different file. The preliminary path metadata check rejects ordinary +nonregular paths; the opened-file metadata check determines whether the accepted +handle is regular. This does not make pathname lookup atomic against a malicious +concurrent substitution during opening. The caller must supply a stable regular +source for opening and prevent **in-place writes for the entire verification, +indexing and read lifetime**. Keeping a file descriptor does not make its bytes +immutable: even same-size writes to the same file remain visible and are not +caught by file length checks. The stored artifact digest records verification at +open, not a later content attestation. Size changes are refused before/after +streaming, and short reads propagate errors; callbacks already delivered before +an I/O failure cannot be retracted. + +The existing path APIs and tensor geometry remain unchanged. Descriptor, tensor +and tokenizer semantics, memory admission, GPU allocation, readiness and +real-model parity remain separate work. The current `strata-control` still has its legacy GGML/build dependencies; extracting this crate does not remove them from that package or its runtime. @@ -43,3 +66,11 @@ cargo tree --locked -p leleka-model-format These are container/parser checks with sanitized synthetic bytes. They do not establish inference, model quality, GPU operation or performance. + +Owned-file tests use generated synthetic GGUF bytes: full-digest and tensor-byte +oracles, multi-chunk and partial streaming, malformed digest, nonregular source, +tamper, truncate, unsupported version/type and overlapping geometry rejection, +range/overflow checks before callbacks, callback abort/recovery, Unix pathname +replacement retaining the original file, and an explicit same-size in-place +mutation counterexample. These tests do not qualify an immutable artifact store +or a complete model loader. diff --git a/crates/model-format/src/gguf.rs b/crates/model-format/src/gguf.rs index ec052e4b..ac8c727c 100644 --- a/crates/model-format/src/gguf.rs +++ b/crates/model-format/src/gguf.rs @@ -52,6 +52,164 @@ pub struct TokenizerMetadata { pub chat_template: String, } +/// An owned GGUF file whose complete bytes matched the declared digest at open. +/// +/// The private file and index stay paired across pathname replacements. This is +/// not an immutable snapshot: callers must prevent in-place writes for the whole +/// verification, indexing and reading lifetime. Size checks cannot prove that. +#[derive(Debug)] +pub struct VerifiedGgufFile { + file: File, + index: TensorIndex, + artifact_sha256: [u8; 32], +} + +const STREAM_BUFFER_BYTES: usize = 64 * 1024; + +impl VerifiedGgufFile { + /// Verify `sha256:<64 hex digits>` and strictly index the same opened file. + /// The opened file's contents must remain stable until this handle is dropped. + pub fn open(path: &Path, expected_digest: &str) -> Result { + let expected = parse_artifact_digest(expected_digest)?; + // Refuse an ordinary nonregular path before opening it (notably FIFOs). + // The opened-file check below is authoritative for the accepted source. + if !std::fs::metadata(path)?.is_file() { + return Err("GGUF source must be a regular file".into()); + } + let mut file = File::open(path)?; + let metadata = file.metadata()?; + if !metadata.is_file() { + return Err("GGUF source must be a regular file".into()); + } + let size = metadata.len(); + let mut digest = Sha256::new(); + stream_file_span(&mut file, 0, size, |chunk| { + digest.update(chunk); + Ok(()) + })?; + let actual: [u8; 32] = digest.finalize().into(); + if actual != expected { + return Err("GGUF artifact SHA256 mismatch".into()); + } + if file.metadata()?.len() != size { + return Err("GGUF source size changed during verification".into()); + } + let index = read_index_file(&mut file, size, true)?; + if file.metadata()?.len() != size { + return Err("GGUF source size changed during indexing".into()); + } + Ok(Self { + file, + index, + artifact_sha256: actual, + }) + } + + pub fn index(&self) -> &TensorIndex { + &self.index + } + + /// Digest verified when opening, not a promise of later source immutability. + pub fn artifact_sha256(&self) -> [u8; 32] { + self.artifact_sha256 + } + + /// Stream an exact byte range within an indexed tensor through a buffer of + /// at most 64 KiB. The consumer may return an I/O error to abort the stream. + /// No pathname is reopened; all range checks precede the first callback. + pub fn stream_tensor( + &mut self, + tensor_number: usize, + offset: u64, + bytes: u64, + consume: impl FnMut(&[u8]) -> std::io::Result<()>, + ) -> Result<()> { + let tensor = self + .index + .tensors + .get(tensor_number) + .ok_or("GGUF tensor index is out of bounds")?; + if tensor.bytes == 0 + || offset + .checked_add(bytes) + .is_none_or(|end| end > tensor.bytes) + { + return Err("GGUF tensor byte range is out of bounds".into()); + } + let absolute = self + .index + .summary + .data_start + .checked_add(tensor.offset) + .and_then(|start| start.checked_add(offset)) + .ok_or("GGUF tensor offset overflow")?; + if absolute + .checked_add(bytes) + .is_none_or(|end| end > self.index.summary.file_size) + { + return Err("GGUF tensor exceeds indexed file".into()); + } + self.check_size()?; + stream_file_span(&mut self.file, absolute, bytes, consume)?; + self.check_size() + } + + /// Hash the complete indexed tensor without allocating its full payload. + pub fn tensor_sha256(&mut self, tensor_number: usize) -> Result<[u8; 32]> { + let bytes = self + .index + .tensors + .get(tensor_number) + .ok_or("GGUF tensor index is out of bounds")? + .bytes; + let mut digest = Sha256::new(); + self.stream_tensor(tensor_number, 0, bytes, |chunk| { + digest.update(chunk); + Ok(()) + })?; + Ok(digest.finalize().into()) + } + + fn check_size(&self) -> Result<()> { + if self.file.metadata()?.len() != self.index.summary.file_size { + return Err("GGUF source size changed after verification".into()); + } + Ok(()) + } +} + +fn parse_artifact_digest(value: &str) -> Result<[u8; 32]> { + let hex = value + .strip_prefix("sha256:") + .ok_or("invalid GGUF artifact digest")?; + if hex.len() != 64 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err("invalid GGUF artifact digest".into()); + } + let mut digest = [0u8; 32]; + for (index, byte) in digest.iter_mut().enumerate() { + *byte = u8::from_str_radix(&hex[index * 2..index * 2 + 2], 16)?; + } + Ok(digest) +} + +fn stream_file_span( + file: &mut File, + absolute: u64, + bytes: u64, + mut consume: impl FnMut(&[u8]) -> std::io::Result<()>, +) -> Result<()> { + file.seek(SeekFrom::Start(absolute))?; + let mut buffer = vec![0u8; bytes.min(STREAM_BUFFER_BYTES as u64) as usize]; + let mut remaining = bytes; + while remaining > 0 { + let count = remaining.min(buffer.len() as u64) as usize; + file.read_exact(&mut buffer[..count])?; + consume(&buffer[..count])?; + remaining -= count as u64; + } + Ok(()) +} + /// Metadata admission for the specialised engine, before expensive preparation. /// Mirrors artifact/gguf_reader.hpp::Qwen4ExpGuard; this does not inspect tensor values. pub fn check_flash_next_profile(path: &Path) -> Result<()> { @@ -240,8 +398,13 @@ pub fn tensor_sha256(path: &Path, index: &TensorIndex, tensor_number: usize) -> } fn read_index(path: &Path, strict: bool) -> Result { - let file = File::open(path)?; + let mut file = File::open(path)?; let size = file.metadata()?.len(); + read_index_file(&mut file, size, strict) +} + +fn read_index_file(file: &mut File, size: u64, strict: bool) -> Result { + file.seek(SeekFrom::Start(0))?; let mut cursor = Cursor { file, size }; if cursor.take(4)? != b"GGUF" { return Err("not a GGUF file".into()); @@ -431,12 +594,12 @@ pub fn block_geometry(kind: u32) -> Option<(u64, u64)> { }) } -struct Cursor { - file: File, +struct Cursor { + file: R, size: u64, } -impl Cursor { +impl Cursor { fn position(&mut self) -> Result { Ok(self.file.stream_position()?) } @@ -784,4 +947,274 @@ mod tests { assert!(tensor_index(&path).is_err()); std::fs::remove_file(path).unwrap(); } + + struct OwnedFixture { + directory: std::path::PathBuf, + path: std::path::PathBuf, + bytes: Vec, + small: Vec, + large: Vec, + kind_at: usize, + offset_at: usize, + } + + impl OwnedFixture { + fn new() -> Self { + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT: AtomicU64 = AtomicU64::new(0); + let directory = std::env::temp_dir().join(format!( + "leleka-owned-gguf-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir(&directory).unwrap(); + let path = directory.join("fixture.gguf"); + let small = (0..16).collect::>(); + let large = (0..STREAM_BUFFER_BYTES * 3 + 11) + .map(|at| (at % 251) as u8) + .collect::>(); + let mut bytes = b"GGUF".to_vec(); + bytes.extend(3u32.to_le_bytes()); + bytes.extend(2u64.to_le_bytes()); + bytes.extend(0u64.to_le_bytes()); + string(&mut bytes, "fixture.small"); + bytes.extend(1u32.to_le_bytes()); + bytes.extend(4u64.to_le_bytes()); + bytes.extend(0u32.to_le_bytes()); + bytes.extend(0u64.to_le_bytes()); + string(&mut bytes, "fixture.large"); + bytes.extend(1u32.to_le_bytes()); + bytes.extend((large.len() as u64).to_le_bytes()); + let kind_at = bytes.len(); + bytes.extend(24u32.to_le_bytes()); + let offset_at = bytes.len(); + bytes.extend(32u64.to_le_bytes()); + bytes.resize(bytes.len().div_ceil(32) * 32, 0); + bytes.extend(&small); + bytes.extend([0u8; 16]); + bytes.extend(&large); + std::fs::write(&path, &bytes).unwrap(); + Self { + directory, + path, + bytes, + small, + large, + kind_at, + offset_at, + } + } + + fn digest(&self) -> String { + let hex = Sha256::digest(&self.bytes) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(); + format!("sha256:{hex}") + } + } + + impl Drop for OwnedFixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.directory); + } + } + + #[test] + fn owned_handle_verifies_artifact_and_streams_exact_tensor_bytes_with_bounded_chunks() { + let fixture = OwnedFixture::new(); + let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); + assert_eq!( + source.artifact_sha256(), + <[u8; 32]>::from(Sha256::digest(&fixture.bytes)) + ); + assert_eq!(source.index().tensors.len(), 2); + assert_eq!(source.index().tensors[1].bytes, fixture.large.len() as u64); + for (number, expected) in [(0, &fixture.small), (1, &fixture.large)] { + assert_eq!( + source.tensor_sha256(number).unwrap(), + <[u8; 32]>::from(Sha256::digest(expected)) + ); + } + let mut seen = 0; + let mut callbacks = 0; + source + .stream_tensor(1, 0, fixture.large.len() as u64, |chunk| { + assert!(!chunk.is_empty() && chunk.len() <= STREAM_BUFFER_BYTES); + assert_eq!(chunk, &fixture.large[seen..seen + chunk.len()]); + seen += chunk.len(); + callbacks += 1; + Ok(()) + }) + .unwrap(); + assert_eq!(seen, fixture.large.len()); + assert_eq!(callbacks, 4); + let mut partial = Vec::new(); + source + .stream_tensor(1, 7, 13, |chunk| { + partial.extend_from_slice(chunk); + Ok(()) + }) + .unwrap(); + assert_eq!(partial, fixture.large[7..20]); + } + + #[test] + fn owned_handle_rejects_bad_digest_nonregular_sources_and_tampering() { + let fixture = OwnedFixture::new(); + for digest in [ + "", + "abc", + "sha256:abc", + &format!("sha256:{}", "g".repeat(64)), + &format!("SHA256:{}", "a".repeat(64)), + ] { + assert!( + VerifiedGgufFile::open(&fixture.path, digest) + .unwrap_err() + .to_string() + .contains("invalid GGUF artifact digest") + ); + } + assert!( + VerifiedGgufFile::open(&fixture.directory, &fixture.digest()) + .unwrap_err() + .to_string() + .contains("regular file") + ); + let mut tampered = fixture.bytes.clone(); + *tampered.last_mut().unwrap() ^= 1; + std::fs::write(&fixture.path, tampered).unwrap(); + assert!( + VerifiedGgufFile::open(&fixture.path, &fixture.digest()) + .unwrap_err() + .to_string() + .contains("SHA256 mismatch") + ); + } + + #[test] + fn owned_handle_rejects_truncated_unsupported_and_bad_geometry_even_with_matching_digest() { + let mut fixture = OwnedFixture::new(); + let original = fixture.bytes.clone(); + for fault in 0..4 { + fixture.bytes = original.clone(); + match fault { + 0 => { + fixture.bytes.pop(); + } + 1 => fixture.bytes[fixture.kind_at..fixture.kind_at + 4] + .copy_from_slice(&u32::MAX.to_le_bytes()), + 2 => fixture.bytes[fixture.offset_at..fixture.offset_at + 8] + .copy_from_slice(&0u64.to_le_bytes()), + 3 => fixture.bytes[4..8].copy_from_slice(&2u32.to_le_bytes()), + _ => unreachable!(), + } + std::fs::write(&fixture.path, &fixture.bytes).unwrap(); + assert!( + VerifiedGgufFile::open(&fixture.path, &fixture.digest()).is_err(), + "fault {fault}" + ); + } + } + + #[test] + fn owned_tensor_bounds_are_checked_before_any_callback_and_stream_can_recover() { + let fixture = OwnedFixture::new(); + let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); + for (number, offset, bytes) in [ + (2, 0, 1), + (0, 0, 17), + (0, 17, 0), + (0, u64::MAX, 1), + (0, 1, u64::MAX), + ] { + let mut called = false; + assert!( + source + .stream_tensor(number, offset, bytes, |_| { + called = true; + Ok(()) + }) + .is_err() + ); + assert!(!called); + } + source + .stream_tensor(0, 16, 0, |_| panic!("empty range invoked consumer")) + .unwrap(); + assert!( + source + .stream_tensor(1, 0, 10, |_| Err(std::io::Error::other( + "synthetic consumer failure" + ))) + .unwrap_err() + .to_string() + .contains("synthetic consumer failure") + ); + assert_eq!( + source.tensor_sha256(0).unwrap(), + <[u8; 32]>::from(Sha256::digest(&fixture.small)) + ); + } + + #[cfg(unix)] + #[test] + fn pathname_replacement_keeps_original_verified_file_and_index() { + let fixture = OwnedFixture::new(); + let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); + std::fs::rename(&fixture.path, fixture.directory.join("original.gguf")).unwrap(); + std::fs::write(&fixture.path, b"replacement is not a GGUF file").unwrap(); + assert!(tensor_index(&fixture.path).is_err()); + assert_eq!( + source.tensor_sha256(1).unwrap(), + <[u8; 32]>::from(Sha256::digest(&fixture.large)) + ); + let mut small = Vec::new(); + source + .stream_tensor(0, 0, 16, |chunk| { + small.extend_from_slice(chunk); + Ok(()) + }) + .unwrap(); + assert_eq!(small, fixture.small); + assert_eq!( + source.artifact_sha256(), + <[u8; 32]>::from(Sha256::digest(&fixture.bytes)) + ); + } + + #[test] + fn opened_file_size_changes_are_refused_and_same_size_mutation_is_not_immutability() { + let fixture = OwnedFixture::new(); + let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); + let mut mutated = fixture.bytes.clone(); + *mutated.last_mut().unwrap() ^= 1; + std::fs::write(&fixture.path, &mutated).unwrap(); + // Explicit counterexample: retaining the descriptor does not freeze bytes. + assert_ne!( + source.tensor_sha256(1).unwrap(), + <[u8; 32]>::from(Sha256::digest(&fixture.large)) + ); + assert_eq!( + source.artifact_sha256(), + <[u8; 32]>::from(Sha256::digest(&fixture.bytes)) + ); + std::fs::OpenOptions::new() + .write(true) + .open(&fixture.path) + .unwrap() + .set_len(0) + .unwrap(); + let mut called = false; + assert!( + source + .stream_tensor(0, 0, 16, |_| { + called = true; + Ok(()) + }) + .is_err() + ); + assert!(!called); + } } diff --git a/crates/model-format/src/lib.rs b/crates/model-format/src/lib.rs index 34cffb26..b954b632 100644 --- a/crates/model-format/src/lib.rs +++ b/crates/model-format/src/lib.rs @@ -1,7 +1,9 @@ //! Backend-independent model-container inspection and indexing. //! //! This foundation exposes bounded GGUF metadata and byte geometry. It does -//! not implement dequantization, model loading, device allocation or inference. +//! not implement dequantization, complete model loading, device allocation or inference. +//! The owned GGUF reader binds digest verification and indexing to one open file; +//! callers must keep that file's contents stable throughout its lifetime. //! Its only direct dependency is the Rust SHA-256 implementation in `sha2`. pub mod gguf;