Skip to main content

scrollcase_consumer/
verify.rs

1//! The half of the trust chain that needs no archive.
2//!
3//! Everything here answers questions about the signed document alone — is the signature good, is the
4//! payload a schema-version-2 release, does it describe a target this build understands. It is split
5//! out for the same reason Node splits it: a box that is already extracted has no archive to check,
6//! and re-deriving these steps beside the ones that do would create the second interpretation of a
7//! signed release that the shared inspection exists to prevent.
8
9use std::collections::BTreeSet;
10use std::path::{Path, PathBuf};
11
12use crate::archive::{list_zip_entries, read_zip_entry_text, ArchiveEntry};
13use crate::contract::documents::SignedDocument;
14use crate::contract::links::EntryKind;
15use crate::contract::targets::{assert_python_entry_point, box_target_adapter, BoxTargetAdapter};
16use crate::error::{fail, Error, Result};
17use crate::execution::assert_execution_files;
18use crate::filesystem::sha256_file;
19use crate::release::{BoxManifest, ReleaseManifest};
20use crate::trust::{verify_signed_document, TrustAnchors};
21
22/// A signed release that has passed every check possible without its archive.
23#[derive(Debug, Clone)]
24pub struct InspectedRelease {
25    /// Where the document was read from.
26    pub release_path: PathBuf,
27    /// The envelope exactly as received, kept so a caller can persist what it verified.
28    pub signed: SignedDocument,
29    /// The verified release.
30    pub release: ReleaseManifest,
31    /// The adapter for the release's target.
32    pub adapter: &'static BoxTargetAdapter,
33}
34
35/// Verifies a signed release document against the caller's trust anchors.
36///
37/// The order is the guarantee. The envelope is shape-checked, then its signature is verified, and
38/// only then is the payload interpreted as a release: nothing about the release is believed — not
39/// its target, not its paths, not its provenance — until a trusted key has vouched for the exact
40/// bytes it was read from.
41///
42/// # Errors
43///
44/// When the anchors cannot be resolved, the document cannot be read, is not a v2 envelope, carries
45/// no signature from a trusted key, or describes a release this build cannot accept.
46pub fn inspect_release_document(
47    release_document_path: &Path,
48    trust: TrustAnchors<'_>,
49) -> Result<InspectedRelease> {
50    let trusted = trust.resolve()?;
51    let release_path = release_document_path
52        .canonicalize()
53        .unwrap_or_else(|_| release_document_path.to_path_buf());
54    let raw = std::fs::read(&release_path).map_err(|error| {
55        Error::new(format!(
56            "Invalid signed release document {}: {error}",
57            release_path.display()
58        ))
59    })?;
60
61    let signed = SignedDocument::parse(&raw)?;
62    let payload = verify_signed_document(&signed, &trusted)?;
63
64    // A v1 payload inside a v2 envelope is refused by name rather than reinterpreted.
65    if payload.value.get("schemaVersion").and_then(serde_json::Value::as_u64) == Some(1) {
66        fail!("Unsupported schemaVersion 1; rebuild this box with Scrollcase v2.");
67    }
68    let release: ReleaseManifest = serde_json::from_value(payload.value)
69        .map_err(|error| Error::new(format!("Invalid release manifest: {error}.")))?;
70    release.validate()?;
71
72    let adapter = box_target_adapter(&release.target)?;
73    assert_python_entry_point(adapter, &release.python_entry_point)?;
74
75    Ok(InspectedRelease {
76        release_path,
77        signed,
78        release,
79        adapter,
80    })
81}
82
83/// Binds the self-description inside the archive to the signed release outside it.
84///
85/// Only fields present in both schema-version-2 documents belong here. Release-only transport data
86/// has no counterpart in `box.json`; every shared identity, target, layout, self-test, environment,
87/// asset-policy and provenance field must agree. Without this, a correctly hashed archive could be
88/// paired with a signed manifest describing something else entirely.
89///
90/// # Errors
91///
92/// When any shared field differs, naming the first one that does.
93pub fn assert_box_manifest_agreement(
94    box_manifest: &BoxManifest,
95    release: &ReleaseManifest,
96) -> Result<()> {
97    // Written as explicit pairs rather than a derived comparison so the field name in the message is
98    // the field that actually differed — the Node and Python consumers report the same way, and the
99    // conformance fixture pins `box.json mismatch: modelId` among others.
100    let mismatch = if box_manifest.schema_version != release.schema_version {
101        Some("schemaVersion")
102    } else if box_manifest.box_id != release.box_id {
103        Some("boxId")
104    } else if box_manifest.model_id != release.model_id {
105        Some("modelId")
106    } else if box_manifest.runtime_id != release.runtime_id {
107        Some("runtimeId")
108    } else if box_manifest.version != release.version {
109        Some("version")
110    } else if box_manifest.target != release.target {
111        Some("target")
112    } else if box_manifest.python_entry_point != release.python_entry_point {
113        Some("pythonEntryPoint")
114    } else if box_manifest.model_cache_subdir != release.model_cache_subdir {
115        Some("modelCacheSubdir")
116    } else if box_manifest.environment != release.environment {
117        Some("environment")
118    } else if box_manifest.self_test != release.self_test {
119        Some("selfTest")
120    } else if box_manifest.execution != release.execution {
121        Some("execution")
122    } else if box_manifest.weights != release.weights {
123        Some("weights")
124    } else if box_manifest.assets != release.assets {
125        Some("assets")
126    } else if box_manifest.provenance != release.provenance {
127        Some("provenance")
128    } else {
129        None
130    };
131    if let Some(field) = mismatch {
132        fail!("box.json mismatch: {field}");
133    }
134    Ok(())
135}
136
137/// A signed release together with the archive it commits to, both checked.
138#[derive(Debug, Clone)]
139pub struct InspectedArchive {
140    /// The archive-free half of the chain.
141    pub release: InspectedRelease,
142    /// Where the archive was read from.
143    pub archive_path: PathBuf,
144    /// The box's own self-description, proved to agree with the release.
145    pub box_manifest: BoxManifest,
146    /// Every validated archive entry.
147    pub entries: Vec<ArchiveEntry>,
148}
149
150/// Performs the complete read-only trust chain, archive included.
151///
152/// Keeping this as one operation matters: an execution API must not create a second, subtly
153/// different interpretation of a signed release. The caller receives validated in-memory objects and
154/// the exact archive path, while extraction and execution remain separate steps.
155///
156/// # Errors
157///
158/// When the release fails inspection, the archive is missing or does not match its signed size and
159/// hash, the archive holds an entry the format forbids, or `box.json` disagrees with the release.
160pub fn inspect_box_archive(
161    release_document_path: &Path,
162    trust: TrustAnchors<'_>,
163    archive_override: Option<&Path>,
164) -> Result<InspectedArchive> {
165    let release = inspect_release_document(release_document_path, trust)?;
166    inspect_archive_for(release, archive_override)
167}
168
169/// The archive half, against a release this process already inspected.
170///
171/// # Errors
172///
173/// See [`inspect_box_archive`].
174pub fn inspect_archive_for(
175    inspected: InspectedRelease,
176    archive_override: Option<&Path>,
177) -> Result<InspectedArchive> {
178    let release = &inspected.release;
179    // By convention the archive sits next to its release document under the hash that document
180    // commits to — the same name it is published under, so this resolves identically against a local
181    // dist tree and a directory copied from a mirror.
182    let archive_path = match archive_override {
183        Some(path) => path.to_path_buf(),
184        None => inspected
185            .release_path
186            .parent()
187            .unwrap_or(Path::new("."))
188            .join(format!("{}.zip", release.archive.sha256)),
189    };
190    let metadata = std::fs::metadata(&archive_path)
191        .map_err(|_| Error::new(format!("Archive not found: {}", archive_path.display())))?;
192    if metadata.len() != release.archive.size_bytes {
193        fail!("Archive size mismatch.");
194    }
195    if sha256_file(&archive_path)? != release.archive.sha256 {
196        fail!("Archive SHA-256 mismatch.");
197    }
198
199    let entries = list_zip_entries(&archive_path)?;
200    // Two questions, deliberately not the same set. `box.json` is read out of the archive, so it must
201    // be an entry with its own bytes. Everything else asks only whether a path resolves — and a link
202    // does resolve, to a file inside this same payload, because nothing else was allowed in.
203    let files: BTreeSet<String> = entries
204        .iter()
205        .filter(|entry| entry.kind == EntryKind::File)
206        .map(|entry| entry.path.clone())
207        .collect();
208    let resolvable: BTreeSet<String> = entries
209        .iter()
210        .filter(|entry| matches!(entry.kind, EntryKind::File | EntryKind::Link))
211        .map(|entry| entry.path.clone())
212        .collect();
213
214    if !files.contains("box.json") {
215        fail!("Archive is missing box.json.");
216    }
217    let raw = read_zip_entry_text(&archive_path, "box.json")?;
218    let box_manifest: BoxManifest = serde_json::from_str(&raw)
219        .map_err(|error| Error::new(format!("Invalid box.json: {error}.")))?;
220    assert_box_manifest_agreement(&box_manifest, release)?;
221
222    if !resolvable.contains(&release.python_entry_point) {
223        fail!("Archive is missing {}.", release.python_entry_point);
224    }
225    assert_execution_files(
226        release.execution.as_ref(),
227        inspected.adapter,
228        &release.provenance.python_version,
229        &resolvable,
230    )?;
231
232    Ok(InspectedArchive {
233        release: inspected,
234        archive_path,
235        box_manifest,
236        entries,
237    })
238}