1use std::{
10 collections::{BTreeMap, HashSet},
11 fmt,
12};
13
14use serde::{de::Error as _, Deserialize, Deserializer, Serialize};
15use serde_json::Value;
16
17use crate::provider_declarations::{deserialize_provider_declarations, ProviderDeclarations};
18use crate::PROTOCOL_VERSION;
19
20pub use crate::provider_declarations::{
21 validate_hello_provider_declarations, ProviderDeclarationsError,
22};
23
24pub const MAX_ROLE_DECLARATIONS_BYTES: usize = 16_384;
26
27pub const MAX_FLOW_OPERATIONS: usize = 256;
29
30pub const MAX_CONFIRM_OPERATIONS: usize = 256;
32
33pub const DOCTOR_CAPABILITY: &str = "doctor/v1";
35
36#[derive(Serialize, Debug, Clone, PartialEq)]
43#[non_exhaustive]
44pub struct ModuleManifest {
45 pub module_id: String,
46 #[serde(default, skip_serializing_if = "Option::is_none")]
48 pub display_name: Option<String>,
49 #[serde(default, skip_serializing_if = "Option::is_none")]
51 pub icon: Option<String>,
52 #[serde(default, skip_serializing_if = "Option::is_none")]
54 pub hosts_third_party_code: Option<bool>,
55 pub module_version: String,
56 pub protocol_ver: u8,
57 #[serde(default, skip_serializing_if = "Option::is_none")]
58 pub trust_tier: Option<TrustTier>,
59 #[serde(default, skip_serializing_if = "Option::is_none")]
66 pub ready: Option<bool>,
67 #[serde(default, skip_serializing_if = "Option::is_none")]
71 pub registration_channel: Option<bool>,
72 pub provides: Vec<ProviderRole>,
75 #[serde(default, skip_serializing_if = "Vec::is_empty")]
76 pub consumes: Vec<ConsumerRole>,
77 #[serde(default, skip_serializing_if = "Option::is_none")]
78 pub bindings: Option<Bindings>,
79 #[serde(default, skip_serializing_if = "Option::is_none")]
85 pub capabilities: Option<CapabilityDeclarations>,
86 #[serde(default, skip_serializing_if = "Option::is_none")]
100 pub events: Option<Vec<EventDeclaration>>,
101 #[serde(default, skip_serializing_if = "Option::is_none")]
136 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
137 #[serde(default, skip_serializing_if = "Option::is_none")]
138 pub provenance: Option<ManifestProvenance>,
139 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
144 pub operation_delivery: BTreeMap<String, OperationDelivery>,
145 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
147 pub operation_titles: BTreeMap<String, String>,
148 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
150 pub operation_groups: BTreeMap<String, OperationGroup>,
151 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
153 pub operation_requires: BTreeMap<String, Vec<String>>,
154 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
157 pub operation_payload: BTreeMap<String, OperationPayload>,
158 #[serde(default, skip_serializing_if = "Option::is_none")]
177 pub flow_operations: Option<Vec<String>>,
178 #[serde(default, skip_serializing_if = "Option::is_none")]
182 pub operation_deferral: Option<BTreeMap<String, bool>>,
183 #[serde(default, skip_serializing_if = "Option::is_none")]
200 pub confirm_operations: Option<Vec<String>>,
201 #[serde(default, skip_serializing_if = "Option::is_none")]
206 pub rich_ui: Option<RichUiDescriptor>,
207 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
216 pub role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
217 #[serde(default, skip_serializing_if = "Option::is_none")]
220 pub provider_declarations: Option<ProviderDeclarations>,
221}
222
223#[derive(Debug, Clone)]
225pub struct ModuleManifestBuilder {
226 module_id: String,
227 display_name: Option<String>,
228 icon: Option<String>,
229 hosts_third_party_code: Option<bool>,
230 module_version: String,
231 protocol_ver: u8,
232 trust_tier: Option<TrustTier>,
233 ready: Option<bool>,
234 registration_channel: Option<bool>,
235 provides: Vec<ProviderRole>,
236 consumes: Vec<ConsumerRole>,
237 bindings: Option<Bindings>,
238 capabilities: Option<CapabilityDeclarations>,
239 events: Option<Vec<EventDeclaration>>,
240 self_signals: Option<Vec<SelfSignalDeclaration>>,
241 provenance: Option<ManifestProvenance>,
242 operation_delivery: BTreeMap<String, OperationDelivery>,
243 operation_titles: BTreeMap<String, String>,
244 operation_groups: BTreeMap<String, OperationGroup>,
245 operation_requires: BTreeMap<String, Vec<String>>,
246 operation_payload: BTreeMap<String, OperationPayload>,
247 flow_operations: Option<Vec<String>>,
248 operation_deferral: Option<BTreeMap<String, bool>>,
249 confirm_operations: Option<Vec<String>>,
250 rich_ui: Option<RichUiDescriptor>,
251 role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
252 provider_declarations: Option<ProviderDeclarations>,
253}
254
255impl ModuleManifest {
256 pub fn builder(
264 module_id: impl Into<String>,
265 module_version: impl Into<String>,
266 ) -> ModuleManifestBuilder {
267 ModuleManifestBuilder {
268 module_id: module_id.into(),
269 display_name: None,
270 icon: None,
271 hosts_third_party_code: None,
272 module_version: module_version.into(),
273 protocol_ver: PROTOCOL_VERSION,
274 trust_tier: None,
275 ready: None,
276 registration_channel: None,
277 provides: Vec::new(),
278 consumes: Vec::new(),
279 bindings: None,
280 capabilities: None,
281 events: None,
282 self_signals: None,
283 provenance: None,
284 operation_delivery: BTreeMap::new(),
285 operation_titles: BTreeMap::new(),
286 operation_groups: BTreeMap::new(),
287 operation_requires: BTreeMap::new(),
288 operation_payload: BTreeMap::new(),
289 flow_operations: None,
290 operation_deferral: None,
291 confirm_operations: None,
292 rich_ui: None,
293 role_declarations: BTreeMap::new(),
294 provider_declarations: None,
295 }
296 }
297
298 pub fn is_watch_operation(&self, name: &str) -> bool {
303 self.operation_delivery
304 .get(name)
305 .is_some_and(OperationDelivery::is_watch)
306 && self.provides.iter().any(|role| match role {
307 ProviderRole::ManagementSurface { operations, .. } => operations
308 .iter()
309 .any(|op| op.name == name && op.kind == ManagementOperationKind::Query),
310 _ => false,
311 })
312 }
313}
314
315impl ModuleManifestBuilder {
316 pub fn display_name(mut self, display_name: Option<String>) -> Result<Self, DisplayNameError> {
318 if let Some(value) = &display_name {
319 validate_display_name(value)?;
320 }
321 self.display_name = display_name;
322 Ok(self)
323 }
324
325 pub fn icon(mut self, icon: impl Into<String>) -> Result<Self, IconError> {
327 let icon = icon.into();
328 validate_icon(&icon)?;
329 self.icon = Some(icon);
330 Ok(self)
331 }
332
333 pub fn hosts_third_party_code(mut self, hosts_third_party_code: bool) -> Self {
335 self.hosts_third_party_code = Some(hosts_third_party_code);
336 self
337 }
338
339 pub fn protocol_ver(mut self, protocol_ver: u8) -> Self {
341 self.protocol_ver = protocol_ver;
342 self
343 }
344
345 pub fn trust_tier(mut self, trust_tier: Option<TrustTier>) -> Self {
349 self.trust_tier = trust_tier;
350 self
351 }
352
353 pub fn ready(mut self, ready: bool) -> Self {
355 self.ready = Some(ready);
356 self
357 }
358
359 pub fn registration_channel(mut self, supported: bool) -> Self {
361 self.registration_channel = Some(supported);
362 self
363 }
364
365 pub fn provides(mut self, provides: Vec<ProviderRole>) -> Self {
367 self.provides = provides;
368 self
369 }
370
371 pub fn consumes(mut self, consumes: Vec<ConsumerRole>) -> Self {
373 self.consumes = consumes;
374 self
375 }
376
377 pub fn bindings(mut self, bindings: Option<Bindings>) -> Self {
381 self.bindings = bindings;
382 self
383 }
384
385 pub fn capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
387 self.capabilities = capabilities;
388 self
389 }
390
391 pub fn events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
393 self.events = events;
394 self
395 }
396
397 pub fn self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
399 self.self_signals = self_signals;
400 self
401 }
402
403 pub fn provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
405 self.provenance = provenance;
406 self
407 }
408
409 pub fn operation_delivery(
411 mut self,
412 operation_delivery: BTreeMap<String, OperationDelivery>,
413 ) -> Self {
414 self.operation_delivery = operation_delivery;
415 self
416 }
417
418 pub fn operation_title(
421 mut self,
422 name: impl Into<String>,
423 title: impl Into<String>,
424 ) -> Result<Self, OperationTitleError> {
425 let name = name.into();
426 let title = title.into();
427 validate_operation_title(&self.provides, &name, &title)?;
428 self.operation_titles.insert(name, title);
429 Ok(self)
430 }
431
432 pub fn operation_group(
435 mut self,
436 id: impl Into<String>,
437 group: OperationGroup,
438 ) -> Result<Self, OperationMetadataError> {
439 let id = id.into();
440 let assigned = self
441 .operation_groups
442 .iter()
443 .filter(|(other_id, _)| other_id.as_str() != id)
444 .flat_map(|(_, other)| other.operations.iter().map(String::as_str))
445 .collect();
446 validate_operation_group(&self.provides, &id, &group, &assigned)?;
447 self.operation_groups.insert(id, group);
448 Ok(self)
449 }
450
451 pub fn operation_requires(
454 mut self,
455 name: impl Into<String>,
456 requires: Vec<String>,
457 ) -> Result<Self, OperationMetadataError> {
458 let name = name.into();
459 validate_operation_requires(&self.provides, &name, &requires)?;
460 self.operation_requires.insert(name, requires);
461 Ok(self)
462 }
463
464 pub fn operation_payload(
466 mut self,
467 operation_payload: BTreeMap<String, OperationPayload>,
468 ) -> Self {
469 self.operation_payload = operation_payload;
470 self
471 }
472
473 pub fn flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
480 self.flow_operations = flow_operations;
481 self
482 }
483
484 pub fn operation_deferral(mut self, operations: Option<BTreeMap<String, bool>>) -> Self {
486 self.operation_deferral = operations;
487 self
488 }
489
490 pub fn confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
497 self.confirm_operations = confirm_operations;
498 self
499 }
500
501 pub fn rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
503 self.rich_ui = rich_ui;
504 self
505 }
506
507 pub fn role_declarations(
509 mut self,
510 role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
511 ) -> Self {
512 self.role_declarations = role_declarations;
513 self
514 }
515
516 pub fn provider_declarations(mut self, declarations: Option<ProviderDeclarations>) -> Self {
519 self.provider_declarations = declarations;
520 self
521 }
522
523 pub fn build(self) -> ModuleManifest {
525 ModuleManifest {
526 module_id: self.module_id,
527 display_name: self.display_name,
528 icon: self.icon,
529 hosts_third_party_code: self.hosts_third_party_code,
530 module_version: self.module_version,
531 protocol_ver: self.protocol_ver,
532 trust_tier: self.trust_tier,
533 ready: self.ready,
534 registration_channel: self.registration_channel,
535 provides: self.provides,
536 consumes: self.consumes,
537 bindings: self.bindings,
538 capabilities: self.capabilities,
539 events: self.events,
540 self_signals: self.self_signals,
541 provenance: self.provenance,
542 operation_delivery: self.operation_delivery,
543 operation_titles: self.operation_titles,
544 operation_groups: self.operation_groups,
545 operation_requires: self.operation_requires,
546 operation_payload: self.operation_payload,
547 flow_operations: self.flow_operations,
548 operation_deferral: self.operation_deferral,
549 confirm_operations: self.confirm_operations,
550 rich_ui: self.rich_ui,
551 role_declarations: self.role_declarations,
552 provider_declarations: self.provider_declarations,
553 }
554 }
555}
556
557#[derive(Deserialize)]
577struct ModuleManifestWire {
578 module_id: String,
579 #[serde(default)]
580 display_name: Option<String>,
581 #[serde(default)]
582 icon: Option<String>,
583 #[serde(default)]
584 hosts_third_party_code: Option<Value>,
585 module_version: String,
586 protocol_ver: u8,
587 #[serde(default)]
588 trust_tier: Option<TrustTier>,
589 #[serde(default)]
590 ready: Option<bool>,
591 #[serde(default)]
592 registration_channel: Option<bool>,
593 provides: Vec<ProviderRole>,
594 #[serde(default)]
595 consumes: Vec<ConsumerRole>,
596 #[serde(default)]
597 bindings: Option<Bindings>,
598 #[serde(default)]
599 capabilities: Option<CapabilityDeclarations>,
600 #[serde(default)]
601 events: Option<Value>,
602 #[serde(default)]
603 self_signals: Option<Vec<SelfSignalDeclaration>>,
604 #[serde(default)]
605 provenance: Option<ManifestProvenance>,
606 #[serde(default)]
607 operation_delivery: Option<Value>,
608 #[serde(default)]
609 operation_titles: BTreeMap<String, String>,
610 #[serde(default)]
611 operation_groups: BTreeMap<String, OperationGroup>,
612 #[serde(default)]
613 operation_requires: BTreeMap<String, Vec<String>>,
614 #[serde(default)]
615 operation_payload: BTreeMap<String, OperationPayload>,
616 #[serde(default)]
618 flow_operations: Option<Value>,
619 #[serde(default)]
620 operation_deferral: Option<Value>,
621 #[serde(default)]
623 confirm_operations: Option<Value>,
624 #[serde(default)]
625 rich_ui: Option<RichUiDescriptor>,
626 #[serde(default)]
630 runtime_computed: Option<Value>,
631 #[serde(default)]
632 role_declarations: Option<Value>,
633 #[serde(default, deserialize_with = "deserialize_provider_declarations")]
634 provider_declarations: Option<ProviderDeclarations>,
635}
636
637impl<'de> Deserialize<'de> for ModuleManifest {
638 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
639 where
640 D: Deserializer<'de>,
641 {
642 let wire = ModuleManifestWire::deserialize(deserializer)?;
643 validate_runtime_computed(wire.runtime_computed.as_ref(), "runtime_computed")
644 .map_err(D::Error::custom)?;
645 validate_events_value(wire.events.as_ref()).map_err(D::Error::custom)?;
646 let events = wire
647 .events
648 .map(serde_json::from_value)
649 .transpose()
650 .map_err(D::Error::custom)?;
651 let mut builder = Self::builder(wire.module_id, wire.module_version)
652 .display_name(wire.display_name)
653 .map_err(D::Error::custom)?
654 .protocol_ver(wire.protocol_ver)
655 .trust_tier(wire.trust_tier);
656 if let Some(icon) = wire.icon {
657 builder = builder.icon(icon).map_err(D::Error::custom)?;
658 }
659 if let Some(hosts) = wire
660 .hosts_third_party_code
661 .as_ref()
662 .and_then(Value::as_bool)
663 {
664 builder = builder.hosts_third_party_code(hosts);
665 }
666 if let Some(ready) = wire.ready {
667 builder = builder.ready(ready);
668 }
669 if let Some(supported) = wire.registration_channel {
670 builder = builder.registration_channel(supported);
671 }
672 builder = builder.provides(wire.provides);
673 validate_operation_metadata(
674 &builder.provides,
675 &wire.operation_titles,
676 &wire.operation_groups,
677 &wire.operation_requires,
678 )
679 .map_err(D::Error::custom)?;
680 builder.operation_titles = wire.operation_titles;
681 builder.operation_groups = wire.operation_groups;
682 builder.operation_requires = wire.operation_requires;
683 let mut manifest = builder
684 .consumes(wire.consumes)
685 .bindings(wire.bindings)
686 .capabilities(wire.capabilities)
687 .events(events)
688 .self_signals(wire.self_signals)
689 .provenance(wire.provenance)
690 .operation_delivery(
691 wire.operation_delivery
692 .and_then(|value| serde_json::from_value(value).ok())
693 .unwrap_or_default(),
694 )
695 .rich_ui(wire.rich_ui)
696 .role_declarations(
697 wire.role_declarations
698 .filter(|value| validate_role_declarations_value(Some(value)).is_ok())
699 .and_then(|value| serde_json::from_value(value).ok())
700 .unwrap_or_default(),
701 )
702 .operation_payload(wire.operation_payload)
703 .provider_declarations(wire.provider_declarations)
704 .build();
705 manifest
706 .validate_operation_payload()
707 .map_err(D::Error::custom)?;
708 manifest.flow_operations = wire
711 .flow_operations
712 .and_then(|value| decode_flow_operations(&manifest, &value).ok());
713 manifest.operation_deferral = wire
714 .operation_deferral
715 .and_then(|value| decode_operation_deferral(&manifest, &value).ok());
716 manifest.confirm_operations = wire
717 .confirm_operations
718 .and_then(|value| decode_confirm_operations(&manifest, &value).ok());
719 manifest
720 .validate_capability_grammar()
721 .map_err(D::Error::custom)?;
722 if let Some(rich_ui) = &manifest.rich_ui {
723 rich_ui.validate().map_err(D::Error::custom)?;
724 }
725 Ok(manifest)
726 }
727}
728
729#[derive(Debug, Clone, PartialEq, Eq)]
731pub struct RoleDeclarationsError(&'static str);
732
733impl fmt::Display for RoleDeclarationsError {
734 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
735 f.write_str(self.0)
736 }
737}
738
739impl std::error::Error for RoleDeclarationsError {}
740
741pub fn validate_hello_role_declarations(hello: &Value) -> Result<(), RoleDeclarationsError> {
743 validate_role_declarations_value(
744 hello
745 .get("manifest")
746 .and_then(|manifest| manifest.get("role_declarations")),
747 )
748}
749
750pub fn validate_role_declarations_value(
753 value: Option<&Value>,
754) -> Result<(), RoleDeclarationsError> {
755 let Some(value) = value else {
756 return Ok(());
757 };
758 let map = value
759 .as_object()
760 .ok_or(RoleDeclarationsError("role_declarations must be an object"))?;
761 for (role, declaration) in map {
762 if !is_valid_capability_identifier(role) {
763 return Err(RoleDeclarationsError(
764 "role_declarations key must use capability-name grammar",
765 ));
766 }
767 if !declaration.is_object() {
768 return Err(RoleDeclarationsError(
769 "role_declarations values must be objects",
770 ));
771 }
772 }
773 let bytes = serde_json::to_vec(value)
774 .map_err(|_| RoleDeclarationsError("role_declarations could not be serialized"))?;
775 if bytes.len() > MAX_ROLE_DECLARATIONS_BYTES {
776 return Err(RoleDeclarationsError(
777 "role_declarations exceeds 16384 compact JSON bytes",
778 ));
779 }
780 Ok(())
781}
782
783#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
789#[non_exhaustive]
790pub struct RichUiDescriptor {
791 pub schema: String,
793 pub manifest_digest: String,
795 pub bytes: u64,
797 pub chunks: u32,
799}
800
801impl RichUiDescriptor {
802 pub fn new(
804 schema: impl Into<String>,
805 manifest_digest: impl Into<String>,
806 bytes: u64,
807 chunks: u32,
808 ) -> Self {
809 Self {
810 schema: schema.into(),
811 manifest_digest: manifest_digest.into(),
812 bytes,
813 chunks,
814 }
815 }
816
817 pub fn validate(&self) -> Result<(), RichUiDescriptorError> {
819 validate_rich_ui_fields(
820 &self.schema,
821 &self.manifest_digest,
822 self.bytes,
823 u64::from(self.chunks),
824 )
825 }
826}
827
828#[derive(Debug, Clone, PartialEq, Eq)]
830pub struct DisplayNameError(&'static str);
831
832impl fmt::Display for DisplayNameError {
833 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
834 write!(f, "invalid manifest display_name: {}", self.0)
835 }
836}
837
838impl std::error::Error for DisplayNameError {}
839
840pub fn validate_display_name(value: &str) -> Result<(), DisplayNameError> {
845 if value.trim() != value || !(1..=40).contains(&value.chars().count()) {
846 return Err(DisplayNameError(
847 "must be trimmed text of 1 to 40 characters",
848 ));
849 }
850 validate_plain_text(value, 40)
851}
852
853pub fn validate_module_id(module_id: &str) -> Result<(), String> {
855 if module_id.is_empty() {
856 return Err("empty".to_string());
857 }
858 if module_id.contains('/') || module_id.contains('\\') {
859 return Err("contains a path separator".to_string());
860 }
861 if module_id == "." || module_id == ".." {
862 return Err("is a dot path component".to_string());
863 }
864 if module_id.chars().any(|c| c.is_control()) {
865 return Err("contains a control character".to_string());
866 }
867 if module_id.len() > 255 {
868 return Err("is longer than 255 bytes".to_string());
869 }
870 Ok(())
871}
872
873pub(crate) fn validate_plain_text(value: &str, max: usize) -> Result<(), DisplayNameError> {
874 if value.is_empty() || value.chars().count() > max {
875 return Err(DisplayNameError(
876 "text length is outside the permitted bounds",
877 ));
878 }
879 if value.chars().any(|ch| {
880 ch.is_control()
881 || matches!(ch, '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')
882 }) {
883 return Err(DisplayNameError("must not contain control or bidi formatting characters"));
884 }
885 Ok(())
886}
887
888pub fn validate_hello_display_name(hello: &Value) -> Result<(), DisplayNameError> {
890 match hello
891 .get("manifest")
892 .and_then(|manifest| manifest.get("display_name"))
893 {
894 None | Some(Value::Null) => Ok(()),
895 Some(Value::String(value)) => validate_display_name(value),
896 Some(_) => Err(DisplayNameError("must be a string")),
897 }
898}
899
900#[derive(Debug, Clone, PartialEq, Eq)]
902pub struct IconError(&'static str);
903
904impl fmt::Display for IconError {
905 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
906 write!(f, "invalid manifest icon: {}", self.0)
907 }
908}
909
910impl std::error::Error for IconError {}
911
912fn validate_icon(value: &str) -> Result<(), IconError> {
913 if !(1..=64).contains(&value.len())
914 || !value.split('-').all(|part| {
915 !part.is_empty()
916 && part
917 .bytes()
918 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
919 })
920 {
921 return Err(IconError(
922 "must be 1 to 64 characters matching ^[a-z0-9]+(-[a-z0-9]+)*$",
923 ));
924 }
925 Ok(())
926}
927
928pub fn validate_hello_icon(hello: &Value) -> Result<(), IconError> {
930 match hello
931 .get("manifest")
932 .and_then(|manifest| manifest.get("icon"))
933 {
934 None | Some(Value::Null) => Ok(()),
935 Some(Value::String(value)) => validate_icon(value),
936 Some(_) => Err(IconError("must be a string")),
937 }
938}
939
940#[derive(Debug, Clone, PartialEq, Eq)]
942pub struct OperationTitleError(&'static str);
943
944impl fmt::Display for OperationTitleError {
945 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
946 write!(f, "invalid manifest operation_titles: {}", self.0)
947 }
948}
949
950impl std::error::Error for OperationTitleError {}
951
952fn validate_operation_title(
953 provides: &[ProviderRole],
954 name: &str,
955 title: &str,
956) -> Result<(), OperationTitleError> {
957 validate_display_name(title).map_err(|error| OperationTitleError(error.0))?;
958 if !declares_management_operation(provides, name) {
959 return Err(OperationTitleError(
960 "keys must name declared management operations",
961 ));
962 }
963 Ok(())
964}
965
966#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
968#[non_exhaustive]
969pub struct OperationGroup {
970 pub title: String,
971 #[serde(default, skip_serializing_if = "Option::is_none")]
972 pub description: Option<String>,
973 pub operations: Vec<String>,
974}
975
976impl OperationGroup {
977 pub fn new(
980 title: impl Into<String>,
981 description: Option<String>,
982 operations: Vec<String>,
983 ) -> Self {
984 Self {
985 title: title.into(),
986 description,
987 operations,
988 }
989 }
990}
991
992#[derive(Debug, Clone, PartialEq, Eq)]
994pub struct OperationMetadataError {
995 field: &'static str,
996 reason: &'static str,
997}
998
999impl fmt::Display for OperationMetadataError {
1000 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1001 write!(f, "invalid manifest {}: {}", self.field, self.reason)
1002 }
1003}
1004
1005impl std::error::Error for OperationMetadataError {}
1006
1007fn validate_operation_group(
1008 provides: &[ProviderRole],
1009 id: &str,
1010 group: &OperationGroup,
1011 assigned: &HashSet<&str>,
1012) -> Result<(), OperationMetadataError> {
1013 let invalid = |reason| OperationMetadataError {
1014 field: "operation_groups",
1015 reason,
1016 };
1017 if !(1..=40).contains(&id.len())
1018 || !id
1019 .bytes()
1020 .all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'_'))
1021 {
1022 return Err(invalid(
1023 "ids must contain 1 to 40 lowercase ASCII letters, digits or underscores",
1024 ));
1025 }
1026 validate_display_name(&group.title).map_err(|error| invalid(error.0))?;
1027 if group.operations.is_empty() {
1028 return Err(invalid("each group must contain at least one operation"));
1029 }
1030 for operation in &group.operations {
1031 if !declares_management_operation(provides, operation) {
1032 return Err(invalid(
1033 "groups may contain only declared management operations",
1034 ));
1035 }
1036 if assigned.contains(operation.as_str()) {
1037 return Err(invalid("an operation may belong to at most one group"));
1038 }
1039 }
1040 Ok(())
1041}
1042
1043fn validate_operation_requires(
1044 provides: &[ProviderRole],
1045 name: &str,
1046 requires: &[String],
1047) -> Result<(), OperationMetadataError> {
1048 let invalid = |reason| OperationMetadataError {
1049 field: "operation_requires",
1050 reason,
1051 };
1052 if !declares_management_operation(provides, name) {
1053 return Err(invalid("keys must name declared management operations"));
1054 }
1055 for dependency in requires {
1056 if let Some((module_id, operation)) = dependency.split_once('/') {
1057 if module_id.is_empty() || operation.is_empty() {
1058 return Err(invalid(
1059 "foreign references must have a module id and operation name",
1060 ));
1061 }
1062 } else if dependency == name {
1063 return Err(invalid("an operation cannot require itself"));
1064 } else if !declares_management_operation(provides, dependency) {
1065 return Err(invalid(
1066 "local references must name declared management operations",
1067 ));
1068 }
1069 }
1070 Ok(())
1071}
1072
1073fn validate_operation_metadata(
1074 provides: &[ProviderRole],
1075 titles: &BTreeMap<String, String>,
1076 groups: &BTreeMap<String, OperationGroup>,
1077 requires: &BTreeMap<String, Vec<String>>,
1078) -> Result<(), OperationMetadataError> {
1079 for (name, title) in titles {
1080 validate_operation_title(provides, name, title).map_err(|error| {
1081 OperationMetadataError {
1082 field: "operation_titles",
1083 reason: error.0,
1084 }
1085 })?;
1086 }
1087 let mut assigned = HashSet::new();
1088 for (id, group) in groups {
1089 validate_operation_group(provides, id, group, &assigned)?;
1090 assigned.extend(group.operations.iter().map(String::as_str));
1091 }
1092 for (name, dependencies) in requires {
1093 validate_operation_requires(provides, name, dependencies)?;
1094 }
1095 Ok(())
1096}
1097
1098fn decode_hello_operation_map<T: serde::de::DeserializeOwned>(
1099 manifest: &Value,
1100 field: &'static str,
1101 reason: &'static str,
1102) -> Result<BTreeMap<String, T>, OperationMetadataError> {
1103 match manifest.get(field) {
1104 Some(value) => {
1105 BTreeMap::deserialize(value).map_err(|_| OperationMetadataError { field, reason })
1106 }
1107 None => Ok(BTreeMap::new()),
1108 }
1109}
1110
1111pub fn validate_hello_operation_metadata(hello: &Value) -> Result<(), OperationMetadataError> {
1113 let Some(manifest) = hello.get("manifest") else {
1114 return Ok(());
1115 };
1116 let titles = decode_hello_operation_map(
1117 manifest,
1118 "operation_titles",
1119 "must be an object with string titles",
1120 )?;
1121 let groups = decode_hello_operation_map(
1122 manifest,
1123 "operation_groups",
1124 "must be an object with group values",
1125 )?;
1126 let requires = decode_hello_operation_map(
1127 manifest,
1128 "operation_requires",
1129 "must be an object with lists of operation names",
1130 )?;
1131 if titles.is_empty() && groups.is_empty() && requires.is_empty() {
1132 return Ok(());
1133 }
1134 let Some(provides) = manifest
1136 .get("provides")
1137 .and_then(|value| Vec::<ProviderRole>::deserialize(value).ok())
1138 else {
1139 return Ok(());
1140 };
1141 validate_operation_metadata(&provides, &titles, &groups, &requires)
1142}
1143
1144#[derive(Debug, Clone, PartialEq, Eq)]
1146#[non_exhaustive]
1147pub struct RichUiDescriptorError {
1148 field: String,
1149 reason: &'static str,
1150}
1151
1152impl RichUiDescriptorError {
1153 fn new(field: impl Into<String>, reason: &'static str) -> Self {
1154 Self {
1155 field: field.into(),
1156 reason,
1157 }
1158 }
1159
1160 pub fn field(&self) -> &str {
1162 &self.field
1163 }
1164}
1165
1166impl fmt::Display for RichUiDescriptorError {
1167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1168 write!(
1169 f,
1170 "invalid rich_ui descriptor: field {} {}",
1171 self.field, self.reason
1172 )
1173 }
1174}
1175
1176impl std::error::Error for RichUiDescriptorError {}
1177
1178pub fn validate_hello_rich_ui_descriptor(hello: &Value) -> Result<(), RichUiDescriptorError> {
1180 let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
1181 return Ok(());
1182 };
1183 let Some(value) = manifest.get("rich_ui") else {
1184 return Ok(());
1185 };
1186 validate_rich_ui_descriptor_value(value)
1187}
1188
1189fn validate_rich_ui_descriptor_value(value: &Value) -> Result<(), RichUiDescriptorError> {
1190 let descriptor = value
1191 .as_object()
1192 .ok_or_else(|| RichUiDescriptorError::new("rich_ui", "must be an object"))?;
1193 let schema = descriptor
1194 .get("schema")
1195 .and_then(Value::as_str)
1196 .ok_or_else(|| RichUiDescriptorError::new("rich_ui.schema", "must be a string"))?;
1197 let digest = descriptor
1198 .get("manifest_digest")
1199 .and_then(Value::as_str)
1200 .ok_or_else(|| RichUiDescriptorError::new("rich_ui.manifest_digest", "must be a string"))?;
1201 let bytes = descriptor
1202 .get("bytes")
1203 .and_then(Value::as_u64)
1204 .ok_or_else(|| {
1205 RichUiDescriptorError::new("rich_ui.bytes", "must be an integer from 1 to 16777216")
1206 })?;
1207 let chunks = descriptor
1208 .get("chunks")
1209 .and_then(Value::as_u64)
1210 .ok_or_else(|| {
1211 RichUiDescriptorError::new("rich_ui.chunks", "must be an integer from 1 to 1024")
1212 })?;
1213 validate_rich_ui_fields(schema, digest, bytes, chunks)
1214}
1215
1216fn validate_rich_ui_fields(
1217 schema: &str,
1218 digest: &str,
1219 bytes: u64,
1220 chunks: u64,
1221) -> Result<(), RichUiDescriptorError> {
1222 if !(1..=64).contains(&schema.len())
1223 || !schema.bytes().all(|byte| {
1224 byte.is_ascii_lowercase()
1225 || byte.is_ascii_digit()
1226 || matches!(byte, b'.' | b'_' | b'/' | b'-')
1227 })
1228 {
1229 return Err(RichUiDescriptorError::new(
1230 "rich_ui.schema",
1231 "must be 1 to 64 bytes of [a-z0-9._/-]",
1232 ));
1233 }
1234 if !digest.strip_prefix("sha256:").is_some_and(|hex| {
1235 hex.len() == 64
1236 && hex
1237 .bytes()
1238 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1239 }) {
1240 return Err(RichUiDescriptorError::new(
1241 "rich_ui.manifest_digest",
1242 "must be sha256: followed by 64 lowercase hexadecimal characters",
1243 ));
1244 }
1245 if !(1..=16_777_216).contains(&bytes) {
1246 return Err(RichUiDescriptorError::new(
1247 "rich_ui.bytes",
1248 "must be an integer from 1 to 16777216",
1249 ));
1250 }
1251 if !(1..=1_024).contains(&chunks) {
1252 return Err(RichUiDescriptorError::new(
1253 "rich_ui.chunks",
1254 "must be an integer from 1 to 1024",
1255 ));
1256 }
1257 Ok(())
1258}
1259
1260pub const CAP_CATALOG_EVENTS_V1: &str = "catalog-events/v1";
1266
1267pub const CAP_SCOPE_BIND_PROOF_V1: &str = "scope-bind-proof/v1";
1271
1272pub const CAP_SCOPE_BIND_PROOF_V2: &str = "scope-bind-proof/v2";
1276
1277pub const CAP_SCOPE_REPLACE_IF_IDLE_V1: &str = "scope-replace-if-idle/v1";
1279
1280#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1282#[non_exhaustive]
1283pub struct EventDeclaration {
1284 pub name: String,
1291 pub version: u32,
1293 pub headers: Vec<String>,
1298 #[serde(default, skip_serializing_if = "Option::is_none")]
1300 pub summary: Option<String>,
1301}
1302
1303impl EventDeclaration {
1304 pub fn new(name: impl Into<String>, version: u32) -> Self {
1307 Self {
1308 name: name.into(),
1309 version,
1310 headers: Vec::new(),
1311 summary: None,
1312 }
1313 }
1314
1315 pub fn with_headers(mut self, headers: Vec<String>) -> Self {
1317 self.headers = headers;
1318 self
1319 }
1320
1321 pub fn with_summary(mut self, summary: Option<String>) -> Self {
1323 self.summary = summary;
1324 self
1325 }
1326}
1327
1328#[derive(Debug, Clone, PartialEq, Eq)]
1330#[non_exhaustive]
1331pub struct EventDeclarationError {
1332 field: String,
1333 reason: &'static str,
1334}
1335
1336impl EventDeclarationError {
1337 fn new(field: impl Into<String>, reason: &'static str) -> Self {
1338 Self {
1339 field: field.into(),
1340 reason,
1341 }
1342 }
1343
1344 pub fn field(&self) -> &str {
1346 &self.field
1347 }
1348}
1349
1350impl fmt::Display for EventDeclarationError {
1351 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1352 write!(
1353 f,
1354 "invalid event declaration: field {} {}",
1355 self.field, self.reason
1356 )
1357 }
1358}
1359
1360impl std::error::Error for EventDeclarationError {}
1361
1362pub fn validate_hello_event_declarations(hello: &Value) -> Result<(), EventDeclarationError> {
1364 validate_events_value(
1365 hello
1366 .get("manifest")
1367 .and_then(|manifest| manifest.get("events")),
1368 )
1369}
1370
1371fn is_valid_event_name(name: &str) -> bool {
1374 let level_count = name.split('.').count();
1375 (1..=4).contains(&level_count)
1376 && name.split('.').all(|level| {
1377 if level.is_empty() {
1378 return false;
1379 }
1380 let first = level.as_bytes()[0];
1381 (1..=63).contains(&level.len())
1382 && (first.is_ascii_lowercase() || first.is_ascii_digit())
1383 && level
1384 .bytes()
1385 .skip(1)
1386 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
1387 && !level.strip_prefix('v').is_some_and(|digits| {
1388 !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit())
1389 })
1390 })
1391}
1392
1393fn validate_events_value(value: Option<&Value>) -> Result<(), EventDeclarationError> {
1394 let Some(value) = value.filter(|value| !value.is_null()) else {
1395 return Ok(());
1396 };
1397 let entries = value
1398 .as_array()
1399 .ok_or_else(|| EventDeclarationError::new("events", "must be a list"))?;
1400 if entries.len() > 64 {
1401 return Err(EventDeclarationError::new(
1402 "events",
1403 "must contain at most 64 declarations",
1404 ));
1405 }
1406 let mut pairs = HashSet::new();
1407 for (index, entry) in entries.iter().enumerate() {
1408 let field = format!("events[{index}]");
1409 let entry = entry
1410 .as_object()
1411 .ok_or_else(|| EventDeclarationError::new(&field, "must be an object"))?;
1412 let name_field = format!("{field}.name");
1413 let name = entry
1414 .get("name")
1415 .and_then(Value::as_str)
1416 .ok_or_else(|| EventDeclarationError::new(&name_field, "must be a string"))?;
1417 if !is_valid_event_name(name) {
1418 return Err(EventDeclarationError::new(
1419 name_field,
1420 "must contain one to four valid dot-separated event-name levels",
1421 ));
1422 }
1423 let version = entry
1424 .get("version")
1425 .and_then(Value::as_u64)
1426 .filter(|version| (1..=u32::MAX as u64).contains(version))
1427 .ok_or_else(|| {
1428 EventDeclarationError::new(
1429 format!("{field}.version"),
1430 "must be an integer between 1 and u32::MAX",
1431 )
1432 })?;
1433 if !pairs.insert((name, version)) {
1434 return Err(EventDeclarationError::new(
1435 &field,
1436 "duplicates an event (name, version) pair",
1437 ));
1438 }
1439 let headers_field = format!("{field}.headers");
1440 let headers = entry
1441 .get("headers")
1442 .and_then(Value::as_array)
1443 .ok_or_else(|| EventDeclarationError::new(&headers_field, "must be a list"))?;
1444 if headers.len() > 16 {
1445 return Err(EventDeclarationError::new(
1446 headers_field,
1447 "must contain at most 16 headers",
1448 ));
1449 }
1450 let mut names = HashSet::new();
1451 for (header_index, header) in headers.iter().enumerate() {
1452 let header_field = format!("{headers_field}[{header_index}]");
1453 let header = header
1454 .as_str()
1455 .ok_or_else(|| EventDeclarationError::new(&header_field, "must be a string"))?;
1456 if !(1..=32).contains(&header.len())
1457 || !header.as_bytes()[0].is_ascii_lowercase()
1458 || !header
1459 .bytes()
1460 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
1461 {
1462 return Err(EventDeclarationError::new(
1463 header_field,
1464 "must match [a-z][a-z0-9_]{0,31}",
1465 ));
1466 }
1467 if !names.insert(header) {
1468 return Err(EventDeclarationError::new(
1469 header_field,
1470 "duplicates a header name",
1471 ));
1472 }
1473 }
1474 if let Some(summary) = entry.get("summary").filter(|value| !value.is_null()) {
1475 let summary_field = format!("{field}.summary");
1476 let summary = summary
1477 .as_str()
1478 .ok_or_else(|| EventDeclarationError::new(&summary_field, "must be a string"))?;
1479 if summary.chars().count() > 200 || summary.chars().any(char::is_control) {
1480 return Err(EventDeclarationError::new(
1481 summary_field,
1482 "must contain at most 200 characters and no control characters",
1483 ));
1484 }
1485 }
1486 }
1487 Ok(())
1488}
1489
1490#[derive(Debug, Clone, PartialEq, Eq)]
1492pub struct SelfSignalDeclarationError {
1493 module_id: String,
1494 entry_index: usize,
1495 field: &'static str,
1496}
1497
1498impl fmt::Display for SelfSignalDeclarationError {
1499 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1500 write!(
1501 f,
1502 "module_id '{}' self_signals[{}] is missing required field '{}'",
1503 self.module_id.escape_debug(),
1504 self.entry_index,
1505 self.field
1506 )
1507 }
1508}
1509
1510pub fn validate_hello_self_signal_declarations(
1517 hello: &Value,
1518) -> Result<(), SelfSignalDeclarationError> {
1519 let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
1520 return Ok(());
1521 };
1522 let module_id = manifest
1523 .get("module_id")
1524 .and_then(Value::as_str)
1525 .unwrap_or("<unknown>");
1526 let Some(entries) = manifest.get("self_signals").and_then(Value::as_array) else {
1527 return Ok(());
1528 };
1529
1530 for (entry_index, entry) in entries.iter().enumerate() {
1531 let Some(entry) = entry.as_object() else {
1532 continue;
1533 };
1534 for field in ["effect", "anchored_to"] {
1535 if !entry.contains_key(field) {
1536 return Err(SelfSignalDeclarationError {
1537 module_id: module_id.to_string(),
1538 entry_index,
1539 field,
1540 });
1541 }
1542 }
1543 }
1544 Ok(())
1545}
1546
1547#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1549#[serde(deny_unknown_fields)]
1550pub struct CapabilityDeclarations {
1551 #[serde(default)]
1552 pub provides: Vec<String>,
1553 #[serde(default)]
1554 pub requires: Vec<CapabilityRequirement>,
1555 #[serde(default)]
1556 pub must_never_reach: Vec<String>,
1557}
1558
1559#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1561pub struct SelfSignalDeclaration {
1562 pub name: String,
1564 pub kind: SelfSignalKind,
1592 pub effect: SelfSignalEffect,
1594 pub anchored_to: SignalAnchor,
1596 #[serde(default, skip_serializing_if = "Option::is_none")]
1603 pub cadence: Option<SignalCadence>,
1604 #[serde(default, skip_serializing_if = "Option::is_none")]
1606 pub domain: Option<String>,
1607 #[serde(default, skip_serializing_if = "Option::is_none")]
1608 pub note: Option<String>,
1609}
1610
1611#[derive(Debug, Clone, PartialEq, Eq)]
1613pub enum SelfSignalKind {
1614 Keepalive,
1615 Busy,
1617 Poller,
1618 Cron,
1619 Sweep,
1620 Watchdog,
1621 Heartbeat,
1622 Other(String),
1623}
1624
1625impl SelfSignalKind {
1626 fn wire_name(&self) -> &str {
1627 match self {
1628 Self::Keepalive => "keepalive",
1629 Self::Busy => "busy",
1630 Self::Poller => "poller",
1631 Self::Cron => "cron",
1632 Self::Sweep => "sweep",
1633 Self::Watchdog => "watchdog",
1634 Self::Heartbeat => "heartbeat",
1635 Self::Other(value) => value,
1636 }
1637 }
1638}
1639
1640impl Serialize for SelfSignalKind {
1641 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1642 where
1643 S: serde::Serializer,
1644 {
1645 serializer.serialize_str(self.wire_name())
1646 }
1647}
1648
1649impl<'de> Deserialize<'de> for SelfSignalKind {
1650 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1651 where
1652 D: Deserializer<'de>,
1653 {
1654 let value = String::deserialize(deserializer)?;
1655 Ok(match value.as_str() {
1656 "keepalive" => Self::Keepalive,
1657 "busy" => Self::Busy,
1658 "poller" => Self::Poller,
1659 "cron" => Self::Cron,
1660 "sweep" => Self::Sweep,
1661 "watchdog" => Self::Watchdog,
1662 "heartbeat" => Self::Heartbeat,
1663 _ => Self::Other(value),
1664 })
1665 }
1666}
1667
1668#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1670#[serde(rename_all = "lowercase")]
1671pub enum SelfSignalEffect {
1672 Observe,
1673 Mutate,
1674}
1675
1676#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1678#[serde(rename_all = "snake_case")]
1679pub enum SignalAnchor {
1680 FixedInterval,
1683 Event { event: String },
1686 HealthGauges { gauges: Vec<String> },
1688}
1689
1690#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1692#[serde(rename_all = "snake_case")]
1693pub enum SignalCadence {
1694 Literal { interval_ms: u64 },
1695 Derived { source: String },
1696}
1697
1698#[derive(Serialize, Debug, Clone, Default, PartialEq, Eq)]
1775#[non_exhaustive]
1776pub struct ManifestProvenance {
1777 #[serde(default, skip_serializing_if = "Option::is_none")]
1778 pub build_git_sha: Option<String>,
1779 #[serde(default, skip_serializing_if = "Option::is_none")]
1783 pub build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1784 #[serde(default, skip_serializing_if = "Option::is_none")]
1785 pub build_lock_digest: Option<String>,
1786 #[serde(default, skip_serializing_if = "Option::is_none")]
1795 pub wire_crate_version: Option<String>,
1796 #[serde(default, skip_serializing_if = "Option::is_none")]
1797 pub store_schema_version: Option<String>,
1798 #[serde(default, skip_serializing_if = "Option::is_none")]
1804 pub launch_nonce_source: Option<LaunchNonceSource>,
1805}
1806
1807#[derive(Debug, Clone, PartialEq, Eq)]
1814#[non_exhaustive]
1815pub enum LaunchNonceSource {
1816 Fd,
1818 Pipe,
1820 Env,
1822 ForwardCompatibleUnknown(String),
1823}
1824
1825impl LaunchNonceSource {
1826 pub fn wire_name(&self) -> &str {
1828 match self {
1829 Self::Fd => "fd",
1830 Self::Pipe => "pipe",
1831 Self::Env => "env",
1832 Self::ForwardCompatibleUnknown(value) => value,
1833 }
1834 }
1835
1836 pub fn from_wire_name(value: &str) -> Self {
1838 match value {
1839 "fd" => Self::Fd,
1840 "pipe" => Self::Pipe,
1841 "env" => Self::Env,
1842 _ => Self::ForwardCompatibleUnknown(value.to_string()),
1843 }
1844 }
1845}
1846
1847impl Serialize for LaunchNonceSource {
1848 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1849 where
1850 S: serde::Serializer,
1851 {
1852 serializer.serialize_str(self.wire_name())
1853 }
1854}
1855
1856impl<'de> Deserialize<'de> for LaunchNonceSource {
1857 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1858 where
1859 D: serde::Deserializer<'de>,
1860 {
1861 let value = String::deserialize(deserializer)?;
1862 Ok(Self::from_wire_name(&value))
1863 }
1864}
1865
1866#[derive(Debug, Clone, PartialEq, Eq)]
1871pub enum BuildGitShaAbsenceReason {
1872 DeclinedDirty,
1873 NeverDerived,
1874 NoGitDir,
1875 ForwardCompatibleUnknown(String),
1876}
1877
1878impl BuildGitShaAbsenceReason {
1879 fn wire_name(&self) -> &str {
1880 match self {
1881 Self::DeclinedDirty => "declined_dirty",
1882 Self::NeverDerived => "never_derived",
1883 Self::NoGitDir => "no_git_dir",
1884 Self::ForwardCompatibleUnknown(value) => value,
1885 }
1886 }
1887}
1888
1889impl Serialize for BuildGitShaAbsenceReason {
1890 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1891 where
1892 S: serde::Serializer,
1893 {
1894 serializer.serialize_str(self.wire_name())
1895 }
1896}
1897
1898impl<'de> Deserialize<'de> for BuildGitShaAbsenceReason {
1899 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1900 where
1901 D: serde::Deserializer<'de>,
1902 {
1903 let value = String::deserialize(deserializer)?;
1904 Ok(match value.as_str() {
1905 "declined_dirty" => Self::DeclinedDirty,
1906 "never_derived" => Self::NeverDerived,
1907 "no_git_dir" => Self::NoGitDir,
1908 _ => Self::ForwardCompatibleUnknown(value),
1909 })
1910 }
1911}
1912
1913#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1915pub enum GitTreeState {
1916 Clean,
1917 Dirty,
1918}
1919
1920#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1925pub enum BuildGitShaSource<'a> {
1926 Git {
1927 revision: &'a str,
1928 tree_state: GitTreeState,
1929 },
1930 NeverDerived,
1931 NoGitDir,
1932}
1933
1934pub fn attestable_commit(revision: &str, tree_state: GitTreeState) -> Option<&str> {
1938 match tree_state {
1939 GitTreeState::Clean => Some(revision),
1940 GitTreeState::Dirty => None,
1941 }
1942}
1943
1944const MAX_PROVENANCE_VALUE_BYTES: usize = 128;
1945const BUILD_GIT_SHA_CANONICAL_FORM: &str = "exactly 40 lowercase hexadecimal characters";
1946const BUILD_LOCK_DIGEST_CANONICAL_FORM: &str = "exactly 64 lowercase hexadecimal characters";
1947
1948#[derive(Deserialize)]
1949struct ManifestProvenanceWire {
1950 #[serde(default)]
1951 build_git_sha: Option<String>,
1952 #[serde(default)]
1953 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1954 #[serde(default)]
1955 build_lock_digest: Option<String>,
1956 #[serde(default)]
1957 wire_crate_version: Option<String>,
1958 #[serde(default)]
1959 store_schema_version: Option<String>,
1960 #[serde(default)]
1961 launch_nonce_source: Option<LaunchNonceSource>,
1962}
1963
1964impl<'de> Deserialize<'de> for ManifestProvenance {
1965 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1966 where
1967 D: Deserializer<'de>,
1968 {
1969 let wire = ManifestProvenanceWire::deserialize(deserializer)?;
1970 let provenance = Self {
1971 build_git_sha: wire.build_git_sha,
1972 build_git_sha_absence_reason: wire.build_git_sha_absence_reason,
1973 build_lock_digest: wire.build_lock_digest,
1974 wire_crate_version: wire.wire_crate_version,
1975 store_schema_version: wire.store_schema_version,
1976 launch_nonce_source: wire.launch_nonce_source,
1977 };
1978 provenance.validate().map_err(D::Error::custom)?;
1979 Ok(provenance)
1980 }
1981}
1982
1983#[derive(Debug, Clone, PartialEq, Eq)]
1985pub struct ProvenanceFormError {
1986 field: &'static str,
1987 length: usize,
1988 canonical_form: &'static str,
1989}
1990
1991impl ProvenanceFormError {
1992 fn new(field: &'static str, length: usize, canonical_form: &'static str) -> Self {
1993 Self {
1994 field,
1995 length,
1996 canonical_form,
1997 }
1998 }
1999
2000 pub fn field(&self) -> &str {
2002 self.field
2003 }
2004
2005 pub fn length(&self) -> usize {
2007 self.length
2008 }
2009
2010 pub fn canonical_form(&self) -> &str {
2012 self.canonical_form
2013 }
2014}
2015
2016impl fmt::Display for ProvenanceFormError {
2017 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2018 write!(
2019 f,
2020 "invalid manifest provenance form: field {} has length {}; canonical form is {}",
2021 self.field, self.length, self.canonical_form
2022 )
2023 }
2024}
2025
2026impl std::error::Error for ProvenanceFormError {}
2027
2028#[derive(Debug, Clone, PartialEq, Eq)]
2029pub struct ManifestProvenanceError {
2030 field: String,
2031 value: String,
2032 reason: &'static str,
2033}
2034
2035impl ManifestProvenanceError {
2036 fn new(field: &str, value: &str, reason: &'static str) -> Self {
2037 Self {
2038 field: field.to_string(),
2039 value: safe_error_value(value),
2040 reason,
2041 }
2042 }
2043
2044 pub fn field(&self) -> &str {
2045 &self.field
2046 }
2047}
2048
2049impl fmt::Display for ManifestProvenanceError {
2050 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2051 write!(
2052 f,
2053 "invalid manifest provenance: field {} has {} (value {:?})",
2054 self.field, self.reason, self.value
2055 )
2056 }
2057}
2058
2059impl std::error::Error for ManifestProvenanceError {}
2060
2061impl ManifestProvenance {
2062 pub fn new() -> Self {
2064 Self::default()
2065 }
2066
2067 pub fn with_build_git_sha(mut self, value: Option<String>) -> Self {
2068 self.build_git_sha = value;
2069 self
2070 }
2071
2072 pub fn with_build_git_sha_absence_reason(
2073 mut self,
2074 value: Option<BuildGitShaAbsenceReason>,
2075 ) -> Self {
2076 self.build_git_sha_absence_reason = value;
2077 self
2078 }
2079
2080 pub fn with_build_lock_digest(mut self, value: Option<String>) -> Self {
2081 self.build_lock_digest = value;
2082 self
2083 }
2084
2085 pub fn with_wire_crate_version(mut self, value: Option<String>) -> Self {
2086 self.wire_crate_version = value;
2087 self
2088 }
2089
2090 pub fn with_store_schema_version(mut self, value: Option<String>) -> Self {
2091 self.store_schema_version = value;
2092 self
2093 }
2094
2095 pub fn with_launch_nonce_source(mut self, value: Option<LaunchNonceSource>) -> Self {
2100 self.launch_nonce_source = value;
2101 self
2102 }
2103
2104 pub fn validate(&self) -> Result<(), ManifestProvenanceError> {
2105 if let (Some(_), Some(reason)) = (
2106 self.build_git_sha.as_ref(),
2107 self.build_git_sha_absence_reason.as_ref(),
2108 ) {
2109 return Err(ManifestProvenanceError::new(
2110 "build_git_sha_absence_reason",
2111 reason.wire_name(),
2112 "must be omitted when build_git_sha is present",
2113 ));
2114 }
2115 for (field, value) in [
2116 ("build_git_sha", self.build_git_sha.as_deref()),
2117 (
2118 "build_git_sha_absence_reason",
2119 self.build_git_sha_absence_reason
2120 .as_ref()
2121 .map(|reason| reason.wire_name()),
2122 ),
2123 ("build_lock_digest", self.build_lock_digest.as_deref()),
2124 ("wire_crate_version", self.wire_crate_version.as_deref()),
2125 ("store_schema_version", self.store_schema_version.as_deref()),
2126 (
2127 "launch_nonce_source",
2128 self.launch_nonce_source
2129 .as_ref()
2130 .map(|source| source.wire_name()),
2131 ),
2132 ] {
2133 let Some(value) = value else { continue };
2134 if value.is_empty() {
2135 return Err(ManifestProvenanceError::new(
2136 field,
2137 value,
2138 "must not be empty",
2139 ));
2140 }
2141 if value.len() > MAX_PROVENANCE_VALUE_BYTES {
2146 return Err(ManifestProvenanceError::new(
2147 field,
2148 value,
2149 "exceeds the 128-byte maximum",
2150 ));
2151 }
2152 if value.bytes().any(|byte| !(0x20..=0x7e).contains(&byte)) {
2153 return Err(ManifestProvenanceError::new(
2154 field,
2155 value,
2156 "contains non-printable ASCII",
2157 ));
2158 }
2159 }
2160 Ok(())
2161 }
2162}
2163
2164pub fn build_provenance(
2182 build_git_sha: Option<&str>,
2183 build_lock_digest: Option<&str>,
2184 store_schema_version: Option<&str>,
2185) -> Result<ManifestProvenance, ProvenanceFormError> {
2186 let build_git_sha = normalize_and_validate_build_git_sha(build_git_sha)?;
2187 build_provenance_with_build_git_sha(
2188 build_git_sha,
2189 None,
2190 build_lock_digest,
2191 store_schema_version,
2192 )
2193}
2194
2195pub fn build_provenance_from_source(
2211 build_git_sha_source: BuildGitShaSource<'_>,
2212 build_lock_digest: Option<&str>,
2213 store_schema_version: Option<&str>,
2214) -> Result<ManifestProvenance, ProvenanceFormError> {
2215 let (raw_build_git_sha, mut build_git_sha_absence_reason) = match build_git_sha_source {
2216 BuildGitShaSource::Git {
2217 revision,
2218 tree_state,
2219 } => match attestable_commit(revision, tree_state) {
2220 Some(revision) => (Some(revision), None),
2221 None => (None, Some(BuildGitShaAbsenceReason::DeclinedDirty)),
2222 },
2223 BuildGitShaSource::NeverDerived => (None, Some(BuildGitShaAbsenceReason::NeverDerived)),
2224 BuildGitShaSource::NoGitDir => (None, Some(BuildGitShaAbsenceReason::NoGitDir)),
2225 };
2226 let build_git_sha = normalize_and_validate_build_git_sha(raw_build_git_sha)?;
2227 if build_git_sha.is_none() {
2228 build_git_sha_absence_reason.get_or_insert(BuildGitShaAbsenceReason::NeverDerived);
2229 }
2230 build_provenance_with_build_git_sha(
2231 build_git_sha,
2232 build_git_sha_absence_reason,
2233 build_lock_digest,
2234 store_schema_version,
2235 )
2236}
2237
2238fn normalize_and_validate_build_git_sha(
2239 build_git_sha: Option<&str>,
2240) -> Result<Option<String>, ProvenanceFormError> {
2241 let build_git_sha = normalize_provenance_fact(build_git_sha);
2242 validate_provenance_form(
2243 "build_git_sha",
2244 build_git_sha.as_deref(),
2245 BUILD_GIT_SHA_CANONICAL_FORM,
2246 40,
2247 )?;
2248 Ok(build_git_sha)
2249}
2250
2251fn build_provenance_with_build_git_sha(
2252 build_git_sha: Option<String>,
2253 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
2254 build_lock_digest: Option<&str>,
2255 store_schema_version: Option<&str>,
2256) -> Result<ManifestProvenance, ProvenanceFormError> {
2257 let build_lock_digest = normalize_provenance_fact(build_lock_digest);
2258 validate_provenance_form(
2259 "build_lock_digest",
2260 build_lock_digest.as_deref(),
2261 BUILD_LOCK_DIGEST_CANONICAL_FORM,
2262 64,
2263 )?;
2264
2265 Ok(ManifestProvenance {
2266 build_git_sha,
2267 build_git_sha_absence_reason,
2268 build_lock_digest,
2269 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
2270 store_schema_version: normalize_provenance_fact(store_schema_version),
2271 launch_nonce_source: None,
2272 })
2273}
2274
2275fn validate_provenance_form(
2276 field: &'static str,
2277 value: Option<&str>,
2278 canonical_form: &'static str,
2279 expected_length: usize,
2280) -> Result<(), ProvenanceFormError> {
2281 let Some(value) = value else { return Ok(()) };
2282 if value.len() != expected_length
2283 || !value
2284 .bytes()
2285 .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
2286 {
2287 return Err(ProvenanceFormError::new(field, value.len(), canonical_form));
2288 }
2289 Ok(())
2290}
2291
2292pub const PROVENANCE_SENTINELS: [&str; 3] = ["unknown", "unavailable", "none"];
2300
2301fn normalize_provenance_fact(value: Option<&str>) -> Option<String> {
2302 let value = value?.trim();
2303 if value.is_empty() {
2304 return None;
2305 }
2306 let lowered = value.to_ascii_lowercase();
2307 if PROVENANCE_SENTINELS.contains(&lowered.as_str()) {
2308 return None;
2309 }
2310 Some(value.to_string())
2311}
2312
2313#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2315#[serde(deny_unknown_fields)]
2316pub struct CapabilityRequirement {
2317 pub capability: String,
2318 pub need: CapabilityNeed,
2319}
2320
2321#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2323#[serde(rename_all = "snake_case")]
2324pub enum CapabilityNeed {
2325 Required,
2326 Optional,
2327}
2328
2329#[derive(Debug, Clone, PartialEq, Eq)]
2331pub struct CapabilityGrammarError {
2332 field: String,
2333 value: String,
2334}
2335
2336impl CapabilityGrammarError {
2337 fn new(field: impl Into<String>, value: impl AsRef<str>) -> Self {
2338 Self {
2339 field: field.into(),
2340 value: safe_error_value(value.as_ref()),
2341 }
2342 }
2343
2344 pub fn field(&self) -> &str {
2346 &self.field
2347 }
2348
2349 pub fn value(&self) -> &str {
2351 &self.value
2352 }
2353}
2354
2355impl fmt::Display for CapabilityGrammarError {
2356 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2357 write!(
2358 f,
2359 "invalid capability grammar: field {} has offending value {:?}",
2360 self.field, self.value
2361 )
2362 }
2363}
2364
2365impl std::error::Error for CapabilityGrammarError {}
2366
2367impl ModuleManifest {
2368 pub fn validate_capability_grammar(&self) -> Result<(), CapabilityGrammarError> {
2370 let Some(capabilities) = &self.capabilities else {
2371 return Ok(());
2372 };
2373
2374 validate_capability_list("capabilities.provides", &capabilities.provides)?;
2375 validate_requires(&capabilities.requires)?;
2376 validate_capability_list(
2377 "capabilities.must_never_reach",
2378 &capabilities.must_never_reach,
2379 )
2380 }
2381}
2382
2383pub fn validate_manifest_capability_grammar(
2388 manifest: &Value,
2389) -> Result<(), CapabilityGrammarError> {
2390 let Some(object) = manifest.as_object() else {
2391 return Ok(());
2392 };
2393
2394 validate_capabilities_value(object.get("capabilities"))?;
2395 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
2396}
2397
2398pub fn validate_hello_capability_grammar(hello: &Value) -> Result<(), CapabilityGrammarError> {
2404 let Some(object) = hello.as_object() else {
2405 return Ok(());
2406 };
2407 if let Some(manifest) = object.get("manifest") {
2408 validate_manifest_capability_grammar(manifest)?;
2409 }
2410 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
2411}
2412
2413pub fn is_valid_capability_identifier(identifier: &str) -> bool {
2415 if identifier.chars().any(char::is_whitespace) {
2416 return false;
2417 }
2418 let Some((name, version)) = identifier.split_once("/v") else {
2419 return false;
2420 };
2421 if name.is_empty() || name.len() > 64 || version.is_empty() {
2422 return false;
2423 }
2424
2425 let name_bytes = name.as_bytes();
2426 if !name_bytes[0].is_ascii_lowercase()
2427 || (name.len() > 1
2428 && !name_bytes[name.len() - 1].is_ascii_lowercase()
2429 && !name_bytes[name.len() - 1].is_ascii_digit())
2430 || name_bytes.windows(2).any(|pair| pair == b"--")
2431 {
2432 return false;
2433 }
2434 if !name_bytes
2435 .iter()
2436 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-')
2437 {
2438 return false;
2439 }
2440
2441 if version.len() > 1 && version.starts_with('0')
2442 || !version.bytes().all(|byte| byte.is_ascii_digit())
2443 {
2444 return false;
2445 }
2446 matches!(
2447 version.parse::<u64>(),
2448 Ok(value) if (1..=u64::from(u32::MAX)).contains(&value)
2449 )
2450}
2451
2452fn validate_capabilities_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
2453 let Some(value) = value else {
2454 return Ok(());
2455 };
2456 let Some(object) = value.as_object() else {
2457 return Err(CapabilityGrammarError::new(
2458 "capabilities",
2459 value_description(value),
2460 ));
2461 };
2462
2463 for (key, value) in object {
2464 if !matches!(key.as_str(), "provides" | "requires" | "must_never_reach") {
2465 return Err(CapabilityGrammarError::new(
2466 field_child("capabilities", key),
2467 value_description(value),
2468 ));
2469 }
2470 }
2471
2472 validate_capability_list_value("capabilities.provides", object.get("provides"))?;
2473 validate_requires_value(object.get("requires"))?;
2474 validate_capability_list_value(
2475 "capabilities.must_never_reach",
2476 object.get("must_never_reach"),
2477 )
2478}
2479
2480fn validate_capability_list_value(
2481 field: &str,
2482 value: Option<&Value>,
2483) -> Result<(), CapabilityGrammarError> {
2484 let Some(value) = value else {
2485 return Ok(());
2486 };
2487 let Some(values) = value.as_array() else {
2488 return Err(CapabilityGrammarError::new(field, value_description(value)));
2489 };
2490
2491 let mut seen = HashSet::new();
2492 for (index, value) in values.iter().enumerate() {
2493 let field = format!("{field}[{index}]");
2494 let Some(identifier) = value.as_str() else {
2495 return Err(CapabilityGrammarError::new(field, value_description(value)));
2496 };
2497 validate_capability_identifier(&field, identifier)?;
2498 if !seen.insert(identifier) {
2499 return Err(CapabilityGrammarError::new(field, identifier));
2500 }
2501 }
2502 Ok(())
2503}
2504
2505fn validate_requires_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
2506 let Some(value) = value else {
2507 return Ok(());
2508 };
2509 let Some(values) = value.as_array() else {
2510 return Err(CapabilityGrammarError::new(
2511 "capabilities.requires",
2512 value_description(value),
2513 ));
2514 };
2515
2516 let mut seen = HashSet::new();
2517 for (index, value) in values.iter().enumerate() {
2518 let entry_field = format!("capabilities.requires[{index}]");
2519 let Some(object) = value.as_object() else {
2520 return Err(CapabilityGrammarError::new(
2521 entry_field,
2522 value_description(value),
2523 ));
2524 };
2525 for (key, value) in object {
2526 if !matches!(key.as_str(), "capability" | "need") {
2527 return Err(CapabilityGrammarError::new(
2528 field_child(&entry_field, key),
2529 value_description(value),
2530 ));
2531 }
2532 }
2533 let capability_field = format!("{entry_field}.capability");
2534 let Some(capability) = object.get("capability").and_then(Value::as_str) else {
2535 return Err(CapabilityGrammarError::new(
2536 capability_field,
2537 object
2538 .get("capability")
2539 .map_or("<missing>".to_string(), value_description),
2540 ));
2541 };
2542 validate_capability_identifier(&capability_field, capability)?;
2543
2544 let need_field = format!("{entry_field}.need");
2545 let Some(need) = object.get("need").and_then(Value::as_str) else {
2546 return Err(CapabilityGrammarError::new(
2547 need_field,
2548 object
2549 .get("need")
2550 .map_or("<missing>".to_string(), value_description),
2551 ));
2552 };
2553 if !matches!(need, "required" | "optional") {
2554 return Err(CapabilityGrammarError::new(need_field, need));
2555 }
2556 if !seen.insert(capability) {
2557 return Err(CapabilityGrammarError::new(entry_field, capability));
2558 }
2559 }
2560 Ok(())
2561}
2562
2563fn validate_capability_list(field: &str, values: &[String]) -> Result<(), CapabilityGrammarError> {
2564 let mut seen = HashSet::new();
2565 for (index, identifier) in values.iter().enumerate() {
2566 let field = format!("{field}[{index}]");
2567 validate_capability_identifier(&field, identifier)?;
2568 if !seen.insert(identifier) {
2569 return Err(CapabilityGrammarError::new(field, identifier));
2570 }
2571 }
2572 Ok(())
2573}
2574
2575fn validate_requires(values: &[CapabilityRequirement]) -> Result<(), CapabilityGrammarError> {
2576 let mut seen = HashSet::new();
2577 for (index, requirement) in values.iter().enumerate() {
2578 let field = format!("capabilities.requires[{index}].capability");
2579 validate_capability_identifier(&field, &requirement.capability)?;
2580 if !seen.insert(&requirement.capability) {
2581 return Err(CapabilityGrammarError::new(
2582 format!("capabilities.requires[{index}]"),
2583 &requirement.capability,
2584 ));
2585 }
2586 }
2587 Ok(())
2588}
2589
2590fn validate_capability_identifier(
2591 field: &str,
2592 identifier: &str,
2593) -> Result<(), CapabilityGrammarError> {
2594 if is_valid_capability_identifier(identifier) {
2595 Ok(())
2596 } else {
2597 Err(CapabilityGrammarError::new(field, identifier))
2598 }
2599}
2600
2601fn validate_runtime_computed(
2602 value: Option<&Value>,
2603 field: &str,
2604) -> Result<(), CapabilityGrammarError> {
2605 let Some(value) = value else {
2606 return Ok(());
2607 };
2608 let Some(pointers) = value.as_array() else {
2609 return Err(CapabilityGrammarError::new(field, value_description(value)));
2610 };
2611
2612 for (index, pointer) in pointers.iter().enumerate() {
2613 let field = format!("{field}[{index}]");
2614 let Some(pointer) = pointer.as_str() else {
2615 return Err(CapabilityGrammarError::new(
2616 field,
2617 value_description(pointer),
2618 ));
2619 };
2620 let Some(tokens) = parse_json_pointer(pointer) else {
2621 return Err(CapabilityGrammarError::new(field, pointer));
2622 };
2623 if tokens.first().is_some_and(|token| token == "capabilities") {
2624 return Err(CapabilityGrammarError::new(field, pointer));
2625 }
2626 }
2627 Ok(())
2628}
2629
2630fn parse_json_pointer(pointer: &str) -> Option<Vec<String>> {
2631 if pointer.is_empty() {
2632 return Some(Vec::new());
2633 }
2634 let raw_tokens = pointer.strip_prefix('/')?;
2635 raw_tokens
2636 .split('/')
2637 .map(unescape_json_pointer_token)
2638 .collect()
2639}
2640
2641fn unescape_json_pointer_token(token: &str) -> Option<String> {
2642 let mut output = String::with_capacity(token.len());
2643 let mut characters = token.chars();
2644 while let Some(character) = characters.next() {
2645 if character != '~' {
2646 output.push(character);
2647 continue;
2648 }
2649 match characters.next()? {
2650 '0' => output.push('~'),
2651 '1' => output.push('/'),
2652 _ => return None,
2653 }
2654 }
2655 Some(output)
2656}
2657
2658fn field_child(parent: &str, child: &str) -> String {
2659 let child = safe_error_value(child);
2660 format!("{parent}.{child}")
2661}
2662
2663fn value_description(value: &Value) -> String {
2664 match value {
2665 Value::String(value) => safe_error_value(value),
2666 Value::Null => "null".to_string(),
2667 Value::Bool(value) => value.to_string(),
2668 Value::Number(value) => value.to_string(),
2669 Value::Array(_) => "<array>".to_string(),
2670 Value::Object(_) => "<object>".to_string(),
2671 }
2672}
2673
2674fn safe_error_value(value: &str) -> String {
2675 let lower = value.to_ascii_lowercase();
2676 if ["secret", "password", "api_key"]
2677 .iter()
2678 .any(|marker| lower.contains(marker))
2679 || lower.starts_with("sk-")
2680 || lower.starts_with("akia")
2681 || lower.starts_with("bearer ")
2682 || lower.starts_with("token=")
2683 || lower.starts_with("credential=")
2684 {
2685 "<redacted>".to_string()
2686 } else {
2687 value.to_string()
2688 }
2689}
2690
2691#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2697#[serde(rename_all = "snake_case")]
2698pub enum TrustTier {
2699 FirstParty,
2700 Reviewed,
2701 Untrusted,
2702}
2703
2704#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2708#[serde(tag = "role", rename_all = "snake_case")]
2709pub enum ProviderRole {
2710 ToolProvider {
2711 tools: Vec<Tool>,
2712 identity_scope: Vec<IdentityScope>,
2720 concurrency: Concurrency,
2721 emits_push: bool,
2722 sub_supervises: bool,
2723 },
2724 PipelineStage {
2725 stage: PipelineStageKind,
2726 applies_to: PipelineAppliesTo,
2727 interface: String,
2728 declares_frozen_floor: bool,
2729 needs_signals: Vec<String>,
2730 conformance_class: String,
2731 },
2732 ManagementSurface {
2733 operations: Vec<ManagementOperation>,
2734 config_schema: Value,
2735 observability: Vec<ObservabilitySurface>,
2736 identity_scope: Vec<IdentityScope>,
2740 #[serde(default)]
2741 concurrency: Concurrency,
2742 },
2743 InternalService {
2744 service_id: String,
2745 transport: InternalTransport,
2746 agent_facing: bool,
2747 operations: Vec<String>,
2748 },
2749}
2750
2751#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2764#[serde(rename_all = "snake_case")]
2765pub enum ExecutionMode {
2766 Pure,
2767 Mutating,
2768 Unfenceable,
2769}
2770
2771#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2773pub struct Tool {
2774 pub name: String,
2775 #[serde(default, skip_serializing_if = "Option::is_none")]
2776 pub description: Option<String>,
2777 pub execution_mode: ExecutionMode,
2782 pub schema: Value,
2783}
2784
2785#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2791#[serde(rename_all = "snake_case")]
2792pub enum Concurrency {
2793 Serial,
2795 ModuleManaged,
2798 StatelessParallel,
2801}
2802
2803#[allow(clippy::derivable_impls)]
2804impl Default for Concurrency {
2815 fn default() -> Self {
2816 Self::ModuleManaged
2817 }
2818}
2819
2820#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2827#[serde(rename_all = "snake_case")]
2828pub enum IdentityScope {
2829 Session,
2830 Project,
2831}
2832
2833#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2835#[serde(rename_all = "snake_case")]
2836pub enum PipelineStageKind {
2837 Transform,
2838 Codec,
2839 Auth,
2840}
2841
2842#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2844pub struct PipelineAppliesTo {
2845 pub provider: String,
2846 pub model: String,
2847}
2848
2849#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2852#[non_exhaustive]
2853pub struct OperationPayload {
2854 max_bytes: usize,
2855}
2856
2857impl OperationPayload {
2858 pub fn new(max_bytes: usize) -> Self {
2859 Self { max_bytes }
2860 }
2861
2862 pub fn max_bytes(&self) -> usize {
2863 self.max_bytes
2864 }
2865}
2866
2867#[derive(Debug, Clone, PartialEq, Eq)]
2869#[non_exhaustive]
2870pub enum OperationPayloadError {
2871 UnknownOperation { operation: String },
2872 WatchOperation { operation: String },
2873 InvalidMaxBytes { operation: String },
2874}
2875
2876impl fmt::Display for OperationPayloadError {
2877 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2878 write!(f, "{self:?}")
2879 }
2880}
2881
2882impl std::error::Error for OperationPayloadError {}
2883
2884impl ModuleManifest {
2885 pub fn validate_operation_payload(&self) -> Result<(), OperationPayloadError> {
2888 for (name, payload) in &self.operation_payload {
2889 if !self.provides.iter().any(|role| match role {
2890 ProviderRole::ManagementSurface { operations, .. } => {
2891 operations.iter().any(|op| op.name == *name)
2892 }
2893 _ => false,
2894 }) {
2895 return Err(OperationPayloadError::UnknownOperation {
2896 operation: name.clone(),
2897 });
2898 }
2899 if self
2900 .operation_delivery
2901 .get(name)
2902 .is_some_and(OperationDelivery::is_watch)
2903 {
2904 return Err(OperationPayloadError::WatchOperation {
2905 operation: name.clone(),
2906 });
2907 }
2908 if !(1..=crate::framed_body::MAX_DECLARED_PAYLOAD_BYTES).contains(&payload.max_bytes) {
2909 return Err(OperationPayloadError::InvalidMaxBytes {
2910 operation: name.clone(),
2911 });
2912 }
2913 }
2914 Ok(())
2915 }
2916}
2917
2918#[derive(Debug, Clone, PartialEq, Eq)]
2923#[non_exhaustive]
2924pub enum FlowOperationsError {
2925 FlowScopesNotDeclared,
2928 NotAList,
2930 TooMany { count: usize },
2932 DuplicateOperation { operation: String },
2934 UnknownOperation { operation: String },
2936}
2937
2938impl fmt::Display for FlowOperationsError {
2939 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2940 match self {
2941 Self::FlowScopesNotDeclared => write!(
2942 f,
2943 "flow_operations requires '{}' or '{}' in capabilities.provides",
2944 crate::scope::FLOW_SCOPES_CAPABILITY,
2945 crate::call_mode::CALL_MODES_CAPABILITY
2946 ),
2947 Self::NotAList => f.write_str("flow_operations must be an array of operation names"),
2948 Self::TooMany { count } => write!(
2949 f,
2950 "flow_operations lists {count} names, more than {MAX_FLOW_OPERATIONS}"
2951 ),
2952 Self::DuplicateOperation { operation } => {
2953 write!(f, "flow_operations names '{operation}' more than once")
2954 }
2955 Self::UnknownOperation { operation } => write!(
2956 f,
2957 "flow_operations names '{operation}', which is not a declared management operation"
2958 ),
2959 }
2960 }
2961}
2962
2963impl std::error::Error for FlowOperationsError {}
2964
2965impl ModuleManifest {
2966 pub fn validate_flow_operations(&self) -> Result<(), FlowOperationsError> {
2971 match &self.flow_operations {
2972 Some(operations) => check_flow_operations(self, operations),
2973 None => Ok(()),
2974 }
2975 }
2976}
2977
2978fn check_flow_operations(
2979 manifest: &ModuleManifest,
2980 operations: &[String],
2981) -> Result<(), FlowOperationsError> {
2982 let admits_flows = manifest.capabilities.as_ref().is_some_and(|capabilities| {
2983 capabilities.provides.iter().any(|capability| {
2984 capability == crate::scope::FLOW_SCOPES_CAPABILITY
2985 || capability == crate::call_mode::CALL_MODES_CAPABILITY
2986 })
2987 });
2988 if !admits_flows {
2989 return Err(FlowOperationsError::FlowScopesNotDeclared);
2990 }
2991 if operations.len() > MAX_FLOW_OPERATIONS {
2992 return Err(FlowOperationsError::TooMany {
2993 count: operations.len(),
2994 });
2995 }
2996 let mut seen = HashSet::new();
2997 for operation in operations {
2998 if !seen.insert(operation.as_str()) {
2999 return Err(FlowOperationsError::DuplicateOperation {
3000 operation: operation.clone(),
3001 });
3002 }
3003 let declared = manifest.provides.iter().any(|role| match role {
3004 ProviderRole::ManagementSurface { operations, .. } => {
3005 operations.iter().any(|op| op.name == *operation)
3006 }
3007 _ => false,
3008 });
3009 if !declared {
3010 return Err(FlowOperationsError::UnknownOperation {
3011 operation: operation.clone(),
3012 });
3013 }
3014 }
3015 Ok(())
3016}
3017
3018fn decode_flow_operations(
3021 manifest: &ModuleManifest,
3022 value: &Value,
3023) -> Result<Vec<String>, FlowOperationsError> {
3024 let operations: Vec<String> =
3025 serde_json::from_value(value.clone()).map_err(|_| FlowOperationsError::NotAList)?;
3026 check_flow_operations(manifest, &operations)?;
3027 Ok(operations)
3028}
3029
3030pub fn validate_hello_flow_operations(hello: &Value) -> Result<(), FlowOperationsError> {
3036 let Some(manifest_value) = hello.get("manifest") else {
3037 return Ok(());
3038 };
3039 let Some(value) = manifest_value
3040 .get("flow_operations")
3041 .filter(|value| !value.is_null())
3042 else {
3043 return Ok(());
3044 };
3045 let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
3046 return Ok(());
3047 };
3048 decode_flow_operations(&manifest, value).map(|_| ())
3049}
3050
3051pub const MAX_OPERATION_DEFERRAL: usize = 256;
3053
3054fn decode_operation_deferral(
3055 manifest: &ModuleManifest,
3056 value: &Value,
3057) -> Result<BTreeMap<String, bool>, String> {
3058 if !manifest.capabilities.as_ref().is_some_and(|caps| {
3059 caps.provides
3060 .iter()
3061 .any(|cap| cap == crate::scope::SCOPE_FEDERATED_CAPABILITY)
3062 }) {
3063 return Err("operation_deferral requires scope-federated/v1".into());
3064 }
3065 let operations = value
3066 .as_object()
3067 .ok_or("operation_deferral must be an object")?;
3068 if operations.len() > MAX_OPERATION_DEFERRAL {
3069 return Err(format!(
3070 "operation_deferral exceeds {MAX_OPERATION_DEFERRAL} entries"
3071 ));
3072 }
3073 for (key, value) in operations {
3074 let (surface, name) = key
3075 .split_once(':')
3076 .ok_or("operation_deferral keys require a surface prefix")?;
3077 if !matches!(surface, "tool" | "management")
3080 || name.is_empty()
3081 || name.len() > 128
3082 || !name
3083 .bytes()
3084 .all(|b| (0x21..=0x7e).contains(&b) && b != b':')
3085 {
3086 return Err(format!("invalid operation_deferral key '{key}'"));
3087 }
3088 if value != &Value::Bool(true) {
3089 return Err(format!("operation_deferral value for '{key}' must be true"));
3090 }
3091 if surface == "management" && !manifest.provides.iter().any(|role| matches!(role,
3092 ProviderRole::ManagementSurface { operations, .. } if operations.iter().any(|op| op.name == name))) {
3093 return Err(format!("operation_deferral names undeclared management operation '{name}'"));
3094 }
3095 }
3096 Ok(operations.keys().map(|key| (key.clone(), true)).collect())
3097}
3098
3099impl ModuleManifest {
3100 pub fn validate_operation_deferral(&self) -> Result<(), String> {
3102 match &self.operation_deferral {
3103 Some(operations) => decode_operation_deferral(
3104 self,
3105 &serde_json::to_value(operations).expect("serializable map"),
3106 )
3107 .map(|_| ()),
3108 None => Ok(()),
3109 }
3110 }
3111}
3112
3113pub fn validate_hello_operation_deferral(hello: &Value) -> Result<(), String> {
3115 let Some(manifest_value) = hello.get("manifest") else {
3116 return Ok(());
3117 };
3118 let Some(value) = manifest_value
3119 .get("operation_deferral")
3120 .filter(|v| !v.is_null())
3121 else {
3122 return Ok(());
3123 };
3124 let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
3125 return Ok(());
3126 };
3127 decode_operation_deferral(&manifest, value).map(|_| ())
3128}
3129
3130#[derive(Debug, Clone, PartialEq, Eq)]
3135#[non_exhaustive]
3136pub enum ConfirmOperationsError {
3137 NotAList,
3139 TooMany { count: usize },
3141 DuplicateOperation { operation: String },
3143 UnknownOperation { operation: String },
3145}
3146
3147impl fmt::Display for ConfirmOperationsError {
3148 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3149 match self {
3150 Self::NotAList => {
3151 f.write_str("confirm_operations must be an array of operation names")
3152 }
3153 Self::TooMany { count } => write!(
3154 f,
3155 "confirm_operations lists {count} names, more than {MAX_CONFIRM_OPERATIONS}"
3156 ),
3157 Self::DuplicateOperation { operation } => {
3158 write!(f, "confirm_operations names '{operation}' more than once")
3159 }
3160 Self::UnknownOperation { operation } => write!(
3161 f,
3162 "confirm_operations names '{operation}', which is not a declared management operation"
3163 ),
3164 }
3165 }
3166}
3167
3168impl std::error::Error for ConfirmOperationsError {}
3169
3170impl ModuleManifest {
3171 pub fn validate_confirm_operations(&self) -> Result<(), ConfirmOperationsError> {
3175 match &self.confirm_operations {
3176 Some(operations) => check_confirm_operations(self, operations),
3177 None => Ok(()),
3178 }
3179 }
3180}
3181
3182fn check_confirm_operations(
3183 manifest: &ModuleManifest,
3184 operations: &[String],
3185) -> Result<(), ConfirmOperationsError> {
3186 if operations.len() > MAX_CONFIRM_OPERATIONS {
3187 return Err(ConfirmOperationsError::TooMany {
3188 count: operations.len(),
3189 });
3190 }
3191 let mut seen = HashSet::new();
3192 for operation in operations {
3193 if !seen.insert(operation.as_str()) {
3194 return Err(ConfirmOperationsError::DuplicateOperation {
3195 operation: operation.clone(),
3196 });
3197 }
3198 if !declares_management_operation(&manifest.provides, operation) {
3199 return Err(ConfirmOperationsError::UnknownOperation {
3200 operation: operation.clone(),
3201 });
3202 }
3203 }
3204 Ok(())
3205}
3206
3207fn declares_management_operation(provides: &[ProviderRole], operation: &str) -> bool {
3208 provides.iter().any(|role| match role {
3209 ProviderRole::ManagementSurface { operations, .. } => {
3210 operations.iter().any(|op| op.name == operation)
3211 }
3212 _ => false,
3213 })
3214}
3215
3216fn decode_confirm_operations(
3219 manifest: &ModuleManifest,
3220 value: &Value,
3221) -> Result<Vec<String>, ConfirmOperationsError> {
3222 let operations: Vec<String> =
3223 serde_json::from_value(value.clone()).map_err(|_| ConfirmOperationsError::NotAList)?;
3224 check_confirm_operations(manifest, &operations)?;
3225 Ok(operations)
3226}
3227
3228pub fn validate_hello_confirm_operations(hello: &Value) -> Result<(), ConfirmOperationsError> {
3234 let Some(manifest_value) = hello.get("manifest") else {
3235 return Ok(());
3236 };
3237 let Some(value) = manifest_value
3238 .get("confirm_operations")
3239 .filter(|value| !value.is_null())
3240 else {
3241 return Ok(());
3242 };
3243 let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
3244 return Ok(());
3245 };
3246 decode_confirm_operations(&manifest, value).map(|_| ())
3247}
3248
3249#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3254pub struct ManagementOperation {
3255 pub name: String,
3256 pub kind: ManagementOperationKind,
3257 #[serde(default, skip_serializing_if = "Option::is_none")]
3258 pub description: Option<String>,
3259}
3260
3261#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3262#[serde(rename_all = "snake_case")]
3263pub enum ManagementOperationKind {
3264 Query,
3265 Mutate,
3266}
3267
3268#[derive(Debug, Clone, PartialEq, Eq)]
3271#[non_exhaustive]
3272pub enum OperationDelivery {
3273 Watch,
3274 Other(String),
3275}
3276
3277impl OperationDelivery {
3278 pub const WATCH: Self = Self::Watch;
3280
3281 pub fn wire_name(&self) -> &str {
3283 match self {
3284 Self::Watch => "watch",
3285 Self::Other(value) => value,
3286 }
3287 }
3288
3289 pub fn is_watch(&self) -> bool {
3291 self.wire_name() == "watch"
3292 }
3293}
3294
3295impl Serialize for OperationDelivery {
3296 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
3297 where
3298 S: serde::Serializer,
3299 {
3300 serializer.serialize_str(self.wire_name())
3301 }
3302}
3303
3304impl<'de> Deserialize<'de> for OperationDelivery {
3305 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3306 where
3307 D: Deserializer<'de>,
3308 {
3309 let value = String::deserialize(deserializer)?;
3310 Ok(if value == "watch" {
3311 Self::WATCH
3312 } else {
3313 Self::Other(value)
3314 })
3315 }
3316}
3317
3318#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3320pub struct ObservabilitySurface {
3321 pub name: String,
3322 pub kind: ObservabilityKind,
3323}
3324
3325#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3326#[serde(rename_all = "snake_case")]
3327pub enum ObservabilityKind {
3328 Snapshot,
3329 Stream,
3330}
3331
3332#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3333#[serde(rename_all = "snake_case")]
3334pub enum InternalTransport {
3335 Bulk,
3336}
3337
3338#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3340#[serde(tag = "role", rename_all = "snake_case")]
3341pub enum ConsumerRole {
3342 ToolClient { of: Vec<String> },
3343 LlmClient { via: String, auth: String },
3344 ServiceClient { of: Vec<String> },
3345}
3346
3347#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3349pub struct Bindings {
3350 pub storage: StorageBinding,
3351 pub vault_grants: Vec<VaultGrant>,
3352 pub identity: IdentityBinding,
3353}
3354
3355#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3357pub struct StorageBinding {
3358 pub kind: StorageKind,
3359 pub scope: StorageScope,
3360 pub owns_schema: bool,
3361}
3362
3363#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3364#[serde(rename_all = "snake_case")]
3365pub enum StorageKind {
3366 Sqlite,
3367}
3368
3369#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3370#[serde(rename_all = "snake_case")]
3371pub enum StorageScope {
3372 Project,
3373}
3374
3375#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3376pub struct VaultGrant {
3377 pub secret: String,
3378 pub reason: String,
3379}
3380
3381#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3382pub struct IdentityBinding {
3383 pub requires: Vec<IdentityScope>,
3384 pub optional: Vec<IdentityScope>,
3385}
3386
3387#[cfg(test)]
3388mod tests {
3389 use super::*;
3390 use serde_json::json;
3391
3392 fn aft_manifest_fixture() -> ModuleManifest {
3393 ModuleManifest::builder("aft", "0.39.2")
3394 .trust_tier(Some(TrustTier::FirstParty))
3395 .bindings(Some(Bindings {
3396 storage: StorageBinding {
3397 kind: StorageKind::Sqlite,
3398 scope: StorageScope::Project,
3399 owns_schema: true,
3400 },
3401 vault_grants: vec![VaultGrant {
3402 secret: "provider_api_key".to_string(),
3403 reason: "cortexkit_native auth".to_string(),
3404 }],
3405 identity: IdentityBinding {
3406 requires: vec![IdentityScope::Project],
3407 optional: vec![IdentityScope::Session],
3408 },
3409 }))
3410 .protocol_ver(1)
3411 .provides(vec![ProviderRole::ToolProvider {
3412 tools: vec![
3413 Tool {
3414 name: "read".to_string(),
3415 description: None,
3416 execution_mode: ExecutionMode::Pure,
3417 schema: json!({"type": "object"}),
3418 },
3419 Tool {
3420 name: "grep".to_string(),
3421 description: None,
3422 execution_mode: ExecutionMode::Pure,
3423 schema: json!({"type": "object"}),
3424 },
3425 Tool {
3426 name: "outline".to_string(),
3427 description: None,
3428 execution_mode: ExecutionMode::Pure,
3429 schema: json!({"type": "object"}),
3430 },
3431 Tool {
3432 name: "semantic_search".to_string(),
3433 description: None,
3434 execution_mode: ExecutionMode::Pure,
3435 schema: json!({"type": "object"}),
3436 },
3437 Tool {
3438 name: "edit".to_string(),
3439 description: None,
3440 execution_mode: ExecutionMode::Mutating,
3441 schema: json!({"type": "object"}),
3442 },
3443 Tool {
3444 name: "write".to_string(),
3445 description: None,
3446 execution_mode: ExecutionMode::Mutating,
3447 schema: json!({"type": "object"}),
3448 },
3449 Tool {
3450 name: "bash".to_string(),
3451 description: None,
3452 execution_mode: ExecutionMode::Unfenceable,
3453 schema: json!({"type": "object"}),
3454 },
3455 ],
3456 identity_scope: vec![IdentityScope::Session, IdentityScope::Project],
3457 concurrency: Concurrency::ModuleManaged,
3458 emits_push: true,
3459 sub_supervises: true,
3460 }])
3461 .consumes(vec![ConsumerRole::ServiceClient {
3462 of: vec!["embedding.v2".to_string()],
3463 }])
3464 .build()
3465 }
3466
3467 #[test]
3468 fn serde_round_trips_representative_manifest() {
3469 let manifest = aft_manifest_fixture();
3470 let serialized = serde_json::to_string_pretty(&manifest).unwrap();
3471 let decoded: ModuleManifest = serde_json::from_str(&serialized).unwrap();
3472
3473 assert_eq!(manifest, decoded);
3474 }
3475
3476 #[test]
3477 fn builder_defaults_additions_to_honest_absence_and_round_trips() {
3478 let manifest = ModuleManifest::builder("builder-defaults", "2.0.0").build();
3479
3480 assert_eq!(manifest.module_id, "builder-defaults");
3481 assert_eq!(manifest.module_version, "2.0.0");
3482 assert_eq!(manifest.display_name, None);
3483 assert_eq!(manifest.protocol_ver, PROTOCOL_VERSION);
3484 assert_eq!(manifest.trust_tier, None);
3485 assert!(manifest.provides.is_empty());
3486 assert!(manifest.consumes.is_empty());
3487 assert_eq!(manifest.bindings, None);
3488 assert_eq!(manifest.capabilities, None);
3489 assert_eq!(manifest.self_signals, None);
3490 assert_eq!(manifest.provenance, None);
3491
3492 let encoded = serde_json::to_value(&manifest).expect("builder manifest serializes");
3493 for optional in [
3494 "display_name",
3495 "trust_tier",
3496 "consumes",
3497 "bindings",
3498 "capabilities",
3499 "self_signals",
3500 "provenance",
3501 ] {
3502 assert!(
3503 encoded.get(optional).is_none(),
3504 "an absent {optional} declaration must stay absent on the wire"
3505 );
3506 }
3507 let decoded: ModuleManifest =
3508 serde_json::from_value(encoded).expect("builder manifest round-trips");
3509 assert_eq!(decoded, manifest);
3510 }
3511
3512 #[test]
3513 fn fully_populated_builder_manifest_matches_the_literal_wire_golden() {
3514 let manifest = ModuleManifest::builder("full-builder", "2.0.0")
3515 .display_name(Some("Example".to_string()))
3516 .unwrap()
3517 .hosts_third_party_code(false)
3518 .trust_tier(Some(TrustTier::Reviewed))
3519 .bindings(Some(Bindings {
3520 storage: StorageBinding {
3521 kind: StorageKind::Sqlite,
3522 scope: StorageScope::Project,
3523 owns_schema: false,
3524 },
3525 vault_grants: Vec::new(),
3526 identity: IdentityBinding {
3527 requires: vec![IdentityScope::Project],
3528 optional: Vec::new(),
3529 },
3530 }))
3531 .provides(vec![ProviderRole::ToolProvider {
3532 tools: vec![Tool {
3533 name: "read".to_string(),
3534 description: None,
3535 execution_mode: ExecutionMode::Pure,
3536 schema: json!({"type": "object"}),
3537 }],
3538 identity_scope: vec![IdentityScope::Project],
3539 concurrency: Concurrency::Serial,
3540 emits_push: false,
3541 sub_supervises: false,
3542 }])
3543 .consumes(vec![ConsumerRole::ServiceClient {
3544 of: vec!["embedding.v2".to_string()],
3545 }])
3546 .capabilities(Some(CapabilityDeclarations {
3547 provides: vec!["embedding/v2".to_string()],
3548 requires: Vec::new(),
3549 must_never_reach: Vec::new(),
3550 }))
3551 .self_signals(Some(vec![SelfSignalDeclaration {
3552 name: "usage_poller".to_string(),
3553 kind: SelfSignalKind::Poller,
3554 effect: SelfSignalEffect::Observe,
3555 anchored_to: SignalAnchor::FixedInterval,
3556 cadence: Some(SignalCadence::Literal {
3557 interval_ms: 60_000,
3558 }),
3559 domain: Some("provider-usage".to_string()),
3560 note: None,
3561 }]))
3562 .provenance(Some(ManifestProvenance {
3563 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
3564 build_git_sha_absence_reason: None,
3565 build_lock_digest: Some(
3566 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
3567 ),
3568 wire_crate_version: Some("0.16.0".to_string()),
3569 store_schema_version: Some("42".to_string()),
3570 launch_nonce_source: None,
3571 }))
3572 .build();
3573
3574 assert_eq!(
3575 serde_json::to_vec(&manifest).expect("builder manifest serializes"),
3576 include_bytes!("../tests/golden/module_manifest_builder_full.json"),
3577 "the builder must match the fully populated manifest wire bytes"
3578 );
3579 }
3580
3581 #[test]
3582 fn hosts_third_party_code_preserves_booleans_and_ignores_invalid_values() {
3583 let legacy =
3584 serde_json::to_value(ModuleManifest::builder("provider", "1.0.0").build()).unwrap();
3585 assert!(legacy.get("hosts_third_party_code").is_none());
3586 for (wire, expected) in [
3587 (json!(false), Some(false)),
3588 (json!(true), Some(true)),
3589 (json!(null), None),
3590 (json!("false"), None),
3591 (json!(0), None),
3592 ] {
3593 let mut manifest = legacy.clone();
3594 manifest["hosts_third_party_code"] = wire;
3595 let decoded: ModuleManifest = serde_json::from_value(manifest).unwrap();
3596 assert_eq!(decoded.hosts_third_party_code, expected);
3597 assert_eq!(
3598 serde_json::to_value(decoded)
3599 .unwrap()
3600 .get("hosts_third_party_code"),
3601 expected.map(|value| json!(value)).as_ref()
3602 );
3603 }
3604 }
3605
3606 #[test]
3607 fn display_name_validator_enforces_scalar_bounds_and_safe_text() {
3608 for valid in [
3609 "Routing".to_string(),
3610 "名".repeat(40),
3611 "a".repeat(40),
3612 "e\u{301}".repeat(20),
3613 ] {
3614 assert!(validate_display_name(&valid).is_ok(), "{valid:?}");
3615 }
3616 let mut invalid = vec![
3617 "".to_string(),
3618 "a".repeat(41),
3619 "名".repeat(41),
3620 " Routing".to_string(),
3621 "Routing ".to_string(),
3622 "\u{2003}Routing".to_string(),
3623 "a\nb".to_string(),
3624 "a\u{0085}b".to_string(),
3625 "a\u{007f}b".to_string(),
3626 ];
3627 for code in [0x061c, 0x200e, 0x200f]
3628 .into_iter()
3629 .chain(0x202a..=0x202e)
3630 .chain(0x2066..=0x2069)
3631 {
3632 invalid.push(format!("a{}b", char::from_u32(code).unwrap()));
3633 }
3634 let accepted: Vec<_> = invalid
3635 .iter()
3636 .filter(|value| validate_display_name(value).is_ok())
3637 .collect();
3638 assert!(
3639 accepted.is_empty(),
3640 "invalid display names accepted: {accepted:?}"
3641 );
3642 }
3643
3644 #[test]
3645 fn display_name_builder_refuses_invalid_value() {
3646 let error = ModuleManifest::builder("provider", "1.0.0")
3647 .display_name(Some(" Routing".to_string()))
3648 .unwrap_err();
3649 assert!(error.to_string().contains("display_name"));
3650 }
3651
3652 #[test]
3653 fn display_name_manifest_round_trips_and_keeps_unknown_fields_lenient() {
3654 let manifest = ModuleManifest::builder("provider", "1.0.0")
3655 .display_name(Some("Routing".to_string()))
3656 .unwrap()
3657 .build();
3658 let mut wire = serde_json::to_value(&manifest).unwrap();
3659 assert_eq!(wire["display_name"], "Routing");
3660 wire["future_manifest_field"] = json!(true);
3661 assert_eq!(
3662 serde_json::from_value::<ModuleManifest>(wire.clone()).unwrap(),
3663 manifest
3664 );
3665 wire["display_name"] = json!("bad\nname");
3666 assert!(serde_json::from_value::<ModuleManifest>(wire)
3667 .unwrap_err()
3668 .to_string()
3669 .contains("display_name"));
3670 }
3671
3672 #[test]
3673 fn icon_name_grammar_and_bounds() {
3674 for valid in ["1", "brain", "message-square", "shield-check", "a-0-b"] {
3675 assert!(validate_icon(valid).is_ok(), "{valid}");
3676 }
3677 assert!(validate_icon(&"a".repeat(64)).is_ok());
3678
3679 for invalid in [
3680 "",
3681 "Brain",
3682 "text icon",
3683 "text_icon",
3684 "-brain",
3685 "brain-",
3686 "message--square",
3687 "brain\n",
3688 "bräin",
3689 &"a".repeat(65),
3690 ] {
3691 let error = ModuleManifest::builder("provider", "1.0.0")
3692 .icon(invalid)
3693 .unwrap_err();
3694 assert!(error.to_string().contains("icon"), "{invalid:?}: {error}");
3695 }
3696 }
3697
3698 #[test]
3699 fn old_manifest_with_unread_fields_decodes_and_round_trips_verbatim() {
3700 let raw = include_bytes!("../tests/golden/module_manifest_builder_full.json");
3701 let decoded: ModuleManifest =
3702 serde_json::from_slice(raw).expect("old manifest with all unread fields decodes");
3703
3704 assert_eq!(decoded.trust_tier, Some(TrustTier::Reviewed));
3705 assert!(!decoded.consumes.is_empty());
3706 assert!(decoded.bindings.is_some());
3707
3708 let reencoded = serde_json::to_vec(&decoded).expect("re-encode succeeds");
3709 assert_eq!(
3710 reencoded, raw,
3711 "old manifest relay stays byte-for-byte verbatim"
3712 );
3713 }
3714
3715 #[test]
3716 fn new_manifest_omits_unread_fields_on_wire_and_decodes_cleanly() {
3717 let raw = include_bytes!("../tests/golden/module_manifest_diet.json");
3718 let decoded: ModuleManifest =
3719 serde_json::from_slice(raw).expect("new manifest omitting unread fields decodes");
3720
3721 assert_eq!(decoded.trust_tier, None);
3722 assert!(decoded.consumes.is_empty());
3723 assert_eq!(decoded.bindings, None);
3724
3725 let pretty = format!("{}\n", serde_json::to_string_pretty(&decoded).unwrap());
3726 assert_eq!(
3727 pretty.as_bytes(),
3728 raw,
3729 "new manifest matches golden byte-for-byte without unread keys"
3730 );
3731
3732 let as_val: serde_json::Value = serde_json::to_value(&decoded).unwrap();
3733 assert!(
3734 as_val.get("trust_tier").is_none(),
3735 "no trust_tier on wire for new manifest"
3736 );
3737 assert!(
3738 as_val.get("consumes").is_none(),
3739 "no consumes on wire for empty consumes"
3740 );
3741 assert!(
3742 as_val.get("bindings").is_none(),
3743 "no bindings on wire for new manifest"
3744 );
3745 }
3746
3747 #[test]
3748 fn aft_manifest_fixture_matches_v1_contract() {
3749 let manifest = aft_manifest_fixture();
3750
3751 assert_eq!(manifest.module_id, "aft");
3752 let ProviderRole::ToolProvider {
3753 tools,
3754 identity_scope,
3755 concurrency,
3756 emits_push,
3757 sub_supervises,
3758 } = &manifest.provides[0]
3759 else {
3760 panic!("AFT fixture must expose one tool_provider role");
3761 };
3762
3763 assert_eq!(*concurrency, Concurrency::ModuleManaged);
3764 assert!(*emits_push);
3765 assert!(*sub_supervises);
3766 assert_eq!(
3767 identity_scope,
3768 &vec![IdentityScope::Session, IdentityScope::Project]
3769 );
3770 assert_eq!(
3771 tools
3772 .iter()
3773 .map(|tool| (tool.name.as_str(), tool.execution_mode))
3774 .collect::<Vec<_>>(),
3775 vec![
3776 ("read", ExecutionMode::Pure),
3777 ("grep", ExecutionMode::Pure),
3778 ("outline", ExecutionMode::Pure),
3779 ("semantic_search", ExecutionMode::Pure),
3780 ("edit", ExecutionMode::Mutating),
3781 ("write", ExecutionMode::Mutating),
3782 ("bash", ExecutionMode::Unfenceable),
3783 ]
3784 );
3785 }
3786
3787 #[test]
3788 fn tool_provider_role_tag_serializes_as_snake_case() {
3789 let manifest = aft_manifest_fixture();
3790 let value = serde_json::to_value(&manifest).unwrap();
3791
3792 assert_eq!(value["provides"][0]["role"], "tool_provider");
3793 }
3794
3795 #[test]
3796 fn manifest_without_capabilities_preserves_the_existing_wire_shape() {
3797 let manifest = aft_manifest_fixture();
3798 let encoded = serde_json::to_value(&manifest).expect("manifest serializes");
3799 assert!(encoded.get("capabilities").is_none());
3800
3801 let decoded: ModuleManifest =
3802 serde_json::from_value(encoded).expect("legacy manifest parses");
3803 assert_eq!(decoded.capabilities, None);
3804 }
3805
3806 #[test]
3807 fn capability_identifier_lexical_grammar_accepts_only_pinned_forms() {
3808 for identifier in [
3809 "a/v1",
3810 "credentials-provider/v1",
3811 "a1-b2/v4294967295",
3812 "a123456789012345678901234567890123456789012345678901234567890123/v1",
3813 ] {
3814 assert!(
3815 is_valid_capability_identifier(identifier),
3816 "identifier must be accepted: {identifier}"
3817 );
3818 }
3819
3820 for identifier in [
3821 "credentials-Provider/v1",
3822 "credentials-provider/v01",
3823 "credentials-provider-/v1",
3824 "credentials--provider/v1",
3825 "Credentials-provider/v1",
3826 "credentials-provider/1",
3827 "credentials provider/v1",
3828 "credentials-provider/v0",
3829 "credentials-provider/v4294967296",
3830 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/v1",
3831 ] {
3832 assert!(
3833 !is_valid_capability_identifier(identifier),
3834 "identifier must be rejected: {identifier}"
3835 );
3836 }
3837 }
3838
3839 #[test]
3840 fn capability_grammar_errors_redact_secret_shaped_values() {
3841 let error = validate_manifest_capability_grammar(&json!({
3842 "capabilities": { "provides": ["sk-secret-value/v0"] }
3843 }))
3844 .expect_err("secret-shaped capability identifier is malformed");
3845 assert_eq!(error.field(), "capabilities.provides[0]");
3846 assert_eq!(error.value(), "<redacted>");
3847 assert!(!error.to_string().contains("sk-secret-value"));
3848 }
3849
3850 #[test]
3857 fn provenance_builder_sentinels_become_field_omission() {
3858 for sentinel in [
3859 "unknown",
3860 "UNKNOWN",
3861 "Unknown",
3862 "unavailable",
3863 "none",
3864 "None",
3865 " unknown ",
3866 "",
3867 ] {
3868 let p = build_provenance_from_source(
3869 BuildGitShaSource::Git {
3870 revision: sentinel,
3871 tree_state: GitTreeState::Clean,
3872 },
3873 Some(sentinel),
3874 Some(sentinel),
3875 )
3876 .expect("sentinels are omitted before form validation");
3877 assert_eq!(
3878 (
3879 p.build_git_sha,
3880 p.build_git_sha_absence_reason,
3881 p.build_lock_digest,
3882 p.store_schema_version,
3883 ),
3884 (
3885 None,
3886 Some(BuildGitShaAbsenceReason::NeverDerived),
3887 None,
3888 None,
3889 ),
3890 "sentinel {sentinel:?} must be omitted, not published"
3891 );
3892 }
3893 let real = build_provenance_from_source(
3894 BuildGitShaSource::Git {
3895 revision: "0123456789abcdef0123456789abcdef01234567",
3896 tree_state: GitTreeState::Clean,
3897 },
3898 None,
3899 Some("9"),
3900 )
3901 .expect("canonical build revision is accepted");
3902 assert_eq!(
3903 real.build_git_sha.as_deref(),
3904 Some("0123456789abcdef0123456789abcdef01234567")
3905 );
3906 assert_eq!(real.store_schema_version.as_deref(), Some("9"));
3907 assert_eq!(
3911 real.wire_crate_version.as_deref(),
3912 Some(crate::SUBC_PROTOCOL_CRATE_VERSION)
3913 );
3914 }
3915
3916 #[test]
3917 fn build_provenance_accepts_canonical_sha_and_lock_digest() {
3918 let provenance = build_provenance_from_source(
3919 BuildGitShaSource::Git {
3920 revision: " 0123456789abcdef0123456789abcdef01234567 ",
3921 tree_state: GitTreeState::Clean,
3922 },
3923 Some(" abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789 "),
3924 Some(" schema-v3 "),
3925 )
3926 .expect("canonical build facts are accepted");
3927
3928 assert_eq!(
3929 provenance,
3930 ManifestProvenance {
3931 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
3932 build_git_sha_absence_reason: None,
3933 build_lock_digest: Some(
3934 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
3935 ),
3936 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
3937 store_schema_version: Some("schema-v3".to_string()),
3938 launch_nonce_source: None,
3939 }
3940 );
3941 }
3942
3943 #[test]
3944 fn build_provenance_refuses_an_abbreviated_git_sha() {
3945 let error = build_provenance_from_source(
3946 BuildGitShaSource::Git {
3947 revision: "0123456789ab",
3948 tree_state: GitTreeState::Clean,
3949 },
3950 None,
3951 None,
3952 )
3953 .expect_err("a 12-character abbreviation is not canonical");
3954
3955 assert_eq!(error.field(), "build_git_sha");
3956 assert_eq!(error.length(), 12);
3957 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3958 assert_eq!(
3959 error.to_string(),
3960 "invalid manifest provenance form: field build_git_sha has length 12; canonical form is exactly 40 lowercase hexadecimal characters"
3961 );
3962 }
3963
3964 #[test]
3965 fn build_provenance_refuses_an_abbreviated_lock_digest() {
3966 let error = build_provenance_from_source(
3967 BuildGitShaSource::NeverDerived,
3968 Some("0123456789abcdef"),
3969 None,
3970 )
3971 .expect_err("a 16-character digest is not canonical");
3972
3973 assert_eq!(error.field(), "build_lock_digest");
3974 assert_eq!(error.length(), 16);
3975 assert_eq!(error.canonical_form(), BUILD_LOCK_DIGEST_CANONICAL_FORM);
3976 }
3977
3978 #[test]
3979 fn build_provenance_refuses_uppercase_hex() {
3980 let uppercase_sha = "A".repeat(40);
3981 let error = build_provenance_from_source(
3982 BuildGitShaSource::Git {
3983 revision: &uppercase_sha,
3984 tree_state: GitTreeState::Clean,
3985 },
3986 None,
3987 None,
3988 )
3989 .expect_err("uppercase hexadecimal is not canonical");
3990
3991 assert_eq!(error.field(), "build_git_sha");
3992 assert_eq!(error.length(), 40);
3993 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3994 }
3995
3996 #[test]
3997 fn build_provenance_refuses_dirty_revision_stamp_claimed_clean() {
3998 let error = build_provenance_from_source(
3999 BuildGitShaSource::Git {
4000 revision: "0123456789abcdef0123456789abcdef01234567-dirty",
4001 tree_state: GitTreeState::Clean,
4002 },
4003 None,
4004 None,
4005 )
4006 .expect_err("a dirty stamp is not a canonical build revision");
4007
4008 assert_eq!(error.field(), "build_git_sha");
4009 assert_eq!(error.length(), 46);
4010 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
4011 }
4012
4013 #[test]
4014 fn build_provenance_keeps_a_lock_digest_when_identity_is_unavailable() {
4015 let provenance = build_provenance_from_source(
4016 BuildGitShaSource::Git {
4017 revision: "unavailable",
4018 tree_state: GitTreeState::Clean,
4019 },
4020 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"),
4021 None,
4022 )
4023 .expect("sentinel SHA is omitted before the valid lock digest is checked");
4024
4025 assert_eq!(provenance.build_git_sha, None);
4026 assert_eq!(
4027 provenance.build_lock_digest,
4028 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string())
4029 );
4030 assert_eq!(
4031 provenance.wire_crate_version,
4032 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
4033 );
4034 }
4035
4036 #[test]
4037 fn build_provenance_omits_fully_unavailable_inputs() {
4038 let provenance = build_provenance_from_source(
4039 BuildGitShaSource::NeverDerived,
4040 Some(" unavailable "),
4041 Some(" "),
4042 )
4043 .expect("omitted and sentinel inputs are not form errors");
4044
4045 assert_eq!(provenance.build_git_sha, None);
4046 assert_eq!(provenance.build_lock_digest, None);
4047 assert_eq!(provenance.store_schema_version, None);
4048 assert_eq!(
4049 provenance.wire_crate_version,
4050 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
4051 );
4052 }
4053
4054 #[test]
4055 fn legacy_build_provenance_keeps_master_wire_bytes_without_an_absence_reason() {
4056 let revision = "0123456789abcdef0123456789abcdef01234567";
4057 for (input, expected) in [
4058 (
4059 Some(revision),
4060 format!(
4061 r#"{{"build_git_sha":"{revision}","wire_crate_version":"{}"}}"#,
4062 crate::SUBC_PROTOCOL_CRATE_VERSION
4063 ),
4064 ),
4065 (
4066 None,
4067 format!(
4068 r#"{{"wire_crate_version":"{}"}}"#,
4069 crate::SUBC_PROTOCOL_CRATE_VERSION
4070 ),
4071 ),
4072 (
4073 Some("unknown"),
4074 format!(
4075 r#"{{"wire_crate_version":"{}"}}"#,
4076 crate::SUBC_PROTOCOL_CRATE_VERSION
4077 ),
4078 ),
4079 ] {
4080 let provenance = build_provenance(input, None, None)
4081 .expect("the legacy build facts remain constructible");
4082 assert_eq!(provenance.build_git_sha_absence_reason, None);
4083 assert_eq!(
4084 serde_json::to_string(&provenance).expect("legacy provenance serializes"),
4085 expected
4086 );
4087 }
4088 }
4089
4090 #[test]
4091 fn build_provenance_derives_git_sha_absence_from_the_stamping_inputs() {
4092 let revision = "0123456789abcdef0123456789abcdef01234567";
4093 let cases = [
4094 (
4095 BuildGitShaSource::Git {
4096 revision,
4097 tree_state: GitTreeState::Clean,
4098 },
4099 Some(revision),
4100 None,
4101 ),
4102 (
4103 BuildGitShaSource::Git {
4104 revision,
4105 tree_state: GitTreeState::Dirty,
4106 },
4107 None,
4108 Some(BuildGitShaAbsenceReason::DeclinedDirty),
4109 ),
4110 (
4111 BuildGitShaSource::NeverDerived,
4112 None,
4113 Some(BuildGitShaAbsenceReason::NeverDerived),
4114 ),
4115 (
4116 BuildGitShaSource::NoGitDir,
4117 None,
4118 Some(BuildGitShaAbsenceReason::NoGitDir),
4119 ),
4120 ];
4121
4122 for (source, expected_sha, expected_reason) in cases {
4123 let provenance = build_provenance_from_source(source, None, None)
4124 .expect("every stamping state constructs honest provenance");
4125 assert_eq!(provenance.build_git_sha.as_deref(), expected_sha);
4126 assert_eq!(provenance.build_git_sha_absence_reason, expected_reason);
4127 }
4128 }
4129
4130 #[test]
4131 fn unknown_git_sha_absence_reason_round_trips_byte_faithfully() {
4132 let wire = format!(
4133 r#"{{"build_git_sha_absence_reason":"future_stamper_state","wire_crate_version":"{}"}}"#,
4134 crate::SUBC_PROTOCOL_CRATE_VERSION
4135 );
4136 let provenance: ManifestProvenance =
4137 serde_json::from_str(&wire).expect("future absence reasons remain readable");
4138
4139 assert_eq!(
4140 provenance.build_git_sha_absence_reason,
4141 Some(BuildGitShaAbsenceReason::ForwardCompatibleUnknown(
4142 "future_stamper_state".to_string()
4143 ))
4144 );
4145 assert_eq!(
4146 serde_json::to_string(&provenance).expect("future absence reason reserializes"),
4147 wire
4148 );
4149 }
4150
4151 #[test]
4152 fn provenance_rejects_an_absence_reason_beside_a_declared_commit() {
4153 let error = serde_json::from_value::<ManifestProvenance>(json!({
4154 "build_git_sha": "0123456789abcdef0123456789abcdef01234567",
4155 "build_git_sha_absence_reason": "declined_dirty"
4156 }))
4157 .expect_err("a declared commit cannot also claim an absence reason");
4158
4159 assert!(error.to_string().contains(
4160 "build_git_sha_absence_reason has must be omitted when build_git_sha is present"
4161 ));
4162 }
4163
4164 #[test]
4165 fn rich_ui_descriptor_is_optional_and_round_trips_when_present() {
4166 let manifest = ModuleManifest::builder("provider", "1.0.0").build();
4167 assert_eq!(
4168 serde_json::to_string(&manifest).unwrap(),
4169 r#"{"module_id":"provider","module_version":"1.0.0","protocol_ver":2,"provides":[]}"#
4170 );
4171
4172 let descriptor = RichUiDescriptor::new(
4173 "ckios.richui.manifest/1",
4174 format!("sha256:{}", "a".repeat(64)),
4175 128,
4176 2,
4177 );
4178 let manifest = ModuleManifest::builder("provider", "1.0.0")
4179 .rich_ui(Some(descriptor.clone()))
4180 .build();
4181 let wire = serde_json::to_string(&manifest).unwrap();
4182 assert!(wire.contains("\"rich_ui\":{\"schema\":\"ckios.richui.manifest/1\""));
4183 assert_eq!(
4184 serde_json::from_str::<ModuleManifest>(&wire)
4185 .unwrap()
4186 .rich_ui,
4187 Some(descriptor)
4188 );
4189 }
4190
4191 #[test]
4192 fn rich_ui_descriptor_validation_names_each_invalid_field() {
4193 let good = json!({
4194 "schema": "ckios.richui.manifest/1",
4195 "manifest_digest": format!("sha256:{}", "a".repeat(64)),
4196 "bytes": 1,
4197 "chunks": 1
4198 });
4199 let hello = json!({"manifest": {"rich_ui": good.clone()}});
4200 assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
4201
4202 for (field, value) in [
4203 ("schema", json!("bad schema")),
4204 (
4205 "manifest_digest",
4206 json!(format!("sha256:{}", "A".repeat(64))),
4207 ),
4208 ("bytes", json!(0)),
4209 ("chunks", json!(1025)),
4210 ] {
4211 let mut invalid = hello.clone();
4212 invalid["manifest"]["rich_ui"][field] = value;
4213 let error = validate_hello_rich_ui_descriptor(&invalid)
4214 .expect_err("an invalid descriptor field must be refused");
4215 assert_eq!(error.field(), format!("rich_ui.{field}"));
4216 }
4217
4218 let mut hello = hello;
4219 hello["manifest"]["rich_ui"] = Value::Null;
4220 let error = validate_hello_rich_ui_descriptor(&hello)
4221 .expect_err("null is not an absent descriptor");
4222 assert_eq!(error.field(), "rich_ui");
4223 }
4224
4225 #[test]
4226 fn rich_ui_descriptor_validation_accepts_inclusive_bounds() {
4227 let hello = json!({"manifest": {"rich_ui": {
4228 "schema": "a".repeat(64),
4229 "manifest_digest": format!("sha256:{}", "f".repeat(64)),
4230 "bytes": 16_777_216,
4231 "chunks": 1024
4232 }}});
4233 assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
4234 }
4235}