Skip to main content

euv_core/dynamic/manifest/
impl.rs

1use super::*;
2
3/// Human-readable diagnostic formatting for `DynamicReleaseError`.
4impl fmt::Display for DynamicReleaseError {
5    /// Formats `self` into a human-readable diagnostic message.
6    ///
7    /// # Arguments
8    ///
9    /// - `&mut Formatter<'_>` - Destination text formatter.
10    ///
11    /// # Returns
12    ///
13    /// - `fmt::Result` - Formatting outcome.
14    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
15        match self {
16            Self::InvalidSignature(msg) => write!(f, "invalid release signature: {msg}"),
17            Self::AbiIncompatible {
18                host_abi,
19                min_abi,
20                max_abi,
21            } => write!(
22                f,
23                "incompatible host ABI {host_abi} (required {min_abi}..={max_abi})"
24            ),
25            Self::UnsupportedDeliveryMode { allowed, incoming } => write!(
26                f,
27                "delivery mode {incoming:?} is not permitted under policy {allowed:?}"
28            ),
29            Self::MissingCapability(cap) => write!(f, "missing required host capability: {cap}"),
30            Self::BrokenDependencyClosure(msg) => {
31                write!(f, "broken release dependency closure: {msg}")
32            }
33            Self::HashMismatch { expected, actual } => {
34                write!(f, "sha256 mismatch: expected {expected}, actual {actual}")
35            }
36            Self::NonMonotonicRelease { current, incoming } => write!(
37                f,
38                "{ERR_NON_MONOTONIC_RELEASE}: current={current}, incoming={incoming}"
39            ),
40            Self::BlobMissing(sha) => write!(f, "content-addressed blob not found: {sha}"),
41            Self::RouteNotFound(route) => write!(f, "route not declared in manifest: {route}"),
42            Self::InterfaceMismatch {
43                expected_interface,
44                actual_interface,
45            } => write!(
46                f,
47                "component interface mismatch: expected {expected_interface}, actual {actual_interface}"
48            ),
49            Self::StateMigrationFailed(msg) => write!(f, "state migration failed: {msg}"),
50            Self::UnsafeSwapPoint(reason) => {
51                write!(f, "swap deferred at unsafe boundary: {reason}")
52            }
53            Self::StateCatchUpConflict {
54                base_revision,
55                live_revision,
56            } => write!(
57                f,
58                "state delta catch-up conflict from rev {base_revision} to rev {live_revision}"
59            ),
60            Self::ProtocolIncompatible(msg) => write!(f, "protocol incompatible: {msg}"),
61            Self::NetworkError(msg) => write!(f, "update network error: {msg}"),
62            Self::StorageError(msg) => write!(f, "update storage error: {msg}"),
63        }
64    }
65}
66
67/// Standard error trait marker for `DynamicReleaseError`.
68impl Error for DynamicReleaseError {}
69
70/// Helper methods on `BlobArtifact`.
71impl BlobArtifact {
72    /// Returns the canonical `"<module_id>@<version>"` artifact key.
73    ///
74    /// # Returns
75    ///
76    /// - `String` - Artifact lookup key.
77    #[must_use]
78    pub fn artifact_key(&self) -> String {
79        format_artifact_key(self.get_module_id(), self.get_version())
80    }
81
82    /// Configures interface contract metadata and host ABI range on this artifact.
83    ///
84    /// # Arguments
85    ///
86    /// - `&str` - Compile-time interface identifier.
87    /// - `u32` - Interface version number.
88    /// - `u32` - Local state schema version number.
89    /// - `u32` - Minimum host ABI version.
90    /// - `u32` - Maximum host ABI version.
91    ///
92    /// # Returns
93    ///
94    /// - `Self` - Updated artifact descriptor.
95    #[must_use]
96    pub fn with_contract(
97        mut self,
98        interface_id: &str,
99        interface_version: u32,
100        state_schema_version: u32,
101        min_host_abi: u32,
102        max_host_abi: u32,
103    ) -> Self {
104        self.set_interface_id(interface_id.to_string())
105            .set_interface_version(interface_version)
106            .set_state_schema_version(state_schema_version)
107            .set_min_host_abi(min_host_abi)
108            .set_max_host_abi(max_host_abi);
109        self
110    }
111
112    /// Appends a pinned transitive dependency key (`"module_id@version"`).
113    ///
114    /// # Arguments
115    ///
116    /// - `String` - Pinned dependency artifact key.
117    ///
118    /// # Returns
119    ///
120    /// - `Self` - Updated artifact descriptor.
121    #[must_use]
122    pub fn with_dependency(mut self, dep_key: String) -> Self {
123        self.get_mut_dependencies().push(dep_key);
124        self
125    }
126
127    /// Sets the logical entrypoint symbol on this artifact.
128    ///
129    /// # Arguments
130    ///
131    /// - `String` - Entrypoint symbol name.
132    ///
133    /// # Returns
134    ///
135    /// - `Self` - Updated artifact descriptor.
136    #[must_use]
137    pub fn with_entrypoint(mut self, entrypoint: String) -> Self {
138        self.set_entrypoint(entrypoint);
139        self
140    }
141
142    /// Appends a required host capability string to this artifact.
143    ///
144    /// # Arguments
145    ///
146    /// - `String` - Capability identifier.
147    ///
148    /// # Returns
149    ///
150    /// - `Self` - Updated artifact descriptor.
151    #[must_use]
152    pub fn with_capability(mut self, capability: String) -> Self {
153        self.get_mut_required_capabilities().push(capability);
154        self
155    }
156}
157
158/// Builder helpers on `RouteManifest`.
159impl RouteManifest {
160    /// Pins a logical slot key to an exact artifact key (`"module_id@version"`).
161    ///
162    /// # Arguments
163    ///
164    /// - `String` - Logical slot identifier.
165    /// - `String` - Exact pinned artifact key.
166    ///
167    /// # Returns
168    ///
169    /// - `Self` - Updated route manifest.
170    #[must_use]
171    pub fn with_slot(mut self, slot_key: String, artifact_key: String) -> Self {
172        let _: Option<String> = self.get_mut_slot_bindings().insert(slot_key, artifact_key);
173        self
174    }
175
176    /// Populates `transitive_hashes` directly from `artifacts`.
177    ///
178    /// # Arguments
179    ///
180    /// - `&BTreeMap<String, BlobArtifact>` - Release artifact table.
181    ///
182    /// # Returns
183    ///
184    /// - `Result<&mut Self, DynamicReleaseError>` - Updated route manifest or closure error.
185    pub fn seal_transitive_hashes(
186        &mut self,
187        artifacts: &BTreeMap<String, BlobArtifact>,
188    ) -> Result<&mut Self, DynamicReleaseError> {
189        let hashes: BTreeSet<String> = compute_route_transitive_hashes(self, artifacts)?;
190        self.set_transitive_hashes(hashes);
191        Ok(self)
192    }
193}
194
195/// Signing, verification, closure validation, and diff helpers on `ReleaseManifest`.
196impl ReleaseManifest {
197    /// Returns the optional prior release sequence targeted by a monotonic rollback.
198    ///
199    /// # Returns
200    ///
201    /// - `Option<u64>` - Prior release sequence if this release is a rollback.
202    #[must_use]
203    pub fn rollback_of_seq(&self) -> Option<u64> {
204        let Self { rollback_of, .. } = *self;
205        rollback_of
206    }
207
208    /// Inserts an artifact into the manifest artifact table keyed by `"module_id@version"`.
209    ///
210    /// # Arguments
211    ///
212    /// - `BlobArtifact` - Artifact metadata entry.
213    ///
214    /// # Returns
215    ///
216    /// - `&mut Self` - Mutable manifest reference for chaining.
217    pub fn insert_artifact(&mut self, artifact: BlobArtifact) -> &mut Self {
218        let key: String = artifact.artifact_key();
219        let _: Option<BlobArtifact> = self.get_mut_artifacts().insert(key, artifact);
220        self
221    }
222
223    /// Inserts a route manifest after normalizing its route path and computing its transitive hash closure.
224    ///
225    /// # Arguments
226    ///
227    /// - `RouteManifest` - Route manifest to seal and register.
228    ///
229    /// # Returns
230    ///
231    /// - `Result<&mut Self, DynamicReleaseError>` - Mutable manifest reference or closure error.
232    pub fn insert_route(
233        &mut self,
234        mut route: RouteManifest,
235    ) -> Result<&mut Self, DynamicReleaseError> {
236        let normalized: String = normalize_dynamic_route(route.get_route());
237        route.set_route(normalized.clone());
238        let hashes: BTreeSet<String> =
239            compute_route_transitive_hashes(&route, self.get_artifacts())?;
240        route.set_transitive_hashes(hashes);
241        let _: Option<RouteManifest> = self.get_mut_routes().insert(normalized, route);
242        Ok(self)
243    }
244
245    /// Produces deterministic canonical JSON bytes over the manifest with `signature` cleared.
246    ///
247    /// # Returns
248    ///
249    /// - `Result<Vec<u8>, DynamicReleaseError>` - Canonical UTF-8 JSON bytes for signing and hashing.
250    pub fn canonical_signing_bytes(&self) -> Result<Vec<u8>, DynamicReleaseError> {
251        let mut unsigned: Self = self.clone();
252        unsigned.set_signature(String::new());
253        match to_string(&unsigned) {
254            Ok(json) => Ok(json.into_bytes()),
255            Err(err) => Err(DynamicReleaseError::StorageError(format!(
256                "{ERR_MANIFEST_SERIALIZE}: {err}"
257            ))),
258        }
259    }
260
261    /// Computes the SHA-256 hex digest of the signed manifest JSON.
262    ///
263    /// # Returns
264    ///
265    /// - `Result<String, DynamicReleaseError>` - 64-character SHA-256 hex digest.
266    pub fn manifest_sha256(&self) -> Result<String, DynamicReleaseError> {
267        let json: String = match to_string(self) {
268            Ok(encoded) => encoded,
269            Err(err) => {
270                return Err(DynamicReleaseError::StorageError(format!(
271                    "{ERR_MANIFEST_SERIALIZE}: {err}"
272                )));
273            }
274        };
275        Ok(sha256_hex(json.as_bytes()))
276    }
277
278    /// Signs the release manifest in place using HMAC-SHA256.
279    ///
280    /// # Arguments
281    ///
282    /// - `&[u8]` - Signing secret key bytes.
283    ///
284    /// # Returns
285    ///
286    /// - `Result<&mut Self, DynamicReleaseError>` - Signed manifest reference.
287    pub fn sign(&mut self, signing_key: &[u8]) -> Result<&mut Self, DynamicReleaseError> {
288        let payload: Vec<u8> = self.canonical_signing_bytes()?;
289        let sig: String = sign_release_payload(&payload, signing_key);
290        self.set_signature(sig);
291        Ok(self)
292    }
293
294    /// Verifies the manifest HMAC-SHA256 signature in constant time against `verify_key`.
295    ///
296    /// # Arguments
297    ///
298    /// - `&[u8]` - Trusted verification key bytes.
299    ///
300    /// # Returns
301    ///
302    /// - `Result<(), DynamicReleaseError>` - `Ok(())` when authentic, or `InvalidSignature`.
303    pub fn verify_signature(&self, verify_key: &[u8]) -> Result<(), DynamicReleaseError> {
304        let payload: Vec<u8> = self.canonical_signing_bytes()?;
305        if verify_release_signature(&payload, self.get_signature(), verify_key) {
306            Ok(())
307        } else {
308            Err(DynamicReleaseError::InvalidSignature(
309                ERR_INVALID_SIGNATURE.to_string(),
310            ))
311        }
312    }
313
314    /// Validates protocol schema, delivery mode, ABI bounds, host capabilities, size ceiling, and full transitive dependency closure.
315    ///
316    /// # Arguments
317    ///
318    /// - `u32` - Running host ABI version.
319    /// - `&[String]` - Capabilities supported by the host runtime.
320    /// - `DeliveryChannelMode` - Delivery mode permitted by the current distribution channel.
321    /// - `u64` - Maximum allowed size in bytes for any individual artifact (`0` disables cap).
322    ///
323    /// # Returns
324    ///
325    /// - `Result<(), DynamicReleaseError>` - `Ok(())` when the complete graph is valid and compatible.
326    pub fn validate_for_host(
327        &self,
328        host_abi: u32,
329        host_capabilities: &[String],
330        allowed_mode: DeliveryChannelMode,
331        max_artifact_bytes: u64,
332    ) -> Result<(), DynamicReleaseError> {
333        if self.get_manifest_schema() != DYNAMIC_MANIFEST_SCHEMA_V1 {
334            return Err(DynamicReleaseError::ProtocolIncompatible(format!(
335                "unsupported manifest schema v{}",
336                self.get_manifest_schema()
337            )));
338        }
339        if allowed_mode == DeliveryChannelMode::DeclarativeData
340            && self.get_delivery_mode() == DeliveryChannelMode::WasmComponent
341        {
342            return Err(DynamicReleaseError::UnsupportedDeliveryMode {
343                allowed: allowed_mode,
344                incoming: self.get_delivery_mode(),
345            });
346        }
347        if host_abi < self.get_min_host_abi() || host_abi > self.get_max_host_abi() {
348            return Err(DynamicReleaseError::AbiIncompatible {
349                host_abi,
350                min_abi: self.get_min_host_abi(),
351                max_abi: self.get_max_host_abi(),
352            });
353        }
354        for cap in self.get_required_capabilities().iter() {
355            if !host_capabilities.iter().any(|c: &String| c == cap) {
356                return Err(DynamicReleaseError::MissingCapability(cap.clone()));
357            }
358        }
359        for (key, artifact) in self.get_artifacts().iter() {
360            if !is_valid_sha256_hex(artifact.get_sha256()) {
361                return Err(DynamicReleaseError::BrokenDependencyClosure(format!(
362                    "{ERR_INVALID_HASH_FORMAT}: {key}"
363                )));
364            }
365            if max_artifact_bytes > 0 && artifact.get_size_bytes() > max_artifact_bytes {
366                return Err(DynamicReleaseError::BrokenDependencyClosure(format!(
367                    "{ERR_ARTIFACT_TOO_LARGE}: {key} ({} > {max_artifact_bytes})",
368                    artifact.get_size_bytes()
369                )));
370            }
371            if allowed_mode == DeliveryChannelMode::DeclarativeData
372                && artifact.get_kind() == ArtifactKind::WasmComponent
373            {
374                return Err(DynamicReleaseError::UnsupportedDeliveryMode {
375                    allowed: allowed_mode,
376                    incoming: DeliveryChannelMode::WasmComponent,
377                });
378            }
379            if artifact.get_min_host_abi() > 0
380                && (host_abi < artifact.get_min_host_abi()
381                    || (artifact.get_max_host_abi() > 0 && host_abi > artifact.get_max_host_abi()))
382            {
383                return Err(DynamicReleaseError::AbiIncompatible {
384                    host_abi,
385                    min_abi: artifact.get_min_host_abi(),
386                    max_abi: artifact.get_max_host_abi(),
387                });
388            }
389            for cap in artifact.get_required_capabilities().iter() {
390                if !host_capabilities.iter().any(|c: &String| c == cap) {
391                    return Err(DynamicReleaseError::MissingCapability(cap.clone()));
392                }
393            }
394        }
395        for (route_key, route_manifest) in self.get_routes().iter() {
396            let computed: BTreeSet<String> =
397                compute_route_transitive_hashes(route_manifest, self.get_artifacts())?;
398            if route_manifest.get_transitive_hashes() != &computed {
399                return Err(DynamicReleaseError::BrokenDependencyClosure(format!(
400                    "{ERR_INCOMPLETE_HASH_CLOSURE}: {route_key}"
401                )));
402            }
403        }
404        Ok(())
405    }
406
407    /// Returns the sorted unique list of SHA-256 digests referenced by this manifest.
408    ///
409    /// # Returns
410    ///
411    /// - `BTreeSet<String>` - All artifact SHA-256 digests in this release.
412    #[must_use]
413    pub fn all_blob_hashes(&self) -> BTreeSet<String> {
414        self.get_artifacts()
415            .values()
416            .map(|art: &BlobArtifact| art.get_sha256().clone())
417            .collect()
418    }
419
420    /// Computes the incremental hash diff of blobs absent from `cached_hashes`.
421    ///
422    /// # Arguments
423    ///
424    /// - `&HashSet<String>` - Verified SHA-256 digests already present locally.
425    ///
426    /// # Returns
427    ///
428    /// - `Vec<String>` - Sorted SHA-256 digests that must be fetched.
429    #[must_use]
430    pub fn missing_blob_hashes(&self, cached_hashes: &HashSet<String>) -> Vec<String> {
431        self.all_blob_hashes()
432            .into_iter()
433            .filter(|sha: &String| !cached_hashes.contains(sha))
434            .collect()
435    }
436
437    /// Computes which routes changed their pinned entry module, slot bindings, or transitive hashes relative to `previous`.
438    ///
439    /// # Arguments
440    ///
441    /// - `Option<&Self>` - Previous active release manifest, if any.
442    ///
443    /// # Returns
444    ///
445    /// - `Vec<String>` - Sorted route paths whose pinned dependency graph changed.
446    #[must_use]
447    pub fn affected_routes_since(&self, previous: Option<&Self>) -> Vec<String> {
448        let Some(prev) = previous else {
449            return self.get_routes().keys().cloned().collect();
450        };
451        let mut changed: Vec<String> = Vec::new();
452        for (route_path, next_route) in self.get_routes().iter() {
453            match prev.get_routes().get(route_path) {
454                Some(prev_route) if prev_route == next_route => {}
455                _ => changed.push(route_path.clone()),
456            }
457        }
458        for prev_route_path in prev.get_routes().keys() {
459            if !self.get_routes().contains_key(prev_route_path) {
460                changed.push(prev_route_path.clone());
461            }
462        }
463        changed.sort();
464        changed
465    }
466}
467
468/// Builder helpers on `ClientNegotiation`.
469impl ClientNegotiation {
470    /// Returns the optional preferred compatibility track name.
471    ///
472    /// # Returns
473    ///
474    /// - `Option<&str>` - Preferred track name if specified.
475    #[must_use]
476    pub fn preferred_track_str(&self) -> Option<&str> {
477        let Self {
478            preferred_track, ..
479        } = self;
480        preferred_track.as_deref()
481    }
482
483    /// Attaches a preferred track name to this negotiation descriptor.
484    ///
485    /// # Arguments
486    ///
487    /// - `String` - Compatibility track identifier.
488    ///
489    /// # Returns
490    ///
491    /// - `Self` - Updated negotiation descriptor.
492    #[must_use]
493    pub fn with_preferred_track(mut self, track: String) -> Self {
494        self.set_preferred_track(Some(track));
495        self
496    }
497
498    /// Attaches host capabilities to this negotiation descriptor.
499    ///
500    /// # Arguments
501    ///
502    /// - `Vec<String>` - Capability names exposed by the host.
503    ///
504    /// # Returns
505    ///
506    /// - `Self` - Updated negotiation descriptor.
507    #[must_use]
508    pub fn with_capabilities(mut self, capabilities: Vec<String>) -> Self {
509        self.set_capabilities(capabilities);
510        self
511    }
512}