Skip to main content

core_api/
node_metadata.rs

1//! Package-owned Node definitions. This contract contains no Plugin registry.
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4use sha2::{Digest, Sha256};
5
6pub const NODE_METADATA_TARGET: &str = "/node/metadata";
7pub const NODE_METADATA_SCHEMA_VERSION: &str = "meow.node.metadata.v2";
8pub const NODE_MANIFEST_MAX_BYTES: usize = 1024 * 1024;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
11#[serde(rename_all = "lowercase")]
12pub enum PluginKind {
13    Core,
14    Extension,
15}
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(rename_all = "lowercase")]
19pub enum NodeDelivery {
20    Host,
21    Firmware,
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "lowercase")]
26pub enum NodeBindingCardinality {
27    Single,
28    Multiple,
29}
30
31impl NodeBindingCardinality {
32    pub const fn as_str(self) -> &'static str {
33        match self {
34            Self::Single => "single",
35            Self::Multiple => "multiple",
36        }
37    }
38    pub fn binding_slot(self, service_instance_id: &str) -> &str {
39        match self {
40            Self::Single => "single",
41            Self::Multiple => service_instance_id,
42        }
43    }
44}
45impl std::fmt::Display for NodeBindingCardinality {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        f.write_str(self.as_str())
48    }
49}
50
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52#[serde(rename_all = "camelCase")]
53pub struct PluginDefinition {
54    pub id: String,
55    pub node_type: String,
56    pub service_id: String,
57    pub component_id: String,
58    pub kind: PluginKind,
59    pub binding_cardinality: NodeBindingCardinality,
60    pub display_name: String,
61    pub description: String,
62}
63
64impl PluginDefinition {
65    pub fn validate(&self) -> Result<(), String> {
66        let valid_id = !self.id.is_empty()
67            && self.id.len() <= 80
68            && self.id.starts_with(|c: char| c.is_ascii_lowercase())
69            && self
70                .id
71                .chars()
72                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
73        if !valid_id
74            || self.node_type != self.id
75            || self.service_id != self.id
76            || self.component_id != format!("node-{}", self.id)
77            || self.display_name.trim().is_empty()
78            || self.description.trim().is_empty()
79        {
80            return Err("Invalid Plugin definition".into());
81        }
82        Ok(())
83    }
84
85    /// These fields identify one Plugin across versions, platforms and delivery forms.
86    pub fn same_identity(&self, other: &Self) -> bool {
87        self.id == other.id
88            && self.node_type == other.node_type
89            && self.service_id == other.service_id
90            && self.component_id == other.component_id
91            && self.kind == other.kind
92            && self.binding_cardinality == other.binding_cardinality
93    }
94}
95
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
97#[serde(rename_all = "camelCase", deny_unknown_fields)]
98pub struct NodeReleaseManifestBundle {
99    pub schema_version: u32,
100    pub kind: String,
101    /// Exact publisher-signed bytes. Consumers must not reserialize before verification.
102    pub manifest: String,
103    pub signature: String,
104}
105
106impl NodeReleaseManifestBundle {
107    pub fn sha256(&self) -> String {
108        format!("{:x}", Sha256::digest(self.manifest.as_bytes()))
109    }
110}
111
112#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
113#[serde(rename_all = "camelCase", deny_unknown_fields)]
114pub struct NodeMetadata {
115    pub schema_version: String,
116    pub delivery: NodeDelivery,
117    pub node_type: String,
118    pub service_id: String,
119    pub service_version: String,
120    pub source: NodeSource,
121}
122
123/// Explicit provenance: failed publisher validation never becomes Preview.
124#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
125#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
126pub enum NodeSource {
127    Published {
128        #[serde(rename = "releaseManifest")]
129        release_manifest: NodeReleaseManifestBundle,
130    },
131    Preview {
132        manifest: String,
133        #[serde(rename = "hostProof")]
134        host_proof: String,
135    },
136}
137impl NodeSource {
138    pub fn kind(&self) -> NodeSourceKind {
139        match self {
140            Self::Published { .. } => NodeSourceKind::Published,
141            Self::Preview { .. } => NodeSourceKind::Preview,
142        }
143    }
144    pub fn manifest_sha256(&self) -> String {
145        match self {
146            Self::Published { release_manifest } => release_manifest.sha256(),
147            Self::Preview { manifest, .. } => {
148                crate::plugin_preview::PluginPreviewManifest::digest(manifest)
149            }
150        }
151    }
152    pub fn published(&self) -> Result<&NodeReleaseManifestBundle, String> {
153        match self {
154            Self::Published { release_manifest } => Ok(release_manifest),
155            Self::Preview { .. } => Err("Preview requires trusted Host provenance".into()),
156        }
157    }
158}
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
160#[serde(rename_all = "camelCase")]
161pub enum NodeSourceKind {
162    Published,
163    Preview,
164}
165
166/// Verified binding state. Persisted with the binding, usable without Host/CDN access.
167#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
168#[serde(rename_all = "camelCase")]
169pub struct NodeBindingMetadata {
170    pub definition: PluginDefinition,
171    pub delivery: NodeDelivery,
172    pub version: String,
173    pub platform: String,
174    pub manifest_sha256: String,
175    pub core_protocol: Option<u32>,
176    pub source: NodeSourceKind,
177    /// Captured from the verified onboarding challenge; a reconnect cannot replace it.
178    pub host_public_key: Option<crate::host::auth::PublicKey>,
179    /// Verified platform attestation; absent for official releases and local Preview.
180    #[serde(default, skip_serializing_if = "Option::is_none")]
181    pub publication: Option<crate::plugin_publication::PluginPublication>,
182}
183
184impl NodeMetadata {
185    /// The caller supplies environment-scoped publisher trust. No device may choose
186    /// its own trusted key. Verification precedes all use of manifest fields.
187    pub fn verify(
188        &self,
189        verify_signature: impl FnOnce(&[u8], &str) -> Result<(), String>,
190    ) -> Result<NodeBindingMetadata, String> {
191        let bundle = self.source.published()?;
192        if self.schema_version != NODE_METADATA_SCHEMA_VERSION
193            || bundle.schema_version != 1
194            || bundle.manifest.len() > NODE_MANIFEST_MAX_BYTES
195            || bundle.signature.len() > 4096
196        {
197            return Err("Invalid Node metadata envelope".into());
198        }
199        let (bundle_kind, manifest_kind) = match self.delivery {
200            NodeDelivery::Host => ("meow.plugin.manifest-bundle", "meow.plugin.manifest"),
201            NodeDelivery::Firmware => (
202                "meow.node.firmware-manifest-bundle",
203                "meow.node.firmware-manifest",
204            ),
205        };
206        if bundle.kind != bundle_kind {
207            return Err("Node delivery and manifest kind disagree".into());
208        }
209        verify_signature(bundle.manifest.as_bytes(), &bundle.signature)?;
210        let manifest: Value = serde_json::from_str(&bundle.manifest).map_err(|e| e.to_string())?;
211        if manifest["schemaVersion"] != 1 || manifest["kind"] != manifest_kind {
212            return Err("Invalid signed Node manifest".into());
213        }
214        let component = match self.delivery {
215            NodeDelivery::Host => &manifest["component"],
216            NodeDelivery::Firmware => &manifest,
217        };
218        let definition: PluginDefinition =
219            serde_json::from_value(component["nodeMetadata"]["plugin"].clone())
220                .map_err(|e| format!("Invalid signed Plugin definition: {e}"))?;
221        definition.validate()?;
222        let publication = manifest
223            .get("publication")
224            .map(|value| {
225                serde_json::from_value::<crate::plugin_publication::PluginPublication>(
226                    value.clone(),
227                )
228                .map_err(|e| format!("Invalid Plugin publication: {e}"))
229            })
230            .transpose()?;
231        if let Some(publication) = &publication {
232            if self.delivery != NodeDelivery::Host {
233                return Err("Community publication requires Host delivery".into());
234            }
235            publication.validate(&definition)?;
236        }
237        let version = component["version"]
238            .as_str()
239            .ok_or("Node manifest version missing")?;
240        let platform = manifest["platform"]
241            .as_str()
242            .filter(|v| !v.trim().is_empty())
243            .ok_or("Node manifest platform missing")?;
244        if version.trim().is_empty()
245            || version != self.service_version
246            || definition.node_type != self.node_type
247            || definition.service_id != self.service_id
248            || manifest["pluginId"] != definition.id
249            || manifest["componentId"] != definition.component_id
250        {
251            return Err("Node manifest does not describe the running service".into());
252        }
253        let protocol_value = &component["compatibility"]["coreProtocol"];
254        let core_protocol = if protocol_value.is_null() {
255            None
256        } else {
257            Some(
258                protocol_value
259                    .as_u64()
260                    .and_then(|p| u32::try_from(p).ok())
261                    .filter(|p| *p > 0)
262                    .ok_or("Invalid Node Core protocol revision")?,
263            )
264        };
265        match (definition.kind, core_protocol) {
266            (PluginKind::Core, Some(_)) | (PluginKind::Extension, None) => {}
267            _ => return Err("Plugin kind and Core protocol disagree".into()),
268        }
269        Ok(NodeBindingMetadata {
270            definition,
271            delivery: self.delivery,
272            version: version.into(),
273            platform: platform.into(),
274            manifest_sha256: bundle.sha256(),
275            core_protocol,
276            source: NodeSourceKind::Published,
277            host_public_key: None,
278            publication,
279        })
280    }
281
282    /// The verifier MUST use a key from authenticated onboarding or an existing
283    /// binding, never one offered in this Node's metadata.
284    pub fn verify_preview(
285        &self,
286        host_id: &str,
287        env: crate::RuntimeEnv,
288        verify_proof: impl FnOnce(&str) -> Result<crate::plugin_preview::PluginPreviewProof, String>,
289    ) -> Result<NodeBindingMetadata, String> {
290        let NodeSource::Preview {
291            manifest,
292            host_proof,
293        } = &self.source
294        else {
295            return Err("Expected Preview provenance".into());
296        };
297        if self.schema_version != NODE_METADATA_SCHEMA_VERSION
298            || self.delivery != NodeDelivery::Host
299            || host_proof.len() > 16384
300            || host_id.is_empty()
301        {
302            return Err("Invalid Preview metadata envelope".into());
303        }
304        let parsed = crate::plugin_preview::PluginPreviewManifest::parse(manifest)?;
305        let proof = verify_proof(host_proof)?;
306        let digest = self.source.manifest_sha256();
307        if proof.host_id != host_id
308            || proof.env != env
309            || proof.manifest_sha256 != digest
310            || parsed.plugin.node_type != self.node_type
311            || parsed.plugin.service_id != self.service_id
312            || parsed.service_version != self.service_version
313        {
314            return Err("Preview proof does not describe this Host and running service".into());
315        }
316        Ok(NodeBindingMetadata {
317            definition: parsed.plugin,
318            delivery: self.delivery,
319            version: parsed.service_version,
320            platform: parsed.platform,
321            manifest_sha256: digest,
322            core_protocol: parsed.core_protocol,
323            source: NodeSourceKind::Preview,
324            host_public_key: None,
325            publication: None,
326        })
327    }
328}
329
330#[cfg(test)]
331mod tests {
332    use super::*;
333    use serde_json::json;
334    fn host() -> NodeMetadata {
335        NodeMetadata {
336            schema_version: NODE_METADATA_SCHEMA_VERSION.into(),
337            delivery: NodeDelivery::Host,
338            node_type: "example-extension".into(),
339            service_id: "example-extension".into(),
340            service_version: "1.0.0".into(),
341            source: NodeSource::Published {
342                release_manifest: serde_json::from_str(include_str!(
343                    "../fixtures/node-metadata/host.bundle.json"
344                ))
345                .unwrap(),
346            },
347        }
348    }
349    fn verify(bytes: &[u8], signature: &str) -> Result<(), String> {
350        let key = minisign_verify::PublicKey::from_base64(
351            include_str!("../fixtures/node-metadata/public-key.txt").trim(),
352        )
353        .unwrap();
354        key.verify(
355            bytes,
356            &minisign_verify::Signature::decode(signature).map_err(|e| e.to_string())?,
357            false,
358        )
359        .map_err(|e| e.to_string())
360    }
361    #[test]
362    fn community_release_retains_only_verified_publication_identity() {
363        let mut metadata = host();
364        metadata.node_type = "u-252beb16094f8b00bc706b2b3c6bc819-garden".into();
365        metadata.service_id = metadata.node_type.clone();
366        metadata.source = NodeSource::Published {
367            release_manifest: serde_json::from_str(include_str!(
368                "../fixtures/node-metadata/community.bundle.json"
369            ))
370            .unwrap(),
371        };
372        let verify = |bytes: &[u8], signature: &str| {
373            minisign_verify::PublicKey::from_base64(
374                include_str!("../fixtures/node-metadata/community-public-key.txt").trim(),
375            )
376            .unwrap()
377            .verify(
378                bytes,
379                &minisign_verify::Signature::decode(signature).map_err(|e| e.to_string())?,
380                false,
381            )
382            .map_err(|e| e.to_string())
383        };
384        let binding = metadata.verify(verify).unwrap();
385        assert_eq!(
386            binding.publication.unwrap().integrations(),
387            &["U-example-publisher_garden.light"]
388        );
389        let NodeSource::Published { release_manifest } = &mut metadata.source else {
390            unreachable!()
391        };
392        release_manifest.manifest = release_manifest
393            .manifest
394            .replace("example-publisher", "another-publisher");
395        assert!(metadata.verify(verify).is_err());
396    }
397    #[test]
398    fn preview_is_explicit_and_bound_to_host_environment_and_complete_content() {
399        use crate::plugin_preview::*;
400        let mut metadata = host();
401        let published = metadata.verify(verify).unwrap();
402        let raw = serde_json::to_string(&PluginPreviewManifest {
403            format_version: 1,
404            plugin: published.definition,
405            platform: "linux-arm64".into(),
406            service_version: metadata.service_version.clone(),
407            core_protocol: None,
408            requires: Default::default(),
409            files_sha256: "a".repeat(64),
410        })
411        .unwrap();
412        metadata.source = NodeSource::Preview {
413            manifest: raw,
414            host_proof: "Host proof".into(),
415        };
416        assert!(metadata
417            .verify(|_, _| panic!("Preview is not a publisher manifest"))
418            .is_err());
419        let proof = PluginPreviewProof {
420            host_id: "desktop".into(),
421            env: crate::RuntimeEnv::Prod,
422            manifest_sha256: metadata.source.manifest_sha256(),
423        };
424        let verify = |metadata: &NodeMetadata, proof: PluginPreviewProof| {
425            metadata.verify_preview("desktop", crate::RuntimeEnv::Prod, |_| Ok(proof))
426        };
427        assert_eq!(
428            verify(&metadata, proof.clone()).unwrap().source,
429            NodeSourceKind::Preview
430        );
431        let mut wrong = proof.clone();
432        wrong.host_id = "other-host".into();
433        assert!(verify(&metadata, wrong).is_err());
434        let mut wrong = proof.clone();
435        wrong.env = crate::RuntimeEnv::Dev;
436        assert!(verify(&metadata, wrong).is_err());
437        let mut wrong = proof.clone();
438        wrong.manifest_sha256 = "b".repeat(64);
439        assert!(verify(&metadata, wrong).is_err());
440        assert!(metadata
441            .verify_preview("desktop", crate::RuntimeEnv::Prod, |_| Err(
442                "bad signature".into()
443            ))
444            .is_err());
445        let mut wrong = metadata.clone();
446        wrong.node_type = "other".into();
447        assert!(verify(&wrong, proof.clone()).is_err());
448        let mut wrong = metadata;
449        wrong.delivery = NodeDelivery::Firmware;
450        assert!(verify(&wrong, proof).is_err());
451    }
452
453    #[test]
454    fn android_aar_firmware_metadata_uses_its_embedded_release_version() {
455        // Generated by Plugin's Android manifest publisher with a disposable test key.
456        let bundle: NodeReleaseManifestBundle = serde_json::from_str(include_str!(
457            "../fixtures/node-metadata/android.bundle.json"
458        ))
459        .unwrap();
460        let metadata = NodeMetadata {
461            schema_version: NODE_METADATA_SCHEMA_VERSION.into(),
462            delivery: NodeDelivery::Firmware,
463            node_type: "camera".into(),
464            service_id: "camera".into(),
465            service_version: "1.0.5".into(),
466            source: NodeSource::Published {
467                release_manifest: bundle,
468            },
469        };
470        let verify_android = |bytes: &[u8], signature: &str| {
471            let key = minisign_verify::PublicKey::from_base64(
472                include_str!("../fixtures/node-metadata/android-public-key.txt").trim(),
473            )
474            .unwrap();
475            key.verify(
476                bytes,
477                &minisign_verify::Signature::decode(signature).map_err(|e| e.to_string())?,
478                false,
479            )
480            .map_err(|e| e.to_string())
481        };
482        let binding = metadata.verify(verify_android).unwrap();
483        assert_eq!(binding.delivery, NodeDelivery::Firmware);
484        assert_eq!(binding.platform, "android");
485        assert_eq!(binding.version, "1.0.5");
486        assert_eq!(binding.core_protocol, Some(2));
487        assert_eq!(
488            binding.definition.binding_cardinality,
489            NodeBindingCardinality::Multiple
490        );
491        let mut wrong_version = metadata;
492        wrong_version.service_version = "1.1.0".into();
493        assert!(wrong_version.verify(verify_android).is_err());
494    }
495
496    #[test]
497    fn installed_release_is_verified_without_a_latest_catalog() {
498        let metadata = host();
499        let binding = metadata.verify(verify).unwrap();
500        assert_eq!(binding.definition.kind, PluginKind::Extension);
501        assert_eq!(
502            binding.definition.binding_cardinality,
503            NodeBindingCardinality::Single
504        );
505        assert_eq!(binding.manifest_sha256.len(), 64);
506        assert_eq!(
507            binding
508                .definition
509                .binding_cardinality
510                .binding_slot("service-a"),
511            "single"
512        );
513        assert_eq!(
514            serde_json::from_str::<NodeBindingMetadata>(&serde_json::to_string(&binding).unwrap())
515                .unwrap(),
516            binding
517        );
518    }
519    #[test]
520    fn wrong_running_identity_version_delivery_and_signature_are_rejected() {
521        let original = host();
522        for field in ["nodeType", "serviceId", "serviceVersion", "delivery"] {
523            let mut value = serde_json::to_value(&original).unwrap();
524            value[field] = json!(if field == "delivery" {
525                "firmware"
526            } else {
527                "other"
528            });
529            assert!(
530                serde_json::from_value::<NodeMetadata>(value)
531                    .unwrap()
532                    .verify(verify)
533                    .is_err(),
534                "{field}"
535            );
536        }
537        let mut tampered = original;
538        let NodeSource::Published { release_manifest } = &mut tampered.source else {
539            unreachable!()
540        };
541        release_manifest.manifest = release_manifest.manifest.replace("single", "multiple");
542        assert!(tampered.verify(verify).is_err());
543    }
544    #[test]
545    fn definition_identity_is_independent_of_version_platform_and_display_text() {
546        let a = host().verify(verify).unwrap().definition;
547        let mut b = a.clone();
548        b.display_name = "New name".into();
549        assert!(a.same_identity(&b));
550        b.binding_cardinality = NodeBindingCardinality::Multiple;
551        assert!(!a.same_identity(&b));
552        b = a.clone();
553        b.kind = PluginKind::Core;
554        assert!(!a.same_identity(&b));
555    }
556    #[test]
557    fn authentication_requires_metadata_and_acknowledges_the_exact_release() {
558        let metadata = host();
559        let binding = metadata.verify(verify).unwrap();
560        let mut wire = json!({"metadata":metadata,"hubId":"hub","token":"token","nodeType":metadata.node_type,
561            "nodeId":"node","hostId":"host","fingerprint":"fingerprint"});
562        let request: crate::NodeAuthRequest = serde_json::from_value(wire.clone()).unwrap();
563        wire.as_object_mut().unwrap().remove("metadata");
564        assert!(serde_json::from_value::<crate::NodeAuthRequest>(wire).is_err());
565        let response: crate::NodeAuthResponse =
566            serde_json::from_value(json!({"ok":true,"bindingMetadata":binding})).unwrap();
567        assert_eq!(response.admitted_metadata(&request).unwrap(), &binding);
568        let envelope = crate::MwsMessage::create(
569            None,
570            "/node/auth".into(),
571            "auth".into(),
572            serde_json::to_string(&request).unwrap(),
573            "nrq".into(),
574        );
575        assert!(serde_json::to_vec(&envelope).unwrap().len() < 32768);
576        for field in ["version", "manifestSha256", "delivery", "coreProtocol"] {
577            let mut bad = serde_json::to_value(&response).unwrap();
578            bad["bindingMetadata"][field] = match field {
579                "delivery" => json!("firmware"),
580                "coreProtocol" => json!(2),
581                _ => json!("other"),
582            };
583            assert!(
584                serde_json::from_value::<crate::NodeAuthResponse>(bad)
585                    .unwrap()
586                    .admitted_metadata(&request)
587                    .is_err(),
588                "{field}"
589            );
590        }
591        let missing: crate::NodeAuthResponse = serde_json::from_value(json!({"ok":true})).unwrap();
592        assert!(missing.admitted_metadata(&request).is_err());
593    }
594}