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