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 hosts_third_party_code: Option<bool>,
52 pub module_version: String,
53 pub protocol_ver: u8,
54 #[serde(default, skip_serializing_if = "Option::is_none")]
55 pub trust_tier: Option<TrustTier>,
56 #[serde(default, skip_serializing_if = "Option::is_none")]
63 pub ready: Option<bool>,
64 #[serde(default, skip_serializing_if = "Option::is_none")]
68 pub registration_channel: Option<bool>,
69 pub provides: Vec<ProviderRole>,
72 #[serde(default, skip_serializing_if = "Vec::is_empty")]
73 pub consumes: Vec<ConsumerRole>,
74 #[serde(default, skip_serializing_if = "Option::is_none")]
75 pub bindings: Option<Bindings>,
76 #[serde(default, skip_serializing_if = "Option::is_none")]
82 pub capabilities: Option<CapabilityDeclarations>,
83 #[serde(default, skip_serializing_if = "Option::is_none")]
97 pub events: Option<Vec<EventDeclaration>>,
98 #[serde(default, skip_serializing_if = "Option::is_none")]
133 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
134 #[serde(default, skip_serializing_if = "Option::is_none")]
135 pub provenance: Option<ManifestProvenance>,
136 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
141 pub operation_delivery: BTreeMap<String, OperationDelivery>,
142 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
144 pub operation_titles: BTreeMap<String, String>,
145 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
147 pub operation_groups: BTreeMap<String, OperationGroup>,
148 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
150 pub operation_requires: BTreeMap<String, Vec<String>>,
151 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
154 pub operation_payload: BTreeMap<String, OperationPayload>,
155 #[serde(default, skip_serializing_if = "Option::is_none")]
174 pub flow_operations: Option<Vec<String>>,
175 #[serde(default, skip_serializing_if = "Option::is_none")]
179 pub operation_deferral: Option<BTreeMap<String, bool>>,
180 #[serde(default, skip_serializing_if = "Option::is_none")]
197 pub confirm_operations: Option<Vec<String>>,
198 #[serde(default, skip_serializing_if = "Option::is_none")]
203 pub rich_ui: Option<RichUiDescriptor>,
204 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
213 pub role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
214 #[serde(default, skip_serializing_if = "Option::is_none")]
217 pub provider_declarations: Option<ProviderDeclarations>,
218}
219
220#[derive(Debug, Clone)]
222pub struct ModuleManifestBuilder {
223 module_id: String,
224 display_name: Option<String>,
225 hosts_third_party_code: Option<bool>,
226 module_version: String,
227 protocol_ver: u8,
228 trust_tier: Option<TrustTier>,
229 ready: Option<bool>,
230 registration_channel: Option<bool>,
231 provides: Vec<ProviderRole>,
232 consumes: Vec<ConsumerRole>,
233 bindings: Option<Bindings>,
234 capabilities: Option<CapabilityDeclarations>,
235 events: Option<Vec<EventDeclaration>>,
236 self_signals: Option<Vec<SelfSignalDeclaration>>,
237 provenance: Option<ManifestProvenance>,
238 operation_delivery: BTreeMap<String, OperationDelivery>,
239 operation_titles: BTreeMap<String, String>,
240 operation_groups: BTreeMap<String, OperationGroup>,
241 operation_requires: BTreeMap<String, Vec<String>>,
242 operation_payload: BTreeMap<String, OperationPayload>,
243 flow_operations: Option<Vec<String>>,
244 operation_deferral: Option<BTreeMap<String, bool>>,
245 confirm_operations: Option<Vec<String>>,
246 rich_ui: Option<RichUiDescriptor>,
247 role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
248 provider_declarations: Option<ProviderDeclarations>,
249}
250
251impl ModuleManifest {
252 pub fn builder(
260 module_id: impl Into<String>,
261 module_version: impl Into<String>,
262 ) -> ModuleManifestBuilder {
263 ModuleManifestBuilder {
264 module_id: module_id.into(),
265 display_name: None,
266 hosts_third_party_code: None,
267 module_version: module_version.into(),
268 protocol_ver: PROTOCOL_VERSION,
269 trust_tier: None,
270 ready: None,
271 registration_channel: None,
272 provides: Vec::new(),
273 consumes: Vec::new(),
274 bindings: None,
275 capabilities: None,
276 events: None,
277 self_signals: None,
278 provenance: None,
279 operation_delivery: BTreeMap::new(),
280 operation_titles: BTreeMap::new(),
281 operation_groups: BTreeMap::new(),
282 operation_requires: BTreeMap::new(),
283 operation_payload: BTreeMap::new(),
284 flow_operations: None,
285 operation_deferral: None,
286 confirm_operations: None,
287 rich_ui: None,
288 role_declarations: BTreeMap::new(),
289 provider_declarations: None,
290 }
291 }
292
293 pub fn is_watch_operation(&self, name: &str) -> bool {
298 self.operation_delivery
299 .get(name)
300 .is_some_and(OperationDelivery::is_watch)
301 && self.provides.iter().any(|role| match role {
302 ProviderRole::ManagementSurface { operations, .. } => operations
303 .iter()
304 .any(|op| op.name == name && op.kind == ManagementOperationKind::Query),
305 _ => false,
306 })
307 }
308}
309
310impl ModuleManifestBuilder {
311 pub fn display_name(mut self, display_name: Option<String>) -> Result<Self, DisplayNameError> {
313 if let Some(value) = &display_name {
314 validate_display_name(value)?;
315 }
316 self.display_name = display_name;
317 Ok(self)
318 }
319
320 pub fn hosts_third_party_code(mut self, hosts_third_party_code: bool) -> Self {
322 self.hosts_third_party_code = Some(hosts_third_party_code);
323 self
324 }
325
326 pub fn protocol_ver(mut self, protocol_ver: u8) -> Self {
328 self.protocol_ver = protocol_ver;
329 self
330 }
331
332 pub fn trust_tier(mut self, trust_tier: Option<TrustTier>) -> Self {
336 self.trust_tier = trust_tier;
337 self
338 }
339
340 pub fn ready(mut self, ready: bool) -> Self {
342 self.ready = Some(ready);
343 self
344 }
345
346 pub fn registration_channel(mut self, supported: bool) -> Self {
348 self.registration_channel = Some(supported);
349 self
350 }
351
352 pub fn provides(mut self, provides: Vec<ProviderRole>) -> Self {
354 self.provides = provides;
355 self
356 }
357
358 pub fn consumes(mut self, consumes: Vec<ConsumerRole>) -> Self {
360 self.consumes = consumes;
361 self
362 }
363
364 pub fn bindings(mut self, bindings: Option<Bindings>) -> Self {
368 self.bindings = bindings;
369 self
370 }
371
372 pub fn capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
374 self.capabilities = capabilities;
375 self
376 }
377
378 pub fn events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
380 self.events = events;
381 self
382 }
383
384 pub fn self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
386 self.self_signals = self_signals;
387 self
388 }
389
390 pub fn provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
392 self.provenance = provenance;
393 self
394 }
395
396 pub fn operation_delivery(
398 mut self,
399 operation_delivery: BTreeMap<String, OperationDelivery>,
400 ) -> Self {
401 self.operation_delivery = operation_delivery;
402 self
403 }
404
405 pub fn operation_title(
408 mut self,
409 name: impl Into<String>,
410 title: impl Into<String>,
411 ) -> Result<Self, OperationTitleError> {
412 let name = name.into();
413 let title = title.into();
414 validate_operation_title(&self.provides, &name, &title)?;
415 self.operation_titles.insert(name, title);
416 Ok(self)
417 }
418
419 pub fn operation_group(
422 mut self,
423 id: impl Into<String>,
424 group: OperationGroup,
425 ) -> Result<Self, OperationMetadataError> {
426 let id = id.into();
427 let assigned = self
428 .operation_groups
429 .iter()
430 .filter(|(other_id, _)| other_id.as_str() != id)
431 .flat_map(|(_, other)| other.operations.iter().map(String::as_str))
432 .collect();
433 validate_operation_group(&self.provides, &id, &group, &assigned)?;
434 self.operation_groups.insert(id, group);
435 Ok(self)
436 }
437
438 pub fn operation_requires(
441 mut self,
442 name: impl Into<String>,
443 requires: Vec<String>,
444 ) -> Result<Self, OperationMetadataError> {
445 let name = name.into();
446 validate_operation_requires(&self.provides, &name, &requires)?;
447 self.operation_requires.insert(name, requires);
448 Ok(self)
449 }
450
451 pub fn operation_payload(
453 mut self,
454 operation_payload: BTreeMap<String, OperationPayload>,
455 ) -> Self {
456 self.operation_payload = operation_payload;
457 self
458 }
459
460 pub fn flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
467 self.flow_operations = flow_operations;
468 self
469 }
470
471 pub fn operation_deferral(mut self, operations: Option<BTreeMap<String, bool>>) -> Self {
473 self.operation_deferral = operations;
474 self
475 }
476
477 pub fn confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
484 self.confirm_operations = confirm_operations;
485 self
486 }
487
488 pub fn rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
490 self.rich_ui = rich_ui;
491 self
492 }
493
494 pub fn role_declarations(
496 mut self,
497 role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
498 ) -> Self {
499 self.role_declarations = role_declarations;
500 self
501 }
502
503 pub fn provider_declarations(mut self, declarations: Option<ProviderDeclarations>) -> Self {
506 self.provider_declarations = declarations;
507 self
508 }
509
510 pub fn build(self) -> ModuleManifest {
512 ModuleManifest {
513 module_id: self.module_id,
514 display_name: self.display_name,
515 hosts_third_party_code: self.hosts_third_party_code,
516 module_version: self.module_version,
517 protocol_ver: self.protocol_ver,
518 trust_tier: self.trust_tier,
519 ready: self.ready,
520 registration_channel: self.registration_channel,
521 provides: self.provides,
522 consumes: self.consumes,
523 bindings: self.bindings,
524 capabilities: self.capabilities,
525 events: self.events,
526 self_signals: self.self_signals,
527 provenance: self.provenance,
528 operation_delivery: self.operation_delivery,
529 operation_titles: self.operation_titles,
530 operation_groups: self.operation_groups,
531 operation_requires: self.operation_requires,
532 operation_payload: self.operation_payload,
533 flow_operations: self.flow_operations,
534 operation_deferral: self.operation_deferral,
535 confirm_operations: self.confirm_operations,
536 rich_ui: self.rich_ui,
537 role_declarations: self.role_declarations,
538 provider_declarations: self.provider_declarations,
539 }
540 }
541}
542
543#[derive(Deserialize)]
563struct ModuleManifestWire {
564 module_id: String,
565 #[serde(default)]
566 display_name: Option<String>,
567 #[serde(default)]
568 hosts_third_party_code: Option<Value>,
569 module_version: String,
570 protocol_ver: u8,
571 #[serde(default)]
572 trust_tier: Option<TrustTier>,
573 #[serde(default)]
574 ready: Option<bool>,
575 #[serde(default)]
576 registration_channel: Option<bool>,
577 provides: Vec<ProviderRole>,
578 #[serde(default)]
579 consumes: Vec<ConsumerRole>,
580 #[serde(default)]
581 bindings: Option<Bindings>,
582 #[serde(default)]
583 capabilities: Option<CapabilityDeclarations>,
584 #[serde(default)]
585 events: Option<Value>,
586 #[serde(default)]
587 self_signals: Option<Vec<SelfSignalDeclaration>>,
588 #[serde(default)]
589 provenance: Option<ManifestProvenance>,
590 #[serde(default)]
591 operation_delivery: Option<Value>,
592 #[serde(default)]
593 operation_titles: BTreeMap<String, String>,
594 #[serde(default)]
595 operation_groups: BTreeMap<String, OperationGroup>,
596 #[serde(default)]
597 operation_requires: BTreeMap<String, Vec<String>>,
598 #[serde(default)]
599 operation_payload: BTreeMap<String, OperationPayload>,
600 #[serde(default)]
602 flow_operations: Option<Value>,
603 #[serde(default)]
604 operation_deferral: Option<Value>,
605 #[serde(default)]
607 confirm_operations: Option<Value>,
608 #[serde(default)]
609 rich_ui: Option<RichUiDescriptor>,
610 #[serde(default)]
614 runtime_computed: Option<Value>,
615 #[serde(default)]
616 role_declarations: Option<Value>,
617 #[serde(default, deserialize_with = "deserialize_provider_declarations")]
618 provider_declarations: Option<ProviderDeclarations>,
619}
620
621impl<'de> Deserialize<'de> for ModuleManifest {
622 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
623 where
624 D: Deserializer<'de>,
625 {
626 let wire = ModuleManifestWire::deserialize(deserializer)?;
627 validate_runtime_computed(wire.runtime_computed.as_ref(), "runtime_computed")
628 .map_err(D::Error::custom)?;
629 validate_events_value(wire.events.as_ref()).map_err(D::Error::custom)?;
630 let events = wire
631 .events
632 .map(serde_json::from_value)
633 .transpose()
634 .map_err(D::Error::custom)?;
635 let mut builder = Self::builder(wire.module_id, wire.module_version)
636 .display_name(wire.display_name)
637 .map_err(D::Error::custom)?
638 .protocol_ver(wire.protocol_ver)
639 .trust_tier(wire.trust_tier);
640 if let Some(hosts) = wire
641 .hosts_third_party_code
642 .as_ref()
643 .and_then(Value::as_bool)
644 {
645 builder = builder.hosts_third_party_code(hosts);
646 }
647 if let Some(ready) = wire.ready {
648 builder = builder.ready(ready);
649 }
650 if let Some(supported) = wire.registration_channel {
651 builder = builder.registration_channel(supported);
652 }
653 builder = builder.provides(wire.provides);
654 validate_operation_metadata(
655 &builder.provides,
656 &wire.operation_titles,
657 &wire.operation_groups,
658 &wire.operation_requires,
659 )
660 .map_err(D::Error::custom)?;
661 builder.operation_titles = wire.operation_titles;
662 builder.operation_groups = wire.operation_groups;
663 builder.operation_requires = wire.operation_requires;
664 let mut manifest = builder
665 .consumes(wire.consumes)
666 .bindings(wire.bindings)
667 .capabilities(wire.capabilities)
668 .events(events)
669 .self_signals(wire.self_signals)
670 .provenance(wire.provenance)
671 .operation_delivery(
672 wire.operation_delivery
673 .and_then(|value| serde_json::from_value(value).ok())
674 .unwrap_or_default(),
675 )
676 .rich_ui(wire.rich_ui)
677 .role_declarations(
678 wire.role_declarations
679 .filter(|value| validate_role_declarations_value(Some(value)).is_ok())
680 .and_then(|value| serde_json::from_value(value).ok())
681 .unwrap_or_default(),
682 )
683 .operation_payload(wire.operation_payload)
684 .provider_declarations(wire.provider_declarations)
685 .build();
686 manifest
687 .validate_operation_payload()
688 .map_err(D::Error::custom)?;
689 manifest.flow_operations = wire
692 .flow_operations
693 .and_then(|value| decode_flow_operations(&manifest, &value).ok());
694 manifest.operation_deferral = wire
695 .operation_deferral
696 .and_then(|value| decode_operation_deferral(&manifest, &value).ok());
697 manifest.confirm_operations = wire
698 .confirm_operations
699 .and_then(|value| decode_confirm_operations(&manifest, &value).ok());
700 manifest
701 .validate_capability_grammar()
702 .map_err(D::Error::custom)?;
703 if let Some(rich_ui) = &manifest.rich_ui {
704 rich_ui.validate().map_err(D::Error::custom)?;
705 }
706 Ok(manifest)
707 }
708}
709
710#[derive(Debug, Clone, PartialEq, Eq)]
712pub struct RoleDeclarationsError(&'static str);
713
714impl fmt::Display for RoleDeclarationsError {
715 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
716 f.write_str(self.0)
717 }
718}
719
720impl std::error::Error for RoleDeclarationsError {}
721
722pub fn validate_hello_role_declarations(hello: &Value) -> Result<(), RoleDeclarationsError> {
724 validate_role_declarations_value(
725 hello
726 .get("manifest")
727 .and_then(|manifest| manifest.get("role_declarations")),
728 )
729}
730
731pub fn validate_role_declarations_value(
734 value: Option<&Value>,
735) -> Result<(), RoleDeclarationsError> {
736 let Some(value) = value else {
737 return Ok(());
738 };
739 let map = value
740 .as_object()
741 .ok_or(RoleDeclarationsError("role_declarations must be an object"))?;
742 for (role, declaration) in map {
743 if !is_valid_capability_identifier(role) {
744 return Err(RoleDeclarationsError(
745 "role_declarations key must use capability-name grammar",
746 ));
747 }
748 if !declaration.is_object() {
749 return Err(RoleDeclarationsError(
750 "role_declarations values must be objects",
751 ));
752 }
753 }
754 let bytes = serde_json::to_vec(value)
755 .map_err(|_| RoleDeclarationsError("role_declarations could not be serialized"))?;
756 if bytes.len() > MAX_ROLE_DECLARATIONS_BYTES {
757 return Err(RoleDeclarationsError(
758 "role_declarations exceeds 16384 compact JSON bytes",
759 ));
760 }
761 Ok(())
762}
763
764#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
770#[non_exhaustive]
771pub struct RichUiDescriptor {
772 pub schema: String,
774 pub manifest_digest: String,
776 pub bytes: u64,
778 pub chunks: u32,
780}
781
782impl RichUiDescriptor {
783 pub fn new(
785 schema: impl Into<String>,
786 manifest_digest: impl Into<String>,
787 bytes: u64,
788 chunks: u32,
789 ) -> Self {
790 Self {
791 schema: schema.into(),
792 manifest_digest: manifest_digest.into(),
793 bytes,
794 chunks,
795 }
796 }
797
798 pub fn validate(&self) -> Result<(), RichUiDescriptorError> {
800 validate_rich_ui_fields(
801 &self.schema,
802 &self.manifest_digest,
803 self.bytes,
804 u64::from(self.chunks),
805 )
806 }
807}
808
809#[derive(Debug, Clone, PartialEq, Eq)]
811pub struct DisplayNameError(&'static str);
812
813impl fmt::Display for DisplayNameError {
814 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
815 write!(f, "invalid manifest display_name: {}", self.0)
816 }
817}
818
819impl std::error::Error for DisplayNameError {}
820
821pub fn validate_display_name(value: &str) -> Result<(), DisplayNameError> {
826 if value.trim() != value || !(1..=40).contains(&value.chars().count()) {
827 return Err(DisplayNameError(
828 "must be trimmed text of 1 to 40 characters",
829 ));
830 }
831 validate_plain_text(value, 40)
832}
833
834pub fn validate_module_id(module_id: &str) -> Result<(), String> {
836 if module_id.is_empty() {
837 return Err("empty".to_string());
838 }
839 if module_id.contains('/') || module_id.contains('\\') {
840 return Err("contains a path separator".to_string());
841 }
842 if module_id == "." || module_id == ".." {
843 return Err("is a dot path component".to_string());
844 }
845 if module_id.chars().any(|c| c.is_control()) {
846 return Err("contains a control character".to_string());
847 }
848 if module_id.len() > 255 {
849 return Err("is longer than 255 bytes".to_string());
850 }
851 Ok(())
852}
853
854pub(crate) fn validate_plain_text(value: &str, max: usize) -> Result<(), DisplayNameError> {
855 if value.is_empty() || value.chars().count() > max {
856 return Err(DisplayNameError(
857 "text length is outside the permitted bounds",
858 ));
859 }
860 if value.chars().any(|ch| {
861 ch.is_control()
862 || matches!(ch, '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')
863 }) {
864 return Err(DisplayNameError("must not contain control or bidi formatting characters"));
865 }
866 Ok(())
867}
868
869pub fn validate_hello_display_name(hello: &Value) -> Result<(), DisplayNameError> {
871 match hello
872 .get("manifest")
873 .and_then(|manifest| manifest.get("display_name"))
874 {
875 None | Some(Value::Null) => Ok(()),
876 Some(Value::String(value)) => validate_display_name(value),
877 Some(_) => Err(DisplayNameError("must be a string")),
878 }
879}
880
881#[derive(Debug, Clone, PartialEq, Eq)]
883pub struct OperationTitleError(&'static str);
884
885impl fmt::Display for OperationTitleError {
886 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
887 write!(f, "invalid manifest operation_titles: {}", self.0)
888 }
889}
890
891impl std::error::Error for OperationTitleError {}
892
893fn validate_operation_title(
894 provides: &[ProviderRole],
895 name: &str,
896 title: &str,
897) -> Result<(), OperationTitleError> {
898 validate_display_name(title).map_err(|error| OperationTitleError(error.0))?;
899 if !declares_management_operation(provides, name) {
900 return Err(OperationTitleError(
901 "keys must name declared management operations",
902 ));
903 }
904 Ok(())
905}
906
907#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
909#[non_exhaustive]
910pub struct OperationGroup {
911 pub title: String,
912 #[serde(default, skip_serializing_if = "Option::is_none")]
913 pub description: Option<String>,
914 pub operations: Vec<String>,
915}
916
917impl OperationGroup {
918 pub fn new(
921 title: impl Into<String>,
922 description: Option<String>,
923 operations: Vec<String>,
924 ) -> Self {
925 Self {
926 title: title.into(),
927 description,
928 operations,
929 }
930 }
931}
932
933#[derive(Debug, Clone, PartialEq, Eq)]
935pub struct OperationMetadataError {
936 field: &'static str,
937 reason: &'static str,
938}
939
940impl fmt::Display for OperationMetadataError {
941 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
942 write!(f, "invalid manifest {}: {}", self.field, self.reason)
943 }
944}
945
946impl std::error::Error for OperationMetadataError {}
947
948fn validate_operation_group(
949 provides: &[ProviderRole],
950 id: &str,
951 group: &OperationGroup,
952 assigned: &HashSet<&str>,
953) -> Result<(), OperationMetadataError> {
954 let invalid = |reason| OperationMetadataError {
955 field: "operation_groups",
956 reason,
957 };
958 if !(1..=40).contains(&id.len())
959 || !id
960 .bytes()
961 .all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'_'))
962 {
963 return Err(invalid(
964 "ids must contain 1 to 40 lowercase ASCII letters, digits or underscores",
965 ));
966 }
967 validate_display_name(&group.title).map_err(|error| invalid(error.0))?;
968 if group.operations.is_empty() {
969 return Err(invalid("each group must contain at least one operation"));
970 }
971 for operation in &group.operations {
972 if !declares_management_operation(provides, operation) {
973 return Err(invalid(
974 "groups may contain only declared management operations",
975 ));
976 }
977 if assigned.contains(operation.as_str()) {
978 return Err(invalid("an operation may belong to at most one group"));
979 }
980 }
981 Ok(())
982}
983
984fn validate_operation_requires(
985 provides: &[ProviderRole],
986 name: &str,
987 requires: &[String],
988) -> Result<(), OperationMetadataError> {
989 let invalid = |reason| OperationMetadataError {
990 field: "operation_requires",
991 reason,
992 };
993 if !declares_management_operation(provides, name) {
994 return Err(invalid("keys must name declared management operations"));
995 }
996 for dependency in requires {
997 if let Some((module_id, operation)) = dependency.split_once('/') {
998 if module_id.is_empty() || operation.is_empty() {
999 return Err(invalid(
1000 "foreign references must have a module id and operation name",
1001 ));
1002 }
1003 } else if dependency == name {
1004 return Err(invalid("an operation cannot require itself"));
1005 } else if !declares_management_operation(provides, dependency) {
1006 return Err(invalid(
1007 "local references must name declared management operations",
1008 ));
1009 }
1010 }
1011 Ok(())
1012}
1013
1014fn validate_operation_metadata(
1015 provides: &[ProviderRole],
1016 titles: &BTreeMap<String, String>,
1017 groups: &BTreeMap<String, OperationGroup>,
1018 requires: &BTreeMap<String, Vec<String>>,
1019) -> Result<(), OperationMetadataError> {
1020 for (name, title) in titles {
1021 validate_operation_title(provides, name, title).map_err(|error| {
1022 OperationMetadataError {
1023 field: "operation_titles",
1024 reason: error.0,
1025 }
1026 })?;
1027 }
1028 let mut assigned = HashSet::new();
1029 for (id, group) in groups {
1030 validate_operation_group(provides, id, group, &assigned)?;
1031 assigned.extend(group.operations.iter().map(String::as_str));
1032 }
1033 for (name, dependencies) in requires {
1034 validate_operation_requires(provides, name, dependencies)?;
1035 }
1036 Ok(())
1037}
1038
1039fn decode_hello_operation_map<T: serde::de::DeserializeOwned>(
1040 manifest: &Value,
1041 field: &'static str,
1042 reason: &'static str,
1043) -> Result<BTreeMap<String, T>, OperationMetadataError> {
1044 match manifest.get(field) {
1045 Some(value) => {
1046 BTreeMap::deserialize(value).map_err(|_| OperationMetadataError { field, reason })
1047 }
1048 None => Ok(BTreeMap::new()),
1049 }
1050}
1051
1052pub fn validate_hello_operation_metadata(hello: &Value) -> Result<(), OperationMetadataError> {
1054 let Some(manifest) = hello.get("manifest") else {
1055 return Ok(());
1056 };
1057 let titles = decode_hello_operation_map(
1058 manifest,
1059 "operation_titles",
1060 "must be an object with string titles",
1061 )?;
1062 let groups = decode_hello_operation_map(
1063 manifest,
1064 "operation_groups",
1065 "must be an object with group values",
1066 )?;
1067 let requires = decode_hello_operation_map(
1068 manifest,
1069 "operation_requires",
1070 "must be an object with lists of operation names",
1071 )?;
1072 if titles.is_empty() && groups.is_empty() && requires.is_empty() {
1073 return Ok(());
1074 }
1075 let Some(provides) = manifest
1077 .get("provides")
1078 .and_then(|value| Vec::<ProviderRole>::deserialize(value).ok())
1079 else {
1080 return Ok(());
1081 };
1082 validate_operation_metadata(&provides, &titles, &groups, &requires)
1083}
1084
1085#[derive(Debug, Clone, PartialEq, Eq)]
1087#[non_exhaustive]
1088pub struct RichUiDescriptorError {
1089 field: String,
1090 reason: &'static str,
1091}
1092
1093impl RichUiDescriptorError {
1094 fn new(field: impl Into<String>, reason: &'static str) -> Self {
1095 Self {
1096 field: field.into(),
1097 reason,
1098 }
1099 }
1100
1101 pub fn field(&self) -> &str {
1103 &self.field
1104 }
1105}
1106
1107impl fmt::Display for RichUiDescriptorError {
1108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1109 write!(
1110 f,
1111 "invalid rich_ui descriptor: field {} {}",
1112 self.field, self.reason
1113 )
1114 }
1115}
1116
1117impl std::error::Error for RichUiDescriptorError {}
1118
1119pub fn validate_hello_rich_ui_descriptor(hello: &Value) -> Result<(), RichUiDescriptorError> {
1121 let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
1122 return Ok(());
1123 };
1124 let Some(value) = manifest.get("rich_ui") else {
1125 return Ok(());
1126 };
1127 validate_rich_ui_descriptor_value(value)
1128}
1129
1130fn validate_rich_ui_descriptor_value(value: &Value) -> Result<(), RichUiDescriptorError> {
1131 let descriptor = value
1132 .as_object()
1133 .ok_or_else(|| RichUiDescriptorError::new("rich_ui", "must be an object"))?;
1134 let schema = descriptor
1135 .get("schema")
1136 .and_then(Value::as_str)
1137 .ok_or_else(|| RichUiDescriptorError::new("rich_ui.schema", "must be a string"))?;
1138 let digest = descriptor
1139 .get("manifest_digest")
1140 .and_then(Value::as_str)
1141 .ok_or_else(|| RichUiDescriptorError::new("rich_ui.manifest_digest", "must be a string"))?;
1142 let bytes = descriptor
1143 .get("bytes")
1144 .and_then(Value::as_u64)
1145 .ok_or_else(|| {
1146 RichUiDescriptorError::new("rich_ui.bytes", "must be an integer from 1 to 16777216")
1147 })?;
1148 let chunks = descriptor
1149 .get("chunks")
1150 .and_then(Value::as_u64)
1151 .ok_or_else(|| {
1152 RichUiDescriptorError::new("rich_ui.chunks", "must be an integer from 1 to 1024")
1153 })?;
1154 validate_rich_ui_fields(schema, digest, bytes, chunks)
1155}
1156
1157fn validate_rich_ui_fields(
1158 schema: &str,
1159 digest: &str,
1160 bytes: u64,
1161 chunks: u64,
1162) -> Result<(), RichUiDescriptorError> {
1163 if !(1..=64).contains(&schema.len())
1164 || !schema.bytes().all(|byte| {
1165 byte.is_ascii_lowercase()
1166 || byte.is_ascii_digit()
1167 || matches!(byte, b'.' | b'_' | b'/' | b'-')
1168 })
1169 {
1170 return Err(RichUiDescriptorError::new(
1171 "rich_ui.schema",
1172 "must be 1 to 64 bytes of [a-z0-9._/-]",
1173 ));
1174 }
1175 if !digest.strip_prefix("sha256:").is_some_and(|hex| {
1176 hex.len() == 64
1177 && hex
1178 .bytes()
1179 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1180 }) {
1181 return Err(RichUiDescriptorError::new(
1182 "rich_ui.manifest_digest",
1183 "must be sha256: followed by 64 lowercase hexadecimal characters",
1184 ));
1185 }
1186 if !(1..=16_777_216).contains(&bytes) {
1187 return Err(RichUiDescriptorError::new(
1188 "rich_ui.bytes",
1189 "must be an integer from 1 to 16777216",
1190 ));
1191 }
1192 if !(1..=1_024).contains(&chunks) {
1193 return Err(RichUiDescriptorError::new(
1194 "rich_ui.chunks",
1195 "must be an integer from 1 to 1024",
1196 ));
1197 }
1198 Ok(())
1199}
1200
1201pub const CAP_CATALOG_EVENTS_V1: &str = "catalog-events/v1";
1207
1208pub const CAP_SCOPE_BIND_PROOF_V1: &str = "scope-bind-proof/v1";
1212
1213pub const CAP_SCOPE_BIND_PROOF_V2: &str = "scope-bind-proof/v2";
1217
1218pub const CAP_SCOPE_REPLACE_IF_IDLE_V1: &str = "scope-replace-if-idle/v1";
1220
1221#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1223#[non_exhaustive]
1224pub struct EventDeclaration {
1225 pub name: String,
1232 pub version: u32,
1234 pub headers: Vec<String>,
1239 #[serde(default, skip_serializing_if = "Option::is_none")]
1241 pub summary: Option<String>,
1242}
1243
1244impl EventDeclaration {
1245 pub fn new(name: impl Into<String>, version: u32) -> Self {
1248 Self {
1249 name: name.into(),
1250 version,
1251 headers: Vec::new(),
1252 summary: None,
1253 }
1254 }
1255
1256 pub fn with_headers(mut self, headers: Vec<String>) -> Self {
1258 self.headers = headers;
1259 self
1260 }
1261
1262 pub fn with_summary(mut self, summary: Option<String>) -> Self {
1264 self.summary = summary;
1265 self
1266 }
1267}
1268
1269#[derive(Debug, Clone, PartialEq, Eq)]
1271#[non_exhaustive]
1272pub struct EventDeclarationError {
1273 field: String,
1274 reason: &'static str,
1275}
1276
1277impl EventDeclarationError {
1278 fn new(field: impl Into<String>, reason: &'static str) -> Self {
1279 Self {
1280 field: field.into(),
1281 reason,
1282 }
1283 }
1284
1285 pub fn field(&self) -> &str {
1287 &self.field
1288 }
1289}
1290
1291impl fmt::Display for EventDeclarationError {
1292 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1293 write!(
1294 f,
1295 "invalid event declaration: field {} {}",
1296 self.field, self.reason
1297 )
1298 }
1299}
1300
1301impl std::error::Error for EventDeclarationError {}
1302
1303pub fn validate_hello_event_declarations(hello: &Value) -> Result<(), EventDeclarationError> {
1305 validate_events_value(
1306 hello
1307 .get("manifest")
1308 .and_then(|manifest| manifest.get("events")),
1309 )
1310}
1311
1312fn is_valid_event_name(name: &str) -> bool {
1315 let level_count = name.split('.').count();
1316 (1..=4).contains(&level_count)
1317 && name.split('.').all(|level| {
1318 if level.is_empty() {
1319 return false;
1320 }
1321 let first = level.as_bytes()[0];
1322 (1..=63).contains(&level.len())
1323 && (first.is_ascii_lowercase() || first.is_ascii_digit())
1324 && level
1325 .bytes()
1326 .skip(1)
1327 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
1328 && !level.strip_prefix('v').is_some_and(|digits| {
1329 !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit())
1330 })
1331 })
1332}
1333
1334fn validate_events_value(value: Option<&Value>) -> Result<(), EventDeclarationError> {
1335 let Some(value) = value.filter(|value| !value.is_null()) else {
1336 return Ok(());
1337 };
1338 let entries = value
1339 .as_array()
1340 .ok_or_else(|| EventDeclarationError::new("events", "must be a list"))?;
1341 if entries.len() > 64 {
1342 return Err(EventDeclarationError::new(
1343 "events",
1344 "must contain at most 64 declarations",
1345 ));
1346 }
1347 let mut pairs = HashSet::new();
1348 for (index, entry) in entries.iter().enumerate() {
1349 let field = format!("events[{index}]");
1350 let entry = entry
1351 .as_object()
1352 .ok_or_else(|| EventDeclarationError::new(&field, "must be an object"))?;
1353 let name_field = format!("{field}.name");
1354 let name = entry
1355 .get("name")
1356 .and_then(Value::as_str)
1357 .ok_or_else(|| EventDeclarationError::new(&name_field, "must be a string"))?;
1358 if !is_valid_event_name(name) {
1359 return Err(EventDeclarationError::new(
1360 name_field,
1361 "must contain one to four valid dot-separated event-name levels",
1362 ));
1363 }
1364 let version = entry
1365 .get("version")
1366 .and_then(Value::as_u64)
1367 .filter(|version| (1..=u32::MAX as u64).contains(version))
1368 .ok_or_else(|| {
1369 EventDeclarationError::new(
1370 format!("{field}.version"),
1371 "must be an integer between 1 and u32::MAX",
1372 )
1373 })?;
1374 if !pairs.insert((name, version)) {
1375 return Err(EventDeclarationError::new(
1376 &field,
1377 "duplicates an event (name, version) pair",
1378 ));
1379 }
1380 let headers_field = format!("{field}.headers");
1381 let headers = entry
1382 .get("headers")
1383 .and_then(Value::as_array)
1384 .ok_or_else(|| EventDeclarationError::new(&headers_field, "must be a list"))?;
1385 if headers.len() > 16 {
1386 return Err(EventDeclarationError::new(
1387 headers_field,
1388 "must contain at most 16 headers",
1389 ));
1390 }
1391 let mut names = HashSet::new();
1392 for (header_index, header) in headers.iter().enumerate() {
1393 let header_field = format!("{headers_field}[{header_index}]");
1394 let header = header
1395 .as_str()
1396 .ok_or_else(|| EventDeclarationError::new(&header_field, "must be a string"))?;
1397 if !(1..=32).contains(&header.len())
1398 || !header.as_bytes()[0].is_ascii_lowercase()
1399 || !header
1400 .bytes()
1401 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
1402 {
1403 return Err(EventDeclarationError::new(
1404 header_field,
1405 "must match [a-z][a-z0-9_]{0,31}",
1406 ));
1407 }
1408 if !names.insert(header) {
1409 return Err(EventDeclarationError::new(
1410 header_field,
1411 "duplicates a header name",
1412 ));
1413 }
1414 }
1415 if let Some(summary) = entry.get("summary").filter(|value| !value.is_null()) {
1416 let summary_field = format!("{field}.summary");
1417 let summary = summary
1418 .as_str()
1419 .ok_or_else(|| EventDeclarationError::new(&summary_field, "must be a string"))?;
1420 if summary.chars().count() > 200 || summary.chars().any(char::is_control) {
1421 return Err(EventDeclarationError::new(
1422 summary_field,
1423 "must contain at most 200 characters and no control characters",
1424 ));
1425 }
1426 }
1427 }
1428 Ok(())
1429}
1430
1431#[derive(Debug, Clone, PartialEq, Eq)]
1433pub struct SelfSignalDeclarationError {
1434 module_id: String,
1435 entry_index: usize,
1436 field: &'static str,
1437}
1438
1439impl fmt::Display for SelfSignalDeclarationError {
1440 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1441 write!(
1442 f,
1443 "module_id '{}' self_signals[{}] is missing required field '{}'",
1444 self.module_id.escape_debug(),
1445 self.entry_index,
1446 self.field
1447 )
1448 }
1449}
1450
1451pub fn validate_hello_self_signal_declarations(
1458 hello: &Value,
1459) -> Result<(), SelfSignalDeclarationError> {
1460 let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
1461 return Ok(());
1462 };
1463 let module_id = manifest
1464 .get("module_id")
1465 .and_then(Value::as_str)
1466 .unwrap_or("<unknown>");
1467 let Some(entries) = manifest.get("self_signals").and_then(Value::as_array) else {
1468 return Ok(());
1469 };
1470
1471 for (entry_index, entry) in entries.iter().enumerate() {
1472 let Some(entry) = entry.as_object() else {
1473 continue;
1474 };
1475 for field in ["effect", "anchored_to"] {
1476 if !entry.contains_key(field) {
1477 return Err(SelfSignalDeclarationError {
1478 module_id: module_id.to_string(),
1479 entry_index,
1480 field,
1481 });
1482 }
1483 }
1484 }
1485 Ok(())
1486}
1487
1488#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1490#[serde(deny_unknown_fields)]
1491pub struct CapabilityDeclarations {
1492 #[serde(default)]
1493 pub provides: Vec<String>,
1494 #[serde(default)]
1495 pub requires: Vec<CapabilityRequirement>,
1496 #[serde(default)]
1497 pub must_never_reach: Vec<String>,
1498}
1499
1500#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1502pub struct SelfSignalDeclaration {
1503 pub name: String,
1505 pub kind: SelfSignalKind,
1533 pub effect: SelfSignalEffect,
1535 pub anchored_to: SignalAnchor,
1537 #[serde(default, skip_serializing_if = "Option::is_none")]
1544 pub cadence: Option<SignalCadence>,
1545 #[serde(default, skip_serializing_if = "Option::is_none")]
1547 pub domain: Option<String>,
1548 #[serde(default, skip_serializing_if = "Option::is_none")]
1549 pub note: Option<String>,
1550}
1551
1552#[derive(Debug, Clone, PartialEq, Eq)]
1554pub enum SelfSignalKind {
1555 Keepalive,
1556 Busy,
1558 Poller,
1559 Cron,
1560 Sweep,
1561 Watchdog,
1562 Heartbeat,
1563 Other(String),
1564}
1565
1566impl SelfSignalKind {
1567 fn wire_name(&self) -> &str {
1568 match self {
1569 Self::Keepalive => "keepalive",
1570 Self::Busy => "busy",
1571 Self::Poller => "poller",
1572 Self::Cron => "cron",
1573 Self::Sweep => "sweep",
1574 Self::Watchdog => "watchdog",
1575 Self::Heartbeat => "heartbeat",
1576 Self::Other(value) => value,
1577 }
1578 }
1579}
1580
1581impl Serialize for SelfSignalKind {
1582 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1583 where
1584 S: serde::Serializer,
1585 {
1586 serializer.serialize_str(self.wire_name())
1587 }
1588}
1589
1590impl<'de> Deserialize<'de> for SelfSignalKind {
1591 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1592 where
1593 D: Deserializer<'de>,
1594 {
1595 let value = String::deserialize(deserializer)?;
1596 Ok(match value.as_str() {
1597 "keepalive" => Self::Keepalive,
1598 "busy" => Self::Busy,
1599 "poller" => Self::Poller,
1600 "cron" => Self::Cron,
1601 "sweep" => Self::Sweep,
1602 "watchdog" => Self::Watchdog,
1603 "heartbeat" => Self::Heartbeat,
1604 _ => Self::Other(value),
1605 })
1606 }
1607}
1608
1609#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1611#[serde(rename_all = "lowercase")]
1612pub enum SelfSignalEffect {
1613 Observe,
1614 Mutate,
1615}
1616
1617#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1619#[serde(rename_all = "snake_case")]
1620pub enum SignalAnchor {
1621 FixedInterval,
1624 Event { event: String },
1627 HealthGauges { gauges: Vec<String> },
1629}
1630
1631#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1633#[serde(rename_all = "snake_case")]
1634pub enum SignalCadence {
1635 Literal { interval_ms: u64 },
1636 Derived { source: String },
1637}
1638
1639#[derive(Serialize, Debug, Clone, Default, PartialEq, Eq)]
1716#[non_exhaustive]
1717pub struct ManifestProvenance {
1718 #[serde(default, skip_serializing_if = "Option::is_none")]
1719 pub build_git_sha: Option<String>,
1720 #[serde(default, skip_serializing_if = "Option::is_none")]
1724 pub build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1725 #[serde(default, skip_serializing_if = "Option::is_none")]
1726 pub build_lock_digest: Option<String>,
1727 #[serde(default, skip_serializing_if = "Option::is_none")]
1736 pub wire_crate_version: Option<String>,
1737 #[serde(default, skip_serializing_if = "Option::is_none")]
1738 pub store_schema_version: Option<String>,
1739 #[serde(default, skip_serializing_if = "Option::is_none")]
1745 pub launch_nonce_source: Option<LaunchNonceSource>,
1746}
1747
1748#[derive(Debug, Clone, PartialEq, Eq)]
1755#[non_exhaustive]
1756pub enum LaunchNonceSource {
1757 Fd,
1759 Pipe,
1761 Env,
1763 ForwardCompatibleUnknown(String),
1764}
1765
1766impl LaunchNonceSource {
1767 pub fn wire_name(&self) -> &str {
1769 match self {
1770 Self::Fd => "fd",
1771 Self::Pipe => "pipe",
1772 Self::Env => "env",
1773 Self::ForwardCompatibleUnknown(value) => value,
1774 }
1775 }
1776
1777 pub fn from_wire_name(value: &str) -> Self {
1779 match value {
1780 "fd" => Self::Fd,
1781 "pipe" => Self::Pipe,
1782 "env" => Self::Env,
1783 _ => Self::ForwardCompatibleUnknown(value.to_string()),
1784 }
1785 }
1786}
1787
1788impl Serialize for LaunchNonceSource {
1789 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1790 where
1791 S: serde::Serializer,
1792 {
1793 serializer.serialize_str(self.wire_name())
1794 }
1795}
1796
1797impl<'de> Deserialize<'de> for LaunchNonceSource {
1798 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1799 where
1800 D: serde::Deserializer<'de>,
1801 {
1802 let value = String::deserialize(deserializer)?;
1803 Ok(Self::from_wire_name(&value))
1804 }
1805}
1806
1807#[derive(Debug, Clone, PartialEq, Eq)]
1812pub enum BuildGitShaAbsenceReason {
1813 DeclinedDirty,
1814 NeverDerived,
1815 NoGitDir,
1816 ForwardCompatibleUnknown(String),
1817}
1818
1819impl BuildGitShaAbsenceReason {
1820 fn wire_name(&self) -> &str {
1821 match self {
1822 Self::DeclinedDirty => "declined_dirty",
1823 Self::NeverDerived => "never_derived",
1824 Self::NoGitDir => "no_git_dir",
1825 Self::ForwardCompatibleUnknown(value) => value,
1826 }
1827 }
1828}
1829
1830impl Serialize for BuildGitShaAbsenceReason {
1831 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1832 where
1833 S: serde::Serializer,
1834 {
1835 serializer.serialize_str(self.wire_name())
1836 }
1837}
1838
1839impl<'de> Deserialize<'de> for BuildGitShaAbsenceReason {
1840 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1841 where
1842 D: serde::Deserializer<'de>,
1843 {
1844 let value = String::deserialize(deserializer)?;
1845 Ok(match value.as_str() {
1846 "declined_dirty" => Self::DeclinedDirty,
1847 "never_derived" => Self::NeverDerived,
1848 "no_git_dir" => Self::NoGitDir,
1849 _ => Self::ForwardCompatibleUnknown(value),
1850 })
1851 }
1852}
1853
1854#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1856pub enum GitTreeState {
1857 Clean,
1858 Dirty,
1859}
1860
1861#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1866pub enum BuildGitShaSource<'a> {
1867 Git {
1868 revision: &'a str,
1869 tree_state: GitTreeState,
1870 },
1871 NeverDerived,
1872 NoGitDir,
1873}
1874
1875pub fn attestable_commit(revision: &str, tree_state: GitTreeState) -> Option<&str> {
1879 match tree_state {
1880 GitTreeState::Clean => Some(revision),
1881 GitTreeState::Dirty => None,
1882 }
1883}
1884
1885const MAX_PROVENANCE_VALUE_BYTES: usize = 128;
1886const BUILD_GIT_SHA_CANONICAL_FORM: &str = "exactly 40 lowercase hexadecimal characters";
1887const BUILD_LOCK_DIGEST_CANONICAL_FORM: &str = "exactly 64 lowercase hexadecimal characters";
1888
1889#[derive(Deserialize)]
1890struct ManifestProvenanceWire {
1891 #[serde(default)]
1892 build_git_sha: Option<String>,
1893 #[serde(default)]
1894 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1895 #[serde(default)]
1896 build_lock_digest: Option<String>,
1897 #[serde(default)]
1898 wire_crate_version: Option<String>,
1899 #[serde(default)]
1900 store_schema_version: Option<String>,
1901 #[serde(default)]
1902 launch_nonce_source: Option<LaunchNonceSource>,
1903}
1904
1905impl<'de> Deserialize<'de> for ManifestProvenance {
1906 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1907 where
1908 D: Deserializer<'de>,
1909 {
1910 let wire = ManifestProvenanceWire::deserialize(deserializer)?;
1911 let provenance = Self {
1912 build_git_sha: wire.build_git_sha,
1913 build_git_sha_absence_reason: wire.build_git_sha_absence_reason,
1914 build_lock_digest: wire.build_lock_digest,
1915 wire_crate_version: wire.wire_crate_version,
1916 store_schema_version: wire.store_schema_version,
1917 launch_nonce_source: wire.launch_nonce_source,
1918 };
1919 provenance.validate().map_err(D::Error::custom)?;
1920 Ok(provenance)
1921 }
1922}
1923
1924#[derive(Debug, Clone, PartialEq, Eq)]
1926pub struct ProvenanceFormError {
1927 field: &'static str,
1928 length: usize,
1929 canonical_form: &'static str,
1930}
1931
1932impl ProvenanceFormError {
1933 fn new(field: &'static str, length: usize, canonical_form: &'static str) -> Self {
1934 Self {
1935 field,
1936 length,
1937 canonical_form,
1938 }
1939 }
1940
1941 pub fn field(&self) -> &str {
1943 self.field
1944 }
1945
1946 pub fn length(&self) -> usize {
1948 self.length
1949 }
1950
1951 pub fn canonical_form(&self) -> &str {
1953 self.canonical_form
1954 }
1955}
1956
1957impl fmt::Display for ProvenanceFormError {
1958 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1959 write!(
1960 f,
1961 "invalid manifest provenance form: field {} has length {}; canonical form is {}",
1962 self.field, self.length, self.canonical_form
1963 )
1964 }
1965}
1966
1967impl std::error::Error for ProvenanceFormError {}
1968
1969#[derive(Debug, Clone, PartialEq, Eq)]
1970pub struct ManifestProvenanceError {
1971 field: String,
1972 value: String,
1973 reason: &'static str,
1974}
1975
1976impl ManifestProvenanceError {
1977 fn new(field: &str, value: &str, reason: &'static str) -> Self {
1978 Self {
1979 field: field.to_string(),
1980 value: safe_error_value(value),
1981 reason,
1982 }
1983 }
1984
1985 pub fn field(&self) -> &str {
1986 &self.field
1987 }
1988}
1989
1990impl fmt::Display for ManifestProvenanceError {
1991 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1992 write!(
1993 f,
1994 "invalid manifest provenance: field {} has {} (value {:?})",
1995 self.field, self.reason, self.value
1996 )
1997 }
1998}
1999
2000impl std::error::Error for ManifestProvenanceError {}
2001
2002impl ManifestProvenance {
2003 pub fn new() -> Self {
2005 Self::default()
2006 }
2007
2008 pub fn with_build_git_sha(mut self, value: Option<String>) -> Self {
2009 self.build_git_sha = value;
2010 self
2011 }
2012
2013 pub fn with_build_git_sha_absence_reason(
2014 mut self,
2015 value: Option<BuildGitShaAbsenceReason>,
2016 ) -> Self {
2017 self.build_git_sha_absence_reason = value;
2018 self
2019 }
2020
2021 pub fn with_build_lock_digest(mut self, value: Option<String>) -> Self {
2022 self.build_lock_digest = value;
2023 self
2024 }
2025
2026 pub fn with_wire_crate_version(mut self, value: Option<String>) -> Self {
2027 self.wire_crate_version = value;
2028 self
2029 }
2030
2031 pub fn with_store_schema_version(mut self, value: Option<String>) -> Self {
2032 self.store_schema_version = value;
2033 self
2034 }
2035
2036 pub fn with_launch_nonce_source(mut self, value: Option<LaunchNonceSource>) -> Self {
2041 self.launch_nonce_source = value;
2042 self
2043 }
2044
2045 pub fn validate(&self) -> Result<(), ManifestProvenanceError> {
2046 if let (Some(_), Some(reason)) = (
2047 self.build_git_sha.as_ref(),
2048 self.build_git_sha_absence_reason.as_ref(),
2049 ) {
2050 return Err(ManifestProvenanceError::new(
2051 "build_git_sha_absence_reason",
2052 reason.wire_name(),
2053 "must be omitted when build_git_sha is present",
2054 ));
2055 }
2056 for (field, value) in [
2057 ("build_git_sha", self.build_git_sha.as_deref()),
2058 (
2059 "build_git_sha_absence_reason",
2060 self.build_git_sha_absence_reason
2061 .as_ref()
2062 .map(|reason| reason.wire_name()),
2063 ),
2064 ("build_lock_digest", self.build_lock_digest.as_deref()),
2065 ("wire_crate_version", self.wire_crate_version.as_deref()),
2066 ("store_schema_version", self.store_schema_version.as_deref()),
2067 (
2068 "launch_nonce_source",
2069 self.launch_nonce_source
2070 .as_ref()
2071 .map(|source| source.wire_name()),
2072 ),
2073 ] {
2074 let Some(value) = value else { continue };
2075 if value.is_empty() {
2076 return Err(ManifestProvenanceError::new(
2077 field,
2078 value,
2079 "must not be empty",
2080 ));
2081 }
2082 if value.len() > MAX_PROVENANCE_VALUE_BYTES {
2087 return Err(ManifestProvenanceError::new(
2088 field,
2089 value,
2090 "exceeds the 128-byte maximum",
2091 ));
2092 }
2093 if value.bytes().any(|byte| !(0x20..=0x7e).contains(&byte)) {
2094 return Err(ManifestProvenanceError::new(
2095 field,
2096 value,
2097 "contains non-printable ASCII",
2098 ));
2099 }
2100 }
2101 Ok(())
2102 }
2103}
2104
2105pub fn build_provenance(
2123 build_git_sha: Option<&str>,
2124 build_lock_digest: Option<&str>,
2125 store_schema_version: Option<&str>,
2126) -> Result<ManifestProvenance, ProvenanceFormError> {
2127 let build_git_sha = normalize_and_validate_build_git_sha(build_git_sha)?;
2128 build_provenance_with_build_git_sha(
2129 build_git_sha,
2130 None,
2131 build_lock_digest,
2132 store_schema_version,
2133 )
2134}
2135
2136pub fn build_provenance_from_source(
2152 build_git_sha_source: BuildGitShaSource<'_>,
2153 build_lock_digest: Option<&str>,
2154 store_schema_version: Option<&str>,
2155) -> Result<ManifestProvenance, ProvenanceFormError> {
2156 let (raw_build_git_sha, mut build_git_sha_absence_reason) = match build_git_sha_source {
2157 BuildGitShaSource::Git {
2158 revision,
2159 tree_state,
2160 } => match attestable_commit(revision, tree_state) {
2161 Some(revision) => (Some(revision), None),
2162 None => (None, Some(BuildGitShaAbsenceReason::DeclinedDirty)),
2163 },
2164 BuildGitShaSource::NeverDerived => (None, Some(BuildGitShaAbsenceReason::NeverDerived)),
2165 BuildGitShaSource::NoGitDir => (None, Some(BuildGitShaAbsenceReason::NoGitDir)),
2166 };
2167 let build_git_sha = normalize_and_validate_build_git_sha(raw_build_git_sha)?;
2168 if build_git_sha.is_none() {
2169 build_git_sha_absence_reason.get_or_insert(BuildGitShaAbsenceReason::NeverDerived);
2170 }
2171 build_provenance_with_build_git_sha(
2172 build_git_sha,
2173 build_git_sha_absence_reason,
2174 build_lock_digest,
2175 store_schema_version,
2176 )
2177}
2178
2179fn normalize_and_validate_build_git_sha(
2180 build_git_sha: Option<&str>,
2181) -> Result<Option<String>, ProvenanceFormError> {
2182 let build_git_sha = normalize_provenance_fact(build_git_sha);
2183 validate_provenance_form(
2184 "build_git_sha",
2185 build_git_sha.as_deref(),
2186 BUILD_GIT_SHA_CANONICAL_FORM,
2187 40,
2188 )?;
2189 Ok(build_git_sha)
2190}
2191
2192fn build_provenance_with_build_git_sha(
2193 build_git_sha: Option<String>,
2194 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
2195 build_lock_digest: Option<&str>,
2196 store_schema_version: Option<&str>,
2197) -> Result<ManifestProvenance, ProvenanceFormError> {
2198 let build_lock_digest = normalize_provenance_fact(build_lock_digest);
2199 validate_provenance_form(
2200 "build_lock_digest",
2201 build_lock_digest.as_deref(),
2202 BUILD_LOCK_DIGEST_CANONICAL_FORM,
2203 64,
2204 )?;
2205
2206 Ok(ManifestProvenance {
2207 build_git_sha,
2208 build_git_sha_absence_reason,
2209 build_lock_digest,
2210 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
2211 store_schema_version: normalize_provenance_fact(store_schema_version),
2212 launch_nonce_source: None,
2213 })
2214}
2215
2216fn validate_provenance_form(
2217 field: &'static str,
2218 value: Option<&str>,
2219 canonical_form: &'static str,
2220 expected_length: usize,
2221) -> Result<(), ProvenanceFormError> {
2222 let Some(value) = value else { return Ok(()) };
2223 if value.len() != expected_length
2224 || !value
2225 .bytes()
2226 .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
2227 {
2228 return Err(ProvenanceFormError::new(field, value.len(), canonical_form));
2229 }
2230 Ok(())
2231}
2232
2233pub const PROVENANCE_SENTINELS: [&str; 3] = ["unknown", "unavailable", "none"];
2241
2242fn normalize_provenance_fact(value: Option<&str>) -> Option<String> {
2243 let value = value?.trim();
2244 if value.is_empty() {
2245 return None;
2246 }
2247 let lowered = value.to_ascii_lowercase();
2248 if PROVENANCE_SENTINELS.contains(&lowered.as_str()) {
2249 return None;
2250 }
2251 Some(value.to_string())
2252}
2253
2254#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2256#[serde(deny_unknown_fields)]
2257pub struct CapabilityRequirement {
2258 pub capability: String,
2259 pub need: CapabilityNeed,
2260}
2261
2262#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2264#[serde(rename_all = "snake_case")]
2265pub enum CapabilityNeed {
2266 Required,
2267 Optional,
2268}
2269
2270#[derive(Debug, Clone, PartialEq, Eq)]
2272pub struct CapabilityGrammarError {
2273 field: String,
2274 value: String,
2275}
2276
2277impl CapabilityGrammarError {
2278 fn new(field: impl Into<String>, value: impl AsRef<str>) -> Self {
2279 Self {
2280 field: field.into(),
2281 value: safe_error_value(value.as_ref()),
2282 }
2283 }
2284
2285 pub fn field(&self) -> &str {
2287 &self.field
2288 }
2289
2290 pub fn value(&self) -> &str {
2292 &self.value
2293 }
2294}
2295
2296impl fmt::Display for CapabilityGrammarError {
2297 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2298 write!(
2299 f,
2300 "invalid capability grammar: field {} has offending value {:?}",
2301 self.field, self.value
2302 )
2303 }
2304}
2305
2306impl std::error::Error for CapabilityGrammarError {}
2307
2308impl ModuleManifest {
2309 pub fn validate_capability_grammar(&self) -> Result<(), CapabilityGrammarError> {
2311 let Some(capabilities) = &self.capabilities else {
2312 return Ok(());
2313 };
2314
2315 validate_capability_list("capabilities.provides", &capabilities.provides)?;
2316 validate_requires(&capabilities.requires)?;
2317 validate_capability_list(
2318 "capabilities.must_never_reach",
2319 &capabilities.must_never_reach,
2320 )
2321 }
2322}
2323
2324pub fn validate_manifest_capability_grammar(
2329 manifest: &Value,
2330) -> Result<(), CapabilityGrammarError> {
2331 let Some(object) = manifest.as_object() else {
2332 return Ok(());
2333 };
2334
2335 validate_capabilities_value(object.get("capabilities"))?;
2336 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
2337}
2338
2339pub fn validate_hello_capability_grammar(hello: &Value) -> Result<(), CapabilityGrammarError> {
2345 let Some(object) = hello.as_object() else {
2346 return Ok(());
2347 };
2348 if let Some(manifest) = object.get("manifest") {
2349 validate_manifest_capability_grammar(manifest)?;
2350 }
2351 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
2352}
2353
2354pub fn is_valid_capability_identifier(identifier: &str) -> bool {
2356 if identifier.chars().any(char::is_whitespace) {
2357 return false;
2358 }
2359 let Some((name, version)) = identifier.split_once("/v") else {
2360 return false;
2361 };
2362 if name.is_empty() || name.len() > 64 || version.is_empty() {
2363 return false;
2364 }
2365
2366 let name_bytes = name.as_bytes();
2367 if !name_bytes[0].is_ascii_lowercase()
2368 || (name.len() > 1
2369 && !name_bytes[name.len() - 1].is_ascii_lowercase()
2370 && !name_bytes[name.len() - 1].is_ascii_digit())
2371 || name_bytes.windows(2).any(|pair| pair == b"--")
2372 {
2373 return false;
2374 }
2375 if !name_bytes
2376 .iter()
2377 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-')
2378 {
2379 return false;
2380 }
2381
2382 if version.len() > 1 && version.starts_with('0')
2383 || !version.bytes().all(|byte| byte.is_ascii_digit())
2384 {
2385 return false;
2386 }
2387 matches!(
2388 version.parse::<u64>(),
2389 Ok(value) if (1..=u64::from(u32::MAX)).contains(&value)
2390 )
2391}
2392
2393fn validate_capabilities_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
2394 let Some(value) = value else {
2395 return Ok(());
2396 };
2397 let Some(object) = value.as_object() else {
2398 return Err(CapabilityGrammarError::new(
2399 "capabilities",
2400 value_description(value),
2401 ));
2402 };
2403
2404 for (key, value) in object {
2405 if !matches!(key.as_str(), "provides" | "requires" | "must_never_reach") {
2406 return Err(CapabilityGrammarError::new(
2407 field_child("capabilities", key),
2408 value_description(value),
2409 ));
2410 }
2411 }
2412
2413 validate_capability_list_value("capabilities.provides", object.get("provides"))?;
2414 validate_requires_value(object.get("requires"))?;
2415 validate_capability_list_value(
2416 "capabilities.must_never_reach",
2417 object.get("must_never_reach"),
2418 )
2419}
2420
2421fn validate_capability_list_value(
2422 field: &str,
2423 value: Option<&Value>,
2424) -> Result<(), CapabilityGrammarError> {
2425 let Some(value) = value else {
2426 return Ok(());
2427 };
2428 let Some(values) = value.as_array() else {
2429 return Err(CapabilityGrammarError::new(field, value_description(value)));
2430 };
2431
2432 let mut seen = HashSet::new();
2433 for (index, value) in values.iter().enumerate() {
2434 let field = format!("{field}[{index}]");
2435 let Some(identifier) = value.as_str() else {
2436 return Err(CapabilityGrammarError::new(field, value_description(value)));
2437 };
2438 validate_capability_identifier(&field, identifier)?;
2439 if !seen.insert(identifier) {
2440 return Err(CapabilityGrammarError::new(field, identifier));
2441 }
2442 }
2443 Ok(())
2444}
2445
2446fn validate_requires_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
2447 let Some(value) = value else {
2448 return Ok(());
2449 };
2450 let Some(values) = value.as_array() else {
2451 return Err(CapabilityGrammarError::new(
2452 "capabilities.requires",
2453 value_description(value),
2454 ));
2455 };
2456
2457 let mut seen = HashSet::new();
2458 for (index, value) in values.iter().enumerate() {
2459 let entry_field = format!("capabilities.requires[{index}]");
2460 let Some(object) = value.as_object() else {
2461 return Err(CapabilityGrammarError::new(
2462 entry_field,
2463 value_description(value),
2464 ));
2465 };
2466 for (key, value) in object {
2467 if !matches!(key.as_str(), "capability" | "need") {
2468 return Err(CapabilityGrammarError::new(
2469 field_child(&entry_field, key),
2470 value_description(value),
2471 ));
2472 }
2473 }
2474 let capability_field = format!("{entry_field}.capability");
2475 let Some(capability) = object.get("capability").and_then(Value::as_str) else {
2476 return Err(CapabilityGrammarError::new(
2477 capability_field,
2478 object
2479 .get("capability")
2480 .map_or("<missing>".to_string(), value_description),
2481 ));
2482 };
2483 validate_capability_identifier(&capability_field, capability)?;
2484
2485 let need_field = format!("{entry_field}.need");
2486 let Some(need) = object.get("need").and_then(Value::as_str) else {
2487 return Err(CapabilityGrammarError::new(
2488 need_field,
2489 object
2490 .get("need")
2491 .map_or("<missing>".to_string(), value_description),
2492 ));
2493 };
2494 if !matches!(need, "required" | "optional") {
2495 return Err(CapabilityGrammarError::new(need_field, need));
2496 }
2497 if !seen.insert(capability) {
2498 return Err(CapabilityGrammarError::new(entry_field, capability));
2499 }
2500 }
2501 Ok(())
2502}
2503
2504fn validate_capability_list(field: &str, values: &[String]) -> Result<(), CapabilityGrammarError> {
2505 let mut seen = HashSet::new();
2506 for (index, identifier) in values.iter().enumerate() {
2507 let field = format!("{field}[{index}]");
2508 validate_capability_identifier(&field, identifier)?;
2509 if !seen.insert(identifier) {
2510 return Err(CapabilityGrammarError::new(field, identifier));
2511 }
2512 }
2513 Ok(())
2514}
2515
2516fn validate_requires(values: &[CapabilityRequirement]) -> Result<(), CapabilityGrammarError> {
2517 let mut seen = HashSet::new();
2518 for (index, requirement) in values.iter().enumerate() {
2519 let field = format!("capabilities.requires[{index}].capability");
2520 validate_capability_identifier(&field, &requirement.capability)?;
2521 if !seen.insert(&requirement.capability) {
2522 return Err(CapabilityGrammarError::new(
2523 format!("capabilities.requires[{index}]"),
2524 &requirement.capability,
2525 ));
2526 }
2527 }
2528 Ok(())
2529}
2530
2531fn validate_capability_identifier(
2532 field: &str,
2533 identifier: &str,
2534) -> Result<(), CapabilityGrammarError> {
2535 if is_valid_capability_identifier(identifier) {
2536 Ok(())
2537 } else {
2538 Err(CapabilityGrammarError::new(field, identifier))
2539 }
2540}
2541
2542fn validate_runtime_computed(
2543 value: Option<&Value>,
2544 field: &str,
2545) -> Result<(), CapabilityGrammarError> {
2546 let Some(value) = value else {
2547 return Ok(());
2548 };
2549 let Some(pointers) = value.as_array() else {
2550 return Err(CapabilityGrammarError::new(field, value_description(value)));
2551 };
2552
2553 for (index, pointer) in pointers.iter().enumerate() {
2554 let field = format!("{field}[{index}]");
2555 let Some(pointer) = pointer.as_str() else {
2556 return Err(CapabilityGrammarError::new(
2557 field,
2558 value_description(pointer),
2559 ));
2560 };
2561 let Some(tokens) = parse_json_pointer(pointer) else {
2562 return Err(CapabilityGrammarError::new(field, pointer));
2563 };
2564 if tokens.first().is_some_and(|token| token == "capabilities") {
2565 return Err(CapabilityGrammarError::new(field, pointer));
2566 }
2567 }
2568 Ok(())
2569}
2570
2571fn parse_json_pointer(pointer: &str) -> Option<Vec<String>> {
2572 if pointer.is_empty() {
2573 return Some(Vec::new());
2574 }
2575 let raw_tokens = pointer.strip_prefix('/')?;
2576 raw_tokens
2577 .split('/')
2578 .map(unescape_json_pointer_token)
2579 .collect()
2580}
2581
2582fn unescape_json_pointer_token(token: &str) -> Option<String> {
2583 let mut output = String::with_capacity(token.len());
2584 let mut characters = token.chars();
2585 while let Some(character) = characters.next() {
2586 if character != '~' {
2587 output.push(character);
2588 continue;
2589 }
2590 match characters.next()? {
2591 '0' => output.push('~'),
2592 '1' => output.push('/'),
2593 _ => return None,
2594 }
2595 }
2596 Some(output)
2597}
2598
2599fn field_child(parent: &str, child: &str) -> String {
2600 let child = safe_error_value(child);
2601 format!("{parent}.{child}")
2602}
2603
2604fn value_description(value: &Value) -> String {
2605 match value {
2606 Value::String(value) => safe_error_value(value),
2607 Value::Null => "null".to_string(),
2608 Value::Bool(value) => value.to_string(),
2609 Value::Number(value) => value.to_string(),
2610 Value::Array(_) => "<array>".to_string(),
2611 Value::Object(_) => "<object>".to_string(),
2612 }
2613}
2614
2615fn safe_error_value(value: &str) -> String {
2616 let lower = value.to_ascii_lowercase();
2617 if ["secret", "password", "api_key"]
2618 .iter()
2619 .any(|marker| lower.contains(marker))
2620 || lower.starts_with("sk-")
2621 || lower.starts_with("akia")
2622 || lower.starts_with("bearer ")
2623 || lower.starts_with("token=")
2624 || lower.starts_with("credential=")
2625 {
2626 "<redacted>".to_string()
2627 } else {
2628 value.to_string()
2629 }
2630}
2631
2632#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2638#[serde(rename_all = "snake_case")]
2639pub enum TrustTier {
2640 FirstParty,
2641 Reviewed,
2642 Untrusted,
2643}
2644
2645#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2649#[serde(tag = "role", rename_all = "snake_case")]
2650pub enum ProviderRole {
2651 ToolProvider {
2652 tools: Vec<Tool>,
2653 identity_scope: Vec<IdentityScope>,
2661 concurrency: Concurrency,
2662 emits_push: bool,
2663 sub_supervises: bool,
2664 },
2665 PipelineStage {
2666 stage: PipelineStageKind,
2667 applies_to: PipelineAppliesTo,
2668 interface: String,
2669 declares_frozen_floor: bool,
2670 needs_signals: Vec<String>,
2671 conformance_class: String,
2672 },
2673 ManagementSurface {
2674 operations: Vec<ManagementOperation>,
2675 config_schema: Value,
2676 observability: Vec<ObservabilitySurface>,
2677 identity_scope: Vec<IdentityScope>,
2681 #[serde(default)]
2682 concurrency: Concurrency,
2683 },
2684 InternalService {
2685 service_id: String,
2686 transport: InternalTransport,
2687 agent_facing: bool,
2688 operations: Vec<String>,
2689 },
2690}
2691
2692#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2705#[serde(rename_all = "snake_case")]
2706pub enum ExecutionMode {
2707 Pure,
2708 Mutating,
2709 Unfenceable,
2710}
2711
2712#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2714pub struct Tool {
2715 pub name: String,
2716 #[serde(default, skip_serializing_if = "Option::is_none")]
2717 pub description: Option<String>,
2718 pub execution_mode: ExecutionMode,
2723 pub schema: Value,
2724}
2725
2726#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2732#[serde(rename_all = "snake_case")]
2733pub enum Concurrency {
2734 Serial,
2736 ModuleManaged,
2739 StatelessParallel,
2742}
2743
2744#[allow(clippy::derivable_impls)]
2745impl Default for Concurrency {
2756 fn default() -> Self {
2757 Self::ModuleManaged
2758 }
2759}
2760
2761#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2768#[serde(rename_all = "snake_case")]
2769pub enum IdentityScope {
2770 Session,
2771 Project,
2772}
2773
2774#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2776#[serde(rename_all = "snake_case")]
2777pub enum PipelineStageKind {
2778 Transform,
2779 Codec,
2780 Auth,
2781}
2782
2783#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2785pub struct PipelineAppliesTo {
2786 pub provider: String,
2787 pub model: String,
2788}
2789
2790#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2793#[non_exhaustive]
2794pub struct OperationPayload {
2795 max_bytes: usize,
2796}
2797
2798impl OperationPayload {
2799 pub fn new(max_bytes: usize) -> Self {
2800 Self { max_bytes }
2801 }
2802
2803 pub fn max_bytes(&self) -> usize {
2804 self.max_bytes
2805 }
2806}
2807
2808#[derive(Debug, Clone, PartialEq, Eq)]
2810#[non_exhaustive]
2811pub enum OperationPayloadError {
2812 UnknownOperation { operation: String },
2813 WatchOperation { operation: String },
2814 InvalidMaxBytes { operation: String },
2815}
2816
2817impl fmt::Display for OperationPayloadError {
2818 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2819 write!(f, "{self:?}")
2820 }
2821}
2822
2823impl std::error::Error for OperationPayloadError {}
2824
2825impl ModuleManifest {
2826 pub fn validate_operation_payload(&self) -> Result<(), OperationPayloadError> {
2829 for (name, payload) in &self.operation_payload {
2830 if !self.provides.iter().any(|role| match role {
2831 ProviderRole::ManagementSurface { operations, .. } => {
2832 operations.iter().any(|op| op.name == *name)
2833 }
2834 _ => false,
2835 }) {
2836 return Err(OperationPayloadError::UnknownOperation {
2837 operation: name.clone(),
2838 });
2839 }
2840 if self
2841 .operation_delivery
2842 .get(name)
2843 .is_some_and(OperationDelivery::is_watch)
2844 {
2845 return Err(OperationPayloadError::WatchOperation {
2846 operation: name.clone(),
2847 });
2848 }
2849 if !(1..=crate::framed_body::MAX_DECLARED_PAYLOAD_BYTES).contains(&payload.max_bytes) {
2850 return Err(OperationPayloadError::InvalidMaxBytes {
2851 operation: name.clone(),
2852 });
2853 }
2854 }
2855 Ok(())
2856 }
2857}
2858
2859#[derive(Debug, Clone, PartialEq, Eq)]
2864#[non_exhaustive]
2865pub enum FlowOperationsError {
2866 FlowScopesNotDeclared,
2869 NotAList,
2871 TooMany { count: usize },
2873 DuplicateOperation { operation: String },
2875 UnknownOperation { operation: String },
2877}
2878
2879impl fmt::Display for FlowOperationsError {
2880 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2881 match self {
2882 Self::FlowScopesNotDeclared => write!(
2883 f,
2884 "flow_operations requires '{}' or '{}' in capabilities.provides",
2885 crate::scope::FLOW_SCOPES_CAPABILITY,
2886 crate::call_mode::CALL_MODES_CAPABILITY
2887 ),
2888 Self::NotAList => f.write_str("flow_operations must be an array of operation names"),
2889 Self::TooMany { count } => write!(
2890 f,
2891 "flow_operations lists {count} names, more than {MAX_FLOW_OPERATIONS}"
2892 ),
2893 Self::DuplicateOperation { operation } => {
2894 write!(f, "flow_operations names '{operation}' more than once")
2895 }
2896 Self::UnknownOperation { operation } => write!(
2897 f,
2898 "flow_operations names '{operation}', which is not a declared management operation"
2899 ),
2900 }
2901 }
2902}
2903
2904impl std::error::Error for FlowOperationsError {}
2905
2906impl ModuleManifest {
2907 pub fn validate_flow_operations(&self) -> Result<(), FlowOperationsError> {
2912 match &self.flow_operations {
2913 Some(operations) => check_flow_operations(self, operations),
2914 None => Ok(()),
2915 }
2916 }
2917}
2918
2919fn check_flow_operations(
2920 manifest: &ModuleManifest,
2921 operations: &[String],
2922) -> Result<(), FlowOperationsError> {
2923 let admits_flows = manifest.capabilities.as_ref().is_some_and(|capabilities| {
2924 capabilities.provides.iter().any(|capability| {
2925 capability == crate::scope::FLOW_SCOPES_CAPABILITY
2926 || capability == crate::call_mode::CALL_MODES_CAPABILITY
2927 })
2928 });
2929 if !admits_flows {
2930 return Err(FlowOperationsError::FlowScopesNotDeclared);
2931 }
2932 if operations.len() > MAX_FLOW_OPERATIONS {
2933 return Err(FlowOperationsError::TooMany {
2934 count: operations.len(),
2935 });
2936 }
2937 let mut seen = HashSet::new();
2938 for operation in operations {
2939 if !seen.insert(operation.as_str()) {
2940 return Err(FlowOperationsError::DuplicateOperation {
2941 operation: operation.clone(),
2942 });
2943 }
2944 let declared = manifest.provides.iter().any(|role| match role {
2945 ProviderRole::ManagementSurface { operations, .. } => {
2946 operations.iter().any(|op| op.name == *operation)
2947 }
2948 _ => false,
2949 });
2950 if !declared {
2951 return Err(FlowOperationsError::UnknownOperation {
2952 operation: operation.clone(),
2953 });
2954 }
2955 }
2956 Ok(())
2957}
2958
2959fn decode_flow_operations(
2962 manifest: &ModuleManifest,
2963 value: &Value,
2964) -> Result<Vec<String>, FlowOperationsError> {
2965 let operations: Vec<String> =
2966 serde_json::from_value(value.clone()).map_err(|_| FlowOperationsError::NotAList)?;
2967 check_flow_operations(manifest, &operations)?;
2968 Ok(operations)
2969}
2970
2971pub fn validate_hello_flow_operations(hello: &Value) -> Result<(), FlowOperationsError> {
2977 let Some(manifest_value) = hello.get("manifest") else {
2978 return Ok(());
2979 };
2980 let Some(value) = manifest_value
2981 .get("flow_operations")
2982 .filter(|value| !value.is_null())
2983 else {
2984 return Ok(());
2985 };
2986 let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
2987 return Ok(());
2988 };
2989 decode_flow_operations(&manifest, value).map(|_| ())
2990}
2991
2992pub const MAX_OPERATION_DEFERRAL: usize = 256;
2994
2995fn decode_operation_deferral(
2996 manifest: &ModuleManifest,
2997 value: &Value,
2998) -> Result<BTreeMap<String, bool>, String> {
2999 if !manifest.capabilities.as_ref().is_some_and(|caps| {
3000 caps.provides
3001 .iter()
3002 .any(|cap| cap == crate::scope::SCOPE_FEDERATED_CAPABILITY)
3003 }) {
3004 return Err("operation_deferral requires scope-federated/v1".into());
3005 }
3006 let operations = value
3007 .as_object()
3008 .ok_or("operation_deferral must be an object")?;
3009 if operations.len() > MAX_OPERATION_DEFERRAL {
3010 return Err(format!(
3011 "operation_deferral exceeds {MAX_OPERATION_DEFERRAL} entries"
3012 ));
3013 }
3014 for (key, value) in operations {
3015 let (surface, name) = key
3016 .split_once(':')
3017 .ok_or("operation_deferral keys require a surface prefix")?;
3018 if !matches!(surface, "tool" | "management")
3021 || name.is_empty()
3022 || name.len() > 128
3023 || !name
3024 .bytes()
3025 .all(|b| (0x21..=0x7e).contains(&b) && b != b':')
3026 {
3027 return Err(format!("invalid operation_deferral key '{key}'"));
3028 }
3029 if value != &Value::Bool(true) {
3030 return Err(format!("operation_deferral value for '{key}' must be true"));
3031 }
3032 if surface == "management" && !manifest.provides.iter().any(|role| matches!(role,
3033 ProviderRole::ManagementSurface { operations, .. } if operations.iter().any(|op| op.name == name))) {
3034 return Err(format!("operation_deferral names undeclared management operation '{name}'"));
3035 }
3036 }
3037 Ok(operations.keys().map(|key| (key.clone(), true)).collect())
3038}
3039
3040impl ModuleManifest {
3041 pub fn validate_operation_deferral(&self) -> Result<(), String> {
3043 match &self.operation_deferral {
3044 Some(operations) => decode_operation_deferral(
3045 self,
3046 &serde_json::to_value(operations).expect("serializable map"),
3047 )
3048 .map(|_| ()),
3049 None => Ok(()),
3050 }
3051 }
3052}
3053
3054pub fn validate_hello_operation_deferral(hello: &Value) -> Result<(), String> {
3056 let Some(manifest_value) = hello.get("manifest") else {
3057 return Ok(());
3058 };
3059 let Some(value) = manifest_value
3060 .get("operation_deferral")
3061 .filter(|v| !v.is_null())
3062 else {
3063 return Ok(());
3064 };
3065 let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
3066 return Ok(());
3067 };
3068 decode_operation_deferral(&manifest, value).map(|_| ())
3069}
3070
3071#[derive(Debug, Clone, PartialEq, Eq)]
3076#[non_exhaustive]
3077pub enum ConfirmOperationsError {
3078 NotAList,
3080 TooMany { count: usize },
3082 DuplicateOperation { operation: String },
3084 UnknownOperation { operation: String },
3086}
3087
3088impl fmt::Display for ConfirmOperationsError {
3089 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3090 match self {
3091 Self::NotAList => {
3092 f.write_str("confirm_operations must be an array of operation names")
3093 }
3094 Self::TooMany { count } => write!(
3095 f,
3096 "confirm_operations lists {count} names, more than {MAX_CONFIRM_OPERATIONS}"
3097 ),
3098 Self::DuplicateOperation { operation } => {
3099 write!(f, "confirm_operations names '{operation}' more than once")
3100 }
3101 Self::UnknownOperation { operation } => write!(
3102 f,
3103 "confirm_operations names '{operation}', which is not a declared management operation"
3104 ),
3105 }
3106 }
3107}
3108
3109impl std::error::Error for ConfirmOperationsError {}
3110
3111impl ModuleManifest {
3112 pub fn validate_confirm_operations(&self) -> Result<(), ConfirmOperationsError> {
3116 match &self.confirm_operations {
3117 Some(operations) => check_confirm_operations(self, operations),
3118 None => Ok(()),
3119 }
3120 }
3121}
3122
3123fn check_confirm_operations(
3124 manifest: &ModuleManifest,
3125 operations: &[String],
3126) -> Result<(), ConfirmOperationsError> {
3127 if operations.len() > MAX_CONFIRM_OPERATIONS {
3128 return Err(ConfirmOperationsError::TooMany {
3129 count: operations.len(),
3130 });
3131 }
3132 let mut seen = HashSet::new();
3133 for operation in operations {
3134 if !seen.insert(operation.as_str()) {
3135 return Err(ConfirmOperationsError::DuplicateOperation {
3136 operation: operation.clone(),
3137 });
3138 }
3139 if !declares_management_operation(&manifest.provides, operation) {
3140 return Err(ConfirmOperationsError::UnknownOperation {
3141 operation: operation.clone(),
3142 });
3143 }
3144 }
3145 Ok(())
3146}
3147
3148fn declares_management_operation(provides: &[ProviderRole], operation: &str) -> bool {
3149 provides.iter().any(|role| match role {
3150 ProviderRole::ManagementSurface { operations, .. } => {
3151 operations.iter().any(|op| op.name == operation)
3152 }
3153 _ => false,
3154 })
3155}
3156
3157fn decode_confirm_operations(
3160 manifest: &ModuleManifest,
3161 value: &Value,
3162) -> Result<Vec<String>, ConfirmOperationsError> {
3163 let operations: Vec<String> =
3164 serde_json::from_value(value.clone()).map_err(|_| ConfirmOperationsError::NotAList)?;
3165 check_confirm_operations(manifest, &operations)?;
3166 Ok(operations)
3167}
3168
3169pub fn validate_hello_confirm_operations(hello: &Value) -> Result<(), ConfirmOperationsError> {
3175 let Some(manifest_value) = hello.get("manifest") else {
3176 return Ok(());
3177 };
3178 let Some(value) = manifest_value
3179 .get("confirm_operations")
3180 .filter(|value| !value.is_null())
3181 else {
3182 return Ok(());
3183 };
3184 let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
3185 return Ok(());
3186 };
3187 decode_confirm_operations(&manifest, value).map(|_| ())
3188}
3189
3190#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3195pub struct ManagementOperation {
3196 pub name: String,
3197 pub kind: ManagementOperationKind,
3198 #[serde(default, skip_serializing_if = "Option::is_none")]
3199 pub description: Option<String>,
3200}
3201
3202#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3203#[serde(rename_all = "snake_case")]
3204pub enum ManagementOperationKind {
3205 Query,
3206 Mutate,
3207}
3208
3209#[derive(Debug, Clone, PartialEq, Eq)]
3212#[non_exhaustive]
3213pub enum OperationDelivery {
3214 Watch,
3215 Other(String),
3216}
3217
3218impl OperationDelivery {
3219 pub const WATCH: Self = Self::Watch;
3221
3222 pub fn wire_name(&self) -> &str {
3224 match self {
3225 Self::Watch => "watch",
3226 Self::Other(value) => value,
3227 }
3228 }
3229
3230 pub fn is_watch(&self) -> bool {
3232 self.wire_name() == "watch"
3233 }
3234}
3235
3236impl Serialize for OperationDelivery {
3237 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
3238 where
3239 S: serde::Serializer,
3240 {
3241 serializer.serialize_str(self.wire_name())
3242 }
3243}
3244
3245impl<'de> Deserialize<'de> for OperationDelivery {
3246 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3247 where
3248 D: Deserializer<'de>,
3249 {
3250 let value = String::deserialize(deserializer)?;
3251 Ok(if value == "watch" {
3252 Self::WATCH
3253 } else {
3254 Self::Other(value)
3255 })
3256 }
3257}
3258
3259#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3261pub struct ObservabilitySurface {
3262 pub name: String,
3263 pub kind: ObservabilityKind,
3264}
3265
3266#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3267#[serde(rename_all = "snake_case")]
3268pub enum ObservabilityKind {
3269 Snapshot,
3270 Stream,
3271}
3272
3273#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3274#[serde(rename_all = "snake_case")]
3275pub enum InternalTransport {
3276 Bulk,
3277}
3278
3279#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3281#[serde(tag = "role", rename_all = "snake_case")]
3282pub enum ConsumerRole {
3283 ToolClient { of: Vec<String> },
3284 LlmClient { via: String, auth: String },
3285 ServiceClient { of: Vec<String> },
3286}
3287
3288#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3290pub struct Bindings {
3291 pub storage: StorageBinding,
3292 pub vault_grants: Vec<VaultGrant>,
3293 pub identity: IdentityBinding,
3294}
3295
3296#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3298pub struct StorageBinding {
3299 pub kind: StorageKind,
3300 pub scope: StorageScope,
3301 pub owns_schema: bool,
3302}
3303
3304#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3305#[serde(rename_all = "snake_case")]
3306pub enum StorageKind {
3307 Sqlite,
3308}
3309
3310#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3311#[serde(rename_all = "snake_case")]
3312pub enum StorageScope {
3313 Project,
3314}
3315
3316#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3317pub struct VaultGrant {
3318 pub secret: String,
3319 pub reason: String,
3320}
3321
3322#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3323pub struct IdentityBinding {
3324 pub requires: Vec<IdentityScope>,
3325 pub optional: Vec<IdentityScope>,
3326}
3327
3328#[cfg(test)]
3329mod tests {
3330 use super::*;
3331 use serde_json::json;
3332
3333 fn aft_manifest_fixture() -> ModuleManifest {
3334 ModuleManifest::builder("aft", "0.39.2")
3335 .trust_tier(Some(TrustTier::FirstParty))
3336 .bindings(Some(Bindings {
3337 storage: StorageBinding {
3338 kind: StorageKind::Sqlite,
3339 scope: StorageScope::Project,
3340 owns_schema: true,
3341 },
3342 vault_grants: vec![VaultGrant {
3343 secret: "provider_api_key".to_string(),
3344 reason: "cortexkit_native auth".to_string(),
3345 }],
3346 identity: IdentityBinding {
3347 requires: vec![IdentityScope::Project],
3348 optional: vec![IdentityScope::Session],
3349 },
3350 }))
3351 .protocol_ver(1)
3352 .provides(vec![ProviderRole::ToolProvider {
3353 tools: vec![
3354 Tool {
3355 name: "read".to_string(),
3356 description: None,
3357 execution_mode: ExecutionMode::Pure,
3358 schema: json!({"type": "object"}),
3359 },
3360 Tool {
3361 name: "grep".to_string(),
3362 description: None,
3363 execution_mode: ExecutionMode::Pure,
3364 schema: json!({"type": "object"}),
3365 },
3366 Tool {
3367 name: "outline".to_string(),
3368 description: None,
3369 execution_mode: ExecutionMode::Pure,
3370 schema: json!({"type": "object"}),
3371 },
3372 Tool {
3373 name: "semantic_search".to_string(),
3374 description: None,
3375 execution_mode: ExecutionMode::Pure,
3376 schema: json!({"type": "object"}),
3377 },
3378 Tool {
3379 name: "edit".to_string(),
3380 description: None,
3381 execution_mode: ExecutionMode::Mutating,
3382 schema: json!({"type": "object"}),
3383 },
3384 Tool {
3385 name: "write".to_string(),
3386 description: None,
3387 execution_mode: ExecutionMode::Mutating,
3388 schema: json!({"type": "object"}),
3389 },
3390 Tool {
3391 name: "bash".to_string(),
3392 description: None,
3393 execution_mode: ExecutionMode::Unfenceable,
3394 schema: json!({"type": "object"}),
3395 },
3396 ],
3397 identity_scope: vec![IdentityScope::Session, IdentityScope::Project],
3398 concurrency: Concurrency::ModuleManaged,
3399 emits_push: true,
3400 sub_supervises: true,
3401 }])
3402 .consumes(vec![ConsumerRole::ServiceClient {
3403 of: vec!["embedding.v2".to_string()],
3404 }])
3405 .build()
3406 }
3407
3408 #[test]
3409 fn serde_round_trips_representative_manifest() {
3410 let manifest = aft_manifest_fixture();
3411 let serialized = serde_json::to_string_pretty(&manifest).unwrap();
3412 let decoded: ModuleManifest = serde_json::from_str(&serialized).unwrap();
3413
3414 assert_eq!(manifest, decoded);
3415 }
3416
3417 #[test]
3418 fn builder_defaults_additions_to_honest_absence_and_round_trips() {
3419 let manifest = ModuleManifest::builder("builder-defaults", "2.0.0").build();
3420
3421 assert_eq!(manifest.module_id, "builder-defaults");
3422 assert_eq!(manifest.module_version, "2.0.0");
3423 assert_eq!(manifest.display_name, None);
3424 assert_eq!(manifest.protocol_ver, PROTOCOL_VERSION);
3425 assert_eq!(manifest.trust_tier, None);
3426 assert!(manifest.provides.is_empty());
3427 assert!(manifest.consumes.is_empty());
3428 assert_eq!(manifest.bindings, None);
3429 assert_eq!(manifest.capabilities, None);
3430 assert_eq!(manifest.self_signals, None);
3431 assert_eq!(manifest.provenance, None);
3432
3433 let encoded = serde_json::to_value(&manifest).expect("builder manifest serializes");
3434 for optional in [
3435 "display_name",
3436 "trust_tier",
3437 "consumes",
3438 "bindings",
3439 "capabilities",
3440 "self_signals",
3441 "provenance",
3442 ] {
3443 assert!(
3444 encoded.get(optional).is_none(),
3445 "an absent {optional} declaration must stay absent on the wire"
3446 );
3447 }
3448 let decoded: ModuleManifest =
3449 serde_json::from_value(encoded).expect("builder manifest round-trips");
3450 assert_eq!(decoded, manifest);
3451 }
3452
3453 #[test]
3454 fn fully_populated_builder_manifest_matches_the_literal_wire_golden() {
3455 let manifest = ModuleManifest::builder("full-builder", "2.0.0")
3456 .display_name(Some("Example".to_string()))
3457 .unwrap()
3458 .hosts_third_party_code(false)
3459 .trust_tier(Some(TrustTier::Reviewed))
3460 .bindings(Some(Bindings {
3461 storage: StorageBinding {
3462 kind: StorageKind::Sqlite,
3463 scope: StorageScope::Project,
3464 owns_schema: false,
3465 },
3466 vault_grants: Vec::new(),
3467 identity: IdentityBinding {
3468 requires: vec![IdentityScope::Project],
3469 optional: Vec::new(),
3470 },
3471 }))
3472 .provides(vec![ProviderRole::ToolProvider {
3473 tools: vec![Tool {
3474 name: "read".to_string(),
3475 description: None,
3476 execution_mode: ExecutionMode::Pure,
3477 schema: json!({"type": "object"}),
3478 }],
3479 identity_scope: vec![IdentityScope::Project],
3480 concurrency: Concurrency::Serial,
3481 emits_push: false,
3482 sub_supervises: false,
3483 }])
3484 .consumes(vec![ConsumerRole::ServiceClient {
3485 of: vec!["embedding.v2".to_string()],
3486 }])
3487 .capabilities(Some(CapabilityDeclarations {
3488 provides: vec!["embedding/v2".to_string()],
3489 requires: Vec::new(),
3490 must_never_reach: Vec::new(),
3491 }))
3492 .self_signals(Some(vec![SelfSignalDeclaration {
3493 name: "usage_poller".to_string(),
3494 kind: SelfSignalKind::Poller,
3495 effect: SelfSignalEffect::Observe,
3496 anchored_to: SignalAnchor::FixedInterval,
3497 cadence: Some(SignalCadence::Literal {
3498 interval_ms: 60_000,
3499 }),
3500 domain: Some("provider-usage".to_string()),
3501 note: None,
3502 }]))
3503 .provenance(Some(ManifestProvenance {
3504 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
3505 build_git_sha_absence_reason: None,
3506 build_lock_digest: Some(
3507 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
3508 ),
3509 wire_crate_version: Some("0.16.0".to_string()),
3510 store_schema_version: Some("42".to_string()),
3511 launch_nonce_source: None,
3512 }))
3513 .build();
3514
3515 assert_eq!(
3516 serde_json::to_vec(&manifest).expect("builder manifest serializes"),
3517 include_bytes!("../tests/golden/module_manifest_builder_full.json"),
3518 "the builder must match the fully populated manifest wire bytes"
3519 );
3520 }
3521
3522 #[test]
3523 fn hosts_third_party_code_preserves_booleans_and_ignores_invalid_values() {
3524 let legacy =
3525 serde_json::to_value(ModuleManifest::builder("provider", "1.0.0").build()).unwrap();
3526 assert!(legacy.get("hosts_third_party_code").is_none());
3527 for (wire, expected) in [
3528 (json!(false), Some(false)),
3529 (json!(true), Some(true)),
3530 (json!(null), None),
3531 (json!("false"), None),
3532 (json!(0), None),
3533 ] {
3534 let mut manifest = legacy.clone();
3535 manifest["hosts_third_party_code"] = wire;
3536 let decoded: ModuleManifest = serde_json::from_value(manifest).unwrap();
3537 assert_eq!(decoded.hosts_third_party_code, expected);
3538 assert_eq!(
3539 serde_json::to_value(decoded)
3540 .unwrap()
3541 .get("hosts_third_party_code"),
3542 expected.map(|value| json!(value)).as_ref()
3543 );
3544 }
3545 }
3546
3547 #[test]
3548 fn display_name_validator_enforces_scalar_bounds_and_safe_text() {
3549 for valid in [
3550 "Routing".to_string(),
3551 "名".repeat(40),
3552 "a".repeat(40),
3553 "e\u{301}".repeat(20),
3554 ] {
3555 assert!(validate_display_name(&valid).is_ok(), "{valid:?}");
3556 }
3557 let mut invalid = vec![
3558 "".to_string(),
3559 "a".repeat(41),
3560 "名".repeat(41),
3561 " Routing".to_string(),
3562 "Routing ".to_string(),
3563 "\u{2003}Routing".to_string(),
3564 "a\nb".to_string(),
3565 "a\u{0085}b".to_string(),
3566 "a\u{007f}b".to_string(),
3567 ];
3568 for code in [0x061c, 0x200e, 0x200f]
3569 .into_iter()
3570 .chain(0x202a..=0x202e)
3571 .chain(0x2066..=0x2069)
3572 {
3573 invalid.push(format!("a{}b", char::from_u32(code).unwrap()));
3574 }
3575 let accepted: Vec<_> = invalid
3576 .iter()
3577 .filter(|value| validate_display_name(value).is_ok())
3578 .collect();
3579 assert!(
3580 accepted.is_empty(),
3581 "invalid display names accepted: {accepted:?}"
3582 );
3583 }
3584
3585 #[test]
3586 fn display_name_builder_refuses_invalid_value() {
3587 let error = ModuleManifest::builder("provider", "1.0.0")
3588 .display_name(Some(" Routing".to_string()))
3589 .unwrap_err();
3590 assert!(error.to_string().contains("display_name"));
3591 }
3592
3593 #[test]
3594 fn display_name_manifest_round_trips_and_keeps_unknown_fields_lenient() {
3595 let manifest = ModuleManifest::builder("provider", "1.0.0")
3596 .display_name(Some("Routing".to_string()))
3597 .unwrap()
3598 .build();
3599 let mut wire = serde_json::to_value(&manifest).unwrap();
3600 assert_eq!(wire["display_name"], "Routing");
3601 wire["future_manifest_field"] = json!(true);
3602 assert_eq!(
3603 serde_json::from_value::<ModuleManifest>(wire.clone()).unwrap(),
3604 manifest
3605 );
3606 wire["display_name"] = json!("bad\nname");
3607 assert!(serde_json::from_value::<ModuleManifest>(wire)
3608 .unwrap_err()
3609 .to_string()
3610 .contains("display_name"));
3611 }
3612
3613 #[test]
3614 fn old_manifest_with_unread_fields_decodes_and_round_trips_verbatim() {
3615 let raw = include_bytes!("../tests/golden/module_manifest_builder_full.json");
3616 let decoded: ModuleManifest =
3617 serde_json::from_slice(raw).expect("old manifest with all unread fields decodes");
3618
3619 assert_eq!(decoded.trust_tier, Some(TrustTier::Reviewed));
3620 assert!(!decoded.consumes.is_empty());
3621 assert!(decoded.bindings.is_some());
3622
3623 let reencoded = serde_json::to_vec(&decoded).expect("re-encode succeeds");
3624 assert_eq!(
3625 reencoded, raw,
3626 "old manifest relay stays byte-for-byte verbatim"
3627 );
3628 }
3629
3630 #[test]
3631 fn new_manifest_omits_unread_fields_on_wire_and_decodes_cleanly() {
3632 let raw = include_bytes!("../tests/golden/module_manifest_diet.json");
3633 let decoded: ModuleManifest =
3634 serde_json::from_slice(raw).expect("new manifest omitting unread fields decodes");
3635
3636 assert_eq!(decoded.trust_tier, None);
3637 assert!(decoded.consumes.is_empty());
3638 assert_eq!(decoded.bindings, None);
3639
3640 let pretty = format!("{}\n", serde_json::to_string_pretty(&decoded).unwrap());
3641 assert_eq!(
3642 pretty.as_bytes(),
3643 raw,
3644 "new manifest matches golden byte-for-byte without unread keys"
3645 );
3646
3647 let as_val: serde_json::Value = serde_json::to_value(&decoded).unwrap();
3648 assert!(
3649 as_val.get("trust_tier").is_none(),
3650 "no trust_tier on wire for new manifest"
3651 );
3652 assert!(
3653 as_val.get("consumes").is_none(),
3654 "no consumes on wire for empty consumes"
3655 );
3656 assert!(
3657 as_val.get("bindings").is_none(),
3658 "no bindings on wire for new manifest"
3659 );
3660 }
3661
3662 #[test]
3663 fn aft_manifest_fixture_matches_v1_contract() {
3664 let manifest = aft_manifest_fixture();
3665
3666 assert_eq!(manifest.module_id, "aft");
3667 let ProviderRole::ToolProvider {
3668 tools,
3669 identity_scope,
3670 concurrency,
3671 emits_push,
3672 sub_supervises,
3673 } = &manifest.provides[0]
3674 else {
3675 panic!("AFT fixture must expose one tool_provider role");
3676 };
3677
3678 assert_eq!(*concurrency, Concurrency::ModuleManaged);
3679 assert!(*emits_push);
3680 assert!(*sub_supervises);
3681 assert_eq!(
3682 identity_scope,
3683 &vec![IdentityScope::Session, IdentityScope::Project]
3684 );
3685 assert_eq!(
3686 tools
3687 .iter()
3688 .map(|tool| (tool.name.as_str(), tool.execution_mode))
3689 .collect::<Vec<_>>(),
3690 vec![
3691 ("read", ExecutionMode::Pure),
3692 ("grep", ExecutionMode::Pure),
3693 ("outline", ExecutionMode::Pure),
3694 ("semantic_search", ExecutionMode::Pure),
3695 ("edit", ExecutionMode::Mutating),
3696 ("write", ExecutionMode::Mutating),
3697 ("bash", ExecutionMode::Unfenceable),
3698 ]
3699 );
3700 }
3701
3702 #[test]
3703 fn tool_provider_role_tag_serializes_as_snake_case() {
3704 let manifest = aft_manifest_fixture();
3705 let value = serde_json::to_value(&manifest).unwrap();
3706
3707 assert_eq!(value["provides"][0]["role"], "tool_provider");
3708 }
3709
3710 #[test]
3711 fn manifest_without_capabilities_preserves_the_existing_wire_shape() {
3712 let manifest = aft_manifest_fixture();
3713 let encoded = serde_json::to_value(&manifest).expect("manifest serializes");
3714 assert!(encoded.get("capabilities").is_none());
3715
3716 let decoded: ModuleManifest =
3717 serde_json::from_value(encoded).expect("legacy manifest parses");
3718 assert_eq!(decoded.capabilities, None);
3719 }
3720
3721 #[test]
3722 fn capability_identifier_lexical_grammar_accepts_only_pinned_forms() {
3723 for identifier in [
3724 "a/v1",
3725 "credentials-provider/v1",
3726 "a1-b2/v4294967295",
3727 "a123456789012345678901234567890123456789012345678901234567890123/v1",
3728 ] {
3729 assert!(
3730 is_valid_capability_identifier(identifier),
3731 "identifier must be accepted: {identifier}"
3732 );
3733 }
3734
3735 for identifier in [
3736 "credentials-Provider/v1",
3737 "credentials-provider/v01",
3738 "credentials-provider-/v1",
3739 "credentials--provider/v1",
3740 "Credentials-provider/v1",
3741 "credentials-provider/1",
3742 "credentials provider/v1",
3743 "credentials-provider/v0",
3744 "credentials-provider/v4294967296",
3745 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/v1",
3746 ] {
3747 assert!(
3748 !is_valid_capability_identifier(identifier),
3749 "identifier must be rejected: {identifier}"
3750 );
3751 }
3752 }
3753
3754 #[test]
3755 fn capability_grammar_errors_redact_secret_shaped_values() {
3756 let error = validate_manifest_capability_grammar(&json!({
3757 "capabilities": { "provides": ["sk-secret-value/v0"] }
3758 }))
3759 .expect_err("secret-shaped capability identifier is malformed");
3760 assert_eq!(error.field(), "capabilities.provides[0]");
3761 assert_eq!(error.value(), "<redacted>");
3762 assert!(!error.to_string().contains("sk-secret-value"));
3763 }
3764
3765 #[test]
3772 fn provenance_builder_sentinels_become_field_omission() {
3773 for sentinel in [
3774 "unknown",
3775 "UNKNOWN",
3776 "Unknown",
3777 "unavailable",
3778 "none",
3779 "None",
3780 " unknown ",
3781 "",
3782 ] {
3783 let p = build_provenance_from_source(
3784 BuildGitShaSource::Git {
3785 revision: sentinel,
3786 tree_state: GitTreeState::Clean,
3787 },
3788 Some(sentinel),
3789 Some(sentinel),
3790 )
3791 .expect("sentinels are omitted before form validation");
3792 assert_eq!(
3793 (
3794 p.build_git_sha,
3795 p.build_git_sha_absence_reason,
3796 p.build_lock_digest,
3797 p.store_schema_version,
3798 ),
3799 (
3800 None,
3801 Some(BuildGitShaAbsenceReason::NeverDerived),
3802 None,
3803 None,
3804 ),
3805 "sentinel {sentinel:?} must be omitted, not published"
3806 );
3807 }
3808 let real = build_provenance_from_source(
3809 BuildGitShaSource::Git {
3810 revision: "0123456789abcdef0123456789abcdef01234567",
3811 tree_state: GitTreeState::Clean,
3812 },
3813 None,
3814 Some("9"),
3815 )
3816 .expect("canonical build revision is accepted");
3817 assert_eq!(
3818 real.build_git_sha.as_deref(),
3819 Some("0123456789abcdef0123456789abcdef01234567")
3820 );
3821 assert_eq!(real.store_schema_version.as_deref(), Some("9"));
3822 assert_eq!(
3826 real.wire_crate_version.as_deref(),
3827 Some(crate::SUBC_PROTOCOL_CRATE_VERSION)
3828 );
3829 }
3830
3831 #[test]
3832 fn build_provenance_accepts_canonical_sha_and_lock_digest() {
3833 let provenance = build_provenance_from_source(
3834 BuildGitShaSource::Git {
3835 revision: " 0123456789abcdef0123456789abcdef01234567 ",
3836 tree_state: GitTreeState::Clean,
3837 },
3838 Some(" abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789 "),
3839 Some(" schema-v3 "),
3840 )
3841 .expect("canonical build facts are accepted");
3842
3843 assert_eq!(
3844 provenance,
3845 ManifestProvenance {
3846 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
3847 build_git_sha_absence_reason: None,
3848 build_lock_digest: Some(
3849 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
3850 ),
3851 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
3852 store_schema_version: Some("schema-v3".to_string()),
3853 launch_nonce_source: None,
3854 }
3855 );
3856 }
3857
3858 #[test]
3859 fn build_provenance_refuses_an_abbreviated_git_sha() {
3860 let error = build_provenance_from_source(
3861 BuildGitShaSource::Git {
3862 revision: "0123456789ab",
3863 tree_state: GitTreeState::Clean,
3864 },
3865 None,
3866 None,
3867 )
3868 .expect_err("a 12-character abbreviation is not canonical");
3869
3870 assert_eq!(error.field(), "build_git_sha");
3871 assert_eq!(error.length(), 12);
3872 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3873 assert_eq!(
3874 error.to_string(),
3875 "invalid manifest provenance form: field build_git_sha has length 12; canonical form is exactly 40 lowercase hexadecimal characters"
3876 );
3877 }
3878
3879 #[test]
3880 fn build_provenance_refuses_an_abbreviated_lock_digest() {
3881 let error = build_provenance_from_source(
3882 BuildGitShaSource::NeverDerived,
3883 Some("0123456789abcdef"),
3884 None,
3885 )
3886 .expect_err("a 16-character digest is not canonical");
3887
3888 assert_eq!(error.field(), "build_lock_digest");
3889 assert_eq!(error.length(), 16);
3890 assert_eq!(error.canonical_form(), BUILD_LOCK_DIGEST_CANONICAL_FORM);
3891 }
3892
3893 #[test]
3894 fn build_provenance_refuses_uppercase_hex() {
3895 let uppercase_sha = "A".repeat(40);
3896 let error = build_provenance_from_source(
3897 BuildGitShaSource::Git {
3898 revision: &uppercase_sha,
3899 tree_state: GitTreeState::Clean,
3900 },
3901 None,
3902 None,
3903 )
3904 .expect_err("uppercase hexadecimal is not canonical");
3905
3906 assert_eq!(error.field(), "build_git_sha");
3907 assert_eq!(error.length(), 40);
3908 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3909 }
3910
3911 #[test]
3912 fn build_provenance_refuses_dirty_revision_stamp_claimed_clean() {
3913 let error = build_provenance_from_source(
3914 BuildGitShaSource::Git {
3915 revision: "0123456789abcdef0123456789abcdef01234567-dirty",
3916 tree_state: GitTreeState::Clean,
3917 },
3918 None,
3919 None,
3920 )
3921 .expect_err("a dirty stamp is not a canonical build revision");
3922
3923 assert_eq!(error.field(), "build_git_sha");
3924 assert_eq!(error.length(), 46);
3925 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3926 }
3927
3928 #[test]
3929 fn build_provenance_keeps_a_lock_digest_when_identity_is_unavailable() {
3930 let provenance = build_provenance_from_source(
3931 BuildGitShaSource::Git {
3932 revision: "unavailable",
3933 tree_state: GitTreeState::Clean,
3934 },
3935 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"),
3936 None,
3937 )
3938 .expect("sentinel SHA is omitted before the valid lock digest is checked");
3939
3940 assert_eq!(provenance.build_git_sha, None);
3941 assert_eq!(
3942 provenance.build_lock_digest,
3943 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string())
3944 );
3945 assert_eq!(
3946 provenance.wire_crate_version,
3947 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
3948 );
3949 }
3950
3951 #[test]
3952 fn build_provenance_omits_fully_unavailable_inputs() {
3953 let provenance = build_provenance_from_source(
3954 BuildGitShaSource::NeverDerived,
3955 Some(" unavailable "),
3956 Some(" "),
3957 )
3958 .expect("omitted and sentinel inputs are not form errors");
3959
3960 assert_eq!(provenance.build_git_sha, None);
3961 assert_eq!(provenance.build_lock_digest, None);
3962 assert_eq!(provenance.store_schema_version, None);
3963 assert_eq!(
3964 provenance.wire_crate_version,
3965 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
3966 );
3967 }
3968
3969 #[test]
3970 fn legacy_build_provenance_keeps_master_wire_bytes_without_an_absence_reason() {
3971 let revision = "0123456789abcdef0123456789abcdef01234567";
3972 for (input, expected) in [
3973 (
3974 Some(revision),
3975 format!(
3976 r#"{{"build_git_sha":"{revision}","wire_crate_version":"{}"}}"#,
3977 crate::SUBC_PROTOCOL_CRATE_VERSION
3978 ),
3979 ),
3980 (
3981 None,
3982 format!(
3983 r#"{{"wire_crate_version":"{}"}}"#,
3984 crate::SUBC_PROTOCOL_CRATE_VERSION
3985 ),
3986 ),
3987 (
3988 Some("unknown"),
3989 format!(
3990 r#"{{"wire_crate_version":"{}"}}"#,
3991 crate::SUBC_PROTOCOL_CRATE_VERSION
3992 ),
3993 ),
3994 ] {
3995 let provenance = build_provenance(input, None, None)
3996 .expect("the legacy build facts remain constructible");
3997 assert_eq!(provenance.build_git_sha_absence_reason, None);
3998 assert_eq!(
3999 serde_json::to_string(&provenance).expect("legacy provenance serializes"),
4000 expected
4001 );
4002 }
4003 }
4004
4005 #[test]
4006 fn build_provenance_derives_git_sha_absence_from_the_stamping_inputs() {
4007 let revision = "0123456789abcdef0123456789abcdef01234567";
4008 let cases = [
4009 (
4010 BuildGitShaSource::Git {
4011 revision,
4012 tree_state: GitTreeState::Clean,
4013 },
4014 Some(revision),
4015 None,
4016 ),
4017 (
4018 BuildGitShaSource::Git {
4019 revision,
4020 tree_state: GitTreeState::Dirty,
4021 },
4022 None,
4023 Some(BuildGitShaAbsenceReason::DeclinedDirty),
4024 ),
4025 (
4026 BuildGitShaSource::NeverDerived,
4027 None,
4028 Some(BuildGitShaAbsenceReason::NeverDerived),
4029 ),
4030 (
4031 BuildGitShaSource::NoGitDir,
4032 None,
4033 Some(BuildGitShaAbsenceReason::NoGitDir),
4034 ),
4035 ];
4036
4037 for (source, expected_sha, expected_reason) in cases {
4038 let provenance = build_provenance_from_source(source, None, None)
4039 .expect("every stamping state constructs honest provenance");
4040 assert_eq!(provenance.build_git_sha.as_deref(), expected_sha);
4041 assert_eq!(provenance.build_git_sha_absence_reason, expected_reason);
4042 }
4043 }
4044
4045 #[test]
4046 fn unknown_git_sha_absence_reason_round_trips_byte_faithfully() {
4047 let wire = format!(
4048 r#"{{"build_git_sha_absence_reason":"future_stamper_state","wire_crate_version":"{}"}}"#,
4049 crate::SUBC_PROTOCOL_CRATE_VERSION
4050 );
4051 let provenance: ManifestProvenance =
4052 serde_json::from_str(&wire).expect("future absence reasons remain readable");
4053
4054 assert_eq!(
4055 provenance.build_git_sha_absence_reason,
4056 Some(BuildGitShaAbsenceReason::ForwardCompatibleUnknown(
4057 "future_stamper_state".to_string()
4058 ))
4059 );
4060 assert_eq!(
4061 serde_json::to_string(&provenance).expect("future absence reason reserializes"),
4062 wire
4063 );
4064 }
4065
4066 #[test]
4067 fn provenance_rejects_an_absence_reason_beside_a_declared_commit() {
4068 let error = serde_json::from_value::<ManifestProvenance>(json!({
4069 "build_git_sha": "0123456789abcdef0123456789abcdef01234567",
4070 "build_git_sha_absence_reason": "declined_dirty"
4071 }))
4072 .expect_err("a declared commit cannot also claim an absence reason");
4073
4074 assert!(error.to_string().contains(
4075 "build_git_sha_absence_reason has must be omitted when build_git_sha is present"
4076 ));
4077 }
4078
4079 #[test]
4080 fn rich_ui_descriptor_is_optional_and_round_trips_when_present() {
4081 let manifest = ModuleManifest::builder("provider", "1.0.0").build();
4082 assert_eq!(
4083 serde_json::to_string(&manifest).unwrap(),
4084 r#"{"module_id":"provider","module_version":"1.0.0","protocol_ver":2,"provides":[]}"#
4085 );
4086
4087 let descriptor = RichUiDescriptor::new(
4088 "ckios.richui.manifest/1",
4089 format!("sha256:{}", "a".repeat(64)),
4090 128,
4091 2,
4092 );
4093 let manifest = ModuleManifest::builder("provider", "1.0.0")
4094 .rich_ui(Some(descriptor.clone()))
4095 .build();
4096 let wire = serde_json::to_string(&manifest).unwrap();
4097 assert!(wire.contains("\"rich_ui\":{\"schema\":\"ckios.richui.manifest/1\""));
4098 assert_eq!(
4099 serde_json::from_str::<ModuleManifest>(&wire)
4100 .unwrap()
4101 .rich_ui,
4102 Some(descriptor)
4103 );
4104 }
4105
4106 #[test]
4107 fn rich_ui_descriptor_validation_names_each_invalid_field() {
4108 let good = json!({
4109 "schema": "ckios.richui.manifest/1",
4110 "manifest_digest": format!("sha256:{}", "a".repeat(64)),
4111 "bytes": 1,
4112 "chunks": 1
4113 });
4114 let hello = json!({"manifest": {"rich_ui": good.clone()}});
4115 assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
4116
4117 for (field, value) in [
4118 ("schema", json!("bad schema")),
4119 (
4120 "manifest_digest",
4121 json!(format!("sha256:{}", "A".repeat(64))),
4122 ),
4123 ("bytes", json!(0)),
4124 ("chunks", json!(1025)),
4125 ] {
4126 let mut invalid = hello.clone();
4127 invalid["manifest"]["rich_ui"][field] = value;
4128 let error = validate_hello_rich_ui_descriptor(&invalid)
4129 .expect_err("an invalid descriptor field must be refused");
4130 assert_eq!(error.field(), format!("rich_ui.{field}"));
4131 }
4132
4133 let mut hello = hello;
4134 hello["manifest"]["rich_ui"] = Value::Null;
4135 let error = validate_hello_rich_ui_descriptor(&hello)
4136 .expect_err("null is not an absent descriptor");
4137 assert_eq!(error.field(), "rich_ui");
4138 }
4139
4140 #[test]
4141 fn rich_ui_descriptor_validation_accepts_inclusive_bounds() {
4142 let hello = json!({"manifest": {"rich_ui": {
4143 "schema": "a".repeat(64),
4144 "manifest_digest": format!("sha256:{}", "f".repeat(64)),
4145 "bytes": 16_777_216,
4146 "chunks": 1024
4147 }}});
4148 assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
4149 }
4150}