Skip to main content

adk_vision/manifest/
verify.rs

1//! [`VerifiedModel`]: model files whose SHA-256 matched their manifest.
2
3use std::path::{Path, PathBuf};
4
5use super::{LicenceGate, ModelFile, ModelManifest};
6use crate::digest::Digest;
7use crate::error::{Result, VisionError};
8
9/// One model file whose size and SHA-256 matched its manifest when it was checked.
10///
11/// Only verification constructs one, so a backend that takes a [`VerifiedModel`] cannot
12/// load an unchecked file (V-I10):
13///
14/// ```compile_fail,E0451
15/// use adk_vision::VerifiedFile;
16///
17/// let forged = VerifiedFile { path: "/tmp/model.onnx".into(), digest: adk_vision::Digest::of(b""), size: 0 };
18/// ```
19#[derive(Clone, Debug, PartialEq, Eq)]
20pub struct VerifiedFile {
21    path: PathBuf,
22    digest: Digest,
23    size: u64,
24}
25
26impl VerifiedFile {
27    /// Checks the file at `path` against its manifest entry: size first, then SHA-256.
28    ///
29    /// # Errors
30    ///
31    /// [`VisionError::SizeMismatch`] or [`VisionError::DigestMismatch`] with both values,
32    /// or [`VisionError::Io`].
33    pub fn check(path: &Path, expected: &ModelFile) -> Result<Self> {
34        let size =
35            std::fs::metadata(path).map_err(|e| VisionError::io("could not read", path, e))?.len();
36        if size != expected.size {
37            return Err(VisionError::SizeMismatch {
38                path: path.to_path_buf(),
39                expected: expected.size,
40                actual: size,
41            });
42        }
43        let (digest, _) = Digest::of_file(path)?;
44        if digest != expected.sha256 {
45            tracing::warn!(
46                model.file = %path.display(),
47                expected = %expected.sha256,
48                actual = %digest,
49                "model file rejected"
50            );
51            return Err(VisionError::DigestMismatch {
52                path: path.to_path_buf(),
53                expected: expected.sha256,
54                actual: digest,
55            });
56        }
57        Ok(Self { path: path.to_path_buf(), digest, size })
58    }
59
60    /// Where the file is.
61    pub fn path(&self) -> &Path {
62        &self.path
63    }
64
65    /// Its SHA-256.
66    pub fn digest(&self) -> Digest {
67        self.digest
68    }
69
70    /// Its size in bytes.
71    pub fn size(&self) -> u64 {
72        self.size
73    }
74}
75
76/// A model whose every file matched its manifest, under a licence the gate allowed.
77#[derive(Clone, Debug, PartialEq)]
78pub struct VerifiedModel {
79    manifest: ModelManifest,
80    files: Vec<(String, VerifiedFile)>,
81}
82
83impl VerifiedModel {
84    pub(crate) fn new(manifest: ModelManifest, files: Vec<(String, VerifiedFile)>) -> Self {
85        Self { manifest, files }
86    }
87
88    /// Checks the files of `manifest` in `dir`, laid out at their manifest paths, after the
89    /// licence gate allows the model. Every file is hashed on every call, so a file changed
90    /// since an earlier check is caught.
91    ///
92    /// # Errors
93    ///
94    /// The licence gate's refusal, then the first file's [`VerifiedFile::check`] error.
95    ///
96    /// # Example
97    ///
98    /// ```
99    /// use adk_vision::{
100    ///     Digest, InMemoryAcceptanceStore, LicenceGate, LicencePolicy, ModelManifest,
101    ///     VerifiedModel, VisionError,
102    /// };
103    ///
104    /// let dir = tempfile::tempdir().unwrap();
105    /// std::fs::write(dir.path().join("w.bin"), b"weights").unwrap();
106    /// let manifest = ModelManifest::from_json(&format!(r#"{{
107    ///     "id": "toy", "task": "detect",
108    ///     "source": {{"kind": "local", "dir": "{}"}},
109    ///     "files": [{{"path": "w.bin", "size": 7, "sha256": "{}"}}],
110    ///     "licence": {{"id": "MIT", "url": "https://opensource.org/license/mit", "class": "permissive"}},
111    ///     "runtime": {{"kind": "candle"}}
112    /// }}"#, dir.path().display(), Digest::of(b"weights"))).unwrap();
113    /// let (policy, store) = (LicencePolicy::new(), InMemoryAcceptanceStore::new());
114    /// let gate = LicenceGate::new(&policy, &store);
115    /// assert!(VerifiedModel::check_dir(&manifest, dir.path(), &gate).is_ok());
116    ///
117    /// std::fs::write(dir.path().join("w.bin"), b"tamper!").unwrap();
118    /// let err = VerifiedModel::check_dir(&manifest, dir.path(), &gate).unwrap_err();
119    /// assert!(matches!(err, VisionError::DigestMismatch { .. }));
120    /// ```
121    pub fn check_dir(manifest: &ModelManifest, dir: &Path, gate: &LicenceGate<'_>) -> Result<Self> {
122        manifest.validate()?;
123        gate.check(manifest)?;
124        let mut files = Vec::with_capacity(manifest.files.len());
125        for file in &manifest.files {
126            let path = dir.join(&file.path);
127            files.push((file.path.clone(), VerifiedFile::check(&path, file)?));
128        }
129        tracing::info!(model.id = %manifest.id, model.files = files.len(), "model verified");
130        Ok(Self::new(manifest.clone(), files))
131    }
132
133    /// The manifest.
134    pub fn manifest(&self) -> &ModelManifest {
135        &self.manifest
136    }
137
138    /// The verified files, in manifest order.
139    pub fn files(&self) -> impl Iterator<Item = &VerifiedFile> {
140        self.files.iter().map(|(_, f)| f)
141    }
142
143    /// The verified file at a manifest path.
144    pub fn file(&self, path: &str) -> Option<&VerifiedFile> {
145        self.files.iter().find(|(p, _)| p == path).map(|(_, f)| f)
146    }
147
148    /// The directory the `required` files sit in, for a loader that reads a whole
149    /// directory, after checking that it will find no weights there the manifest does not
150    /// pin.
151    #[cfg(any(feature = "ocr-vl", feature = "mistralrs"))]
152    pub(crate) fn dir_of(&self, required: &[&str]) -> Result<PathBuf> {
153        let id = &self.manifest().id;
154        let invalid = |reason: String| VisionError::Manifest { id: id.clone(), reason };
155        let mut dir: Option<PathBuf> = None;
156        for path in required {
157            let file = self.file(path).ok_or_else(|| {
158                invalid(format!("the manifest pins no `{path}`, which the loader reads"))
159            })?;
160            let parent = file.path().parent().map(Path::to_path_buf).unwrap_or_default();
161            match &dir {
162                None => dir = Some(parent),
163                Some(d) if *d != parent => {
164                    return Err(invalid(format!("`{path}` is not beside the model's other files")));
165                }
166                Some(_) => {}
167            }
168        }
169        let dir = dir.ok_or_else(|| invalid("no file to load".into()))?;
170        // The loaders collect every `*.safetensors` in the directory; each must be pinned.
171        let entries =
172            std::fs::read_dir(&dir).map_err(|e| VisionError::io("could not read", &dir, e))?;
173        for entry in entries.flatten() {
174            let name = entry.file_name().to_string_lossy().to_string();
175            if name.ends_with(".safetensors") && self.file(&name).is_none() {
176                return Err(invalid(format!(
177                    "`{name}` in {} is not in the manifest and would load unverified; remove it",
178                    dir.display()
179                )));
180            }
181        }
182        Ok(dir)
183    }
184}