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