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