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::PROTOCOL_VERSION;
18
19pub const MAX_ROLE_DECLARATIONS_BYTES: usize = 16_384;
21
22pub const MAX_FLOW_OPERATIONS: usize = 256;
24
25pub const MAX_CONFIRM_OPERATIONS: usize = 256;
27
28#[derive(Serialize, Debug, Clone, PartialEq)]
35#[non_exhaustive]
36pub struct ModuleManifest {
37 pub module_id: String,
38 pub module_version: String,
39 pub protocol_ver: u8,
40 #[serde(default, skip_serializing_if = "Option::is_none")]
41 pub trust_tier: Option<TrustTier>,
42 #[serde(default, skip_serializing_if = "Option::is_none")]
49 pub ready: Option<bool>,
50 pub provides: Vec<ProviderRole>,
53 #[serde(default, skip_serializing_if = "Vec::is_empty")]
54 pub consumes: Vec<ConsumerRole>,
55 #[serde(default, skip_serializing_if = "Option::is_none")]
56 pub bindings: Option<Bindings>,
57 #[serde(default, skip_serializing_if = "Option::is_none")]
63 pub capabilities: Option<CapabilityDeclarations>,
64 #[serde(default, skip_serializing_if = "Option::is_none")]
78 pub events: Option<Vec<EventDeclaration>>,
79 #[serde(default, skip_serializing_if = "Option::is_none")]
114 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
115 #[serde(default, skip_serializing_if = "Option::is_none")]
116 pub provenance: Option<ManifestProvenance>,
117 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
122 pub operation_delivery: BTreeMap<String, OperationDelivery>,
123 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
126 pub operation_payload: BTreeMap<String, OperationPayload>,
127 #[serde(default, skip_serializing_if = "Option::is_none")]
146 pub flow_operations: Option<Vec<String>>,
147 #[serde(default, skip_serializing_if = "Option::is_none")]
164 pub confirm_operations: Option<Vec<String>>,
165 #[serde(default, skip_serializing_if = "Option::is_none")]
170 pub rich_ui: Option<RichUiDescriptor>,
171 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
180 pub role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
181}
182
183#[derive(Debug, Clone)]
185pub struct ModuleManifestBuilder {
186 module_id: String,
187 module_version: String,
188 protocol_ver: u8,
189 trust_tier: Option<TrustTier>,
190 ready: Option<bool>,
191 provides: Vec<ProviderRole>,
192 consumes: Vec<ConsumerRole>,
193 bindings: Option<Bindings>,
194 capabilities: Option<CapabilityDeclarations>,
195 events: Option<Vec<EventDeclaration>>,
196 self_signals: Option<Vec<SelfSignalDeclaration>>,
197 provenance: Option<ManifestProvenance>,
198 operation_delivery: BTreeMap<String, OperationDelivery>,
199 operation_payload: BTreeMap<String, OperationPayload>,
200 flow_operations: Option<Vec<String>>,
201 confirm_operations: Option<Vec<String>>,
202 rich_ui: Option<RichUiDescriptor>,
203 role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
204}
205
206impl ModuleManifest {
207 pub fn builder(
215 module_id: impl Into<String>,
216 module_version: impl Into<String>,
217 ) -> ModuleManifestBuilder {
218 ModuleManifestBuilder {
219 module_id: module_id.into(),
220 module_version: module_version.into(),
221 protocol_ver: PROTOCOL_VERSION,
222 trust_tier: None,
223 ready: None,
224 provides: Vec::new(),
225 consumes: Vec::new(),
226 bindings: None,
227 capabilities: None,
228 events: None,
229 self_signals: None,
230 provenance: None,
231 operation_delivery: BTreeMap::new(),
232 operation_payload: BTreeMap::new(),
233 flow_operations: None,
234 confirm_operations: None,
235 rich_ui: None,
236 role_declarations: BTreeMap::new(),
237 }
238 }
239
240 pub fn is_watch_operation(&self, name: &str) -> bool {
245 self.operation_delivery
246 .get(name)
247 .is_some_and(OperationDelivery::is_watch)
248 && self.provides.iter().any(|role| match role {
249 ProviderRole::ManagementSurface { operations, .. } => operations
250 .iter()
251 .any(|op| op.name == name && op.kind == ManagementOperationKind::Query),
252 _ => false,
253 })
254 }
255}
256
257impl ModuleManifestBuilder {
258 pub fn protocol_ver(mut self, protocol_ver: u8) -> Self {
260 self.protocol_ver = protocol_ver;
261 self
262 }
263
264 pub fn trust_tier(mut self, trust_tier: Option<TrustTier>) -> Self {
268 self.trust_tier = trust_tier;
269 self
270 }
271
272 pub fn ready(mut self, ready: bool) -> Self {
274 self.ready = Some(ready);
275 self
276 }
277
278 pub fn provides(mut self, provides: Vec<ProviderRole>) -> Self {
280 self.provides = provides;
281 self
282 }
283
284 pub fn consumes(mut self, consumes: Vec<ConsumerRole>) -> Self {
286 self.consumes = consumes;
287 self
288 }
289
290 pub fn bindings(mut self, bindings: Option<Bindings>) -> Self {
294 self.bindings = bindings;
295 self
296 }
297
298 pub fn capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
300 self.capabilities = capabilities;
301 self
302 }
303
304 pub fn events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
306 self.events = events;
307 self
308 }
309
310 pub fn self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
312 self.self_signals = self_signals;
313 self
314 }
315
316 pub fn provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
318 self.provenance = provenance;
319 self
320 }
321
322 pub fn operation_delivery(
324 mut self,
325 operation_delivery: BTreeMap<String, OperationDelivery>,
326 ) -> Self {
327 self.operation_delivery = operation_delivery;
328 self
329 }
330
331 pub fn operation_payload(
333 mut self,
334 operation_payload: BTreeMap<String, OperationPayload>,
335 ) -> Self {
336 self.operation_payload = operation_payload;
337 self
338 }
339
340 pub fn flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
347 self.flow_operations = flow_operations;
348 self
349 }
350
351 pub fn confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
358 self.confirm_operations = confirm_operations;
359 self
360 }
361
362 pub fn rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
364 self.rich_ui = rich_ui;
365 self
366 }
367
368 pub fn role_declarations(
370 mut self,
371 role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
372 ) -> Self {
373 self.role_declarations = role_declarations;
374 self
375 }
376
377 pub fn build(self) -> ModuleManifest {
379 ModuleManifest {
380 module_id: self.module_id,
381 module_version: self.module_version,
382 protocol_ver: self.protocol_ver,
383 trust_tier: self.trust_tier,
384 ready: self.ready,
385 provides: self.provides,
386 consumes: self.consumes,
387 bindings: self.bindings,
388 capabilities: self.capabilities,
389 events: self.events,
390 self_signals: self.self_signals,
391 provenance: self.provenance,
392 operation_delivery: self.operation_delivery,
393 operation_payload: self.operation_payload,
394 flow_operations: self.flow_operations,
395 confirm_operations: self.confirm_operations,
396 rich_ui: self.rich_ui,
397 role_declarations: self.role_declarations,
398 }
399 }
400}
401
402#[derive(Deserialize)]
422struct ModuleManifestWire {
423 module_id: String,
424 module_version: String,
425 protocol_ver: u8,
426 #[serde(default)]
427 trust_tier: Option<TrustTier>,
428 #[serde(default)]
429 ready: Option<bool>,
430 provides: Vec<ProviderRole>,
431 #[serde(default)]
432 consumes: Vec<ConsumerRole>,
433 #[serde(default)]
434 bindings: Option<Bindings>,
435 #[serde(default)]
436 capabilities: Option<CapabilityDeclarations>,
437 #[serde(default)]
438 events: Option<Value>,
439 #[serde(default)]
440 self_signals: Option<Vec<SelfSignalDeclaration>>,
441 #[serde(default)]
442 provenance: Option<ManifestProvenance>,
443 #[serde(default)]
444 operation_delivery: Option<Value>,
445 #[serde(default)]
446 operation_payload: BTreeMap<String, OperationPayload>,
447 #[serde(default)]
449 flow_operations: Option<Value>,
450 #[serde(default)]
452 confirm_operations: Option<Value>,
453 #[serde(default)]
454 rich_ui: Option<RichUiDescriptor>,
455 #[serde(default)]
459 runtime_computed: Option<Value>,
460 #[serde(default)]
461 role_declarations: Option<Value>,
462}
463
464impl<'de> Deserialize<'de> for ModuleManifest {
465 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
466 where
467 D: Deserializer<'de>,
468 {
469 let wire = ModuleManifestWire::deserialize(deserializer)?;
470 validate_runtime_computed(wire.runtime_computed.as_ref(), "runtime_computed")
471 .map_err(D::Error::custom)?;
472 validate_events_value(wire.events.as_ref()).map_err(D::Error::custom)?;
473 let events = wire
474 .events
475 .map(serde_json::from_value)
476 .transpose()
477 .map_err(D::Error::custom)?;
478 let mut builder = Self::builder(wire.module_id, wire.module_version)
479 .protocol_ver(wire.protocol_ver)
480 .trust_tier(wire.trust_tier);
481 if let Some(ready) = wire.ready {
482 builder = builder.ready(ready);
483 }
484 let mut manifest = builder
485 .provides(wire.provides)
486 .consumes(wire.consumes)
487 .bindings(wire.bindings)
488 .capabilities(wire.capabilities)
489 .events(events)
490 .self_signals(wire.self_signals)
491 .provenance(wire.provenance)
492 .operation_delivery(
493 wire.operation_delivery
494 .and_then(|value| serde_json::from_value(value).ok())
495 .unwrap_or_default(),
496 )
497 .rich_ui(wire.rich_ui)
498 .role_declarations(
499 wire.role_declarations
500 .filter(|value| validate_role_declarations_value(Some(value)).is_ok())
501 .and_then(|value| serde_json::from_value(value).ok())
502 .unwrap_or_default(),
503 )
504 .operation_payload(wire.operation_payload)
505 .build();
506 manifest
507 .validate_operation_payload()
508 .map_err(D::Error::custom)?;
509 manifest.flow_operations = wire
512 .flow_operations
513 .and_then(|value| decode_flow_operations(&manifest, &value).ok());
514 manifest.confirm_operations = wire
515 .confirm_operations
516 .and_then(|value| decode_confirm_operations(&manifest, &value).ok());
517 manifest
518 .validate_capability_grammar()
519 .map_err(D::Error::custom)?;
520 if let Some(rich_ui) = &manifest.rich_ui {
521 rich_ui.validate().map_err(D::Error::custom)?;
522 }
523 Ok(manifest)
524 }
525}
526
527#[derive(Debug, Clone, PartialEq, Eq)]
529pub struct RoleDeclarationsError(&'static str);
530
531impl fmt::Display for RoleDeclarationsError {
532 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
533 f.write_str(self.0)
534 }
535}
536
537impl std::error::Error for RoleDeclarationsError {}
538
539pub fn validate_hello_role_declarations(hello: &Value) -> Result<(), RoleDeclarationsError> {
541 validate_role_declarations_value(
542 hello
543 .get("manifest")
544 .and_then(|manifest| manifest.get("role_declarations")),
545 )
546}
547
548fn validate_role_declarations_value(value: Option<&Value>) -> Result<(), RoleDeclarationsError> {
549 let Some(value) = value else {
550 return Ok(());
551 };
552 let map = value
553 .as_object()
554 .ok_or(RoleDeclarationsError("role_declarations must be an object"))?;
555 for (role, declaration) in map {
556 if !is_valid_capability_identifier(role) {
557 return Err(RoleDeclarationsError(
558 "role_declarations key must use capability-name grammar",
559 ));
560 }
561 if !declaration.is_object() {
562 return Err(RoleDeclarationsError(
563 "role_declarations values must be objects",
564 ));
565 }
566 }
567 let bytes = serde_json::to_vec(value)
568 .map_err(|_| RoleDeclarationsError("role_declarations could not be serialized"))?;
569 if bytes.len() > MAX_ROLE_DECLARATIONS_BYTES {
570 return Err(RoleDeclarationsError(
571 "role_declarations exceeds 16384 compact JSON bytes",
572 ));
573 }
574 Ok(())
575}
576
577#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
583#[non_exhaustive]
584pub struct RichUiDescriptor {
585 pub schema: String,
587 pub manifest_digest: String,
589 pub bytes: u64,
591 pub chunks: u32,
593}
594
595impl RichUiDescriptor {
596 pub fn new(
598 schema: impl Into<String>,
599 manifest_digest: impl Into<String>,
600 bytes: u64,
601 chunks: u32,
602 ) -> Self {
603 Self {
604 schema: schema.into(),
605 manifest_digest: manifest_digest.into(),
606 bytes,
607 chunks,
608 }
609 }
610
611 pub fn validate(&self) -> Result<(), RichUiDescriptorError> {
613 validate_rich_ui_fields(
614 &self.schema,
615 &self.manifest_digest,
616 self.bytes,
617 u64::from(self.chunks),
618 )
619 }
620}
621
622#[derive(Debug, Clone, PartialEq, Eq)]
624#[non_exhaustive]
625pub struct RichUiDescriptorError {
626 field: String,
627 reason: &'static str,
628}
629
630impl RichUiDescriptorError {
631 fn new(field: impl Into<String>, reason: &'static str) -> Self {
632 Self {
633 field: field.into(),
634 reason,
635 }
636 }
637
638 pub fn field(&self) -> &str {
640 &self.field
641 }
642}
643
644impl fmt::Display for RichUiDescriptorError {
645 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
646 write!(
647 f,
648 "invalid rich_ui descriptor: field {} {}",
649 self.field, self.reason
650 )
651 }
652}
653
654impl std::error::Error for RichUiDescriptorError {}
655
656pub fn validate_hello_rich_ui_descriptor(hello: &Value) -> Result<(), RichUiDescriptorError> {
658 let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
659 return Ok(());
660 };
661 let Some(value) = manifest.get("rich_ui") else {
662 return Ok(());
663 };
664 validate_rich_ui_descriptor_value(value)
665}
666
667fn validate_rich_ui_descriptor_value(value: &Value) -> Result<(), RichUiDescriptorError> {
668 let descriptor = value
669 .as_object()
670 .ok_or_else(|| RichUiDescriptorError::new("rich_ui", "must be an object"))?;
671 let schema = descriptor
672 .get("schema")
673 .and_then(Value::as_str)
674 .ok_or_else(|| RichUiDescriptorError::new("rich_ui.schema", "must be a string"))?;
675 let digest = descriptor
676 .get("manifest_digest")
677 .and_then(Value::as_str)
678 .ok_or_else(|| RichUiDescriptorError::new("rich_ui.manifest_digest", "must be a string"))?;
679 let bytes = descriptor
680 .get("bytes")
681 .and_then(Value::as_u64)
682 .ok_or_else(|| {
683 RichUiDescriptorError::new("rich_ui.bytes", "must be an integer from 1 to 16777216")
684 })?;
685 let chunks = descriptor
686 .get("chunks")
687 .and_then(Value::as_u64)
688 .ok_or_else(|| {
689 RichUiDescriptorError::new("rich_ui.chunks", "must be an integer from 1 to 1024")
690 })?;
691 validate_rich_ui_fields(schema, digest, bytes, chunks)
692}
693
694fn validate_rich_ui_fields(
695 schema: &str,
696 digest: &str,
697 bytes: u64,
698 chunks: u64,
699) -> Result<(), RichUiDescriptorError> {
700 if !(1..=64).contains(&schema.len())
701 || !schema.bytes().all(|byte| {
702 byte.is_ascii_lowercase()
703 || byte.is_ascii_digit()
704 || matches!(byte, b'.' | b'_' | b'/' | b'-')
705 })
706 {
707 return Err(RichUiDescriptorError::new(
708 "rich_ui.schema",
709 "must be 1 to 64 bytes of [a-z0-9._/-]",
710 ));
711 }
712 if !digest.strip_prefix("sha256:").is_some_and(|hex| {
713 hex.len() == 64
714 && hex
715 .bytes()
716 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
717 }) {
718 return Err(RichUiDescriptorError::new(
719 "rich_ui.manifest_digest",
720 "must be sha256: followed by 64 lowercase hexadecimal characters",
721 ));
722 }
723 if !(1..=16_777_216).contains(&bytes) {
724 return Err(RichUiDescriptorError::new(
725 "rich_ui.bytes",
726 "must be an integer from 1 to 16777216",
727 ));
728 }
729 if !(1..=1_024).contains(&chunks) {
730 return Err(RichUiDescriptorError::new(
731 "rich_ui.chunks",
732 "must be an integer from 1 to 1024",
733 ));
734 }
735 Ok(())
736}
737
738pub const CAP_CATALOG_EVENTS_V1: &str = "catalog-events/v1";
744
745pub const CAP_SCOPE_BIND_PROOF_V1: &str = "scope-bind-proof/v1";
749
750pub const CAP_SCOPE_BIND_PROOF_V2: &str = "scope-bind-proof/v2";
754
755pub const CAP_SCOPE_REPLACE_IF_IDLE_V1: &str = "scope-replace-if-idle/v1";
757
758#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
760#[non_exhaustive]
761pub struct EventDeclaration {
762 pub name: String,
769 pub version: u32,
771 pub headers: Vec<String>,
776 #[serde(default, skip_serializing_if = "Option::is_none")]
778 pub summary: Option<String>,
779}
780
781impl EventDeclaration {
782 pub fn new(name: impl Into<String>, version: u32) -> Self {
785 Self {
786 name: name.into(),
787 version,
788 headers: Vec::new(),
789 summary: None,
790 }
791 }
792
793 pub fn with_headers(mut self, headers: Vec<String>) -> Self {
795 self.headers = headers;
796 self
797 }
798
799 pub fn with_summary(mut self, summary: Option<String>) -> Self {
801 self.summary = summary;
802 self
803 }
804}
805
806#[derive(Debug, Clone, PartialEq, Eq)]
808#[non_exhaustive]
809pub struct EventDeclarationError {
810 field: String,
811 reason: &'static str,
812}
813
814impl EventDeclarationError {
815 fn new(field: impl Into<String>, reason: &'static str) -> Self {
816 Self {
817 field: field.into(),
818 reason,
819 }
820 }
821
822 pub fn field(&self) -> &str {
824 &self.field
825 }
826}
827
828impl fmt::Display for EventDeclarationError {
829 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
830 write!(
831 f,
832 "invalid event declaration: field {} {}",
833 self.field, self.reason
834 )
835 }
836}
837
838impl std::error::Error for EventDeclarationError {}
839
840pub fn validate_hello_event_declarations(hello: &Value) -> Result<(), EventDeclarationError> {
842 validate_events_value(
843 hello
844 .get("manifest")
845 .and_then(|manifest| manifest.get("events")),
846 )
847}
848
849fn is_valid_event_name(name: &str) -> bool {
852 let level_count = name.split('.').count();
853 (1..=4).contains(&level_count)
854 && name.split('.').all(|level| {
855 if level.is_empty() {
856 return false;
857 }
858 let first = level.as_bytes()[0];
859 (1..=63).contains(&level.len())
860 && (first.is_ascii_lowercase() || first.is_ascii_digit())
861 && level
862 .bytes()
863 .skip(1)
864 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
865 && !level.strip_prefix('v').is_some_and(|digits| {
866 !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit())
867 })
868 })
869}
870
871fn validate_events_value(value: Option<&Value>) -> Result<(), EventDeclarationError> {
872 let Some(value) = value.filter(|value| !value.is_null()) else {
873 return Ok(());
874 };
875 let entries = value
876 .as_array()
877 .ok_or_else(|| EventDeclarationError::new("events", "must be a list"))?;
878 if entries.len() > 64 {
879 return Err(EventDeclarationError::new(
880 "events",
881 "must contain at most 64 declarations",
882 ));
883 }
884 let mut pairs = HashSet::new();
885 for (index, entry) in entries.iter().enumerate() {
886 let field = format!("events[{index}]");
887 let entry = entry
888 .as_object()
889 .ok_or_else(|| EventDeclarationError::new(&field, "must be an object"))?;
890 let name_field = format!("{field}.name");
891 let name = entry
892 .get("name")
893 .and_then(Value::as_str)
894 .ok_or_else(|| EventDeclarationError::new(&name_field, "must be a string"))?;
895 if !is_valid_event_name(name) {
896 return Err(EventDeclarationError::new(
897 name_field,
898 "must contain one to four valid dot-separated event-name levels",
899 ));
900 }
901 let version = entry
902 .get("version")
903 .and_then(Value::as_u64)
904 .filter(|version| (1..=u32::MAX as u64).contains(version))
905 .ok_or_else(|| {
906 EventDeclarationError::new(
907 format!("{field}.version"),
908 "must be an integer between 1 and u32::MAX",
909 )
910 })?;
911 if !pairs.insert((name, version)) {
912 return Err(EventDeclarationError::new(
913 &field,
914 "duplicates an event (name, version) pair",
915 ));
916 }
917 let headers_field = format!("{field}.headers");
918 let headers = entry
919 .get("headers")
920 .and_then(Value::as_array)
921 .ok_or_else(|| EventDeclarationError::new(&headers_field, "must be a list"))?;
922 if headers.len() > 16 {
923 return Err(EventDeclarationError::new(
924 headers_field,
925 "must contain at most 16 headers",
926 ));
927 }
928 let mut names = HashSet::new();
929 for (header_index, header) in headers.iter().enumerate() {
930 let header_field = format!("{headers_field}[{header_index}]");
931 let header = header
932 .as_str()
933 .ok_or_else(|| EventDeclarationError::new(&header_field, "must be a string"))?;
934 if !(1..=32).contains(&header.len())
935 || !header.as_bytes()[0].is_ascii_lowercase()
936 || !header
937 .bytes()
938 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
939 {
940 return Err(EventDeclarationError::new(
941 header_field,
942 "must match [a-z][a-z0-9_]{0,31}",
943 ));
944 }
945 if !names.insert(header) {
946 return Err(EventDeclarationError::new(
947 header_field,
948 "duplicates a header name",
949 ));
950 }
951 }
952 if let Some(summary) = entry.get("summary").filter(|value| !value.is_null()) {
953 let summary_field = format!("{field}.summary");
954 let summary = summary
955 .as_str()
956 .ok_or_else(|| EventDeclarationError::new(&summary_field, "must be a string"))?;
957 if summary.chars().count() > 200 || summary.chars().any(char::is_control) {
958 return Err(EventDeclarationError::new(
959 summary_field,
960 "must contain at most 200 characters and no control characters",
961 ));
962 }
963 }
964 }
965 Ok(())
966}
967
968#[derive(Debug, Clone, PartialEq, Eq)]
970pub struct SelfSignalDeclarationError {
971 module_id: String,
972 entry_index: usize,
973 field: &'static str,
974}
975
976impl fmt::Display for SelfSignalDeclarationError {
977 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
978 write!(
979 f,
980 "module_id '{}' self_signals[{}] is missing required field '{}'",
981 self.module_id.escape_debug(),
982 self.entry_index,
983 self.field
984 )
985 }
986}
987
988pub fn validate_hello_self_signal_declarations(
995 hello: &Value,
996) -> Result<(), SelfSignalDeclarationError> {
997 let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
998 return Ok(());
999 };
1000 let module_id = manifest
1001 .get("module_id")
1002 .and_then(Value::as_str)
1003 .unwrap_or("<unknown>");
1004 let Some(entries) = manifest.get("self_signals").and_then(Value::as_array) else {
1005 return Ok(());
1006 };
1007
1008 for (entry_index, entry) in entries.iter().enumerate() {
1009 let Some(entry) = entry.as_object() else {
1010 continue;
1011 };
1012 for field in ["effect", "anchored_to"] {
1013 if !entry.contains_key(field) {
1014 return Err(SelfSignalDeclarationError {
1015 module_id: module_id.to_string(),
1016 entry_index,
1017 field,
1018 });
1019 }
1020 }
1021 }
1022 Ok(())
1023}
1024
1025#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1027#[serde(deny_unknown_fields)]
1028pub struct CapabilityDeclarations {
1029 #[serde(default)]
1030 pub provides: Vec<String>,
1031 #[serde(default)]
1032 pub requires: Vec<CapabilityRequirement>,
1033 #[serde(default)]
1034 pub must_never_reach: Vec<String>,
1035}
1036
1037#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1039pub struct SelfSignalDeclaration {
1040 pub name: String,
1042 pub kind: SelfSignalKind,
1070 pub effect: SelfSignalEffect,
1072 pub anchored_to: SignalAnchor,
1074 #[serde(default, skip_serializing_if = "Option::is_none")]
1081 pub cadence: Option<SignalCadence>,
1082 #[serde(default, skip_serializing_if = "Option::is_none")]
1084 pub domain: Option<String>,
1085 #[serde(default, skip_serializing_if = "Option::is_none")]
1086 pub note: Option<String>,
1087}
1088
1089#[derive(Debug, Clone, PartialEq, Eq)]
1091pub enum SelfSignalKind {
1092 Keepalive,
1093 Busy,
1095 Poller,
1096 Cron,
1097 Sweep,
1098 Watchdog,
1099 Heartbeat,
1100 Other(String),
1101}
1102
1103impl SelfSignalKind {
1104 fn wire_name(&self) -> &str {
1105 match self {
1106 Self::Keepalive => "keepalive",
1107 Self::Busy => "busy",
1108 Self::Poller => "poller",
1109 Self::Cron => "cron",
1110 Self::Sweep => "sweep",
1111 Self::Watchdog => "watchdog",
1112 Self::Heartbeat => "heartbeat",
1113 Self::Other(value) => value,
1114 }
1115 }
1116}
1117
1118impl Serialize for SelfSignalKind {
1119 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1120 where
1121 S: serde::Serializer,
1122 {
1123 serializer.serialize_str(self.wire_name())
1124 }
1125}
1126
1127impl<'de> Deserialize<'de> for SelfSignalKind {
1128 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1129 where
1130 D: Deserializer<'de>,
1131 {
1132 let value = String::deserialize(deserializer)?;
1133 Ok(match value.as_str() {
1134 "keepalive" => Self::Keepalive,
1135 "busy" => Self::Busy,
1136 "poller" => Self::Poller,
1137 "cron" => Self::Cron,
1138 "sweep" => Self::Sweep,
1139 "watchdog" => Self::Watchdog,
1140 "heartbeat" => Self::Heartbeat,
1141 _ => Self::Other(value),
1142 })
1143 }
1144}
1145
1146#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1148#[serde(rename_all = "lowercase")]
1149pub enum SelfSignalEffect {
1150 Observe,
1151 Mutate,
1152}
1153
1154#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1156#[serde(rename_all = "snake_case")]
1157pub enum SignalAnchor {
1158 FixedInterval,
1161 Event { event: String },
1164 HealthGauges { gauges: Vec<String> },
1166}
1167
1168#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1170#[serde(rename_all = "snake_case")]
1171pub enum SignalCadence {
1172 Literal { interval_ms: u64 },
1173 Derived { source: String },
1174}
1175
1176#[derive(Serialize, Debug, Clone, Default, PartialEq, Eq)]
1253#[non_exhaustive]
1254pub struct ManifestProvenance {
1255 #[serde(default, skip_serializing_if = "Option::is_none")]
1256 pub build_git_sha: Option<String>,
1257 #[serde(default, skip_serializing_if = "Option::is_none")]
1261 pub build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1262 #[serde(default, skip_serializing_if = "Option::is_none")]
1263 pub build_lock_digest: Option<String>,
1264 #[serde(default, skip_serializing_if = "Option::is_none")]
1273 pub wire_crate_version: Option<String>,
1274 #[serde(default, skip_serializing_if = "Option::is_none")]
1275 pub store_schema_version: Option<String>,
1276 #[serde(default, skip_serializing_if = "Option::is_none")]
1282 pub launch_nonce_source: Option<LaunchNonceSource>,
1283}
1284
1285#[derive(Debug, Clone, PartialEq, Eq)]
1292#[non_exhaustive]
1293pub enum LaunchNonceSource {
1294 Fd,
1296 Pipe,
1298 Env,
1300 ForwardCompatibleUnknown(String),
1301}
1302
1303impl LaunchNonceSource {
1304 pub fn wire_name(&self) -> &str {
1306 match self {
1307 Self::Fd => "fd",
1308 Self::Pipe => "pipe",
1309 Self::Env => "env",
1310 Self::ForwardCompatibleUnknown(value) => value,
1311 }
1312 }
1313
1314 pub fn from_wire_name(value: &str) -> Self {
1316 match value {
1317 "fd" => Self::Fd,
1318 "pipe" => Self::Pipe,
1319 "env" => Self::Env,
1320 _ => Self::ForwardCompatibleUnknown(value.to_string()),
1321 }
1322 }
1323}
1324
1325impl Serialize for LaunchNonceSource {
1326 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1327 where
1328 S: serde::Serializer,
1329 {
1330 serializer.serialize_str(self.wire_name())
1331 }
1332}
1333
1334impl<'de> Deserialize<'de> for LaunchNonceSource {
1335 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1336 where
1337 D: serde::Deserializer<'de>,
1338 {
1339 let value = String::deserialize(deserializer)?;
1340 Ok(Self::from_wire_name(&value))
1341 }
1342}
1343
1344#[derive(Debug, Clone, PartialEq, Eq)]
1349pub enum BuildGitShaAbsenceReason {
1350 DeclinedDirty,
1351 NeverDerived,
1352 NoGitDir,
1353 ForwardCompatibleUnknown(String),
1354}
1355
1356impl BuildGitShaAbsenceReason {
1357 fn wire_name(&self) -> &str {
1358 match self {
1359 Self::DeclinedDirty => "declined_dirty",
1360 Self::NeverDerived => "never_derived",
1361 Self::NoGitDir => "no_git_dir",
1362 Self::ForwardCompatibleUnknown(value) => value,
1363 }
1364 }
1365}
1366
1367impl Serialize for BuildGitShaAbsenceReason {
1368 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1369 where
1370 S: serde::Serializer,
1371 {
1372 serializer.serialize_str(self.wire_name())
1373 }
1374}
1375
1376impl<'de> Deserialize<'de> for BuildGitShaAbsenceReason {
1377 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1378 where
1379 D: serde::Deserializer<'de>,
1380 {
1381 let value = String::deserialize(deserializer)?;
1382 Ok(match value.as_str() {
1383 "declined_dirty" => Self::DeclinedDirty,
1384 "never_derived" => Self::NeverDerived,
1385 "no_git_dir" => Self::NoGitDir,
1386 _ => Self::ForwardCompatibleUnknown(value),
1387 })
1388 }
1389}
1390
1391#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1393pub enum GitTreeState {
1394 Clean,
1395 Dirty,
1396}
1397
1398#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1403pub enum BuildGitShaSource<'a> {
1404 Git {
1405 revision: &'a str,
1406 tree_state: GitTreeState,
1407 },
1408 NeverDerived,
1409 NoGitDir,
1410}
1411
1412pub fn attestable_commit(revision: &str, tree_state: GitTreeState) -> Option<&str> {
1416 match tree_state {
1417 GitTreeState::Clean => Some(revision),
1418 GitTreeState::Dirty => None,
1419 }
1420}
1421
1422const MAX_PROVENANCE_VALUE_BYTES: usize = 128;
1423const BUILD_GIT_SHA_CANONICAL_FORM: &str = "exactly 40 lowercase hexadecimal characters";
1424const BUILD_LOCK_DIGEST_CANONICAL_FORM: &str = "exactly 64 lowercase hexadecimal characters";
1425
1426#[derive(Deserialize)]
1427struct ManifestProvenanceWire {
1428 #[serde(default)]
1429 build_git_sha: Option<String>,
1430 #[serde(default)]
1431 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1432 #[serde(default)]
1433 build_lock_digest: Option<String>,
1434 #[serde(default)]
1435 wire_crate_version: Option<String>,
1436 #[serde(default)]
1437 store_schema_version: Option<String>,
1438 #[serde(default)]
1439 launch_nonce_source: Option<LaunchNonceSource>,
1440}
1441
1442impl<'de> Deserialize<'de> for ManifestProvenance {
1443 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1444 where
1445 D: Deserializer<'de>,
1446 {
1447 let wire = ManifestProvenanceWire::deserialize(deserializer)?;
1448 let provenance = Self {
1449 build_git_sha: wire.build_git_sha,
1450 build_git_sha_absence_reason: wire.build_git_sha_absence_reason,
1451 build_lock_digest: wire.build_lock_digest,
1452 wire_crate_version: wire.wire_crate_version,
1453 store_schema_version: wire.store_schema_version,
1454 launch_nonce_source: wire.launch_nonce_source,
1455 };
1456 provenance.validate().map_err(D::Error::custom)?;
1457 Ok(provenance)
1458 }
1459}
1460
1461#[derive(Debug, Clone, PartialEq, Eq)]
1463pub struct ProvenanceFormError {
1464 field: &'static str,
1465 length: usize,
1466 canonical_form: &'static str,
1467}
1468
1469impl ProvenanceFormError {
1470 fn new(field: &'static str, length: usize, canonical_form: &'static str) -> Self {
1471 Self {
1472 field,
1473 length,
1474 canonical_form,
1475 }
1476 }
1477
1478 pub fn field(&self) -> &str {
1480 self.field
1481 }
1482
1483 pub fn length(&self) -> usize {
1485 self.length
1486 }
1487
1488 pub fn canonical_form(&self) -> &str {
1490 self.canonical_form
1491 }
1492}
1493
1494impl fmt::Display for ProvenanceFormError {
1495 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1496 write!(
1497 f,
1498 "invalid manifest provenance form: field {} has length {}; canonical form is {}",
1499 self.field, self.length, self.canonical_form
1500 )
1501 }
1502}
1503
1504impl std::error::Error for ProvenanceFormError {}
1505
1506#[derive(Debug, Clone, PartialEq, Eq)]
1507pub struct ManifestProvenanceError {
1508 field: String,
1509 value: String,
1510 reason: &'static str,
1511}
1512
1513impl ManifestProvenanceError {
1514 fn new(field: &str, value: &str, reason: &'static str) -> Self {
1515 Self {
1516 field: field.to_string(),
1517 value: safe_error_value(value),
1518 reason,
1519 }
1520 }
1521
1522 pub fn field(&self) -> &str {
1523 &self.field
1524 }
1525}
1526
1527impl fmt::Display for ManifestProvenanceError {
1528 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1529 write!(
1530 f,
1531 "invalid manifest provenance: field {} has {} (value {:?})",
1532 self.field, self.reason, self.value
1533 )
1534 }
1535}
1536
1537impl std::error::Error for ManifestProvenanceError {}
1538
1539impl ManifestProvenance {
1540 pub fn new() -> Self {
1542 Self::default()
1543 }
1544
1545 pub fn with_build_git_sha(mut self, value: Option<String>) -> Self {
1546 self.build_git_sha = value;
1547 self
1548 }
1549
1550 pub fn with_build_git_sha_absence_reason(
1551 mut self,
1552 value: Option<BuildGitShaAbsenceReason>,
1553 ) -> Self {
1554 self.build_git_sha_absence_reason = value;
1555 self
1556 }
1557
1558 pub fn with_build_lock_digest(mut self, value: Option<String>) -> Self {
1559 self.build_lock_digest = value;
1560 self
1561 }
1562
1563 pub fn with_wire_crate_version(mut self, value: Option<String>) -> Self {
1564 self.wire_crate_version = value;
1565 self
1566 }
1567
1568 pub fn with_store_schema_version(mut self, value: Option<String>) -> Self {
1569 self.store_schema_version = value;
1570 self
1571 }
1572
1573 pub fn with_launch_nonce_source(mut self, value: Option<LaunchNonceSource>) -> Self {
1578 self.launch_nonce_source = value;
1579 self
1580 }
1581
1582 pub fn validate(&self) -> Result<(), ManifestProvenanceError> {
1583 if let (Some(_), Some(reason)) = (
1584 self.build_git_sha.as_ref(),
1585 self.build_git_sha_absence_reason.as_ref(),
1586 ) {
1587 return Err(ManifestProvenanceError::new(
1588 "build_git_sha_absence_reason",
1589 reason.wire_name(),
1590 "must be omitted when build_git_sha is present",
1591 ));
1592 }
1593 for (field, value) in [
1594 ("build_git_sha", self.build_git_sha.as_deref()),
1595 (
1596 "build_git_sha_absence_reason",
1597 self.build_git_sha_absence_reason
1598 .as_ref()
1599 .map(|reason| reason.wire_name()),
1600 ),
1601 ("build_lock_digest", self.build_lock_digest.as_deref()),
1602 ("wire_crate_version", self.wire_crate_version.as_deref()),
1603 ("store_schema_version", self.store_schema_version.as_deref()),
1604 (
1605 "launch_nonce_source",
1606 self.launch_nonce_source
1607 .as_ref()
1608 .map(|source| source.wire_name()),
1609 ),
1610 ] {
1611 let Some(value) = value else { continue };
1612 if value.is_empty() {
1613 return Err(ManifestProvenanceError::new(
1614 field,
1615 value,
1616 "must not be empty",
1617 ));
1618 }
1619 if value.len() > MAX_PROVENANCE_VALUE_BYTES {
1624 return Err(ManifestProvenanceError::new(
1625 field,
1626 value,
1627 "exceeds the 128-byte maximum",
1628 ));
1629 }
1630 if value.bytes().any(|byte| !(0x20..=0x7e).contains(&byte)) {
1631 return Err(ManifestProvenanceError::new(
1632 field,
1633 value,
1634 "contains non-printable ASCII",
1635 ));
1636 }
1637 }
1638 Ok(())
1639 }
1640}
1641
1642pub fn build_provenance(
1660 build_git_sha: Option<&str>,
1661 build_lock_digest: Option<&str>,
1662 store_schema_version: Option<&str>,
1663) -> Result<ManifestProvenance, ProvenanceFormError> {
1664 let build_git_sha = normalize_and_validate_build_git_sha(build_git_sha)?;
1665 build_provenance_with_build_git_sha(
1666 build_git_sha,
1667 None,
1668 build_lock_digest,
1669 store_schema_version,
1670 )
1671}
1672
1673pub fn build_provenance_from_source(
1689 build_git_sha_source: BuildGitShaSource<'_>,
1690 build_lock_digest: Option<&str>,
1691 store_schema_version: Option<&str>,
1692) -> Result<ManifestProvenance, ProvenanceFormError> {
1693 let (raw_build_git_sha, mut build_git_sha_absence_reason) = match build_git_sha_source {
1694 BuildGitShaSource::Git {
1695 revision,
1696 tree_state,
1697 } => match attestable_commit(revision, tree_state) {
1698 Some(revision) => (Some(revision), None),
1699 None => (None, Some(BuildGitShaAbsenceReason::DeclinedDirty)),
1700 },
1701 BuildGitShaSource::NeverDerived => (None, Some(BuildGitShaAbsenceReason::NeverDerived)),
1702 BuildGitShaSource::NoGitDir => (None, Some(BuildGitShaAbsenceReason::NoGitDir)),
1703 };
1704 let build_git_sha = normalize_and_validate_build_git_sha(raw_build_git_sha)?;
1705 if build_git_sha.is_none() {
1706 build_git_sha_absence_reason.get_or_insert(BuildGitShaAbsenceReason::NeverDerived);
1707 }
1708 build_provenance_with_build_git_sha(
1709 build_git_sha,
1710 build_git_sha_absence_reason,
1711 build_lock_digest,
1712 store_schema_version,
1713 )
1714}
1715
1716fn normalize_and_validate_build_git_sha(
1717 build_git_sha: Option<&str>,
1718) -> Result<Option<String>, ProvenanceFormError> {
1719 let build_git_sha = normalize_provenance_fact(build_git_sha);
1720 validate_provenance_form(
1721 "build_git_sha",
1722 build_git_sha.as_deref(),
1723 BUILD_GIT_SHA_CANONICAL_FORM,
1724 40,
1725 )?;
1726 Ok(build_git_sha)
1727}
1728
1729fn build_provenance_with_build_git_sha(
1730 build_git_sha: Option<String>,
1731 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1732 build_lock_digest: Option<&str>,
1733 store_schema_version: Option<&str>,
1734) -> Result<ManifestProvenance, ProvenanceFormError> {
1735 let build_lock_digest = normalize_provenance_fact(build_lock_digest);
1736 validate_provenance_form(
1737 "build_lock_digest",
1738 build_lock_digest.as_deref(),
1739 BUILD_LOCK_DIGEST_CANONICAL_FORM,
1740 64,
1741 )?;
1742
1743 Ok(ManifestProvenance {
1744 build_git_sha,
1745 build_git_sha_absence_reason,
1746 build_lock_digest,
1747 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
1748 store_schema_version: normalize_provenance_fact(store_schema_version),
1749 launch_nonce_source: None,
1750 })
1751}
1752
1753fn validate_provenance_form(
1754 field: &'static str,
1755 value: Option<&str>,
1756 canonical_form: &'static str,
1757 expected_length: usize,
1758) -> Result<(), ProvenanceFormError> {
1759 let Some(value) = value else { return Ok(()) };
1760 if value.len() != expected_length
1761 || !value
1762 .bytes()
1763 .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
1764 {
1765 return Err(ProvenanceFormError::new(field, value.len(), canonical_form));
1766 }
1767 Ok(())
1768}
1769
1770pub const PROVENANCE_SENTINELS: [&str; 3] = ["unknown", "unavailable", "none"];
1778
1779fn normalize_provenance_fact(value: Option<&str>) -> Option<String> {
1780 let value = value?.trim();
1781 if value.is_empty() {
1782 return None;
1783 }
1784 let lowered = value.to_ascii_lowercase();
1785 if PROVENANCE_SENTINELS.contains(&lowered.as_str()) {
1786 return None;
1787 }
1788 Some(value.to_string())
1789}
1790
1791#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1793#[serde(deny_unknown_fields)]
1794pub struct CapabilityRequirement {
1795 pub capability: String,
1796 pub need: CapabilityNeed,
1797}
1798
1799#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1801#[serde(rename_all = "snake_case")]
1802pub enum CapabilityNeed {
1803 Required,
1804 Optional,
1805}
1806
1807#[derive(Debug, Clone, PartialEq, Eq)]
1809pub struct CapabilityGrammarError {
1810 field: String,
1811 value: String,
1812}
1813
1814impl CapabilityGrammarError {
1815 fn new(field: impl Into<String>, value: impl AsRef<str>) -> Self {
1816 Self {
1817 field: field.into(),
1818 value: safe_error_value(value.as_ref()),
1819 }
1820 }
1821
1822 pub fn field(&self) -> &str {
1824 &self.field
1825 }
1826
1827 pub fn value(&self) -> &str {
1829 &self.value
1830 }
1831}
1832
1833impl fmt::Display for CapabilityGrammarError {
1834 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1835 write!(
1836 f,
1837 "invalid capability grammar: field {} has offending value {:?}",
1838 self.field, self.value
1839 )
1840 }
1841}
1842
1843impl std::error::Error for CapabilityGrammarError {}
1844
1845impl ModuleManifest {
1846 pub fn validate_capability_grammar(&self) -> Result<(), CapabilityGrammarError> {
1848 let Some(capabilities) = &self.capabilities else {
1849 return Ok(());
1850 };
1851
1852 validate_capability_list("capabilities.provides", &capabilities.provides)?;
1853 validate_requires(&capabilities.requires)?;
1854 validate_capability_list(
1855 "capabilities.must_never_reach",
1856 &capabilities.must_never_reach,
1857 )
1858 }
1859}
1860
1861pub fn validate_manifest_capability_grammar(
1866 manifest: &Value,
1867) -> Result<(), CapabilityGrammarError> {
1868 let Some(object) = manifest.as_object() else {
1869 return Ok(());
1870 };
1871
1872 validate_capabilities_value(object.get("capabilities"))?;
1873 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
1874}
1875
1876pub fn validate_hello_capability_grammar(hello: &Value) -> Result<(), CapabilityGrammarError> {
1882 let Some(object) = hello.as_object() else {
1883 return Ok(());
1884 };
1885 if let Some(manifest) = object.get("manifest") {
1886 validate_manifest_capability_grammar(manifest)?;
1887 }
1888 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
1889}
1890
1891pub fn is_valid_capability_identifier(identifier: &str) -> bool {
1893 if identifier.chars().any(char::is_whitespace) {
1894 return false;
1895 }
1896 let Some((name, version)) = identifier.split_once("/v") else {
1897 return false;
1898 };
1899 if name.is_empty() || name.len() > 64 || version.is_empty() {
1900 return false;
1901 }
1902
1903 let name_bytes = name.as_bytes();
1904 if !name_bytes[0].is_ascii_lowercase()
1905 || (name.len() > 1
1906 && !name_bytes[name.len() - 1].is_ascii_lowercase()
1907 && !name_bytes[name.len() - 1].is_ascii_digit())
1908 || name_bytes.windows(2).any(|pair| pair == b"--")
1909 {
1910 return false;
1911 }
1912 if !name_bytes
1913 .iter()
1914 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-')
1915 {
1916 return false;
1917 }
1918
1919 if version.len() > 1 && version.starts_with('0')
1920 || !version.bytes().all(|byte| byte.is_ascii_digit())
1921 {
1922 return false;
1923 }
1924 matches!(
1925 version.parse::<u64>(),
1926 Ok(value) if (1..=u64::from(u32::MAX)).contains(&value)
1927 )
1928}
1929
1930fn validate_capabilities_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
1931 let Some(value) = value else {
1932 return Ok(());
1933 };
1934 let Some(object) = value.as_object() else {
1935 return Err(CapabilityGrammarError::new(
1936 "capabilities",
1937 value_description(value),
1938 ));
1939 };
1940
1941 for (key, value) in object {
1942 if !matches!(key.as_str(), "provides" | "requires" | "must_never_reach") {
1943 return Err(CapabilityGrammarError::new(
1944 field_child("capabilities", key),
1945 value_description(value),
1946 ));
1947 }
1948 }
1949
1950 validate_capability_list_value("capabilities.provides", object.get("provides"))?;
1951 validate_requires_value(object.get("requires"))?;
1952 validate_capability_list_value(
1953 "capabilities.must_never_reach",
1954 object.get("must_never_reach"),
1955 )
1956}
1957
1958fn validate_capability_list_value(
1959 field: &str,
1960 value: Option<&Value>,
1961) -> Result<(), CapabilityGrammarError> {
1962 let Some(value) = value else {
1963 return Ok(());
1964 };
1965 let Some(values) = value.as_array() else {
1966 return Err(CapabilityGrammarError::new(field, value_description(value)));
1967 };
1968
1969 let mut seen = HashSet::new();
1970 for (index, value) in values.iter().enumerate() {
1971 let field = format!("{field}[{index}]");
1972 let Some(identifier) = value.as_str() else {
1973 return Err(CapabilityGrammarError::new(field, value_description(value)));
1974 };
1975 validate_capability_identifier(&field, identifier)?;
1976 if !seen.insert(identifier) {
1977 return Err(CapabilityGrammarError::new(field, identifier));
1978 }
1979 }
1980 Ok(())
1981}
1982
1983fn validate_requires_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
1984 let Some(value) = value else {
1985 return Ok(());
1986 };
1987 let Some(values) = value.as_array() else {
1988 return Err(CapabilityGrammarError::new(
1989 "capabilities.requires",
1990 value_description(value),
1991 ));
1992 };
1993
1994 let mut seen = HashSet::new();
1995 for (index, value) in values.iter().enumerate() {
1996 let entry_field = format!("capabilities.requires[{index}]");
1997 let Some(object) = value.as_object() else {
1998 return Err(CapabilityGrammarError::new(
1999 entry_field,
2000 value_description(value),
2001 ));
2002 };
2003 for (key, value) in object {
2004 if !matches!(key.as_str(), "capability" | "need") {
2005 return Err(CapabilityGrammarError::new(
2006 field_child(&entry_field, key),
2007 value_description(value),
2008 ));
2009 }
2010 }
2011 let capability_field = format!("{entry_field}.capability");
2012 let Some(capability) = object.get("capability").and_then(Value::as_str) else {
2013 return Err(CapabilityGrammarError::new(
2014 capability_field,
2015 object
2016 .get("capability")
2017 .map_or("<missing>".to_string(), value_description),
2018 ));
2019 };
2020 validate_capability_identifier(&capability_field, capability)?;
2021
2022 let need_field = format!("{entry_field}.need");
2023 let Some(need) = object.get("need").and_then(Value::as_str) else {
2024 return Err(CapabilityGrammarError::new(
2025 need_field,
2026 object
2027 .get("need")
2028 .map_or("<missing>".to_string(), value_description),
2029 ));
2030 };
2031 if !matches!(need, "required" | "optional") {
2032 return Err(CapabilityGrammarError::new(need_field, need));
2033 }
2034 if !seen.insert(capability) {
2035 return Err(CapabilityGrammarError::new(entry_field, capability));
2036 }
2037 }
2038 Ok(())
2039}
2040
2041fn validate_capability_list(field: &str, values: &[String]) -> Result<(), CapabilityGrammarError> {
2042 let mut seen = HashSet::new();
2043 for (index, identifier) in values.iter().enumerate() {
2044 let field = format!("{field}[{index}]");
2045 validate_capability_identifier(&field, identifier)?;
2046 if !seen.insert(identifier) {
2047 return Err(CapabilityGrammarError::new(field, identifier));
2048 }
2049 }
2050 Ok(())
2051}
2052
2053fn validate_requires(values: &[CapabilityRequirement]) -> Result<(), CapabilityGrammarError> {
2054 let mut seen = HashSet::new();
2055 for (index, requirement) in values.iter().enumerate() {
2056 let field = format!("capabilities.requires[{index}].capability");
2057 validate_capability_identifier(&field, &requirement.capability)?;
2058 if !seen.insert(&requirement.capability) {
2059 return Err(CapabilityGrammarError::new(
2060 format!("capabilities.requires[{index}]"),
2061 &requirement.capability,
2062 ));
2063 }
2064 }
2065 Ok(())
2066}
2067
2068fn validate_capability_identifier(
2069 field: &str,
2070 identifier: &str,
2071) -> Result<(), CapabilityGrammarError> {
2072 if is_valid_capability_identifier(identifier) {
2073 Ok(())
2074 } else {
2075 Err(CapabilityGrammarError::new(field, identifier))
2076 }
2077}
2078
2079fn validate_runtime_computed(
2080 value: Option<&Value>,
2081 field: &str,
2082) -> Result<(), CapabilityGrammarError> {
2083 let Some(value) = value else {
2084 return Ok(());
2085 };
2086 let Some(pointers) = value.as_array() else {
2087 return Err(CapabilityGrammarError::new(field, value_description(value)));
2088 };
2089
2090 for (index, pointer) in pointers.iter().enumerate() {
2091 let field = format!("{field}[{index}]");
2092 let Some(pointer) = pointer.as_str() else {
2093 return Err(CapabilityGrammarError::new(
2094 field,
2095 value_description(pointer),
2096 ));
2097 };
2098 let Some(tokens) = parse_json_pointer(pointer) else {
2099 return Err(CapabilityGrammarError::new(field, pointer));
2100 };
2101 if tokens.first().is_some_and(|token| token == "capabilities") {
2102 return Err(CapabilityGrammarError::new(field, pointer));
2103 }
2104 }
2105 Ok(())
2106}
2107
2108fn parse_json_pointer(pointer: &str) -> Option<Vec<String>> {
2109 if pointer.is_empty() {
2110 return Some(Vec::new());
2111 }
2112 let raw_tokens = pointer.strip_prefix('/')?;
2113 raw_tokens
2114 .split('/')
2115 .map(unescape_json_pointer_token)
2116 .collect()
2117}
2118
2119fn unescape_json_pointer_token(token: &str) -> Option<String> {
2120 let mut output = String::with_capacity(token.len());
2121 let mut characters = token.chars();
2122 while let Some(character) = characters.next() {
2123 if character != '~' {
2124 output.push(character);
2125 continue;
2126 }
2127 match characters.next()? {
2128 '0' => output.push('~'),
2129 '1' => output.push('/'),
2130 _ => return None,
2131 }
2132 }
2133 Some(output)
2134}
2135
2136fn field_child(parent: &str, child: &str) -> String {
2137 let child = safe_error_value(child);
2138 format!("{parent}.{child}")
2139}
2140
2141fn value_description(value: &Value) -> String {
2142 match value {
2143 Value::String(value) => safe_error_value(value),
2144 Value::Null => "null".to_string(),
2145 Value::Bool(value) => value.to_string(),
2146 Value::Number(value) => value.to_string(),
2147 Value::Array(_) => "<array>".to_string(),
2148 Value::Object(_) => "<object>".to_string(),
2149 }
2150}
2151
2152fn safe_error_value(value: &str) -> String {
2153 let lower = value.to_ascii_lowercase();
2154 if ["secret", "password", "api_key"]
2155 .iter()
2156 .any(|marker| lower.contains(marker))
2157 || lower.starts_with("sk-")
2158 || lower.starts_with("akia")
2159 || lower.starts_with("bearer ")
2160 || lower.starts_with("token=")
2161 || lower.starts_with("credential=")
2162 {
2163 "<redacted>".to_string()
2164 } else {
2165 value.to_string()
2166 }
2167}
2168
2169#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2175#[serde(rename_all = "snake_case")]
2176pub enum TrustTier {
2177 FirstParty,
2178 Reviewed,
2179 Untrusted,
2180}
2181
2182#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2186#[serde(tag = "role", rename_all = "snake_case")]
2187pub enum ProviderRole {
2188 ToolProvider {
2189 tools: Vec<Tool>,
2190 identity_scope: Vec<IdentityScope>,
2198 concurrency: Concurrency,
2199 emits_push: bool,
2200 sub_supervises: bool,
2201 },
2202 PipelineStage {
2203 stage: PipelineStageKind,
2204 applies_to: PipelineAppliesTo,
2205 interface: String,
2206 declares_frozen_floor: bool,
2207 needs_signals: Vec<String>,
2208 conformance_class: String,
2209 },
2210 ManagementSurface {
2211 operations: Vec<ManagementOperation>,
2212 config_schema: Value,
2213 observability: Vec<ObservabilitySurface>,
2214 identity_scope: Vec<IdentityScope>,
2218 #[serde(default)]
2219 concurrency: Concurrency,
2220 },
2221 InternalService {
2222 service_id: String,
2223 transport: InternalTransport,
2224 agent_facing: bool,
2225 operations: Vec<String>,
2226 },
2227}
2228
2229#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2242#[serde(rename_all = "snake_case")]
2243pub enum ExecutionMode {
2244 Pure,
2245 Mutating,
2246 Unfenceable,
2247}
2248
2249#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2251pub struct Tool {
2252 pub name: String,
2253 #[serde(default, skip_serializing_if = "Option::is_none")]
2254 pub description: Option<String>,
2255 pub execution_mode: ExecutionMode,
2260 pub schema: Value,
2261}
2262
2263#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2269#[serde(rename_all = "snake_case")]
2270pub enum Concurrency {
2271 Serial,
2273 ModuleManaged,
2276 StatelessParallel,
2279}
2280
2281#[allow(clippy::derivable_impls)]
2282impl Default for Concurrency {
2293 fn default() -> Self {
2294 Self::ModuleManaged
2295 }
2296}
2297
2298#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2305#[serde(rename_all = "snake_case")]
2306pub enum IdentityScope {
2307 Session,
2308 Project,
2309}
2310
2311#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2313#[serde(rename_all = "snake_case")]
2314pub enum PipelineStageKind {
2315 Transform,
2316 Codec,
2317 Auth,
2318}
2319
2320#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2322pub struct PipelineAppliesTo {
2323 pub provider: String,
2324 pub model: String,
2325}
2326
2327#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2330#[non_exhaustive]
2331pub struct OperationPayload {
2332 max_bytes: usize,
2333}
2334
2335impl OperationPayload {
2336 pub fn new(max_bytes: usize) -> Self {
2337 Self { max_bytes }
2338 }
2339
2340 pub fn max_bytes(&self) -> usize {
2341 self.max_bytes
2342 }
2343}
2344
2345#[derive(Debug, Clone, PartialEq, Eq)]
2347#[non_exhaustive]
2348pub enum OperationPayloadError {
2349 UnknownOperation { operation: String },
2350 WatchOperation { operation: String },
2351 InvalidMaxBytes { operation: String },
2352}
2353
2354impl fmt::Display for OperationPayloadError {
2355 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2356 write!(f, "{self:?}")
2357 }
2358}
2359
2360impl std::error::Error for OperationPayloadError {}
2361
2362impl ModuleManifest {
2363 pub fn validate_operation_payload(&self) -> Result<(), OperationPayloadError> {
2366 for (name, payload) in &self.operation_payload {
2367 if !self.provides.iter().any(|role| match role {
2368 ProviderRole::ManagementSurface { operations, .. } => {
2369 operations.iter().any(|op| op.name == *name)
2370 }
2371 _ => false,
2372 }) {
2373 return Err(OperationPayloadError::UnknownOperation {
2374 operation: name.clone(),
2375 });
2376 }
2377 if self
2378 .operation_delivery
2379 .get(name)
2380 .is_some_and(OperationDelivery::is_watch)
2381 {
2382 return Err(OperationPayloadError::WatchOperation {
2383 operation: name.clone(),
2384 });
2385 }
2386 if !(1..=crate::framed_body::MAX_DECLARED_PAYLOAD_BYTES).contains(&payload.max_bytes) {
2387 return Err(OperationPayloadError::InvalidMaxBytes {
2388 operation: name.clone(),
2389 });
2390 }
2391 }
2392 Ok(())
2393 }
2394}
2395
2396#[derive(Debug, Clone, PartialEq, Eq)]
2401#[non_exhaustive]
2402pub enum FlowOperationsError {
2403 FlowScopesNotDeclared,
2406 NotAList,
2408 TooMany { count: usize },
2410 DuplicateOperation { operation: String },
2412 UnknownOperation { operation: String },
2414}
2415
2416impl fmt::Display for FlowOperationsError {
2417 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2418 match self {
2419 Self::FlowScopesNotDeclared => write!(
2420 f,
2421 "flow_operations requires '{}' or '{}' in capabilities.provides",
2422 crate::scope::FLOW_SCOPES_CAPABILITY,
2423 crate::call_mode::CALL_MODES_CAPABILITY
2424 ),
2425 Self::NotAList => f.write_str("flow_operations must be an array of operation names"),
2426 Self::TooMany { count } => write!(
2427 f,
2428 "flow_operations lists {count} names, more than {MAX_FLOW_OPERATIONS}"
2429 ),
2430 Self::DuplicateOperation { operation } => {
2431 write!(f, "flow_operations names '{operation}' more than once")
2432 }
2433 Self::UnknownOperation { operation } => write!(
2434 f,
2435 "flow_operations names '{operation}', which is not a declared management operation"
2436 ),
2437 }
2438 }
2439}
2440
2441impl std::error::Error for FlowOperationsError {}
2442
2443impl ModuleManifest {
2444 pub fn validate_flow_operations(&self) -> Result<(), FlowOperationsError> {
2449 match &self.flow_operations {
2450 Some(operations) => check_flow_operations(self, operations),
2451 None => Ok(()),
2452 }
2453 }
2454}
2455
2456fn check_flow_operations(
2457 manifest: &ModuleManifest,
2458 operations: &[String],
2459) -> Result<(), FlowOperationsError> {
2460 let admits_flows = manifest.capabilities.as_ref().is_some_and(|capabilities| {
2461 capabilities.provides.iter().any(|capability| {
2462 capability == crate::scope::FLOW_SCOPES_CAPABILITY
2463 || capability == crate::call_mode::CALL_MODES_CAPABILITY
2464 })
2465 });
2466 if !admits_flows {
2467 return Err(FlowOperationsError::FlowScopesNotDeclared);
2468 }
2469 if operations.len() > MAX_FLOW_OPERATIONS {
2470 return Err(FlowOperationsError::TooMany {
2471 count: operations.len(),
2472 });
2473 }
2474 let mut seen = HashSet::new();
2475 for operation in operations {
2476 if !seen.insert(operation.as_str()) {
2477 return Err(FlowOperationsError::DuplicateOperation {
2478 operation: operation.clone(),
2479 });
2480 }
2481 let declared = manifest.provides.iter().any(|role| match role {
2482 ProviderRole::ManagementSurface { operations, .. } => {
2483 operations.iter().any(|op| op.name == *operation)
2484 }
2485 _ => false,
2486 });
2487 if !declared {
2488 return Err(FlowOperationsError::UnknownOperation {
2489 operation: operation.clone(),
2490 });
2491 }
2492 }
2493 Ok(())
2494}
2495
2496fn decode_flow_operations(
2499 manifest: &ModuleManifest,
2500 value: &Value,
2501) -> Result<Vec<String>, FlowOperationsError> {
2502 let operations: Vec<String> =
2503 serde_json::from_value(value.clone()).map_err(|_| FlowOperationsError::NotAList)?;
2504 check_flow_operations(manifest, &operations)?;
2505 Ok(operations)
2506}
2507
2508pub fn validate_hello_flow_operations(hello: &Value) -> Result<(), FlowOperationsError> {
2514 let Some(manifest_value) = hello.get("manifest") else {
2515 return Ok(());
2516 };
2517 let Some(value) = manifest_value
2518 .get("flow_operations")
2519 .filter(|value| !value.is_null())
2520 else {
2521 return Ok(());
2522 };
2523 let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
2524 return Ok(());
2525 };
2526 decode_flow_operations(&manifest, value).map(|_| ())
2527}
2528
2529#[derive(Debug, Clone, PartialEq, Eq)]
2534#[non_exhaustive]
2535pub enum ConfirmOperationsError {
2536 NotAList,
2538 TooMany { count: usize },
2540 DuplicateOperation { operation: String },
2542 UnknownOperation { operation: String },
2544}
2545
2546impl fmt::Display for ConfirmOperationsError {
2547 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2548 match self {
2549 Self::NotAList => {
2550 f.write_str("confirm_operations must be an array of operation names")
2551 }
2552 Self::TooMany { count } => write!(
2553 f,
2554 "confirm_operations lists {count} names, more than {MAX_CONFIRM_OPERATIONS}"
2555 ),
2556 Self::DuplicateOperation { operation } => {
2557 write!(f, "confirm_operations names '{operation}' more than once")
2558 }
2559 Self::UnknownOperation { operation } => write!(
2560 f,
2561 "confirm_operations names '{operation}', which is not a declared management operation"
2562 ),
2563 }
2564 }
2565}
2566
2567impl std::error::Error for ConfirmOperationsError {}
2568
2569impl ModuleManifest {
2570 pub fn validate_confirm_operations(&self) -> Result<(), ConfirmOperationsError> {
2574 match &self.confirm_operations {
2575 Some(operations) => check_confirm_operations(self, operations),
2576 None => Ok(()),
2577 }
2578 }
2579}
2580
2581fn check_confirm_operations(
2582 manifest: &ModuleManifest,
2583 operations: &[String],
2584) -> Result<(), ConfirmOperationsError> {
2585 if operations.len() > MAX_CONFIRM_OPERATIONS {
2586 return Err(ConfirmOperationsError::TooMany {
2587 count: operations.len(),
2588 });
2589 }
2590 let mut seen = HashSet::new();
2591 for operation in operations {
2592 if !seen.insert(operation.as_str()) {
2593 return Err(ConfirmOperationsError::DuplicateOperation {
2594 operation: operation.clone(),
2595 });
2596 }
2597 if !declares_management_operation(manifest, operation) {
2598 return Err(ConfirmOperationsError::UnknownOperation {
2599 operation: operation.clone(),
2600 });
2601 }
2602 }
2603 Ok(())
2604}
2605
2606fn declares_management_operation(manifest: &ModuleManifest, operation: &str) -> bool {
2607 manifest.provides.iter().any(|role| match role {
2608 ProviderRole::ManagementSurface { operations, .. } => {
2609 operations.iter().any(|op| op.name == operation)
2610 }
2611 _ => false,
2612 })
2613}
2614
2615fn decode_confirm_operations(
2618 manifest: &ModuleManifest,
2619 value: &Value,
2620) -> Result<Vec<String>, ConfirmOperationsError> {
2621 let operations: Vec<String> =
2622 serde_json::from_value(value.clone()).map_err(|_| ConfirmOperationsError::NotAList)?;
2623 check_confirm_operations(manifest, &operations)?;
2624 Ok(operations)
2625}
2626
2627pub fn validate_hello_confirm_operations(hello: &Value) -> Result<(), ConfirmOperationsError> {
2633 let Some(manifest_value) = hello.get("manifest") else {
2634 return Ok(());
2635 };
2636 let Some(value) = manifest_value
2637 .get("confirm_operations")
2638 .filter(|value| !value.is_null())
2639 else {
2640 return Ok(());
2641 };
2642 let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
2643 return Ok(());
2644 };
2645 decode_confirm_operations(&manifest, value).map(|_| ())
2646}
2647
2648#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2653pub struct ManagementOperation {
2654 pub name: String,
2655 pub kind: ManagementOperationKind,
2656 #[serde(default, skip_serializing_if = "Option::is_none")]
2657 pub description: Option<String>,
2658}
2659
2660#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2661#[serde(rename_all = "snake_case")]
2662pub enum ManagementOperationKind {
2663 Query,
2664 Mutate,
2665}
2666
2667#[derive(Debug, Clone, PartialEq, Eq)]
2670#[non_exhaustive]
2671pub enum OperationDelivery {
2672 Watch,
2673 Other(String),
2674}
2675
2676impl OperationDelivery {
2677 pub const WATCH: Self = Self::Watch;
2679
2680 pub fn wire_name(&self) -> &str {
2682 match self {
2683 Self::Watch => "watch",
2684 Self::Other(value) => value,
2685 }
2686 }
2687
2688 pub fn is_watch(&self) -> bool {
2690 self.wire_name() == "watch"
2691 }
2692}
2693
2694impl Serialize for OperationDelivery {
2695 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2696 where
2697 S: serde::Serializer,
2698 {
2699 serializer.serialize_str(self.wire_name())
2700 }
2701}
2702
2703impl<'de> Deserialize<'de> for OperationDelivery {
2704 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2705 where
2706 D: Deserializer<'de>,
2707 {
2708 let value = String::deserialize(deserializer)?;
2709 Ok(if value == "watch" {
2710 Self::WATCH
2711 } else {
2712 Self::Other(value)
2713 })
2714 }
2715}
2716
2717#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2719pub struct ObservabilitySurface {
2720 pub name: String,
2721 pub kind: ObservabilityKind,
2722}
2723
2724#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2725#[serde(rename_all = "snake_case")]
2726pub enum ObservabilityKind {
2727 Snapshot,
2728 Stream,
2729}
2730
2731#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2732#[serde(rename_all = "snake_case")]
2733pub enum InternalTransport {
2734 Bulk,
2735}
2736
2737#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2739#[serde(tag = "role", rename_all = "snake_case")]
2740pub enum ConsumerRole {
2741 ToolClient { of: Vec<String> },
2742 LlmClient { via: String, auth: String },
2743 ServiceClient { of: Vec<String> },
2744}
2745
2746#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2748pub struct Bindings {
2749 pub storage: StorageBinding,
2750 pub vault_grants: Vec<VaultGrant>,
2751 pub identity: IdentityBinding,
2752}
2753
2754#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2756pub struct StorageBinding {
2757 pub kind: StorageKind,
2758 pub scope: StorageScope,
2759 pub owns_schema: bool,
2760}
2761
2762#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2763#[serde(rename_all = "snake_case")]
2764pub enum StorageKind {
2765 Sqlite,
2766}
2767
2768#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2769#[serde(rename_all = "snake_case")]
2770pub enum StorageScope {
2771 Project,
2772}
2773
2774#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2775pub struct VaultGrant {
2776 pub secret: String,
2777 pub reason: String,
2778}
2779
2780#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2781pub struct IdentityBinding {
2782 pub requires: Vec<IdentityScope>,
2783 pub optional: Vec<IdentityScope>,
2784}
2785
2786#[cfg(test)]
2787mod tests {
2788 use super::*;
2789 use serde_json::json;
2790
2791 fn aft_manifest_fixture() -> ModuleManifest {
2792 ModuleManifest::builder("aft", "0.39.2")
2793 .trust_tier(Some(TrustTier::FirstParty))
2794 .bindings(Some(Bindings {
2795 storage: StorageBinding {
2796 kind: StorageKind::Sqlite,
2797 scope: StorageScope::Project,
2798 owns_schema: true,
2799 },
2800 vault_grants: vec![VaultGrant {
2801 secret: "provider_api_key".to_string(),
2802 reason: "cortexkit_native auth".to_string(),
2803 }],
2804 identity: IdentityBinding {
2805 requires: vec![IdentityScope::Project],
2806 optional: vec![IdentityScope::Session],
2807 },
2808 }))
2809 .protocol_ver(1)
2810 .provides(vec![ProviderRole::ToolProvider {
2811 tools: vec![
2812 Tool {
2813 name: "read".to_string(),
2814 description: None,
2815 execution_mode: ExecutionMode::Pure,
2816 schema: json!({"type": "object"}),
2817 },
2818 Tool {
2819 name: "grep".to_string(),
2820 description: None,
2821 execution_mode: ExecutionMode::Pure,
2822 schema: json!({"type": "object"}),
2823 },
2824 Tool {
2825 name: "outline".to_string(),
2826 description: None,
2827 execution_mode: ExecutionMode::Pure,
2828 schema: json!({"type": "object"}),
2829 },
2830 Tool {
2831 name: "semantic_search".to_string(),
2832 description: None,
2833 execution_mode: ExecutionMode::Pure,
2834 schema: json!({"type": "object"}),
2835 },
2836 Tool {
2837 name: "edit".to_string(),
2838 description: None,
2839 execution_mode: ExecutionMode::Mutating,
2840 schema: json!({"type": "object"}),
2841 },
2842 Tool {
2843 name: "write".to_string(),
2844 description: None,
2845 execution_mode: ExecutionMode::Mutating,
2846 schema: json!({"type": "object"}),
2847 },
2848 Tool {
2849 name: "bash".to_string(),
2850 description: None,
2851 execution_mode: ExecutionMode::Unfenceable,
2852 schema: json!({"type": "object"}),
2853 },
2854 ],
2855 identity_scope: vec![IdentityScope::Session, IdentityScope::Project],
2856 concurrency: Concurrency::ModuleManaged,
2857 emits_push: true,
2858 sub_supervises: true,
2859 }])
2860 .consumes(vec![ConsumerRole::ServiceClient {
2861 of: vec!["embedding.v2".to_string()],
2862 }])
2863 .build()
2864 }
2865
2866 #[test]
2867 fn serde_round_trips_representative_manifest() {
2868 let manifest = aft_manifest_fixture();
2869 let serialized = serde_json::to_string_pretty(&manifest).unwrap();
2870 let decoded: ModuleManifest = serde_json::from_str(&serialized).unwrap();
2871
2872 assert_eq!(manifest, decoded);
2873 }
2874
2875 #[test]
2876 fn builder_defaults_additions_to_honest_absence_and_round_trips() {
2877 let manifest = ModuleManifest::builder("builder-defaults", "2.0.0").build();
2878
2879 assert_eq!(manifest.module_id, "builder-defaults");
2880 assert_eq!(manifest.module_version, "2.0.0");
2881 assert_eq!(manifest.protocol_ver, PROTOCOL_VERSION);
2882 assert_eq!(manifest.trust_tier, None);
2883 assert!(manifest.provides.is_empty());
2884 assert!(manifest.consumes.is_empty());
2885 assert_eq!(manifest.bindings, None);
2886 assert_eq!(manifest.capabilities, None);
2887 assert_eq!(manifest.self_signals, None);
2888 assert_eq!(manifest.provenance, None);
2889
2890 let encoded = serde_json::to_value(&manifest).expect("builder manifest serializes");
2891 for optional in [
2892 "trust_tier",
2893 "consumes",
2894 "bindings",
2895 "capabilities",
2896 "self_signals",
2897 "provenance",
2898 ] {
2899 assert!(
2900 encoded.get(optional).is_none(),
2901 "an absent {optional} declaration must stay absent on the wire"
2902 );
2903 }
2904 let decoded: ModuleManifest =
2905 serde_json::from_value(encoded).expect("builder manifest round-trips");
2906 assert_eq!(decoded, manifest);
2907 }
2908
2909 #[test]
2910 fn fully_populated_builder_manifest_matches_the_literal_wire_golden() {
2911 let manifest = ModuleManifest::builder("full-builder", "2.0.0")
2912 .trust_tier(Some(TrustTier::Reviewed))
2913 .bindings(Some(Bindings {
2914 storage: StorageBinding {
2915 kind: StorageKind::Sqlite,
2916 scope: StorageScope::Project,
2917 owns_schema: false,
2918 },
2919 vault_grants: Vec::new(),
2920 identity: IdentityBinding {
2921 requires: vec![IdentityScope::Project],
2922 optional: Vec::new(),
2923 },
2924 }))
2925 .provides(vec![ProviderRole::ToolProvider {
2926 tools: vec![Tool {
2927 name: "read".to_string(),
2928 description: None,
2929 execution_mode: ExecutionMode::Pure,
2930 schema: json!({"type": "object"}),
2931 }],
2932 identity_scope: vec![IdentityScope::Project],
2933 concurrency: Concurrency::Serial,
2934 emits_push: false,
2935 sub_supervises: false,
2936 }])
2937 .consumes(vec![ConsumerRole::ServiceClient {
2938 of: vec!["embedding.v2".to_string()],
2939 }])
2940 .capabilities(Some(CapabilityDeclarations {
2941 provides: vec!["embedding/v2".to_string()],
2942 requires: Vec::new(),
2943 must_never_reach: Vec::new(),
2944 }))
2945 .self_signals(Some(vec![SelfSignalDeclaration {
2946 name: "usage_poller".to_string(),
2947 kind: SelfSignalKind::Poller,
2948 effect: SelfSignalEffect::Observe,
2949 anchored_to: SignalAnchor::FixedInterval,
2950 cadence: Some(SignalCadence::Literal {
2951 interval_ms: 60_000,
2952 }),
2953 domain: Some("provider-usage".to_string()),
2954 note: None,
2955 }]))
2956 .provenance(Some(ManifestProvenance {
2957 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
2958 build_git_sha_absence_reason: None,
2959 build_lock_digest: Some(
2960 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
2961 ),
2962 wire_crate_version: Some("0.16.0".to_string()),
2963 store_schema_version: Some("42".to_string()),
2964 launch_nonce_source: None,
2965 }))
2966 .build();
2967
2968 assert_eq!(
2969 serde_json::to_vec(&manifest).expect("builder manifest serializes"),
2970 include_bytes!("../tests/golden/module_manifest_builder_full.json"),
2971 "the builder must preserve the prior fully populated literal wire bytes"
2972 );
2973 }
2974
2975 #[test]
2976 fn old_manifest_with_unread_fields_decodes_and_round_trips_verbatim() {
2977 let raw = include_bytes!("../tests/golden/module_manifest_builder_full.json");
2978 let decoded: ModuleManifest =
2979 serde_json::from_slice(raw).expect("old manifest with all unread fields decodes");
2980
2981 assert_eq!(decoded.trust_tier, Some(TrustTier::Reviewed));
2982 assert!(!decoded.consumes.is_empty());
2983 assert!(decoded.bindings.is_some());
2984
2985 let reencoded = serde_json::to_vec(&decoded).expect("re-encode succeeds");
2986 assert_eq!(
2987 reencoded, raw,
2988 "old manifest relay stays byte-for-byte verbatim"
2989 );
2990 }
2991
2992 #[test]
2993 fn new_manifest_omits_unread_fields_on_wire_and_decodes_cleanly() {
2994 let raw = include_bytes!("../tests/golden/module_manifest_diet.json");
2995 let decoded: ModuleManifest =
2996 serde_json::from_slice(raw).expect("new manifest omitting unread fields decodes");
2997
2998 assert_eq!(decoded.trust_tier, None);
2999 assert!(decoded.consumes.is_empty());
3000 assert_eq!(decoded.bindings, None);
3001
3002 let pretty = format!("{}\n", serde_json::to_string_pretty(&decoded).unwrap());
3003 assert_eq!(
3004 pretty.as_bytes(),
3005 raw,
3006 "new manifest matches golden byte-for-byte without unread keys"
3007 );
3008
3009 let as_val: serde_json::Value = serde_json::to_value(&decoded).unwrap();
3010 assert!(
3011 as_val.get("trust_tier").is_none(),
3012 "no trust_tier on wire for new manifest"
3013 );
3014 assert!(
3015 as_val.get("consumes").is_none(),
3016 "no consumes on wire for empty consumes"
3017 );
3018 assert!(
3019 as_val.get("bindings").is_none(),
3020 "no bindings on wire for new manifest"
3021 );
3022 }
3023
3024 #[test]
3025 fn aft_manifest_fixture_matches_v1_contract() {
3026 let manifest = aft_manifest_fixture();
3027
3028 assert_eq!(manifest.module_id, "aft");
3029 let ProviderRole::ToolProvider {
3030 tools,
3031 identity_scope,
3032 concurrency,
3033 emits_push,
3034 sub_supervises,
3035 } = &manifest.provides[0]
3036 else {
3037 panic!("AFT fixture must expose one tool_provider role");
3038 };
3039
3040 assert_eq!(*concurrency, Concurrency::ModuleManaged);
3041 assert!(*emits_push);
3042 assert!(*sub_supervises);
3043 assert_eq!(
3044 identity_scope,
3045 &vec![IdentityScope::Session, IdentityScope::Project]
3046 );
3047 assert_eq!(
3048 tools
3049 .iter()
3050 .map(|tool| (tool.name.as_str(), tool.execution_mode))
3051 .collect::<Vec<_>>(),
3052 vec![
3053 ("read", ExecutionMode::Pure),
3054 ("grep", ExecutionMode::Pure),
3055 ("outline", ExecutionMode::Pure),
3056 ("semantic_search", ExecutionMode::Pure),
3057 ("edit", ExecutionMode::Mutating),
3058 ("write", ExecutionMode::Mutating),
3059 ("bash", ExecutionMode::Unfenceable),
3060 ]
3061 );
3062 }
3063
3064 #[test]
3065 fn tool_provider_role_tag_serializes_as_snake_case() {
3066 let manifest = aft_manifest_fixture();
3067 let value = serde_json::to_value(&manifest).unwrap();
3068
3069 assert_eq!(value["provides"][0]["role"], "tool_provider");
3070 }
3071
3072 #[test]
3073 fn manifest_without_capabilities_preserves_the_existing_wire_shape() {
3074 let manifest = aft_manifest_fixture();
3075 let encoded = serde_json::to_value(&manifest).expect("manifest serializes");
3076 assert!(encoded.get("capabilities").is_none());
3077
3078 let decoded: ModuleManifest =
3079 serde_json::from_value(encoded).expect("legacy manifest parses");
3080 assert_eq!(decoded.capabilities, None);
3081 }
3082
3083 #[test]
3084 fn capability_identifier_lexical_grammar_accepts_only_pinned_forms() {
3085 for identifier in [
3086 "a/v1",
3087 "credentials-provider/v1",
3088 "a1-b2/v4294967295",
3089 "a123456789012345678901234567890123456789012345678901234567890123/v1",
3090 ] {
3091 assert!(
3092 is_valid_capability_identifier(identifier),
3093 "identifier must be accepted: {identifier}"
3094 );
3095 }
3096
3097 for identifier in [
3098 "credentials-Provider/v1",
3099 "credentials-provider/v01",
3100 "credentials-provider-/v1",
3101 "credentials--provider/v1",
3102 "Credentials-provider/v1",
3103 "credentials-provider/1",
3104 "credentials provider/v1",
3105 "credentials-provider/v0",
3106 "credentials-provider/v4294967296",
3107 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/v1",
3108 ] {
3109 assert!(
3110 !is_valid_capability_identifier(identifier),
3111 "identifier must be rejected: {identifier}"
3112 );
3113 }
3114 }
3115
3116 #[test]
3117 fn capability_grammar_errors_redact_secret_shaped_values() {
3118 let error = validate_manifest_capability_grammar(&json!({
3119 "capabilities": { "provides": ["sk-secret-value/v0"] }
3120 }))
3121 .expect_err("secret-shaped capability identifier is malformed");
3122 assert_eq!(error.field(), "capabilities.provides[0]");
3123 assert_eq!(error.value(), "<redacted>");
3124 assert!(!error.to_string().contains("sk-secret-value"));
3125 }
3126
3127 #[test]
3134 fn provenance_builder_sentinels_become_field_omission() {
3135 for sentinel in [
3136 "unknown",
3137 "UNKNOWN",
3138 "Unknown",
3139 "unavailable",
3140 "none",
3141 "None",
3142 " unknown ",
3143 "",
3144 ] {
3145 let p = build_provenance_from_source(
3146 BuildGitShaSource::Git {
3147 revision: sentinel,
3148 tree_state: GitTreeState::Clean,
3149 },
3150 Some(sentinel),
3151 Some(sentinel),
3152 )
3153 .expect("sentinels are omitted before form validation");
3154 assert_eq!(
3155 (
3156 p.build_git_sha,
3157 p.build_git_sha_absence_reason,
3158 p.build_lock_digest,
3159 p.store_schema_version,
3160 ),
3161 (
3162 None,
3163 Some(BuildGitShaAbsenceReason::NeverDerived),
3164 None,
3165 None,
3166 ),
3167 "sentinel {sentinel:?} must be omitted, not published"
3168 );
3169 }
3170 let real = build_provenance_from_source(
3171 BuildGitShaSource::Git {
3172 revision: "0123456789abcdef0123456789abcdef01234567",
3173 tree_state: GitTreeState::Clean,
3174 },
3175 None,
3176 Some("9"),
3177 )
3178 .expect("canonical build revision is accepted");
3179 assert_eq!(
3180 real.build_git_sha.as_deref(),
3181 Some("0123456789abcdef0123456789abcdef01234567")
3182 );
3183 assert_eq!(real.store_schema_version.as_deref(), Some("9"));
3184 assert_eq!(
3188 real.wire_crate_version.as_deref(),
3189 Some(crate::SUBC_PROTOCOL_CRATE_VERSION)
3190 );
3191 }
3192
3193 #[test]
3194 fn build_provenance_accepts_canonical_sha_and_lock_digest() {
3195 let provenance = build_provenance_from_source(
3196 BuildGitShaSource::Git {
3197 revision: " 0123456789abcdef0123456789abcdef01234567 ",
3198 tree_state: GitTreeState::Clean,
3199 },
3200 Some(" abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789 "),
3201 Some(" schema-v3 "),
3202 )
3203 .expect("canonical build facts are accepted");
3204
3205 assert_eq!(
3206 provenance,
3207 ManifestProvenance {
3208 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
3209 build_git_sha_absence_reason: None,
3210 build_lock_digest: Some(
3211 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
3212 ),
3213 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
3214 store_schema_version: Some("schema-v3".to_string()),
3215 launch_nonce_source: None,
3216 }
3217 );
3218 }
3219
3220 #[test]
3221 fn build_provenance_refuses_an_abbreviated_git_sha() {
3222 let error = build_provenance_from_source(
3223 BuildGitShaSource::Git {
3224 revision: "0123456789ab",
3225 tree_state: GitTreeState::Clean,
3226 },
3227 None,
3228 None,
3229 )
3230 .expect_err("a 12-character abbreviation is not canonical");
3231
3232 assert_eq!(error.field(), "build_git_sha");
3233 assert_eq!(error.length(), 12);
3234 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3235 assert_eq!(
3236 error.to_string(),
3237 "invalid manifest provenance form: field build_git_sha has length 12; canonical form is exactly 40 lowercase hexadecimal characters"
3238 );
3239 }
3240
3241 #[test]
3242 fn build_provenance_refuses_an_abbreviated_lock_digest() {
3243 let error = build_provenance_from_source(
3244 BuildGitShaSource::NeverDerived,
3245 Some("0123456789abcdef"),
3246 None,
3247 )
3248 .expect_err("a 16-character digest is not canonical");
3249
3250 assert_eq!(error.field(), "build_lock_digest");
3251 assert_eq!(error.length(), 16);
3252 assert_eq!(error.canonical_form(), BUILD_LOCK_DIGEST_CANONICAL_FORM);
3253 }
3254
3255 #[test]
3256 fn build_provenance_refuses_uppercase_hex() {
3257 let uppercase_sha = "A".repeat(40);
3258 let error = build_provenance_from_source(
3259 BuildGitShaSource::Git {
3260 revision: &uppercase_sha,
3261 tree_state: GitTreeState::Clean,
3262 },
3263 None,
3264 None,
3265 )
3266 .expect_err("uppercase hexadecimal is not canonical");
3267
3268 assert_eq!(error.field(), "build_git_sha");
3269 assert_eq!(error.length(), 40);
3270 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3271 }
3272
3273 #[test]
3274 fn build_provenance_refuses_dirty_revision_stamp_claimed_clean() {
3275 let error = build_provenance_from_source(
3276 BuildGitShaSource::Git {
3277 revision: "0123456789abcdef0123456789abcdef01234567-dirty",
3278 tree_state: GitTreeState::Clean,
3279 },
3280 None,
3281 None,
3282 )
3283 .expect_err("a dirty stamp is not a canonical build revision");
3284
3285 assert_eq!(error.field(), "build_git_sha");
3286 assert_eq!(error.length(), 46);
3287 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3288 }
3289
3290 #[test]
3291 fn build_provenance_keeps_a_lock_digest_when_identity_is_unavailable() {
3292 let provenance = build_provenance_from_source(
3293 BuildGitShaSource::Git {
3294 revision: "unavailable",
3295 tree_state: GitTreeState::Clean,
3296 },
3297 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"),
3298 None,
3299 )
3300 .expect("sentinel SHA is omitted before the valid lock digest is checked");
3301
3302 assert_eq!(provenance.build_git_sha, None);
3303 assert_eq!(
3304 provenance.build_lock_digest,
3305 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string())
3306 );
3307 assert_eq!(
3308 provenance.wire_crate_version,
3309 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
3310 );
3311 }
3312
3313 #[test]
3314 fn build_provenance_omits_fully_unavailable_inputs() {
3315 let provenance = build_provenance_from_source(
3316 BuildGitShaSource::NeverDerived,
3317 Some(" unavailable "),
3318 Some(" "),
3319 )
3320 .expect("omitted and sentinel inputs are not form errors");
3321
3322 assert_eq!(provenance.build_git_sha, None);
3323 assert_eq!(provenance.build_lock_digest, None);
3324 assert_eq!(provenance.store_schema_version, None);
3325 assert_eq!(
3326 provenance.wire_crate_version,
3327 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
3328 );
3329 }
3330
3331 #[test]
3332 fn legacy_build_provenance_keeps_master_wire_bytes_without_an_absence_reason() {
3333 let revision = "0123456789abcdef0123456789abcdef01234567";
3334 for (input, expected) in [
3335 (
3336 Some(revision),
3337 format!(
3338 r#"{{"build_git_sha":"{revision}","wire_crate_version":"{}"}}"#,
3339 crate::SUBC_PROTOCOL_CRATE_VERSION
3340 ),
3341 ),
3342 (
3343 None,
3344 format!(
3345 r#"{{"wire_crate_version":"{}"}}"#,
3346 crate::SUBC_PROTOCOL_CRATE_VERSION
3347 ),
3348 ),
3349 (
3350 Some("unknown"),
3351 format!(
3352 r#"{{"wire_crate_version":"{}"}}"#,
3353 crate::SUBC_PROTOCOL_CRATE_VERSION
3354 ),
3355 ),
3356 ] {
3357 let provenance = build_provenance(input, None, None)
3358 .expect("the legacy build facts remain constructible");
3359 assert_eq!(provenance.build_git_sha_absence_reason, None);
3360 assert_eq!(
3361 serde_json::to_string(&provenance).expect("legacy provenance serializes"),
3362 expected
3363 );
3364 }
3365 }
3366
3367 #[test]
3368 fn build_provenance_derives_git_sha_absence_from_the_stamping_inputs() {
3369 let revision = "0123456789abcdef0123456789abcdef01234567";
3370 let cases = [
3371 (
3372 BuildGitShaSource::Git {
3373 revision,
3374 tree_state: GitTreeState::Clean,
3375 },
3376 Some(revision),
3377 None,
3378 ),
3379 (
3380 BuildGitShaSource::Git {
3381 revision,
3382 tree_state: GitTreeState::Dirty,
3383 },
3384 None,
3385 Some(BuildGitShaAbsenceReason::DeclinedDirty),
3386 ),
3387 (
3388 BuildGitShaSource::NeverDerived,
3389 None,
3390 Some(BuildGitShaAbsenceReason::NeverDerived),
3391 ),
3392 (
3393 BuildGitShaSource::NoGitDir,
3394 None,
3395 Some(BuildGitShaAbsenceReason::NoGitDir),
3396 ),
3397 ];
3398
3399 for (source, expected_sha, expected_reason) in cases {
3400 let provenance = build_provenance_from_source(source, None, None)
3401 .expect("every stamping state constructs honest provenance");
3402 assert_eq!(provenance.build_git_sha.as_deref(), expected_sha);
3403 assert_eq!(provenance.build_git_sha_absence_reason, expected_reason);
3404 }
3405 }
3406
3407 #[test]
3408 fn unknown_git_sha_absence_reason_round_trips_byte_faithfully() {
3409 let wire = format!(
3410 r#"{{"build_git_sha_absence_reason":"future_stamper_state","wire_crate_version":"{}"}}"#,
3411 crate::SUBC_PROTOCOL_CRATE_VERSION
3412 );
3413 let provenance: ManifestProvenance =
3414 serde_json::from_str(&wire).expect("future absence reasons remain readable");
3415
3416 assert_eq!(
3417 provenance.build_git_sha_absence_reason,
3418 Some(BuildGitShaAbsenceReason::ForwardCompatibleUnknown(
3419 "future_stamper_state".to_string()
3420 ))
3421 );
3422 assert_eq!(
3423 serde_json::to_string(&provenance).expect("future absence reason reserializes"),
3424 wire
3425 );
3426 }
3427
3428 #[test]
3429 fn provenance_rejects_an_absence_reason_beside_a_declared_commit() {
3430 let error = serde_json::from_value::<ManifestProvenance>(json!({
3431 "build_git_sha": "0123456789abcdef0123456789abcdef01234567",
3432 "build_git_sha_absence_reason": "declined_dirty"
3433 }))
3434 .expect_err("a declared commit cannot also claim an absence reason");
3435
3436 assert!(error.to_string().contains(
3437 "build_git_sha_absence_reason has must be omitted when build_git_sha is present"
3438 ));
3439 }
3440
3441 #[test]
3442 fn rich_ui_descriptor_is_optional_and_round_trips_when_present() {
3443 let manifest = ModuleManifest::builder("provider", "1.0.0").build();
3444 assert_eq!(
3445 serde_json::to_string(&manifest).unwrap(),
3446 r#"{"module_id":"provider","module_version":"1.0.0","protocol_ver":2,"provides":[]}"#
3447 );
3448
3449 let descriptor = RichUiDescriptor::new(
3450 "ckios.richui.manifest/1",
3451 format!("sha256:{}", "a".repeat(64)),
3452 128,
3453 2,
3454 );
3455 let manifest = ModuleManifest::builder("provider", "1.0.0")
3456 .rich_ui(Some(descriptor.clone()))
3457 .build();
3458 let wire = serde_json::to_string(&manifest).unwrap();
3459 assert!(wire.contains("\"rich_ui\":{\"schema\":\"ckios.richui.manifest/1\""));
3460 assert_eq!(
3461 serde_json::from_str::<ModuleManifest>(&wire)
3462 .unwrap()
3463 .rich_ui,
3464 Some(descriptor)
3465 );
3466 }
3467
3468 #[test]
3469 fn rich_ui_descriptor_validation_names_each_invalid_field() {
3470 let good = json!({
3471 "schema": "ckios.richui.manifest/1",
3472 "manifest_digest": format!("sha256:{}", "a".repeat(64)),
3473 "bytes": 1,
3474 "chunks": 1
3475 });
3476 let hello = json!({"manifest": {"rich_ui": good.clone()}});
3477 assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
3478
3479 for (field, value) in [
3480 ("schema", json!("bad schema")),
3481 (
3482 "manifest_digest",
3483 json!(format!("sha256:{}", "A".repeat(64))),
3484 ),
3485 ("bytes", json!(0)),
3486 ("chunks", json!(1025)),
3487 ] {
3488 let mut invalid = hello.clone();
3489 invalid["manifest"]["rich_ui"][field] = value;
3490 let error = validate_hello_rich_ui_descriptor(&invalid)
3491 .expect_err("an invalid descriptor field must be refused");
3492 assert_eq!(error.field(), format!("rich_ui.{field}"));
3493 }
3494
3495 let mut hello = hello;
3496 hello["manifest"]["rich_ui"] = Value::Null;
3497 let error = validate_hello_rich_ui_descriptor(&hello)
3498 .expect_err("null is not an absent descriptor");
3499 assert_eq!(error.field(), "rich_ui");
3500 }
3501
3502 #[test]
3503 fn rich_ui_descriptor_validation_accepts_inclusive_bounds() {
3504 let hello = json!({"manifest": {"rich_ui": {
3505 "schema": "a".repeat(64),
3506 "manifest_digest": format!("sha256:{}", "f".repeat(64)),
3507 "bytes": 16_777_216,
3508 "chunks": 1024
3509 }}});
3510 assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
3511 }
3512}