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>,
774 #[serde(default, skip_serializing_if = "Option::is_none")]
776 pub summary: Option<String>,
777}
778
779impl EventDeclaration {
780 pub fn new(name: impl Into<String>, version: u32) -> Self {
783 Self {
784 name: name.into(),
785 version,
786 headers: Vec::new(),
787 summary: None,
788 }
789 }
790
791 pub fn with_headers(mut self, headers: Vec<String>) -> Self {
793 self.headers = headers;
794 self
795 }
796
797 pub fn with_summary(mut self, summary: Option<String>) -> Self {
799 self.summary = summary;
800 self
801 }
802}
803
804#[derive(Debug, Clone, PartialEq, Eq)]
806#[non_exhaustive]
807pub struct EventDeclarationError {
808 field: String,
809 reason: &'static str,
810}
811
812impl EventDeclarationError {
813 fn new(field: impl Into<String>, reason: &'static str) -> Self {
814 Self {
815 field: field.into(),
816 reason,
817 }
818 }
819
820 pub fn field(&self) -> &str {
822 &self.field
823 }
824}
825
826impl fmt::Display for EventDeclarationError {
827 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
828 write!(
829 f,
830 "invalid event declaration: field {} {}",
831 self.field, self.reason
832 )
833 }
834}
835
836impl std::error::Error for EventDeclarationError {}
837
838pub fn validate_hello_event_declarations(hello: &Value) -> Result<(), EventDeclarationError> {
840 validate_events_value(
841 hello
842 .get("manifest")
843 .and_then(|manifest| manifest.get("events")),
844 )
845}
846
847fn is_valid_event_name(name: &str) -> bool {
850 let level_count = name.split('.').count();
851 (1..=4).contains(&level_count)
852 && name.split('.').all(|level| {
853 if level.is_empty() {
854 return false;
855 }
856 let first = level.as_bytes()[0];
857 (1..=63).contains(&level.len())
858 && (first.is_ascii_lowercase() || first.is_ascii_digit())
859 && level
860 .bytes()
861 .skip(1)
862 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
863 && !level.strip_prefix('v').is_some_and(|digits| {
864 !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit())
865 })
866 })
867}
868
869fn validate_events_value(value: Option<&Value>) -> Result<(), EventDeclarationError> {
870 let Some(value) = value.filter(|value| !value.is_null()) else {
871 return Ok(());
872 };
873 let entries = value
874 .as_array()
875 .ok_or_else(|| EventDeclarationError::new("events", "must be a list"))?;
876 if entries.len() > 64 {
877 return Err(EventDeclarationError::new(
878 "events",
879 "must contain at most 64 declarations",
880 ));
881 }
882 let mut pairs = HashSet::new();
883 for (index, entry) in entries.iter().enumerate() {
884 let field = format!("events[{index}]");
885 let entry = entry
886 .as_object()
887 .ok_or_else(|| EventDeclarationError::new(&field, "must be an object"))?;
888 let name_field = format!("{field}.name");
889 let name = entry
890 .get("name")
891 .and_then(Value::as_str)
892 .ok_or_else(|| EventDeclarationError::new(&name_field, "must be a string"))?;
893 if !is_valid_event_name(name) {
894 return Err(EventDeclarationError::new(
895 name_field,
896 "must contain one to four valid dot-separated event-name levels",
897 ));
898 }
899 let version = entry
900 .get("version")
901 .and_then(Value::as_u64)
902 .filter(|version| (1..=u32::MAX as u64).contains(version))
903 .ok_or_else(|| {
904 EventDeclarationError::new(
905 format!("{field}.version"),
906 "must be an integer between 1 and u32::MAX",
907 )
908 })?;
909 if !pairs.insert((name, version)) {
910 return Err(EventDeclarationError::new(
911 &field,
912 "duplicates an event (name, version) pair",
913 ));
914 }
915 let headers_field = format!("{field}.headers");
916 let headers = entry
917 .get("headers")
918 .and_then(Value::as_array)
919 .ok_or_else(|| EventDeclarationError::new(&headers_field, "must be a list"))?;
920 if headers.len() > 16 {
921 return Err(EventDeclarationError::new(
922 headers_field,
923 "must contain at most 16 headers",
924 ));
925 }
926 let mut names = HashSet::new();
927 for (header_index, header) in headers.iter().enumerate() {
928 let header_field = format!("{headers_field}[{header_index}]");
929 let header = header
930 .as_str()
931 .ok_or_else(|| EventDeclarationError::new(&header_field, "must be a string"))?;
932 if !(1..=32).contains(&header.len())
933 || !header.as_bytes()[0].is_ascii_lowercase()
934 || !header
935 .bytes()
936 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
937 {
938 return Err(EventDeclarationError::new(
939 header_field,
940 "must match [a-z][a-z0-9_]{0,31}",
941 ));
942 }
943 if !names.insert(header) {
944 return Err(EventDeclarationError::new(
945 header_field,
946 "duplicates a header name",
947 ));
948 }
949 }
950 if let Some(summary) = entry.get("summary").filter(|value| !value.is_null()) {
951 let summary_field = format!("{field}.summary");
952 let summary = summary
953 .as_str()
954 .ok_or_else(|| EventDeclarationError::new(&summary_field, "must be a string"))?;
955 if summary.chars().count() > 200 || summary.chars().any(char::is_control) {
956 return Err(EventDeclarationError::new(
957 summary_field,
958 "must contain at most 200 characters and no control characters",
959 ));
960 }
961 }
962 }
963 Ok(())
964}
965
966#[derive(Debug, Clone, PartialEq, Eq)]
968pub struct SelfSignalDeclarationError {
969 module_id: String,
970 entry_index: usize,
971 field: &'static str,
972}
973
974impl fmt::Display for SelfSignalDeclarationError {
975 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
976 write!(
977 f,
978 "module_id '{}' self_signals[{}] is missing required field '{}'",
979 self.module_id.escape_debug(),
980 self.entry_index,
981 self.field
982 )
983 }
984}
985
986pub fn validate_hello_self_signal_declarations(
993 hello: &Value,
994) -> Result<(), SelfSignalDeclarationError> {
995 let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
996 return Ok(());
997 };
998 let module_id = manifest
999 .get("module_id")
1000 .and_then(Value::as_str)
1001 .unwrap_or("<unknown>");
1002 let Some(entries) = manifest.get("self_signals").and_then(Value::as_array) else {
1003 return Ok(());
1004 };
1005
1006 for (entry_index, entry) in entries.iter().enumerate() {
1007 let Some(entry) = entry.as_object() else {
1008 continue;
1009 };
1010 for field in ["effect", "anchored_to"] {
1011 if !entry.contains_key(field) {
1012 return Err(SelfSignalDeclarationError {
1013 module_id: module_id.to_string(),
1014 entry_index,
1015 field,
1016 });
1017 }
1018 }
1019 }
1020 Ok(())
1021}
1022
1023#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1025#[serde(deny_unknown_fields)]
1026pub struct CapabilityDeclarations {
1027 #[serde(default)]
1028 pub provides: Vec<String>,
1029 #[serde(default)]
1030 pub requires: Vec<CapabilityRequirement>,
1031 #[serde(default)]
1032 pub must_never_reach: Vec<String>,
1033}
1034
1035#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1037pub struct SelfSignalDeclaration {
1038 pub name: String,
1040 pub kind: SelfSignalKind,
1068 pub effect: SelfSignalEffect,
1070 pub anchored_to: SignalAnchor,
1072 #[serde(default, skip_serializing_if = "Option::is_none")]
1079 pub cadence: Option<SignalCadence>,
1080 #[serde(default, skip_serializing_if = "Option::is_none")]
1082 pub domain: Option<String>,
1083 #[serde(default, skip_serializing_if = "Option::is_none")]
1084 pub note: Option<String>,
1085}
1086
1087#[derive(Debug, Clone, PartialEq, Eq)]
1089pub enum SelfSignalKind {
1090 Keepalive,
1091 Busy,
1093 Poller,
1094 Cron,
1095 Sweep,
1096 Watchdog,
1097 Heartbeat,
1098 Other(String),
1099}
1100
1101impl SelfSignalKind {
1102 fn wire_name(&self) -> &str {
1103 match self {
1104 Self::Keepalive => "keepalive",
1105 Self::Busy => "busy",
1106 Self::Poller => "poller",
1107 Self::Cron => "cron",
1108 Self::Sweep => "sweep",
1109 Self::Watchdog => "watchdog",
1110 Self::Heartbeat => "heartbeat",
1111 Self::Other(value) => value,
1112 }
1113 }
1114}
1115
1116impl Serialize for SelfSignalKind {
1117 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1118 where
1119 S: serde::Serializer,
1120 {
1121 serializer.serialize_str(self.wire_name())
1122 }
1123}
1124
1125impl<'de> Deserialize<'de> for SelfSignalKind {
1126 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1127 where
1128 D: Deserializer<'de>,
1129 {
1130 let value = String::deserialize(deserializer)?;
1131 Ok(match value.as_str() {
1132 "keepalive" => Self::Keepalive,
1133 "busy" => Self::Busy,
1134 "poller" => Self::Poller,
1135 "cron" => Self::Cron,
1136 "sweep" => Self::Sweep,
1137 "watchdog" => Self::Watchdog,
1138 "heartbeat" => Self::Heartbeat,
1139 _ => Self::Other(value),
1140 })
1141 }
1142}
1143
1144#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1146#[serde(rename_all = "lowercase")]
1147pub enum SelfSignalEffect {
1148 Observe,
1149 Mutate,
1150}
1151
1152#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1154#[serde(rename_all = "snake_case")]
1155pub enum SignalAnchor {
1156 FixedInterval,
1159 Event { event: String },
1162 HealthGauges { gauges: Vec<String> },
1164}
1165
1166#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1168#[serde(rename_all = "snake_case")]
1169pub enum SignalCadence {
1170 Literal { interval_ms: u64 },
1171 Derived { source: String },
1172}
1173
1174#[derive(Serialize, Debug, Clone, Default, PartialEq, Eq)]
1251#[non_exhaustive]
1252pub struct ManifestProvenance {
1253 #[serde(default, skip_serializing_if = "Option::is_none")]
1254 pub build_git_sha: Option<String>,
1255 #[serde(default, skip_serializing_if = "Option::is_none")]
1259 pub build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1260 #[serde(default, skip_serializing_if = "Option::is_none")]
1261 pub build_lock_digest: Option<String>,
1262 #[serde(default, skip_serializing_if = "Option::is_none")]
1271 pub wire_crate_version: Option<String>,
1272 #[serde(default, skip_serializing_if = "Option::is_none")]
1273 pub store_schema_version: Option<String>,
1274 #[serde(default, skip_serializing_if = "Option::is_none")]
1280 pub launch_nonce_source: Option<LaunchNonceSource>,
1281}
1282
1283#[derive(Debug, Clone, PartialEq, Eq)]
1290#[non_exhaustive]
1291pub enum LaunchNonceSource {
1292 Fd,
1294 Pipe,
1296 Env,
1298 ForwardCompatibleUnknown(String),
1299}
1300
1301impl LaunchNonceSource {
1302 pub fn wire_name(&self) -> &str {
1304 match self {
1305 Self::Fd => "fd",
1306 Self::Pipe => "pipe",
1307 Self::Env => "env",
1308 Self::ForwardCompatibleUnknown(value) => value,
1309 }
1310 }
1311
1312 pub fn from_wire_name(value: &str) -> Self {
1314 match value {
1315 "fd" => Self::Fd,
1316 "pipe" => Self::Pipe,
1317 "env" => Self::Env,
1318 _ => Self::ForwardCompatibleUnknown(value.to_string()),
1319 }
1320 }
1321}
1322
1323impl Serialize for LaunchNonceSource {
1324 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1325 where
1326 S: serde::Serializer,
1327 {
1328 serializer.serialize_str(self.wire_name())
1329 }
1330}
1331
1332impl<'de> Deserialize<'de> for LaunchNonceSource {
1333 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1334 where
1335 D: serde::Deserializer<'de>,
1336 {
1337 let value = String::deserialize(deserializer)?;
1338 Ok(Self::from_wire_name(&value))
1339 }
1340}
1341
1342#[derive(Debug, Clone, PartialEq, Eq)]
1347pub enum BuildGitShaAbsenceReason {
1348 DeclinedDirty,
1349 NeverDerived,
1350 NoGitDir,
1351 ForwardCompatibleUnknown(String),
1352}
1353
1354impl BuildGitShaAbsenceReason {
1355 fn wire_name(&self) -> &str {
1356 match self {
1357 Self::DeclinedDirty => "declined_dirty",
1358 Self::NeverDerived => "never_derived",
1359 Self::NoGitDir => "no_git_dir",
1360 Self::ForwardCompatibleUnknown(value) => value,
1361 }
1362 }
1363}
1364
1365impl Serialize for BuildGitShaAbsenceReason {
1366 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1367 where
1368 S: serde::Serializer,
1369 {
1370 serializer.serialize_str(self.wire_name())
1371 }
1372}
1373
1374impl<'de> Deserialize<'de> for BuildGitShaAbsenceReason {
1375 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1376 where
1377 D: serde::Deserializer<'de>,
1378 {
1379 let value = String::deserialize(deserializer)?;
1380 Ok(match value.as_str() {
1381 "declined_dirty" => Self::DeclinedDirty,
1382 "never_derived" => Self::NeverDerived,
1383 "no_git_dir" => Self::NoGitDir,
1384 _ => Self::ForwardCompatibleUnknown(value),
1385 })
1386 }
1387}
1388
1389#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1391pub enum GitTreeState {
1392 Clean,
1393 Dirty,
1394}
1395
1396#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1401pub enum BuildGitShaSource<'a> {
1402 Git {
1403 revision: &'a str,
1404 tree_state: GitTreeState,
1405 },
1406 NeverDerived,
1407 NoGitDir,
1408}
1409
1410pub fn attestable_commit(revision: &str, tree_state: GitTreeState) -> Option<&str> {
1414 match tree_state {
1415 GitTreeState::Clean => Some(revision),
1416 GitTreeState::Dirty => None,
1417 }
1418}
1419
1420const MAX_PROVENANCE_VALUE_BYTES: usize = 128;
1421const BUILD_GIT_SHA_CANONICAL_FORM: &str = "exactly 40 lowercase hexadecimal characters";
1422const BUILD_LOCK_DIGEST_CANONICAL_FORM: &str = "exactly 64 lowercase hexadecimal characters";
1423
1424#[derive(Deserialize)]
1425struct ManifestProvenanceWire {
1426 #[serde(default)]
1427 build_git_sha: Option<String>,
1428 #[serde(default)]
1429 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1430 #[serde(default)]
1431 build_lock_digest: Option<String>,
1432 #[serde(default)]
1433 wire_crate_version: Option<String>,
1434 #[serde(default)]
1435 store_schema_version: Option<String>,
1436 #[serde(default)]
1437 launch_nonce_source: Option<LaunchNonceSource>,
1438}
1439
1440impl<'de> Deserialize<'de> for ManifestProvenance {
1441 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1442 where
1443 D: Deserializer<'de>,
1444 {
1445 let wire = ManifestProvenanceWire::deserialize(deserializer)?;
1446 let provenance = Self {
1447 build_git_sha: wire.build_git_sha,
1448 build_git_sha_absence_reason: wire.build_git_sha_absence_reason,
1449 build_lock_digest: wire.build_lock_digest,
1450 wire_crate_version: wire.wire_crate_version,
1451 store_schema_version: wire.store_schema_version,
1452 launch_nonce_source: wire.launch_nonce_source,
1453 };
1454 provenance.validate().map_err(D::Error::custom)?;
1455 Ok(provenance)
1456 }
1457}
1458
1459#[derive(Debug, Clone, PartialEq, Eq)]
1461pub struct ProvenanceFormError {
1462 field: &'static str,
1463 length: usize,
1464 canonical_form: &'static str,
1465}
1466
1467impl ProvenanceFormError {
1468 fn new(field: &'static str, length: usize, canonical_form: &'static str) -> Self {
1469 Self {
1470 field,
1471 length,
1472 canonical_form,
1473 }
1474 }
1475
1476 pub fn field(&self) -> &str {
1478 self.field
1479 }
1480
1481 pub fn length(&self) -> usize {
1483 self.length
1484 }
1485
1486 pub fn canonical_form(&self) -> &str {
1488 self.canonical_form
1489 }
1490}
1491
1492impl fmt::Display for ProvenanceFormError {
1493 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1494 write!(
1495 f,
1496 "invalid manifest provenance form: field {} has length {}; canonical form is {}",
1497 self.field, self.length, self.canonical_form
1498 )
1499 }
1500}
1501
1502impl std::error::Error for ProvenanceFormError {}
1503
1504#[derive(Debug, Clone, PartialEq, Eq)]
1505pub struct ManifestProvenanceError {
1506 field: String,
1507 value: String,
1508 reason: &'static str,
1509}
1510
1511impl ManifestProvenanceError {
1512 fn new(field: &str, value: &str, reason: &'static str) -> Self {
1513 Self {
1514 field: field.to_string(),
1515 value: safe_error_value(value),
1516 reason,
1517 }
1518 }
1519
1520 pub fn field(&self) -> &str {
1521 &self.field
1522 }
1523}
1524
1525impl fmt::Display for ManifestProvenanceError {
1526 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1527 write!(
1528 f,
1529 "invalid manifest provenance: field {} has {} (value {:?})",
1530 self.field, self.reason, self.value
1531 )
1532 }
1533}
1534
1535impl std::error::Error for ManifestProvenanceError {}
1536
1537impl ManifestProvenance {
1538 pub fn new() -> Self {
1540 Self::default()
1541 }
1542
1543 pub fn with_build_git_sha(mut self, value: Option<String>) -> Self {
1544 self.build_git_sha = value;
1545 self
1546 }
1547
1548 pub fn with_build_git_sha_absence_reason(
1549 mut self,
1550 value: Option<BuildGitShaAbsenceReason>,
1551 ) -> Self {
1552 self.build_git_sha_absence_reason = value;
1553 self
1554 }
1555
1556 pub fn with_build_lock_digest(mut self, value: Option<String>) -> Self {
1557 self.build_lock_digest = value;
1558 self
1559 }
1560
1561 pub fn with_wire_crate_version(mut self, value: Option<String>) -> Self {
1562 self.wire_crate_version = value;
1563 self
1564 }
1565
1566 pub fn with_store_schema_version(mut self, value: Option<String>) -> Self {
1567 self.store_schema_version = value;
1568 self
1569 }
1570
1571 pub fn with_launch_nonce_source(mut self, value: Option<LaunchNonceSource>) -> Self {
1576 self.launch_nonce_source = value;
1577 self
1578 }
1579
1580 pub fn validate(&self) -> Result<(), ManifestProvenanceError> {
1581 if let (Some(_), Some(reason)) = (
1582 self.build_git_sha.as_ref(),
1583 self.build_git_sha_absence_reason.as_ref(),
1584 ) {
1585 return Err(ManifestProvenanceError::new(
1586 "build_git_sha_absence_reason",
1587 reason.wire_name(),
1588 "must be omitted when build_git_sha is present",
1589 ));
1590 }
1591 for (field, value) in [
1592 ("build_git_sha", self.build_git_sha.as_deref()),
1593 (
1594 "build_git_sha_absence_reason",
1595 self.build_git_sha_absence_reason
1596 .as_ref()
1597 .map(|reason| reason.wire_name()),
1598 ),
1599 ("build_lock_digest", self.build_lock_digest.as_deref()),
1600 ("wire_crate_version", self.wire_crate_version.as_deref()),
1601 ("store_schema_version", self.store_schema_version.as_deref()),
1602 (
1603 "launch_nonce_source",
1604 self.launch_nonce_source
1605 .as_ref()
1606 .map(|source| source.wire_name()),
1607 ),
1608 ] {
1609 let Some(value) = value else { continue };
1610 if value.is_empty() {
1611 return Err(ManifestProvenanceError::new(
1612 field,
1613 value,
1614 "must not be empty",
1615 ));
1616 }
1617 if value.len() > MAX_PROVENANCE_VALUE_BYTES {
1622 return Err(ManifestProvenanceError::new(
1623 field,
1624 value,
1625 "exceeds the 128-byte maximum",
1626 ));
1627 }
1628 if value.bytes().any(|byte| !(0x20..=0x7e).contains(&byte)) {
1629 return Err(ManifestProvenanceError::new(
1630 field,
1631 value,
1632 "contains non-printable ASCII",
1633 ));
1634 }
1635 }
1636 Ok(())
1637 }
1638}
1639
1640pub fn build_provenance(
1658 build_git_sha: Option<&str>,
1659 build_lock_digest: Option<&str>,
1660 store_schema_version: Option<&str>,
1661) -> Result<ManifestProvenance, ProvenanceFormError> {
1662 let build_git_sha = normalize_and_validate_build_git_sha(build_git_sha)?;
1663 build_provenance_with_build_git_sha(
1664 build_git_sha,
1665 None,
1666 build_lock_digest,
1667 store_schema_version,
1668 )
1669}
1670
1671pub fn build_provenance_from_source(
1687 build_git_sha_source: BuildGitShaSource<'_>,
1688 build_lock_digest: Option<&str>,
1689 store_schema_version: Option<&str>,
1690) -> Result<ManifestProvenance, ProvenanceFormError> {
1691 let (raw_build_git_sha, mut build_git_sha_absence_reason) = match build_git_sha_source {
1692 BuildGitShaSource::Git {
1693 revision,
1694 tree_state,
1695 } => match attestable_commit(revision, tree_state) {
1696 Some(revision) => (Some(revision), None),
1697 None => (None, Some(BuildGitShaAbsenceReason::DeclinedDirty)),
1698 },
1699 BuildGitShaSource::NeverDerived => (None, Some(BuildGitShaAbsenceReason::NeverDerived)),
1700 BuildGitShaSource::NoGitDir => (None, Some(BuildGitShaAbsenceReason::NoGitDir)),
1701 };
1702 let build_git_sha = normalize_and_validate_build_git_sha(raw_build_git_sha)?;
1703 if build_git_sha.is_none() {
1704 build_git_sha_absence_reason.get_or_insert(BuildGitShaAbsenceReason::NeverDerived);
1705 }
1706 build_provenance_with_build_git_sha(
1707 build_git_sha,
1708 build_git_sha_absence_reason,
1709 build_lock_digest,
1710 store_schema_version,
1711 )
1712}
1713
1714fn normalize_and_validate_build_git_sha(
1715 build_git_sha: Option<&str>,
1716) -> Result<Option<String>, ProvenanceFormError> {
1717 let build_git_sha = normalize_provenance_fact(build_git_sha);
1718 validate_provenance_form(
1719 "build_git_sha",
1720 build_git_sha.as_deref(),
1721 BUILD_GIT_SHA_CANONICAL_FORM,
1722 40,
1723 )?;
1724 Ok(build_git_sha)
1725}
1726
1727fn build_provenance_with_build_git_sha(
1728 build_git_sha: Option<String>,
1729 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1730 build_lock_digest: Option<&str>,
1731 store_schema_version: Option<&str>,
1732) -> Result<ManifestProvenance, ProvenanceFormError> {
1733 let build_lock_digest = normalize_provenance_fact(build_lock_digest);
1734 validate_provenance_form(
1735 "build_lock_digest",
1736 build_lock_digest.as_deref(),
1737 BUILD_LOCK_DIGEST_CANONICAL_FORM,
1738 64,
1739 )?;
1740
1741 Ok(ManifestProvenance {
1742 build_git_sha,
1743 build_git_sha_absence_reason,
1744 build_lock_digest,
1745 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
1746 store_schema_version: normalize_provenance_fact(store_schema_version),
1747 launch_nonce_source: None,
1748 })
1749}
1750
1751fn validate_provenance_form(
1752 field: &'static str,
1753 value: Option<&str>,
1754 canonical_form: &'static str,
1755 expected_length: usize,
1756) -> Result<(), ProvenanceFormError> {
1757 let Some(value) = value else { return Ok(()) };
1758 if value.len() != expected_length
1759 || !value
1760 .bytes()
1761 .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
1762 {
1763 return Err(ProvenanceFormError::new(field, value.len(), canonical_form));
1764 }
1765 Ok(())
1766}
1767
1768pub const PROVENANCE_SENTINELS: [&str; 3] = ["unknown", "unavailable", "none"];
1776
1777fn normalize_provenance_fact(value: Option<&str>) -> Option<String> {
1778 let value = value?.trim();
1779 if value.is_empty() {
1780 return None;
1781 }
1782 let lowered = value.to_ascii_lowercase();
1783 if PROVENANCE_SENTINELS.contains(&lowered.as_str()) {
1784 return None;
1785 }
1786 Some(value.to_string())
1787}
1788
1789#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1791#[serde(deny_unknown_fields)]
1792pub struct CapabilityRequirement {
1793 pub capability: String,
1794 pub need: CapabilityNeed,
1795}
1796
1797#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1799#[serde(rename_all = "snake_case")]
1800pub enum CapabilityNeed {
1801 Required,
1802 Optional,
1803}
1804
1805#[derive(Debug, Clone, PartialEq, Eq)]
1807pub struct CapabilityGrammarError {
1808 field: String,
1809 value: String,
1810}
1811
1812impl CapabilityGrammarError {
1813 fn new(field: impl Into<String>, value: impl AsRef<str>) -> Self {
1814 Self {
1815 field: field.into(),
1816 value: safe_error_value(value.as_ref()),
1817 }
1818 }
1819
1820 pub fn field(&self) -> &str {
1822 &self.field
1823 }
1824
1825 pub fn value(&self) -> &str {
1827 &self.value
1828 }
1829}
1830
1831impl fmt::Display for CapabilityGrammarError {
1832 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1833 write!(
1834 f,
1835 "invalid capability grammar: field {} has offending value {:?}",
1836 self.field, self.value
1837 )
1838 }
1839}
1840
1841impl std::error::Error for CapabilityGrammarError {}
1842
1843impl ModuleManifest {
1844 pub fn validate_capability_grammar(&self) -> Result<(), CapabilityGrammarError> {
1846 let Some(capabilities) = &self.capabilities else {
1847 return Ok(());
1848 };
1849
1850 validate_capability_list("capabilities.provides", &capabilities.provides)?;
1851 validate_requires(&capabilities.requires)?;
1852 validate_capability_list(
1853 "capabilities.must_never_reach",
1854 &capabilities.must_never_reach,
1855 )
1856 }
1857}
1858
1859pub fn validate_manifest_capability_grammar(
1864 manifest: &Value,
1865) -> Result<(), CapabilityGrammarError> {
1866 let Some(object) = manifest.as_object() else {
1867 return Ok(());
1868 };
1869
1870 validate_capabilities_value(object.get("capabilities"))?;
1871 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
1872}
1873
1874pub fn validate_hello_capability_grammar(hello: &Value) -> Result<(), CapabilityGrammarError> {
1880 let Some(object) = hello.as_object() else {
1881 return Ok(());
1882 };
1883 if let Some(manifest) = object.get("manifest") {
1884 validate_manifest_capability_grammar(manifest)?;
1885 }
1886 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
1887}
1888
1889pub fn is_valid_capability_identifier(identifier: &str) -> bool {
1891 if identifier.chars().any(char::is_whitespace) {
1892 return false;
1893 }
1894 let Some((name, version)) = identifier.split_once("/v") else {
1895 return false;
1896 };
1897 if name.is_empty() || name.len() > 64 || version.is_empty() {
1898 return false;
1899 }
1900
1901 let name_bytes = name.as_bytes();
1902 if !name_bytes[0].is_ascii_lowercase()
1903 || (name.len() > 1
1904 && !name_bytes[name.len() - 1].is_ascii_lowercase()
1905 && !name_bytes[name.len() - 1].is_ascii_digit())
1906 || name_bytes.windows(2).any(|pair| pair == b"--")
1907 {
1908 return false;
1909 }
1910 if !name_bytes
1911 .iter()
1912 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-')
1913 {
1914 return false;
1915 }
1916
1917 if version.len() > 1 && version.starts_with('0')
1918 || !version.bytes().all(|byte| byte.is_ascii_digit())
1919 {
1920 return false;
1921 }
1922 matches!(
1923 version.parse::<u64>(),
1924 Ok(value) if (1..=u64::from(u32::MAX)).contains(&value)
1925 )
1926}
1927
1928fn validate_capabilities_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
1929 let Some(value) = value else {
1930 return Ok(());
1931 };
1932 let Some(object) = value.as_object() else {
1933 return Err(CapabilityGrammarError::new(
1934 "capabilities",
1935 value_description(value),
1936 ));
1937 };
1938
1939 for (key, value) in object {
1940 if !matches!(key.as_str(), "provides" | "requires" | "must_never_reach") {
1941 return Err(CapabilityGrammarError::new(
1942 field_child("capabilities", key),
1943 value_description(value),
1944 ));
1945 }
1946 }
1947
1948 validate_capability_list_value("capabilities.provides", object.get("provides"))?;
1949 validate_requires_value(object.get("requires"))?;
1950 validate_capability_list_value(
1951 "capabilities.must_never_reach",
1952 object.get("must_never_reach"),
1953 )
1954}
1955
1956fn validate_capability_list_value(
1957 field: &str,
1958 value: Option<&Value>,
1959) -> Result<(), CapabilityGrammarError> {
1960 let Some(value) = value else {
1961 return Ok(());
1962 };
1963 let Some(values) = value.as_array() else {
1964 return Err(CapabilityGrammarError::new(field, value_description(value)));
1965 };
1966
1967 let mut seen = HashSet::new();
1968 for (index, value) in values.iter().enumerate() {
1969 let field = format!("{field}[{index}]");
1970 let Some(identifier) = value.as_str() else {
1971 return Err(CapabilityGrammarError::new(field, value_description(value)));
1972 };
1973 validate_capability_identifier(&field, identifier)?;
1974 if !seen.insert(identifier) {
1975 return Err(CapabilityGrammarError::new(field, identifier));
1976 }
1977 }
1978 Ok(())
1979}
1980
1981fn validate_requires_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
1982 let Some(value) = value else {
1983 return Ok(());
1984 };
1985 let Some(values) = value.as_array() else {
1986 return Err(CapabilityGrammarError::new(
1987 "capabilities.requires",
1988 value_description(value),
1989 ));
1990 };
1991
1992 let mut seen = HashSet::new();
1993 for (index, value) in values.iter().enumerate() {
1994 let entry_field = format!("capabilities.requires[{index}]");
1995 let Some(object) = value.as_object() else {
1996 return Err(CapabilityGrammarError::new(
1997 entry_field,
1998 value_description(value),
1999 ));
2000 };
2001 for (key, value) in object {
2002 if !matches!(key.as_str(), "capability" | "need") {
2003 return Err(CapabilityGrammarError::new(
2004 field_child(&entry_field, key),
2005 value_description(value),
2006 ));
2007 }
2008 }
2009 let capability_field = format!("{entry_field}.capability");
2010 let Some(capability) = object.get("capability").and_then(Value::as_str) else {
2011 return Err(CapabilityGrammarError::new(
2012 capability_field,
2013 object
2014 .get("capability")
2015 .map_or("<missing>".to_string(), value_description),
2016 ));
2017 };
2018 validate_capability_identifier(&capability_field, capability)?;
2019
2020 let need_field = format!("{entry_field}.need");
2021 let Some(need) = object.get("need").and_then(Value::as_str) else {
2022 return Err(CapabilityGrammarError::new(
2023 need_field,
2024 object
2025 .get("need")
2026 .map_or("<missing>".to_string(), value_description),
2027 ));
2028 };
2029 if !matches!(need, "required" | "optional") {
2030 return Err(CapabilityGrammarError::new(need_field, need));
2031 }
2032 if !seen.insert(capability) {
2033 return Err(CapabilityGrammarError::new(entry_field, capability));
2034 }
2035 }
2036 Ok(())
2037}
2038
2039fn validate_capability_list(field: &str, values: &[String]) -> Result<(), CapabilityGrammarError> {
2040 let mut seen = HashSet::new();
2041 for (index, identifier) in values.iter().enumerate() {
2042 let field = format!("{field}[{index}]");
2043 validate_capability_identifier(&field, identifier)?;
2044 if !seen.insert(identifier) {
2045 return Err(CapabilityGrammarError::new(field, identifier));
2046 }
2047 }
2048 Ok(())
2049}
2050
2051fn validate_requires(values: &[CapabilityRequirement]) -> Result<(), CapabilityGrammarError> {
2052 let mut seen = HashSet::new();
2053 for (index, requirement) in values.iter().enumerate() {
2054 let field = format!("capabilities.requires[{index}].capability");
2055 validate_capability_identifier(&field, &requirement.capability)?;
2056 if !seen.insert(&requirement.capability) {
2057 return Err(CapabilityGrammarError::new(
2058 format!("capabilities.requires[{index}]"),
2059 &requirement.capability,
2060 ));
2061 }
2062 }
2063 Ok(())
2064}
2065
2066fn validate_capability_identifier(
2067 field: &str,
2068 identifier: &str,
2069) -> Result<(), CapabilityGrammarError> {
2070 if is_valid_capability_identifier(identifier) {
2071 Ok(())
2072 } else {
2073 Err(CapabilityGrammarError::new(field, identifier))
2074 }
2075}
2076
2077fn validate_runtime_computed(
2078 value: Option<&Value>,
2079 field: &str,
2080) -> Result<(), CapabilityGrammarError> {
2081 let Some(value) = value else {
2082 return Ok(());
2083 };
2084 let Some(pointers) = value.as_array() else {
2085 return Err(CapabilityGrammarError::new(field, value_description(value)));
2086 };
2087
2088 for (index, pointer) in pointers.iter().enumerate() {
2089 let field = format!("{field}[{index}]");
2090 let Some(pointer) = pointer.as_str() else {
2091 return Err(CapabilityGrammarError::new(
2092 field,
2093 value_description(pointer),
2094 ));
2095 };
2096 let Some(tokens) = parse_json_pointer(pointer) else {
2097 return Err(CapabilityGrammarError::new(field, pointer));
2098 };
2099 if tokens.first().is_some_and(|token| token == "capabilities") {
2100 return Err(CapabilityGrammarError::new(field, pointer));
2101 }
2102 }
2103 Ok(())
2104}
2105
2106fn parse_json_pointer(pointer: &str) -> Option<Vec<String>> {
2107 if pointer.is_empty() {
2108 return Some(Vec::new());
2109 }
2110 let raw_tokens = pointer.strip_prefix('/')?;
2111 raw_tokens
2112 .split('/')
2113 .map(unescape_json_pointer_token)
2114 .collect()
2115}
2116
2117fn unescape_json_pointer_token(token: &str) -> Option<String> {
2118 let mut output = String::with_capacity(token.len());
2119 let mut characters = token.chars();
2120 while let Some(character) = characters.next() {
2121 if character != '~' {
2122 output.push(character);
2123 continue;
2124 }
2125 match characters.next()? {
2126 '0' => output.push('~'),
2127 '1' => output.push('/'),
2128 _ => return None,
2129 }
2130 }
2131 Some(output)
2132}
2133
2134fn field_child(parent: &str, child: &str) -> String {
2135 let child = safe_error_value(child);
2136 format!("{parent}.{child}")
2137}
2138
2139fn value_description(value: &Value) -> String {
2140 match value {
2141 Value::String(value) => safe_error_value(value),
2142 Value::Null => "null".to_string(),
2143 Value::Bool(value) => value.to_string(),
2144 Value::Number(value) => value.to_string(),
2145 Value::Array(_) => "<array>".to_string(),
2146 Value::Object(_) => "<object>".to_string(),
2147 }
2148}
2149
2150fn safe_error_value(value: &str) -> String {
2151 let lower = value.to_ascii_lowercase();
2152 if ["secret", "password", "api_key"]
2153 .iter()
2154 .any(|marker| lower.contains(marker))
2155 || lower.starts_with("sk-")
2156 || lower.starts_with("akia")
2157 || lower.starts_with("bearer ")
2158 || lower.starts_with("token=")
2159 || lower.starts_with("credential=")
2160 {
2161 "<redacted>".to_string()
2162 } else {
2163 value.to_string()
2164 }
2165}
2166
2167#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2173#[serde(rename_all = "snake_case")]
2174pub enum TrustTier {
2175 FirstParty,
2176 Reviewed,
2177 Untrusted,
2178}
2179
2180#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2184#[serde(tag = "role", rename_all = "snake_case")]
2185pub enum ProviderRole {
2186 ToolProvider {
2187 tools: Vec<Tool>,
2188 identity_scope: Vec<IdentityScope>,
2196 concurrency: Concurrency,
2197 emits_push: bool,
2198 sub_supervises: bool,
2199 },
2200 PipelineStage {
2201 stage: PipelineStageKind,
2202 applies_to: PipelineAppliesTo,
2203 interface: String,
2204 declares_frozen_floor: bool,
2205 needs_signals: Vec<String>,
2206 conformance_class: String,
2207 },
2208 ManagementSurface {
2209 operations: Vec<ManagementOperation>,
2210 config_schema: Value,
2211 observability: Vec<ObservabilitySurface>,
2212 identity_scope: Vec<IdentityScope>,
2216 #[serde(default)]
2217 concurrency: Concurrency,
2218 },
2219 InternalService {
2220 service_id: String,
2221 transport: InternalTransport,
2222 agent_facing: bool,
2223 operations: Vec<String>,
2224 },
2225}
2226
2227#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2240#[serde(rename_all = "snake_case")]
2241pub enum ExecutionMode {
2242 Pure,
2243 Mutating,
2244 Unfenceable,
2245}
2246
2247#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2249pub struct Tool {
2250 pub name: String,
2251 #[serde(default, skip_serializing_if = "Option::is_none")]
2252 pub description: Option<String>,
2253 pub execution_mode: ExecutionMode,
2258 pub schema: Value,
2259}
2260
2261#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2267#[serde(rename_all = "snake_case")]
2268pub enum Concurrency {
2269 Serial,
2271 ModuleManaged,
2274 StatelessParallel,
2277}
2278
2279#[allow(clippy::derivable_impls)]
2280impl Default for Concurrency {
2291 fn default() -> Self {
2292 Self::ModuleManaged
2293 }
2294}
2295
2296#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2303#[serde(rename_all = "snake_case")]
2304pub enum IdentityScope {
2305 Session,
2306 Project,
2307}
2308
2309#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2311#[serde(rename_all = "snake_case")]
2312pub enum PipelineStageKind {
2313 Transform,
2314 Codec,
2315 Auth,
2316}
2317
2318#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2320pub struct PipelineAppliesTo {
2321 pub provider: String,
2322 pub model: String,
2323}
2324
2325#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2328#[non_exhaustive]
2329pub struct OperationPayload {
2330 max_bytes: usize,
2331}
2332
2333impl OperationPayload {
2334 pub fn new(max_bytes: usize) -> Self {
2335 Self { max_bytes }
2336 }
2337
2338 pub fn max_bytes(&self) -> usize {
2339 self.max_bytes
2340 }
2341}
2342
2343#[derive(Debug, Clone, PartialEq, Eq)]
2345#[non_exhaustive]
2346pub enum OperationPayloadError {
2347 UnknownOperation { operation: String },
2348 WatchOperation { operation: String },
2349 InvalidMaxBytes { operation: String },
2350}
2351
2352impl fmt::Display for OperationPayloadError {
2353 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2354 write!(f, "{self:?}")
2355 }
2356}
2357
2358impl std::error::Error for OperationPayloadError {}
2359
2360impl ModuleManifest {
2361 pub fn validate_operation_payload(&self) -> Result<(), OperationPayloadError> {
2364 for (name, payload) in &self.operation_payload {
2365 if !self.provides.iter().any(|role| match role {
2366 ProviderRole::ManagementSurface { operations, .. } => {
2367 operations.iter().any(|op| op.name == *name)
2368 }
2369 _ => false,
2370 }) {
2371 return Err(OperationPayloadError::UnknownOperation {
2372 operation: name.clone(),
2373 });
2374 }
2375 if self
2376 .operation_delivery
2377 .get(name)
2378 .is_some_and(OperationDelivery::is_watch)
2379 {
2380 return Err(OperationPayloadError::WatchOperation {
2381 operation: name.clone(),
2382 });
2383 }
2384 if !(1..=crate::framed_body::MAX_DECLARED_PAYLOAD_BYTES).contains(&payload.max_bytes) {
2385 return Err(OperationPayloadError::InvalidMaxBytes {
2386 operation: name.clone(),
2387 });
2388 }
2389 }
2390 Ok(())
2391 }
2392}
2393
2394#[derive(Debug, Clone, PartialEq, Eq)]
2399#[non_exhaustive]
2400pub enum FlowOperationsError {
2401 FlowScopesNotDeclared,
2404 NotAList,
2406 TooMany { count: usize },
2408 DuplicateOperation { operation: String },
2410 UnknownOperation { operation: String },
2412}
2413
2414impl fmt::Display for FlowOperationsError {
2415 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2416 match self {
2417 Self::FlowScopesNotDeclared => write!(
2418 f,
2419 "flow_operations requires '{}' or '{}' in capabilities.provides",
2420 crate::scope::FLOW_SCOPES_CAPABILITY,
2421 crate::call_mode::CALL_MODES_CAPABILITY
2422 ),
2423 Self::NotAList => f.write_str("flow_operations must be an array of operation names"),
2424 Self::TooMany { count } => write!(
2425 f,
2426 "flow_operations lists {count} names, more than {MAX_FLOW_OPERATIONS}"
2427 ),
2428 Self::DuplicateOperation { operation } => {
2429 write!(f, "flow_operations names '{operation}' more than once")
2430 }
2431 Self::UnknownOperation { operation } => write!(
2432 f,
2433 "flow_operations names '{operation}', which is not a declared management operation"
2434 ),
2435 }
2436 }
2437}
2438
2439impl std::error::Error for FlowOperationsError {}
2440
2441impl ModuleManifest {
2442 pub fn validate_flow_operations(&self) -> Result<(), FlowOperationsError> {
2447 match &self.flow_operations {
2448 Some(operations) => check_flow_operations(self, operations),
2449 None => Ok(()),
2450 }
2451 }
2452}
2453
2454fn check_flow_operations(
2455 manifest: &ModuleManifest,
2456 operations: &[String],
2457) -> Result<(), FlowOperationsError> {
2458 let admits_flows = manifest.capabilities.as_ref().is_some_and(|capabilities| {
2459 capabilities.provides.iter().any(|capability| {
2460 capability == crate::scope::FLOW_SCOPES_CAPABILITY
2461 || capability == crate::call_mode::CALL_MODES_CAPABILITY
2462 })
2463 });
2464 if !admits_flows {
2465 return Err(FlowOperationsError::FlowScopesNotDeclared);
2466 }
2467 if operations.len() > MAX_FLOW_OPERATIONS {
2468 return Err(FlowOperationsError::TooMany {
2469 count: operations.len(),
2470 });
2471 }
2472 let mut seen = HashSet::new();
2473 for operation in operations {
2474 if !seen.insert(operation.as_str()) {
2475 return Err(FlowOperationsError::DuplicateOperation {
2476 operation: operation.clone(),
2477 });
2478 }
2479 let declared = manifest.provides.iter().any(|role| match role {
2480 ProviderRole::ManagementSurface { operations, .. } => {
2481 operations.iter().any(|op| op.name == *operation)
2482 }
2483 _ => false,
2484 });
2485 if !declared {
2486 return Err(FlowOperationsError::UnknownOperation {
2487 operation: operation.clone(),
2488 });
2489 }
2490 }
2491 Ok(())
2492}
2493
2494fn decode_flow_operations(
2497 manifest: &ModuleManifest,
2498 value: &Value,
2499) -> Result<Vec<String>, FlowOperationsError> {
2500 let operations: Vec<String> =
2501 serde_json::from_value(value.clone()).map_err(|_| FlowOperationsError::NotAList)?;
2502 check_flow_operations(manifest, &operations)?;
2503 Ok(operations)
2504}
2505
2506pub fn validate_hello_flow_operations(hello: &Value) -> Result<(), FlowOperationsError> {
2512 let Some(manifest_value) = hello.get("manifest") else {
2513 return Ok(());
2514 };
2515 let Some(value) = manifest_value
2516 .get("flow_operations")
2517 .filter(|value| !value.is_null())
2518 else {
2519 return Ok(());
2520 };
2521 let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
2522 return Ok(());
2523 };
2524 decode_flow_operations(&manifest, value).map(|_| ())
2525}
2526
2527#[derive(Debug, Clone, PartialEq, Eq)]
2532#[non_exhaustive]
2533pub enum ConfirmOperationsError {
2534 NotAList,
2536 TooMany { count: usize },
2538 DuplicateOperation { operation: String },
2540 UnknownOperation { operation: String },
2542}
2543
2544impl fmt::Display for ConfirmOperationsError {
2545 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2546 match self {
2547 Self::NotAList => {
2548 f.write_str("confirm_operations must be an array of operation names")
2549 }
2550 Self::TooMany { count } => write!(
2551 f,
2552 "confirm_operations lists {count} names, more than {MAX_CONFIRM_OPERATIONS}"
2553 ),
2554 Self::DuplicateOperation { operation } => {
2555 write!(f, "confirm_operations names '{operation}' more than once")
2556 }
2557 Self::UnknownOperation { operation } => write!(
2558 f,
2559 "confirm_operations names '{operation}', which is not a declared management operation"
2560 ),
2561 }
2562 }
2563}
2564
2565impl std::error::Error for ConfirmOperationsError {}
2566
2567impl ModuleManifest {
2568 pub fn validate_confirm_operations(&self) -> Result<(), ConfirmOperationsError> {
2572 match &self.confirm_operations {
2573 Some(operations) => check_confirm_operations(self, operations),
2574 None => Ok(()),
2575 }
2576 }
2577}
2578
2579fn check_confirm_operations(
2580 manifest: &ModuleManifest,
2581 operations: &[String],
2582) -> Result<(), ConfirmOperationsError> {
2583 if operations.len() > MAX_CONFIRM_OPERATIONS {
2584 return Err(ConfirmOperationsError::TooMany {
2585 count: operations.len(),
2586 });
2587 }
2588 let mut seen = HashSet::new();
2589 for operation in operations {
2590 if !seen.insert(operation.as_str()) {
2591 return Err(ConfirmOperationsError::DuplicateOperation {
2592 operation: operation.clone(),
2593 });
2594 }
2595 if !declares_management_operation(manifest, operation) {
2596 return Err(ConfirmOperationsError::UnknownOperation {
2597 operation: operation.clone(),
2598 });
2599 }
2600 }
2601 Ok(())
2602}
2603
2604fn declares_management_operation(manifest: &ModuleManifest, operation: &str) -> bool {
2605 manifest.provides.iter().any(|role| match role {
2606 ProviderRole::ManagementSurface { operations, .. } => {
2607 operations.iter().any(|op| op.name == operation)
2608 }
2609 _ => false,
2610 })
2611}
2612
2613fn decode_confirm_operations(
2616 manifest: &ModuleManifest,
2617 value: &Value,
2618) -> Result<Vec<String>, ConfirmOperationsError> {
2619 let operations: Vec<String> =
2620 serde_json::from_value(value.clone()).map_err(|_| ConfirmOperationsError::NotAList)?;
2621 check_confirm_operations(manifest, &operations)?;
2622 Ok(operations)
2623}
2624
2625pub fn validate_hello_confirm_operations(hello: &Value) -> Result<(), ConfirmOperationsError> {
2631 let Some(manifest_value) = hello.get("manifest") else {
2632 return Ok(());
2633 };
2634 let Some(value) = manifest_value
2635 .get("confirm_operations")
2636 .filter(|value| !value.is_null())
2637 else {
2638 return Ok(());
2639 };
2640 let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
2641 return Ok(());
2642 };
2643 decode_confirm_operations(&manifest, value).map(|_| ())
2644}
2645
2646#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2651pub struct ManagementOperation {
2652 pub name: String,
2653 pub kind: ManagementOperationKind,
2654 #[serde(default, skip_serializing_if = "Option::is_none")]
2655 pub description: Option<String>,
2656}
2657
2658#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2659#[serde(rename_all = "snake_case")]
2660pub enum ManagementOperationKind {
2661 Query,
2662 Mutate,
2663}
2664
2665#[derive(Debug, Clone, PartialEq, Eq)]
2668#[non_exhaustive]
2669pub enum OperationDelivery {
2670 Watch,
2671 Other(String),
2672}
2673
2674impl OperationDelivery {
2675 pub const WATCH: Self = Self::Watch;
2677
2678 pub fn wire_name(&self) -> &str {
2680 match self {
2681 Self::Watch => "watch",
2682 Self::Other(value) => value,
2683 }
2684 }
2685
2686 pub fn is_watch(&self) -> bool {
2688 self.wire_name() == "watch"
2689 }
2690}
2691
2692impl Serialize for OperationDelivery {
2693 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2694 where
2695 S: serde::Serializer,
2696 {
2697 serializer.serialize_str(self.wire_name())
2698 }
2699}
2700
2701impl<'de> Deserialize<'de> for OperationDelivery {
2702 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2703 where
2704 D: Deserializer<'de>,
2705 {
2706 let value = String::deserialize(deserializer)?;
2707 Ok(if value == "watch" {
2708 Self::WATCH
2709 } else {
2710 Self::Other(value)
2711 })
2712 }
2713}
2714
2715#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2717pub struct ObservabilitySurface {
2718 pub name: String,
2719 pub kind: ObservabilityKind,
2720}
2721
2722#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2723#[serde(rename_all = "snake_case")]
2724pub enum ObservabilityKind {
2725 Snapshot,
2726 Stream,
2727}
2728
2729#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2730#[serde(rename_all = "snake_case")]
2731pub enum InternalTransport {
2732 Bulk,
2733}
2734
2735#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2737#[serde(tag = "role", rename_all = "snake_case")]
2738pub enum ConsumerRole {
2739 ToolClient { of: Vec<String> },
2740 LlmClient { via: String, auth: String },
2741 ServiceClient { of: Vec<String> },
2742}
2743
2744#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2746pub struct Bindings {
2747 pub storage: StorageBinding,
2748 pub vault_grants: Vec<VaultGrant>,
2749 pub identity: IdentityBinding,
2750}
2751
2752#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2754pub struct StorageBinding {
2755 pub kind: StorageKind,
2756 pub scope: StorageScope,
2757 pub owns_schema: bool,
2758}
2759
2760#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2761#[serde(rename_all = "snake_case")]
2762pub enum StorageKind {
2763 Sqlite,
2764}
2765
2766#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2767#[serde(rename_all = "snake_case")]
2768pub enum StorageScope {
2769 Project,
2770}
2771
2772#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2773pub struct VaultGrant {
2774 pub secret: String,
2775 pub reason: String,
2776}
2777
2778#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2779pub struct IdentityBinding {
2780 pub requires: Vec<IdentityScope>,
2781 pub optional: Vec<IdentityScope>,
2782}
2783
2784#[cfg(test)]
2785mod tests {
2786 use super::*;
2787 use serde_json::json;
2788
2789 fn aft_manifest_fixture() -> ModuleManifest {
2790 ModuleManifest::builder("aft", "0.39.2")
2791 .trust_tier(Some(TrustTier::FirstParty))
2792 .bindings(Some(Bindings {
2793 storage: StorageBinding {
2794 kind: StorageKind::Sqlite,
2795 scope: StorageScope::Project,
2796 owns_schema: true,
2797 },
2798 vault_grants: vec![VaultGrant {
2799 secret: "provider_api_key".to_string(),
2800 reason: "cortexkit_native auth".to_string(),
2801 }],
2802 identity: IdentityBinding {
2803 requires: vec![IdentityScope::Project],
2804 optional: vec![IdentityScope::Session],
2805 },
2806 }))
2807 .protocol_ver(1)
2808 .provides(vec![ProviderRole::ToolProvider {
2809 tools: vec![
2810 Tool {
2811 name: "read".to_string(),
2812 description: None,
2813 execution_mode: ExecutionMode::Pure,
2814 schema: json!({"type": "object"}),
2815 },
2816 Tool {
2817 name: "grep".to_string(),
2818 description: None,
2819 execution_mode: ExecutionMode::Pure,
2820 schema: json!({"type": "object"}),
2821 },
2822 Tool {
2823 name: "outline".to_string(),
2824 description: None,
2825 execution_mode: ExecutionMode::Pure,
2826 schema: json!({"type": "object"}),
2827 },
2828 Tool {
2829 name: "semantic_search".to_string(),
2830 description: None,
2831 execution_mode: ExecutionMode::Pure,
2832 schema: json!({"type": "object"}),
2833 },
2834 Tool {
2835 name: "edit".to_string(),
2836 description: None,
2837 execution_mode: ExecutionMode::Mutating,
2838 schema: json!({"type": "object"}),
2839 },
2840 Tool {
2841 name: "write".to_string(),
2842 description: None,
2843 execution_mode: ExecutionMode::Mutating,
2844 schema: json!({"type": "object"}),
2845 },
2846 Tool {
2847 name: "bash".to_string(),
2848 description: None,
2849 execution_mode: ExecutionMode::Unfenceable,
2850 schema: json!({"type": "object"}),
2851 },
2852 ],
2853 identity_scope: vec![IdentityScope::Session, IdentityScope::Project],
2854 concurrency: Concurrency::ModuleManaged,
2855 emits_push: true,
2856 sub_supervises: true,
2857 }])
2858 .consumes(vec![ConsumerRole::ServiceClient {
2859 of: vec!["embedding.v2".to_string()],
2860 }])
2861 .build()
2862 }
2863
2864 #[test]
2865 fn serde_round_trips_representative_manifest() {
2866 let manifest = aft_manifest_fixture();
2867 let serialized = serde_json::to_string_pretty(&manifest).unwrap();
2868 let decoded: ModuleManifest = serde_json::from_str(&serialized).unwrap();
2869
2870 assert_eq!(manifest, decoded);
2871 }
2872
2873 #[test]
2874 fn builder_defaults_additions_to_honest_absence_and_round_trips() {
2875 let manifest = ModuleManifest::builder("builder-defaults", "2.0.0").build();
2876
2877 assert_eq!(manifest.module_id, "builder-defaults");
2878 assert_eq!(manifest.module_version, "2.0.0");
2879 assert_eq!(manifest.protocol_ver, PROTOCOL_VERSION);
2880 assert_eq!(manifest.trust_tier, None);
2881 assert!(manifest.provides.is_empty());
2882 assert!(manifest.consumes.is_empty());
2883 assert_eq!(manifest.bindings, None);
2884 assert_eq!(manifest.capabilities, None);
2885 assert_eq!(manifest.self_signals, None);
2886 assert_eq!(manifest.provenance, None);
2887
2888 let encoded = serde_json::to_value(&manifest).expect("builder manifest serializes");
2889 for optional in [
2890 "trust_tier",
2891 "consumes",
2892 "bindings",
2893 "capabilities",
2894 "self_signals",
2895 "provenance",
2896 ] {
2897 assert!(
2898 encoded.get(optional).is_none(),
2899 "an absent {optional} declaration must stay absent on the wire"
2900 );
2901 }
2902 let decoded: ModuleManifest =
2903 serde_json::from_value(encoded).expect("builder manifest round-trips");
2904 assert_eq!(decoded, manifest);
2905 }
2906
2907 #[test]
2908 fn fully_populated_builder_manifest_matches_the_literal_wire_golden() {
2909 let manifest = ModuleManifest::builder("full-builder", "2.0.0")
2910 .trust_tier(Some(TrustTier::Reviewed))
2911 .bindings(Some(Bindings {
2912 storage: StorageBinding {
2913 kind: StorageKind::Sqlite,
2914 scope: StorageScope::Project,
2915 owns_schema: false,
2916 },
2917 vault_grants: Vec::new(),
2918 identity: IdentityBinding {
2919 requires: vec![IdentityScope::Project],
2920 optional: Vec::new(),
2921 },
2922 }))
2923 .provides(vec![ProviderRole::ToolProvider {
2924 tools: vec![Tool {
2925 name: "read".to_string(),
2926 description: None,
2927 execution_mode: ExecutionMode::Pure,
2928 schema: json!({"type": "object"}),
2929 }],
2930 identity_scope: vec![IdentityScope::Project],
2931 concurrency: Concurrency::Serial,
2932 emits_push: false,
2933 sub_supervises: false,
2934 }])
2935 .consumes(vec![ConsumerRole::ServiceClient {
2936 of: vec!["embedding.v2".to_string()],
2937 }])
2938 .capabilities(Some(CapabilityDeclarations {
2939 provides: vec!["embedding/v2".to_string()],
2940 requires: Vec::new(),
2941 must_never_reach: Vec::new(),
2942 }))
2943 .self_signals(Some(vec![SelfSignalDeclaration {
2944 name: "usage_poller".to_string(),
2945 kind: SelfSignalKind::Poller,
2946 effect: SelfSignalEffect::Observe,
2947 anchored_to: SignalAnchor::FixedInterval,
2948 cadence: Some(SignalCadence::Literal {
2949 interval_ms: 60_000,
2950 }),
2951 domain: Some("provider-usage".to_string()),
2952 note: None,
2953 }]))
2954 .provenance(Some(ManifestProvenance {
2955 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
2956 build_git_sha_absence_reason: None,
2957 build_lock_digest: Some(
2958 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
2959 ),
2960 wire_crate_version: Some("0.16.0".to_string()),
2961 store_schema_version: Some("42".to_string()),
2962 launch_nonce_source: None,
2963 }))
2964 .build();
2965
2966 assert_eq!(
2967 serde_json::to_vec(&manifest).expect("builder manifest serializes"),
2968 include_bytes!("../tests/golden/module_manifest_builder_full.json"),
2969 "the builder must preserve the prior fully populated literal wire bytes"
2970 );
2971 }
2972
2973 #[test]
2974 fn old_manifest_with_unread_fields_decodes_and_round_trips_verbatim() {
2975 let raw = include_bytes!("../tests/golden/module_manifest_builder_full.json");
2976 let decoded: ModuleManifest =
2977 serde_json::from_slice(raw).expect("old manifest with all unread fields decodes");
2978
2979 assert_eq!(decoded.trust_tier, Some(TrustTier::Reviewed));
2980 assert!(!decoded.consumes.is_empty());
2981 assert!(decoded.bindings.is_some());
2982
2983 let reencoded = serde_json::to_vec(&decoded).expect("re-encode succeeds");
2984 assert_eq!(
2985 reencoded, raw,
2986 "old manifest relay stays byte-for-byte verbatim"
2987 );
2988 }
2989
2990 #[test]
2991 fn new_manifest_omits_unread_fields_on_wire_and_decodes_cleanly() {
2992 let raw = include_bytes!("../tests/golden/module_manifest_diet.json");
2993 let decoded: ModuleManifest =
2994 serde_json::from_slice(raw).expect("new manifest omitting unread fields decodes");
2995
2996 assert_eq!(decoded.trust_tier, None);
2997 assert!(decoded.consumes.is_empty());
2998 assert_eq!(decoded.bindings, None);
2999
3000 let pretty = format!("{}\n", serde_json::to_string_pretty(&decoded).unwrap());
3001 assert_eq!(
3002 pretty.as_bytes(),
3003 raw,
3004 "new manifest matches golden byte-for-byte without unread keys"
3005 );
3006
3007 let as_val: serde_json::Value = serde_json::to_value(&decoded).unwrap();
3008 assert!(
3009 as_val.get("trust_tier").is_none(),
3010 "no trust_tier on wire for new manifest"
3011 );
3012 assert!(
3013 as_val.get("consumes").is_none(),
3014 "no consumes on wire for empty consumes"
3015 );
3016 assert!(
3017 as_val.get("bindings").is_none(),
3018 "no bindings on wire for new manifest"
3019 );
3020 }
3021
3022 #[test]
3023 fn aft_manifest_fixture_matches_v1_contract() {
3024 let manifest = aft_manifest_fixture();
3025
3026 assert_eq!(manifest.module_id, "aft");
3027 let ProviderRole::ToolProvider {
3028 tools,
3029 identity_scope,
3030 concurrency,
3031 emits_push,
3032 sub_supervises,
3033 } = &manifest.provides[0]
3034 else {
3035 panic!("AFT fixture must expose one tool_provider role");
3036 };
3037
3038 assert_eq!(*concurrency, Concurrency::ModuleManaged);
3039 assert!(*emits_push);
3040 assert!(*sub_supervises);
3041 assert_eq!(
3042 identity_scope,
3043 &vec![IdentityScope::Session, IdentityScope::Project]
3044 );
3045 assert_eq!(
3046 tools
3047 .iter()
3048 .map(|tool| (tool.name.as_str(), tool.execution_mode))
3049 .collect::<Vec<_>>(),
3050 vec![
3051 ("read", ExecutionMode::Pure),
3052 ("grep", ExecutionMode::Pure),
3053 ("outline", ExecutionMode::Pure),
3054 ("semantic_search", ExecutionMode::Pure),
3055 ("edit", ExecutionMode::Mutating),
3056 ("write", ExecutionMode::Mutating),
3057 ("bash", ExecutionMode::Unfenceable),
3058 ]
3059 );
3060 }
3061
3062 #[test]
3063 fn tool_provider_role_tag_serializes_as_snake_case() {
3064 let manifest = aft_manifest_fixture();
3065 let value = serde_json::to_value(&manifest).unwrap();
3066
3067 assert_eq!(value["provides"][0]["role"], "tool_provider");
3068 }
3069
3070 #[test]
3071 fn manifest_without_capabilities_preserves_the_existing_wire_shape() {
3072 let manifest = aft_manifest_fixture();
3073 let encoded = serde_json::to_value(&manifest).expect("manifest serializes");
3074 assert!(encoded.get("capabilities").is_none());
3075
3076 let decoded: ModuleManifest =
3077 serde_json::from_value(encoded).expect("legacy manifest parses");
3078 assert_eq!(decoded.capabilities, None);
3079 }
3080
3081 #[test]
3082 fn capability_identifier_lexical_grammar_accepts_only_pinned_forms() {
3083 for identifier in [
3084 "a/v1",
3085 "credentials-provider/v1",
3086 "a1-b2/v4294967295",
3087 "a123456789012345678901234567890123456789012345678901234567890123/v1",
3088 ] {
3089 assert!(
3090 is_valid_capability_identifier(identifier),
3091 "identifier must be accepted: {identifier}"
3092 );
3093 }
3094
3095 for identifier in [
3096 "credentials-Provider/v1",
3097 "credentials-provider/v01",
3098 "credentials-provider-/v1",
3099 "credentials--provider/v1",
3100 "Credentials-provider/v1",
3101 "credentials-provider/1",
3102 "credentials provider/v1",
3103 "credentials-provider/v0",
3104 "credentials-provider/v4294967296",
3105 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/v1",
3106 ] {
3107 assert!(
3108 !is_valid_capability_identifier(identifier),
3109 "identifier must be rejected: {identifier}"
3110 );
3111 }
3112 }
3113
3114 #[test]
3115 fn capability_grammar_errors_redact_secret_shaped_values() {
3116 let error = validate_manifest_capability_grammar(&json!({
3117 "capabilities": { "provides": ["sk-secret-value/v0"] }
3118 }))
3119 .expect_err("secret-shaped capability identifier is malformed");
3120 assert_eq!(error.field(), "capabilities.provides[0]");
3121 assert_eq!(error.value(), "<redacted>");
3122 assert!(!error.to_string().contains("sk-secret-value"));
3123 }
3124
3125 #[test]
3132 fn provenance_builder_sentinels_become_field_omission() {
3133 for sentinel in [
3134 "unknown",
3135 "UNKNOWN",
3136 "Unknown",
3137 "unavailable",
3138 "none",
3139 "None",
3140 " unknown ",
3141 "",
3142 ] {
3143 let p = build_provenance_from_source(
3144 BuildGitShaSource::Git {
3145 revision: sentinel,
3146 tree_state: GitTreeState::Clean,
3147 },
3148 Some(sentinel),
3149 Some(sentinel),
3150 )
3151 .expect("sentinels are omitted before form validation");
3152 assert_eq!(
3153 (
3154 p.build_git_sha,
3155 p.build_git_sha_absence_reason,
3156 p.build_lock_digest,
3157 p.store_schema_version,
3158 ),
3159 (
3160 None,
3161 Some(BuildGitShaAbsenceReason::NeverDerived),
3162 None,
3163 None,
3164 ),
3165 "sentinel {sentinel:?} must be omitted, not published"
3166 );
3167 }
3168 let real = build_provenance_from_source(
3169 BuildGitShaSource::Git {
3170 revision: "0123456789abcdef0123456789abcdef01234567",
3171 tree_state: GitTreeState::Clean,
3172 },
3173 None,
3174 Some("9"),
3175 )
3176 .expect("canonical build revision is accepted");
3177 assert_eq!(
3178 real.build_git_sha.as_deref(),
3179 Some("0123456789abcdef0123456789abcdef01234567")
3180 );
3181 assert_eq!(real.store_schema_version.as_deref(), Some("9"));
3182 assert_eq!(
3186 real.wire_crate_version.as_deref(),
3187 Some(crate::SUBC_PROTOCOL_CRATE_VERSION)
3188 );
3189 }
3190
3191 #[test]
3192 fn build_provenance_accepts_canonical_sha_and_lock_digest() {
3193 let provenance = build_provenance_from_source(
3194 BuildGitShaSource::Git {
3195 revision: " 0123456789abcdef0123456789abcdef01234567 ",
3196 tree_state: GitTreeState::Clean,
3197 },
3198 Some(" abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789 "),
3199 Some(" schema-v3 "),
3200 )
3201 .expect("canonical build facts are accepted");
3202
3203 assert_eq!(
3204 provenance,
3205 ManifestProvenance {
3206 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
3207 build_git_sha_absence_reason: None,
3208 build_lock_digest: Some(
3209 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
3210 ),
3211 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
3212 store_schema_version: Some("schema-v3".to_string()),
3213 launch_nonce_source: None,
3214 }
3215 );
3216 }
3217
3218 #[test]
3219 fn build_provenance_refuses_an_abbreviated_git_sha() {
3220 let error = build_provenance_from_source(
3221 BuildGitShaSource::Git {
3222 revision: "0123456789ab",
3223 tree_state: GitTreeState::Clean,
3224 },
3225 None,
3226 None,
3227 )
3228 .expect_err("a 12-character abbreviation is not canonical");
3229
3230 assert_eq!(error.field(), "build_git_sha");
3231 assert_eq!(error.length(), 12);
3232 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3233 assert_eq!(
3234 error.to_string(),
3235 "invalid manifest provenance form: field build_git_sha has length 12; canonical form is exactly 40 lowercase hexadecimal characters"
3236 );
3237 }
3238
3239 #[test]
3240 fn build_provenance_refuses_an_abbreviated_lock_digest() {
3241 let error = build_provenance_from_source(
3242 BuildGitShaSource::NeverDerived,
3243 Some("0123456789abcdef"),
3244 None,
3245 )
3246 .expect_err("a 16-character digest is not canonical");
3247
3248 assert_eq!(error.field(), "build_lock_digest");
3249 assert_eq!(error.length(), 16);
3250 assert_eq!(error.canonical_form(), BUILD_LOCK_DIGEST_CANONICAL_FORM);
3251 }
3252
3253 #[test]
3254 fn build_provenance_refuses_uppercase_hex() {
3255 let uppercase_sha = "A".repeat(40);
3256 let error = build_provenance_from_source(
3257 BuildGitShaSource::Git {
3258 revision: &uppercase_sha,
3259 tree_state: GitTreeState::Clean,
3260 },
3261 None,
3262 None,
3263 )
3264 .expect_err("uppercase hexadecimal is not canonical");
3265
3266 assert_eq!(error.field(), "build_git_sha");
3267 assert_eq!(error.length(), 40);
3268 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3269 }
3270
3271 #[test]
3272 fn build_provenance_refuses_dirty_revision_stamp_claimed_clean() {
3273 let error = build_provenance_from_source(
3274 BuildGitShaSource::Git {
3275 revision: "0123456789abcdef0123456789abcdef01234567-dirty",
3276 tree_state: GitTreeState::Clean,
3277 },
3278 None,
3279 None,
3280 )
3281 .expect_err("a dirty stamp is not a canonical build revision");
3282
3283 assert_eq!(error.field(), "build_git_sha");
3284 assert_eq!(error.length(), 46);
3285 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3286 }
3287
3288 #[test]
3289 fn build_provenance_keeps_a_lock_digest_when_identity_is_unavailable() {
3290 let provenance = build_provenance_from_source(
3291 BuildGitShaSource::Git {
3292 revision: "unavailable",
3293 tree_state: GitTreeState::Clean,
3294 },
3295 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"),
3296 None,
3297 )
3298 .expect("sentinel SHA is omitted before the valid lock digest is checked");
3299
3300 assert_eq!(provenance.build_git_sha, None);
3301 assert_eq!(
3302 provenance.build_lock_digest,
3303 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string())
3304 );
3305 assert_eq!(
3306 provenance.wire_crate_version,
3307 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
3308 );
3309 }
3310
3311 #[test]
3312 fn build_provenance_omits_fully_unavailable_inputs() {
3313 let provenance = build_provenance_from_source(
3314 BuildGitShaSource::NeverDerived,
3315 Some(" unavailable "),
3316 Some(" "),
3317 )
3318 .expect("omitted and sentinel inputs are not form errors");
3319
3320 assert_eq!(provenance.build_git_sha, None);
3321 assert_eq!(provenance.build_lock_digest, None);
3322 assert_eq!(provenance.store_schema_version, None);
3323 assert_eq!(
3324 provenance.wire_crate_version,
3325 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
3326 );
3327 }
3328
3329 #[test]
3330 fn legacy_build_provenance_keeps_master_wire_bytes_without_an_absence_reason() {
3331 let revision = "0123456789abcdef0123456789abcdef01234567";
3332 for (input, expected) in [
3333 (
3334 Some(revision),
3335 format!(
3336 r#"{{"build_git_sha":"{revision}","wire_crate_version":"{}"}}"#,
3337 crate::SUBC_PROTOCOL_CRATE_VERSION
3338 ),
3339 ),
3340 (
3341 None,
3342 format!(
3343 r#"{{"wire_crate_version":"{}"}}"#,
3344 crate::SUBC_PROTOCOL_CRATE_VERSION
3345 ),
3346 ),
3347 (
3348 Some("unknown"),
3349 format!(
3350 r#"{{"wire_crate_version":"{}"}}"#,
3351 crate::SUBC_PROTOCOL_CRATE_VERSION
3352 ),
3353 ),
3354 ] {
3355 let provenance = build_provenance(input, None, None)
3356 .expect("the legacy build facts remain constructible");
3357 assert_eq!(provenance.build_git_sha_absence_reason, None);
3358 assert_eq!(
3359 serde_json::to_string(&provenance).expect("legacy provenance serializes"),
3360 expected
3361 );
3362 }
3363 }
3364
3365 #[test]
3366 fn build_provenance_derives_git_sha_absence_from_the_stamping_inputs() {
3367 let revision = "0123456789abcdef0123456789abcdef01234567";
3368 let cases = [
3369 (
3370 BuildGitShaSource::Git {
3371 revision,
3372 tree_state: GitTreeState::Clean,
3373 },
3374 Some(revision),
3375 None,
3376 ),
3377 (
3378 BuildGitShaSource::Git {
3379 revision,
3380 tree_state: GitTreeState::Dirty,
3381 },
3382 None,
3383 Some(BuildGitShaAbsenceReason::DeclinedDirty),
3384 ),
3385 (
3386 BuildGitShaSource::NeverDerived,
3387 None,
3388 Some(BuildGitShaAbsenceReason::NeverDerived),
3389 ),
3390 (
3391 BuildGitShaSource::NoGitDir,
3392 None,
3393 Some(BuildGitShaAbsenceReason::NoGitDir),
3394 ),
3395 ];
3396
3397 for (source, expected_sha, expected_reason) in cases {
3398 let provenance = build_provenance_from_source(source, None, None)
3399 .expect("every stamping state constructs honest provenance");
3400 assert_eq!(provenance.build_git_sha.as_deref(), expected_sha);
3401 assert_eq!(provenance.build_git_sha_absence_reason, expected_reason);
3402 }
3403 }
3404
3405 #[test]
3406 fn unknown_git_sha_absence_reason_round_trips_byte_faithfully() {
3407 let wire = format!(
3408 r#"{{"build_git_sha_absence_reason":"future_stamper_state","wire_crate_version":"{}"}}"#,
3409 crate::SUBC_PROTOCOL_CRATE_VERSION
3410 );
3411 let provenance: ManifestProvenance =
3412 serde_json::from_str(&wire).expect("future absence reasons remain readable");
3413
3414 assert_eq!(
3415 provenance.build_git_sha_absence_reason,
3416 Some(BuildGitShaAbsenceReason::ForwardCompatibleUnknown(
3417 "future_stamper_state".to_string()
3418 ))
3419 );
3420 assert_eq!(
3421 serde_json::to_string(&provenance).expect("future absence reason reserializes"),
3422 wire
3423 );
3424 }
3425
3426 #[test]
3427 fn provenance_rejects_an_absence_reason_beside_a_declared_commit() {
3428 let error = serde_json::from_value::<ManifestProvenance>(json!({
3429 "build_git_sha": "0123456789abcdef0123456789abcdef01234567",
3430 "build_git_sha_absence_reason": "declined_dirty"
3431 }))
3432 .expect_err("a declared commit cannot also claim an absence reason");
3433
3434 assert!(error.to_string().contains(
3435 "build_git_sha_absence_reason has must be omitted when build_git_sha is present"
3436 ));
3437 }
3438
3439 #[test]
3440 fn rich_ui_descriptor_is_optional_and_round_trips_when_present() {
3441 let manifest = ModuleManifest::builder("provider", "1.0.0").build();
3442 assert_eq!(
3443 serde_json::to_string(&manifest).unwrap(),
3444 r#"{"module_id":"provider","module_version":"1.0.0","protocol_ver":2,"provides":[]}"#
3445 );
3446
3447 let descriptor = RichUiDescriptor::new(
3448 "ckios.richui.manifest/1",
3449 format!("sha256:{}", "a".repeat(64)),
3450 128,
3451 2,
3452 );
3453 let manifest = ModuleManifest::builder("provider", "1.0.0")
3454 .rich_ui(Some(descriptor.clone()))
3455 .build();
3456 let wire = serde_json::to_string(&manifest).unwrap();
3457 assert!(wire.contains("\"rich_ui\":{\"schema\":\"ckios.richui.manifest/1\""));
3458 assert_eq!(
3459 serde_json::from_str::<ModuleManifest>(&wire)
3460 .unwrap()
3461 .rich_ui,
3462 Some(descriptor)
3463 );
3464 }
3465
3466 #[test]
3467 fn rich_ui_descriptor_validation_names_each_invalid_field() {
3468 let good = json!({
3469 "schema": "ckios.richui.manifest/1",
3470 "manifest_digest": format!("sha256:{}", "a".repeat(64)),
3471 "bytes": 1,
3472 "chunks": 1
3473 });
3474 let hello = json!({"manifest": {"rich_ui": good.clone()}});
3475 assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
3476
3477 for (field, value) in [
3478 ("schema", json!("bad schema")),
3479 (
3480 "manifest_digest",
3481 json!(format!("sha256:{}", "A".repeat(64))),
3482 ),
3483 ("bytes", json!(0)),
3484 ("chunks", json!(1025)),
3485 ] {
3486 let mut invalid = hello.clone();
3487 invalid["manifest"]["rich_ui"][field] = value;
3488 let error = validate_hello_rich_ui_descriptor(&invalid)
3489 .expect_err("an invalid descriptor field must be refused");
3490 assert_eq!(error.field(), format!("rich_ui.{field}"));
3491 }
3492
3493 let mut hello = hello;
3494 hello["manifest"]["rich_ui"] = Value::Null;
3495 let error = validate_hello_rich_ui_descriptor(&hello)
3496 .expect_err("null is not an absent descriptor");
3497 assert_eq!(error.field(), "rich_ui");
3498 }
3499
3500 #[test]
3501 fn rich_ui_descriptor_validation_accepts_inclusive_bounds() {
3502 let hello = json!({"manifest": {"rich_ui": {
3503 "schema": "a".repeat(64),
3504 "manifest_digest": format!("sha256:{}", "f".repeat(64)),
3505 "bytes": 16_777_216,
3506 "chunks": 1024
3507 }}});
3508 assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
3509 }
3510}