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 #[serde(default, skip_serializing_if = "Option::is_none")]
40 pub display_name: Option<String>,
41 pub module_version: String,
42 pub protocol_ver: u8,
43 #[serde(default, skip_serializing_if = "Option::is_none")]
44 pub trust_tier: Option<TrustTier>,
45 #[serde(default, skip_serializing_if = "Option::is_none")]
52 pub ready: Option<bool>,
53 pub provides: Vec<ProviderRole>,
56 #[serde(default, skip_serializing_if = "Vec::is_empty")]
57 pub consumes: Vec<ConsumerRole>,
58 #[serde(default, skip_serializing_if = "Option::is_none")]
59 pub bindings: Option<Bindings>,
60 #[serde(default, skip_serializing_if = "Option::is_none")]
66 pub capabilities: Option<CapabilityDeclarations>,
67 #[serde(default, skip_serializing_if = "Option::is_none")]
81 pub events: Option<Vec<EventDeclaration>>,
82 #[serde(default, skip_serializing_if = "Option::is_none")]
117 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
118 #[serde(default, skip_serializing_if = "Option::is_none")]
119 pub provenance: Option<ManifestProvenance>,
120 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
125 pub operation_delivery: BTreeMap<String, OperationDelivery>,
126 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
129 pub operation_payload: BTreeMap<String, OperationPayload>,
130 #[serde(default, skip_serializing_if = "Option::is_none")]
149 pub flow_operations: Option<Vec<String>>,
150 #[serde(default, skip_serializing_if = "Option::is_none")]
167 pub confirm_operations: Option<Vec<String>>,
168 #[serde(default, skip_serializing_if = "Option::is_none")]
173 pub rich_ui: Option<RichUiDescriptor>,
174 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
183 pub role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
184}
185
186#[derive(Debug, Clone)]
188pub struct ModuleManifestBuilder {
189 module_id: String,
190 display_name: Option<String>,
191 module_version: String,
192 protocol_ver: u8,
193 trust_tier: Option<TrustTier>,
194 ready: Option<bool>,
195 provides: Vec<ProviderRole>,
196 consumes: Vec<ConsumerRole>,
197 bindings: Option<Bindings>,
198 capabilities: Option<CapabilityDeclarations>,
199 events: Option<Vec<EventDeclaration>>,
200 self_signals: Option<Vec<SelfSignalDeclaration>>,
201 provenance: Option<ManifestProvenance>,
202 operation_delivery: BTreeMap<String, OperationDelivery>,
203 operation_payload: BTreeMap<String, OperationPayload>,
204 flow_operations: Option<Vec<String>>,
205 confirm_operations: Option<Vec<String>>,
206 rich_ui: Option<RichUiDescriptor>,
207 role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
208}
209
210impl ModuleManifest {
211 pub fn builder(
219 module_id: impl Into<String>,
220 module_version: impl Into<String>,
221 ) -> ModuleManifestBuilder {
222 ModuleManifestBuilder {
223 module_id: module_id.into(),
224 display_name: None,
225 module_version: module_version.into(),
226 protocol_ver: PROTOCOL_VERSION,
227 trust_tier: None,
228 ready: None,
229 provides: Vec::new(),
230 consumes: Vec::new(),
231 bindings: None,
232 capabilities: None,
233 events: None,
234 self_signals: None,
235 provenance: None,
236 operation_delivery: BTreeMap::new(),
237 operation_payload: BTreeMap::new(),
238 flow_operations: None,
239 confirm_operations: None,
240 rich_ui: None,
241 role_declarations: BTreeMap::new(),
242 }
243 }
244
245 pub fn is_watch_operation(&self, name: &str) -> bool {
250 self.operation_delivery
251 .get(name)
252 .is_some_and(OperationDelivery::is_watch)
253 && self.provides.iter().any(|role| match role {
254 ProviderRole::ManagementSurface { operations, .. } => operations
255 .iter()
256 .any(|op| op.name == name && op.kind == ManagementOperationKind::Query),
257 _ => false,
258 })
259 }
260}
261
262impl ModuleManifestBuilder {
263 pub fn display_name(mut self, display_name: Option<String>) -> Result<Self, DisplayNameError> {
265 if let Some(value) = &display_name {
266 validate_display_name(value)?;
267 }
268 self.display_name = display_name;
269 Ok(self)
270 }
271
272 pub fn protocol_ver(mut self, protocol_ver: u8) -> Self {
274 self.protocol_ver = protocol_ver;
275 self
276 }
277
278 pub fn trust_tier(mut self, trust_tier: Option<TrustTier>) -> Self {
282 self.trust_tier = trust_tier;
283 self
284 }
285
286 pub fn ready(mut self, ready: bool) -> Self {
288 self.ready = Some(ready);
289 self
290 }
291
292 pub fn provides(mut self, provides: Vec<ProviderRole>) -> Self {
294 self.provides = provides;
295 self
296 }
297
298 pub fn consumes(mut self, consumes: Vec<ConsumerRole>) -> Self {
300 self.consumes = consumes;
301 self
302 }
303
304 pub fn bindings(mut self, bindings: Option<Bindings>) -> Self {
308 self.bindings = bindings;
309 self
310 }
311
312 pub fn capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
314 self.capabilities = capabilities;
315 self
316 }
317
318 pub fn events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
320 self.events = events;
321 self
322 }
323
324 pub fn self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
326 self.self_signals = self_signals;
327 self
328 }
329
330 pub fn provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
332 self.provenance = provenance;
333 self
334 }
335
336 pub fn operation_delivery(
338 mut self,
339 operation_delivery: BTreeMap<String, OperationDelivery>,
340 ) -> Self {
341 self.operation_delivery = operation_delivery;
342 self
343 }
344
345 pub fn operation_payload(
347 mut self,
348 operation_payload: BTreeMap<String, OperationPayload>,
349 ) -> Self {
350 self.operation_payload = operation_payload;
351 self
352 }
353
354 pub fn flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
361 self.flow_operations = flow_operations;
362 self
363 }
364
365 pub fn confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
372 self.confirm_operations = confirm_operations;
373 self
374 }
375
376 pub fn rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
378 self.rich_ui = rich_ui;
379 self
380 }
381
382 pub fn role_declarations(
384 mut self,
385 role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
386 ) -> Self {
387 self.role_declarations = role_declarations;
388 self
389 }
390
391 pub fn build(self) -> ModuleManifest {
393 ModuleManifest {
394 module_id: self.module_id,
395 display_name: self.display_name,
396 module_version: self.module_version,
397 protocol_ver: self.protocol_ver,
398 trust_tier: self.trust_tier,
399 ready: self.ready,
400 provides: self.provides,
401 consumes: self.consumes,
402 bindings: self.bindings,
403 capabilities: self.capabilities,
404 events: self.events,
405 self_signals: self.self_signals,
406 provenance: self.provenance,
407 operation_delivery: self.operation_delivery,
408 operation_payload: self.operation_payload,
409 flow_operations: self.flow_operations,
410 confirm_operations: self.confirm_operations,
411 rich_ui: self.rich_ui,
412 role_declarations: self.role_declarations,
413 }
414 }
415}
416
417#[derive(Deserialize)]
437struct ModuleManifestWire {
438 module_id: String,
439 #[serde(default)]
440 display_name: Option<String>,
441 module_version: String,
442 protocol_ver: u8,
443 #[serde(default)]
444 trust_tier: Option<TrustTier>,
445 #[serde(default)]
446 ready: Option<bool>,
447 provides: Vec<ProviderRole>,
448 #[serde(default)]
449 consumes: Vec<ConsumerRole>,
450 #[serde(default)]
451 bindings: Option<Bindings>,
452 #[serde(default)]
453 capabilities: Option<CapabilityDeclarations>,
454 #[serde(default)]
455 events: Option<Value>,
456 #[serde(default)]
457 self_signals: Option<Vec<SelfSignalDeclaration>>,
458 #[serde(default)]
459 provenance: Option<ManifestProvenance>,
460 #[serde(default)]
461 operation_delivery: Option<Value>,
462 #[serde(default)]
463 operation_payload: BTreeMap<String, OperationPayload>,
464 #[serde(default)]
466 flow_operations: Option<Value>,
467 #[serde(default)]
469 confirm_operations: Option<Value>,
470 #[serde(default)]
471 rich_ui: Option<RichUiDescriptor>,
472 #[serde(default)]
476 runtime_computed: Option<Value>,
477 #[serde(default)]
478 role_declarations: Option<Value>,
479}
480
481impl<'de> Deserialize<'de> for ModuleManifest {
482 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
483 where
484 D: Deserializer<'de>,
485 {
486 let wire = ModuleManifestWire::deserialize(deserializer)?;
487 validate_runtime_computed(wire.runtime_computed.as_ref(), "runtime_computed")
488 .map_err(D::Error::custom)?;
489 validate_events_value(wire.events.as_ref()).map_err(D::Error::custom)?;
490 let events = wire
491 .events
492 .map(serde_json::from_value)
493 .transpose()
494 .map_err(D::Error::custom)?;
495 let mut builder = Self::builder(wire.module_id, wire.module_version)
496 .display_name(wire.display_name)
497 .map_err(D::Error::custom)?
498 .protocol_ver(wire.protocol_ver)
499 .trust_tier(wire.trust_tier);
500 if let Some(ready) = wire.ready {
501 builder = builder.ready(ready);
502 }
503 let mut manifest = builder
504 .provides(wire.provides)
505 .consumes(wire.consumes)
506 .bindings(wire.bindings)
507 .capabilities(wire.capabilities)
508 .events(events)
509 .self_signals(wire.self_signals)
510 .provenance(wire.provenance)
511 .operation_delivery(
512 wire.operation_delivery
513 .and_then(|value| serde_json::from_value(value).ok())
514 .unwrap_or_default(),
515 )
516 .rich_ui(wire.rich_ui)
517 .role_declarations(
518 wire.role_declarations
519 .filter(|value| validate_role_declarations_value(Some(value)).is_ok())
520 .and_then(|value| serde_json::from_value(value).ok())
521 .unwrap_or_default(),
522 )
523 .operation_payload(wire.operation_payload)
524 .build();
525 manifest
526 .validate_operation_payload()
527 .map_err(D::Error::custom)?;
528 manifest.flow_operations = wire
531 .flow_operations
532 .and_then(|value| decode_flow_operations(&manifest, &value).ok());
533 manifest.confirm_operations = wire
534 .confirm_operations
535 .and_then(|value| decode_confirm_operations(&manifest, &value).ok());
536 manifest
537 .validate_capability_grammar()
538 .map_err(D::Error::custom)?;
539 if let Some(rich_ui) = &manifest.rich_ui {
540 rich_ui.validate().map_err(D::Error::custom)?;
541 }
542 Ok(manifest)
543 }
544}
545
546#[derive(Debug, Clone, PartialEq, Eq)]
548pub struct RoleDeclarationsError(&'static str);
549
550impl fmt::Display for RoleDeclarationsError {
551 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
552 f.write_str(self.0)
553 }
554}
555
556impl std::error::Error for RoleDeclarationsError {}
557
558pub fn validate_hello_role_declarations(hello: &Value) -> Result<(), RoleDeclarationsError> {
560 validate_role_declarations_value(
561 hello
562 .get("manifest")
563 .and_then(|manifest| manifest.get("role_declarations")),
564 )
565}
566
567fn validate_role_declarations_value(value: Option<&Value>) -> Result<(), RoleDeclarationsError> {
568 let Some(value) = value else {
569 return Ok(());
570 };
571 let map = value
572 .as_object()
573 .ok_or(RoleDeclarationsError("role_declarations must be an object"))?;
574 for (role, declaration) in map {
575 if !is_valid_capability_identifier(role) {
576 return Err(RoleDeclarationsError(
577 "role_declarations key must use capability-name grammar",
578 ));
579 }
580 if !declaration.is_object() {
581 return Err(RoleDeclarationsError(
582 "role_declarations values must be objects",
583 ));
584 }
585 }
586 let bytes = serde_json::to_vec(value)
587 .map_err(|_| RoleDeclarationsError("role_declarations could not be serialized"))?;
588 if bytes.len() > MAX_ROLE_DECLARATIONS_BYTES {
589 return Err(RoleDeclarationsError(
590 "role_declarations exceeds 16384 compact JSON bytes",
591 ));
592 }
593 Ok(())
594}
595
596#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
602#[non_exhaustive]
603pub struct RichUiDescriptor {
604 pub schema: String,
606 pub manifest_digest: String,
608 pub bytes: u64,
610 pub chunks: u32,
612}
613
614impl RichUiDescriptor {
615 pub fn new(
617 schema: impl Into<String>,
618 manifest_digest: impl Into<String>,
619 bytes: u64,
620 chunks: u32,
621 ) -> Self {
622 Self {
623 schema: schema.into(),
624 manifest_digest: manifest_digest.into(),
625 bytes,
626 chunks,
627 }
628 }
629
630 pub fn validate(&self) -> Result<(), RichUiDescriptorError> {
632 validate_rich_ui_fields(
633 &self.schema,
634 &self.manifest_digest,
635 self.bytes,
636 u64::from(self.chunks),
637 )
638 }
639}
640
641#[derive(Debug, Clone, PartialEq, Eq)]
643pub struct DisplayNameError(&'static str);
644
645impl fmt::Display for DisplayNameError {
646 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
647 write!(f, "invalid manifest display_name: {}", self.0)
648 }
649}
650
651impl std::error::Error for DisplayNameError {}
652
653pub fn validate_display_name(value: &str) -> Result<(), DisplayNameError> {
658 if value.trim() != value || !(1..=40).contains(&value.chars().count()) {
659 return Err(DisplayNameError(
660 "must be trimmed text of 1 to 40 characters",
661 ));
662 }
663 if value.chars().any(|ch| {
664 ch.is_control()
665 || matches!(ch, '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')
666 }) {
667 return Err(DisplayNameError("must not contain control or bidi formatting characters"));
668 }
669 Ok(())
670}
671
672pub fn validate_hello_display_name(hello: &Value) -> Result<(), DisplayNameError> {
674 match hello
675 .get("manifest")
676 .and_then(|manifest| manifest.get("display_name"))
677 {
678 None | Some(Value::Null) => Ok(()),
679 Some(Value::String(value)) => validate_display_name(value),
680 Some(_) => Err(DisplayNameError("must be a string")),
681 }
682}
683
684#[derive(Debug, Clone, PartialEq, Eq)]
686#[non_exhaustive]
687pub struct RichUiDescriptorError {
688 field: String,
689 reason: &'static str,
690}
691
692impl RichUiDescriptorError {
693 fn new(field: impl Into<String>, reason: &'static str) -> Self {
694 Self {
695 field: field.into(),
696 reason,
697 }
698 }
699
700 pub fn field(&self) -> &str {
702 &self.field
703 }
704}
705
706impl fmt::Display for RichUiDescriptorError {
707 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
708 write!(
709 f,
710 "invalid rich_ui descriptor: field {} {}",
711 self.field, self.reason
712 )
713 }
714}
715
716impl std::error::Error for RichUiDescriptorError {}
717
718pub fn validate_hello_rich_ui_descriptor(hello: &Value) -> Result<(), RichUiDescriptorError> {
720 let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
721 return Ok(());
722 };
723 let Some(value) = manifest.get("rich_ui") else {
724 return Ok(());
725 };
726 validate_rich_ui_descriptor_value(value)
727}
728
729fn validate_rich_ui_descriptor_value(value: &Value) -> Result<(), RichUiDescriptorError> {
730 let descriptor = value
731 .as_object()
732 .ok_or_else(|| RichUiDescriptorError::new("rich_ui", "must be an object"))?;
733 let schema = descriptor
734 .get("schema")
735 .and_then(Value::as_str)
736 .ok_or_else(|| RichUiDescriptorError::new("rich_ui.schema", "must be a string"))?;
737 let digest = descriptor
738 .get("manifest_digest")
739 .and_then(Value::as_str)
740 .ok_or_else(|| RichUiDescriptorError::new("rich_ui.manifest_digest", "must be a string"))?;
741 let bytes = descriptor
742 .get("bytes")
743 .and_then(Value::as_u64)
744 .ok_or_else(|| {
745 RichUiDescriptorError::new("rich_ui.bytes", "must be an integer from 1 to 16777216")
746 })?;
747 let chunks = descriptor
748 .get("chunks")
749 .and_then(Value::as_u64)
750 .ok_or_else(|| {
751 RichUiDescriptorError::new("rich_ui.chunks", "must be an integer from 1 to 1024")
752 })?;
753 validate_rich_ui_fields(schema, digest, bytes, chunks)
754}
755
756fn validate_rich_ui_fields(
757 schema: &str,
758 digest: &str,
759 bytes: u64,
760 chunks: u64,
761) -> Result<(), RichUiDescriptorError> {
762 if !(1..=64).contains(&schema.len())
763 || !schema.bytes().all(|byte| {
764 byte.is_ascii_lowercase()
765 || byte.is_ascii_digit()
766 || matches!(byte, b'.' | b'_' | b'/' | b'-')
767 })
768 {
769 return Err(RichUiDescriptorError::new(
770 "rich_ui.schema",
771 "must be 1 to 64 bytes of [a-z0-9._/-]",
772 ));
773 }
774 if !digest.strip_prefix("sha256:").is_some_and(|hex| {
775 hex.len() == 64
776 && hex
777 .bytes()
778 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
779 }) {
780 return Err(RichUiDescriptorError::new(
781 "rich_ui.manifest_digest",
782 "must be sha256: followed by 64 lowercase hexadecimal characters",
783 ));
784 }
785 if !(1..=16_777_216).contains(&bytes) {
786 return Err(RichUiDescriptorError::new(
787 "rich_ui.bytes",
788 "must be an integer from 1 to 16777216",
789 ));
790 }
791 if !(1..=1_024).contains(&chunks) {
792 return Err(RichUiDescriptorError::new(
793 "rich_ui.chunks",
794 "must be an integer from 1 to 1024",
795 ));
796 }
797 Ok(())
798}
799
800pub const CAP_CATALOG_EVENTS_V1: &str = "catalog-events/v1";
806
807pub const CAP_SCOPE_BIND_PROOF_V1: &str = "scope-bind-proof/v1";
811
812pub const CAP_SCOPE_BIND_PROOF_V2: &str = "scope-bind-proof/v2";
816
817pub const CAP_SCOPE_REPLACE_IF_IDLE_V1: &str = "scope-replace-if-idle/v1";
819
820#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
822#[non_exhaustive]
823pub struct EventDeclaration {
824 pub name: String,
831 pub version: u32,
833 pub headers: Vec<String>,
838 #[serde(default, skip_serializing_if = "Option::is_none")]
840 pub summary: Option<String>,
841}
842
843impl EventDeclaration {
844 pub fn new(name: impl Into<String>, version: u32) -> Self {
847 Self {
848 name: name.into(),
849 version,
850 headers: Vec::new(),
851 summary: None,
852 }
853 }
854
855 pub fn with_headers(mut self, headers: Vec<String>) -> Self {
857 self.headers = headers;
858 self
859 }
860
861 pub fn with_summary(mut self, summary: Option<String>) -> Self {
863 self.summary = summary;
864 self
865 }
866}
867
868#[derive(Debug, Clone, PartialEq, Eq)]
870#[non_exhaustive]
871pub struct EventDeclarationError {
872 field: String,
873 reason: &'static str,
874}
875
876impl EventDeclarationError {
877 fn new(field: impl Into<String>, reason: &'static str) -> Self {
878 Self {
879 field: field.into(),
880 reason,
881 }
882 }
883
884 pub fn field(&self) -> &str {
886 &self.field
887 }
888}
889
890impl fmt::Display for EventDeclarationError {
891 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
892 write!(
893 f,
894 "invalid event declaration: field {} {}",
895 self.field, self.reason
896 )
897 }
898}
899
900impl std::error::Error for EventDeclarationError {}
901
902pub fn validate_hello_event_declarations(hello: &Value) -> Result<(), EventDeclarationError> {
904 validate_events_value(
905 hello
906 .get("manifest")
907 .and_then(|manifest| manifest.get("events")),
908 )
909}
910
911fn is_valid_event_name(name: &str) -> bool {
914 let level_count = name.split('.').count();
915 (1..=4).contains(&level_count)
916 && name.split('.').all(|level| {
917 if level.is_empty() {
918 return false;
919 }
920 let first = level.as_bytes()[0];
921 (1..=63).contains(&level.len())
922 && (first.is_ascii_lowercase() || first.is_ascii_digit())
923 && level
924 .bytes()
925 .skip(1)
926 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
927 && !level.strip_prefix('v').is_some_and(|digits| {
928 !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit())
929 })
930 })
931}
932
933fn validate_events_value(value: Option<&Value>) -> Result<(), EventDeclarationError> {
934 let Some(value) = value.filter(|value| !value.is_null()) else {
935 return Ok(());
936 };
937 let entries = value
938 .as_array()
939 .ok_or_else(|| EventDeclarationError::new("events", "must be a list"))?;
940 if entries.len() > 64 {
941 return Err(EventDeclarationError::new(
942 "events",
943 "must contain at most 64 declarations",
944 ));
945 }
946 let mut pairs = HashSet::new();
947 for (index, entry) in entries.iter().enumerate() {
948 let field = format!("events[{index}]");
949 let entry = entry
950 .as_object()
951 .ok_or_else(|| EventDeclarationError::new(&field, "must be an object"))?;
952 let name_field = format!("{field}.name");
953 let name = entry
954 .get("name")
955 .and_then(Value::as_str)
956 .ok_or_else(|| EventDeclarationError::new(&name_field, "must be a string"))?;
957 if !is_valid_event_name(name) {
958 return Err(EventDeclarationError::new(
959 name_field,
960 "must contain one to four valid dot-separated event-name levels",
961 ));
962 }
963 let version = entry
964 .get("version")
965 .and_then(Value::as_u64)
966 .filter(|version| (1..=u32::MAX as u64).contains(version))
967 .ok_or_else(|| {
968 EventDeclarationError::new(
969 format!("{field}.version"),
970 "must be an integer between 1 and u32::MAX",
971 )
972 })?;
973 if !pairs.insert((name, version)) {
974 return Err(EventDeclarationError::new(
975 &field,
976 "duplicates an event (name, version) pair",
977 ));
978 }
979 let headers_field = format!("{field}.headers");
980 let headers = entry
981 .get("headers")
982 .and_then(Value::as_array)
983 .ok_or_else(|| EventDeclarationError::new(&headers_field, "must be a list"))?;
984 if headers.len() > 16 {
985 return Err(EventDeclarationError::new(
986 headers_field,
987 "must contain at most 16 headers",
988 ));
989 }
990 let mut names = HashSet::new();
991 for (header_index, header) in headers.iter().enumerate() {
992 let header_field = format!("{headers_field}[{header_index}]");
993 let header = header
994 .as_str()
995 .ok_or_else(|| EventDeclarationError::new(&header_field, "must be a string"))?;
996 if !(1..=32).contains(&header.len())
997 || !header.as_bytes()[0].is_ascii_lowercase()
998 || !header
999 .bytes()
1000 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
1001 {
1002 return Err(EventDeclarationError::new(
1003 header_field,
1004 "must match [a-z][a-z0-9_]{0,31}",
1005 ));
1006 }
1007 if !names.insert(header) {
1008 return Err(EventDeclarationError::new(
1009 header_field,
1010 "duplicates a header name",
1011 ));
1012 }
1013 }
1014 if let Some(summary) = entry.get("summary").filter(|value| !value.is_null()) {
1015 let summary_field = format!("{field}.summary");
1016 let summary = summary
1017 .as_str()
1018 .ok_or_else(|| EventDeclarationError::new(&summary_field, "must be a string"))?;
1019 if summary.chars().count() > 200 || summary.chars().any(char::is_control) {
1020 return Err(EventDeclarationError::new(
1021 summary_field,
1022 "must contain at most 200 characters and no control characters",
1023 ));
1024 }
1025 }
1026 }
1027 Ok(())
1028}
1029
1030#[derive(Debug, Clone, PartialEq, Eq)]
1032pub struct SelfSignalDeclarationError {
1033 module_id: String,
1034 entry_index: usize,
1035 field: &'static str,
1036}
1037
1038impl fmt::Display for SelfSignalDeclarationError {
1039 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1040 write!(
1041 f,
1042 "module_id '{}' self_signals[{}] is missing required field '{}'",
1043 self.module_id.escape_debug(),
1044 self.entry_index,
1045 self.field
1046 )
1047 }
1048}
1049
1050pub fn validate_hello_self_signal_declarations(
1057 hello: &Value,
1058) -> Result<(), SelfSignalDeclarationError> {
1059 let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
1060 return Ok(());
1061 };
1062 let module_id = manifest
1063 .get("module_id")
1064 .and_then(Value::as_str)
1065 .unwrap_or("<unknown>");
1066 let Some(entries) = manifest.get("self_signals").and_then(Value::as_array) else {
1067 return Ok(());
1068 };
1069
1070 for (entry_index, entry) in entries.iter().enumerate() {
1071 let Some(entry) = entry.as_object() else {
1072 continue;
1073 };
1074 for field in ["effect", "anchored_to"] {
1075 if !entry.contains_key(field) {
1076 return Err(SelfSignalDeclarationError {
1077 module_id: module_id.to_string(),
1078 entry_index,
1079 field,
1080 });
1081 }
1082 }
1083 }
1084 Ok(())
1085}
1086
1087#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1089#[serde(deny_unknown_fields)]
1090pub struct CapabilityDeclarations {
1091 #[serde(default)]
1092 pub provides: Vec<String>,
1093 #[serde(default)]
1094 pub requires: Vec<CapabilityRequirement>,
1095 #[serde(default)]
1096 pub must_never_reach: Vec<String>,
1097}
1098
1099#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1101pub struct SelfSignalDeclaration {
1102 pub name: String,
1104 pub kind: SelfSignalKind,
1132 pub effect: SelfSignalEffect,
1134 pub anchored_to: SignalAnchor,
1136 #[serde(default, skip_serializing_if = "Option::is_none")]
1143 pub cadence: Option<SignalCadence>,
1144 #[serde(default, skip_serializing_if = "Option::is_none")]
1146 pub domain: Option<String>,
1147 #[serde(default, skip_serializing_if = "Option::is_none")]
1148 pub note: Option<String>,
1149}
1150
1151#[derive(Debug, Clone, PartialEq, Eq)]
1153pub enum SelfSignalKind {
1154 Keepalive,
1155 Busy,
1157 Poller,
1158 Cron,
1159 Sweep,
1160 Watchdog,
1161 Heartbeat,
1162 Other(String),
1163}
1164
1165impl SelfSignalKind {
1166 fn wire_name(&self) -> &str {
1167 match self {
1168 Self::Keepalive => "keepalive",
1169 Self::Busy => "busy",
1170 Self::Poller => "poller",
1171 Self::Cron => "cron",
1172 Self::Sweep => "sweep",
1173 Self::Watchdog => "watchdog",
1174 Self::Heartbeat => "heartbeat",
1175 Self::Other(value) => value,
1176 }
1177 }
1178}
1179
1180impl Serialize for SelfSignalKind {
1181 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1182 where
1183 S: serde::Serializer,
1184 {
1185 serializer.serialize_str(self.wire_name())
1186 }
1187}
1188
1189impl<'de> Deserialize<'de> for SelfSignalKind {
1190 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1191 where
1192 D: Deserializer<'de>,
1193 {
1194 let value = String::deserialize(deserializer)?;
1195 Ok(match value.as_str() {
1196 "keepalive" => Self::Keepalive,
1197 "busy" => Self::Busy,
1198 "poller" => Self::Poller,
1199 "cron" => Self::Cron,
1200 "sweep" => Self::Sweep,
1201 "watchdog" => Self::Watchdog,
1202 "heartbeat" => Self::Heartbeat,
1203 _ => Self::Other(value),
1204 })
1205 }
1206}
1207
1208#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1210#[serde(rename_all = "lowercase")]
1211pub enum SelfSignalEffect {
1212 Observe,
1213 Mutate,
1214}
1215
1216#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1218#[serde(rename_all = "snake_case")]
1219pub enum SignalAnchor {
1220 FixedInterval,
1223 Event { event: String },
1226 HealthGauges { gauges: Vec<String> },
1228}
1229
1230#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1232#[serde(rename_all = "snake_case")]
1233pub enum SignalCadence {
1234 Literal { interval_ms: u64 },
1235 Derived { source: String },
1236}
1237
1238#[derive(Serialize, Debug, Clone, Default, PartialEq, Eq)]
1315#[non_exhaustive]
1316pub struct ManifestProvenance {
1317 #[serde(default, skip_serializing_if = "Option::is_none")]
1318 pub build_git_sha: Option<String>,
1319 #[serde(default, skip_serializing_if = "Option::is_none")]
1323 pub build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1324 #[serde(default, skip_serializing_if = "Option::is_none")]
1325 pub build_lock_digest: Option<String>,
1326 #[serde(default, skip_serializing_if = "Option::is_none")]
1335 pub wire_crate_version: Option<String>,
1336 #[serde(default, skip_serializing_if = "Option::is_none")]
1337 pub store_schema_version: Option<String>,
1338 #[serde(default, skip_serializing_if = "Option::is_none")]
1344 pub launch_nonce_source: Option<LaunchNonceSource>,
1345}
1346
1347#[derive(Debug, Clone, PartialEq, Eq)]
1354#[non_exhaustive]
1355pub enum LaunchNonceSource {
1356 Fd,
1358 Pipe,
1360 Env,
1362 ForwardCompatibleUnknown(String),
1363}
1364
1365impl LaunchNonceSource {
1366 pub fn wire_name(&self) -> &str {
1368 match self {
1369 Self::Fd => "fd",
1370 Self::Pipe => "pipe",
1371 Self::Env => "env",
1372 Self::ForwardCompatibleUnknown(value) => value,
1373 }
1374 }
1375
1376 pub fn from_wire_name(value: &str) -> Self {
1378 match value {
1379 "fd" => Self::Fd,
1380 "pipe" => Self::Pipe,
1381 "env" => Self::Env,
1382 _ => Self::ForwardCompatibleUnknown(value.to_string()),
1383 }
1384 }
1385}
1386
1387impl Serialize for LaunchNonceSource {
1388 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1389 where
1390 S: serde::Serializer,
1391 {
1392 serializer.serialize_str(self.wire_name())
1393 }
1394}
1395
1396impl<'de> Deserialize<'de> for LaunchNonceSource {
1397 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1398 where
1399 D: serde::Deserializer<'de>,
1400 {
1401 let value = String::deserialize(deserializer)?;
1402 Ok(Self::from_wire_name(&value))
1403 }
1404}
1405
1406#[derive(Debug, Clone, PartialEq, Eq)]
1411pub enum BuildGitShaAbsenceReason {
1412 DeclinedDirty,
1413 NeverDerived,
1414 NoGitDir,
1415 ForwardCompatibleUnknown(String),
1416}
1417
1418impl BuildGitShaAbsenceReason {
1419 fn wire_name(&self) -> &str {
1420 match self {
1421 Self::DeclinedDirty => "declined_dirty",
1422 Self::NeverDerived => "never_derived",
1423 Self::NoGitDir => "no_git_dir",
1424 Self::ForwardCompatibleUnknown(value) => value,
1425 }
1426 }
1427}
1428
1429impl Serialize for BuildGitShaAbsenceReason {
1430 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1431 where
1432 S: serde::Serializer,
1433 {
1434 serializer.serialize_str(self.wire_name())
1435 }
1436}
1437
1438impl<'de> Deserialize<'de> for BuildGitShaAbsenceReason {
1439 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1440 where
1441 D: serde::Deserializer<'de>,
1442 {
1443 let value = String::deserialize(deserializer)?;
1444 Ok(match value.as_str() {
1445 "declined_dirty" => Self::DeclinedDirty,
1446 "never_derived" => Self::NeverDerived,
1447 "no_git_dir" => Self::NoGitDir,
1448 _ => Self::ForwardCompatibleUnknown(value),
1449 })
1450 }
1451}
1452
1453#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1455pub enum GitTreeState {
1456 Clean,
1457 Dirty,
1458}
1459
1460#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1465pub enum BuildGitShaSource<'a> {
1466 Git {
1467 revision: &'a str,
1468 tree_state: GitTreeState,
1469 },
1470 NeverDerived,
1471 NoGitDir,
1472}
1473
1474pub fn attestable_commit(revision: &str, tree_state: GitTreeState) -> Option<&str> {
1478 match tree_state {
1479 GitTreeState::Clean => Some(revision),
1480 GitTreeState::Dirty => None,
1481 }
1482}
1483
1484const MAX_PROVENANCE_VALUE_BYTES: usize = 128;
1485const BUILD_GIT_SHA_CANONICAL_FORM: &str = "exactly 40 lowercase hexadecimal characters";
1486const BUILD_LOCK_DIGEST_CANONICAL_FORM: &str = "exactly 64 lowercase hexadecimal characters";
1487
1488#[derive(Deserialize)]
1489struct ManifestProvenanceWire {
1490 #[serde(default)]
1491 build_git_sha: Option<String>,
1492 #[serde(default)]
1493 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1494 #[serde(default)]
1495 build_lock_digest: Option<String>,
1496 #[serde(default)]
1497 wire_crate_version: Option<String>,
1498 #[serde(default)]
1499 store_schema_version: Option<String>,
1500 #[serde(default)]
1501 launch_nonce_source: Option<LaunchNonceSource>,
1502}
1503
1504impl<'de> Deserialize<'de> for ManifestProvenance {
1505 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1506 where
1507 D: Deserializer<'de>,
1508 {
1509 let wire = ManifestProvenanceWire::deserialize(deserializer)?;
1510 let provenance = Self {
1511 build_git_sha: wire.build_git_sha,
1512 build_git_sha_absence_reason: wire.build_git_sha_absence_reason,
1513 build_lock_digest: wire.build_lock_digest,
1514 wire_crate_version: wire.wire_crate_version,
1515 store_schema_version: wire.store_schema_version,
1516 launch_nonce_source: wire.launch_nonce_source,
1517 };
1518 provenance.validate().map_err(D::Error::custom)?;
1519 Ok(provenance)
1520 }
1521}
1522
1523#[derive(Debug, Clone, PartialEq, Eq)]
1525pub struct ProvenanceFormError {
1526 field: &'static str,
1527 length: usize,
1528 canonical_form: &'static str,
1529}
1530
1531impl ProvenanceFormError {
1532 fn new(field: &'static str, length: usize, canonical_form: &'static str) -> Self {
1533 Self {
1534 field,
1535 length,
1536 canonical_form,
1537 }
1538 }
1539
1540 pub fn field(&self) -> &str {
1542 self.field
1543 }
1544
1545 pub fn length(&self) -> usize {
1547 self.length
1548 }
1549
1550 pub fn canonical_form(&self) -> &str {
1552 self.canonical_form
1553 }
1554}
1555
1556impl fmt::Display for ProvenanceFormError {
1557 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1558 write!(
1559 f,
1560 "invalid manifest provenance form: field {} has length {}; canonical form is {}",
1561 self.field, self.length, self.canonical_form
1562 )
1563 }
1564}
1565
1566impl std::error::Error for ProvenanceFormError {}
1567
1568#[derive(Debug, Clone, PartialEq, Eq)]
1569pub struct ManifestProvenanceError {
1570 field: String,
1571 value: String,
1572 reason: &'static str,
1573}
1574
1575impl ManifestProvenanceError {
1576 fn new(field: &str, value: &str, reason: &'static str) -> Self {
1577 Self {
1578 field: field.to_string(),
1579 value: safe_error_value(value),
1580 reason,
1581 }
1582 }
1583
1584 pub fn field(&self) -> &str {
1585 &self.field
1586 }
1587}
1588
1589impl fmt::Display for ManifestProvenanceError {
1590 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1591 write!(
1592 f,
1593 "invalid manifest provenance: field {} has {} (value {:?})",
1594 self.field, self.reason, self.value
1595 )
1596 }
1597}
1598
1599impl std::error::Error for ManifestProvenanceError {}
1600
1601impl ManifestProvenance {
1602 pub fn new() -> Self {
1604 Self::default()
1605 }
1606
1607 pub fn with_build_git_sha(mut self, value: Option<String>) -> Self {
1608 self.build_git_sha = value;
1609 self
1610 }
1611
1612 pub fn with_build_git_sha_absence_reason(
1613 mut self,
1614 value: Option<BuildGitShaAbsenceReason>,
1615 ) -> Self {
1616 self.build_git_sha_absence_reason = value;
1617 self
1618 }
1619
1620 pub fn with_build_lock_digest(mut self, value: Option<String>) -> Self {
1621 self.build_lock_digest = value;
1622 self
1623 }
1624
1625 pub fn with_wire_crate_version(mut self, value: Option<String>) -> Self {
1626 self.wire_crate_version = value;
1627 self
1628 }
1629
1630 pub fn with_store_schema_version(mut self, value: Option<String>) -> Self {
1631 self.store_schema_version = value;
1632 self
1633 }
1634
1635 pub fn with_launch_nonce_source(mut self, value: Option<LaunchNonceSource>) -> Self {
1640 self.launch_nonce_source = value;
1641 self
1642 }
1643
1644 pub fn validate(&self) -> Result<(), ManifestProvenanceError> {
1645 if let (Some(_), Some(reason)) = (
1646 self.build_git_sha.as_ref(),
1647 self.build_git_sha_absence_reason.as_ref(),
1648 ) {
1649 return Err(ManifestProvenanceError::new(
1650 "build_git_sha_absence_reason",
1651 reason.wire_name(),
1652 "must be omitted when build_git_sha is present",
1653 ));
1654 }
1655 for (field, value) in [
1656 ("build_git_sha", self.build_git_sha.as_deref()),
1657 (
1658 "build_git_sha_absence_reason",
1659 self.build_git_sha_absence_reason
1660 .as_ref()
1661 .map(|reason| reason.wire_name()),
1662 ),
1663 ("build_lock_digest", self.build_lock_digest.as_deref()),
1664 ("wire_crate_version", self.wire_crate_version.as_deref()),
1665 ("store_schema_version", self.store_schema_version.as_deref()),
1666 (
1667 "launch_nonce_source",
1668 self.launch_nonce_source
1669 .as_ref()
1670 .map(|source| source.wire_name()),
1671 ),
1672 ] {
1673 let Some(value) = value else { continue };
1674 if value.is_empty() {
1675 return Err(ManifestProvenanceError::new(
1676 field,
1677 value,
1678 "must not be empty",
1679 ));
1680 }
1681 if value.len() > MAX_PROVENANCE_VALUE_BYTES {
1686 return Err(ManifestProvenanceError::new(
1687 field,
1688 value,
1689 "exceeds the 128-byte maximum",
1690 ));
1691 }
1692 if value.bytes().any(|byte| !(0x20..=0x7e).contains(&byte)) {
1693 return Err(ManifestProvenanceError::new(
1694 field,
1695 value,
1696 "contains non-printable ASCII",
1697 ));
1698 }
1699 }
1700 Ok(())
1701 }
1702}
1703
1704pub fn build_provenance(
1722 build_git_sha: Option<&str>,
1723 build_lock_digest: Option<&str>,
1724 store_schema_version: Option<&str>,
1725) -> Result<ManifestProvenance, ProvenanceFormError> {
1726 let build_git_sha = normalize_and_validate_build_git_sha(build_git_sha)?;
1727 build_provenance_with_build_git_sha(
1728 build_git_sha,
1729 None,
1730 build_lock_digest,
1731 store_schema_version,
1732 )
1733}
1734
1735pub fn build_provenance_from_source(
1751 build_git_sha_source: BuildGitShaSource<'_>,
1752 build_lock_digest: Option<&str>,
1753 store_schema_version: Option<&str>,
1754) -> Result<ManifestProvenance, ProvenanceFormError> {
1755 let (raw_build_git_sha, mut build_git_sha_absence_reason) = match build_git_sha_source {
1756 BuildGitShaSource::Git {
1757 revision,
1758 tree_state,
1759 } => match attestable_commit(revision, tree_state) {
1760 Some(revision) => (Some(revision), None),
1761 None => (None, Some(BuildGitShaAbsenceReason::DeclinedDirty)),
1762 },
1763 BuildGitShaSource::NeverDerived => (None, Some(BuildGitShaAbsenceReason::NeverDerived)),
1764 BuildGitShaSource::NoGitDir => (None, Some(BuildGitShaAbsenceReason::NoGitDir)),
1765 };
1766 let build_git_sha = normalize_and_validate_build_git_sha(raw_build_git_sha)?;
1767 if build_git_sha.is_none() {
1768 build_git_sha_absence_reason.get_or_insert(BuildGitShaAbsenceReason::NeverDerived);
1769 }
1770 build_provenance_with_build_git_sha(
1771 build_git_sha,
1772 build_git_sha_absence_reason,
1773 build_lock_digest,
1774 store_schema_version,
1775 )
1776}
1777
1778fn normalize_and_validate_build_git_sha(
1779 build_git_sha: Option<&str>,
1780) -> Result<Option<String>, ProvenanceFormError> {
1781 let build_git_sha = normalize_provenance_fact(build_git_sha);
1782 validate_provenance_form(
1783 "build_git_sha",
1784 build_git_sha.as_deref(),
1785 BUILD_GIT_SHA_CANONICAL_FORM,
1786 40,
1787 )?;
1788 Ok(build_git_sha)
1789}
1790
1791fn build_provenance_with_build_git_sha(
1792 build_git_sha: Option<String>,
1793 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1794 build_lock_digest: Option<&str>,
1795 store_schema_version: Option<&str>,
1796) -> Result<ManifestProvenance, ProvenanceFormError> {
1797 let build_lock_digest = normalize_provenance_fact(build_lock_digest);
1798 validate_provenance_form(
1799 "build_lock_digest",
1800 build_lock_digest.as_deref(),
1801 BUILD_LOCK_DIGEST_CANONICAL_FORM,
1802 64,
1803 )?;
1804
1805 Ok(ManifestProvenance {
1806 build_git_sha,
1807 build_git_sha_absence_reason,
1808 build_lock_digest,
1809 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
1810 store_schema_version: normalize_provenance_fact(store_schema_version),
1811 launch_nonce_source: None,
1812 })
1813}
1814
1815fn validate_provenance_form(
1816 field: &'static str,
1817 value: Option<&str>,
1818 canonical_form: &'static str,
1819 expected_length: usize,
1820) -> Result<(), ProvenanceFormError> {
1821 let Some(value) = value else { return Ok(()) };
1822 if value.len() != expected_length
1823 || !value
1824 .bytes()
1825 .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
1826 {
1827 return Err(ProvenanceFormError::new(field, value.len(), canonical_form));
1828 }
1829 Ok(())
1830}
1831
1832pub const PROVENANCE_SENTINELS: [&str; 3] = ["unknown", "unavailable", "none"];
1840
1841fn normalize_provenance_fact(value: Option<&str>) -> Option<String> {
1842 let value = value?.trim();
1843 if value.is_empty() {
1844 return None;
1845 }
1846 let lowered = value.to_ascii_lowercase();
1847 if PROVENANCE_SENTINELS.contains(&lowered.as_str()) {
1848 return None;
1849 }
1850 Some(value.to_string())
1851}
1852
1853#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1855#[serde(deny_unknown_fields)]
1856pub struct CapabilityRequirement {
1857 pub capability: String,
1858 pub need: CapabilityNeed,
1859}
1860
1861#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1863#[serde(rename_all = "snake_case")]
1864pub enum CapabilityNeed {
1865 Required,
1866 Optional,
1867}
1868
1869#[derive(Debug, Clone, PartialEq, Eq)]
1871pub struct CapabilityGrammarError {
1872 field: String,
1873 value: String,
1874}
1875
1876impl CapabilityGrammarError {
1877 fn new(field: impl Into<String>, value: impl AsRef<str>) -> Self {
1878 Self {
1879 field: field.into(),
1880 value: safe_error_value(value.as_ref()),
1881 }
1882 }
1883
1884 pub fn field(&self) -> &str {
1886 &self.field
1887 }
1888
1889 pub fn value(&self) -> &str {
1891 &self.value
1892 }
1893}
1894
1895impl fmt::Display for CapabilityGrammarError {
1896 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1897 write!(
1898 f,
1899 "invalid capability grammar: field {} has offending value {:?}",
1900 self.field, self.value
1901 )
1902 }
1903}
1904
1905impl std::error::Error for CapabilityGrammarError {}
1906
1907impl ModuleManifest {
1908 pub fn validate_capability_grammar(&self) -> Result<(), CapabilityGrammarError> {
1910 let Some(capabilities) = &self.capabilities else {
1911 return Ok(());
1912 };
1913
1914 validate_capability_list("capabilities.provides", &capabilities.provides)?;
1915 validate_requires(&capabilities.requires)?;
1916 validate_capability_list(
1917 "capabilities.must_never_reach",
1918 &capabilities.must_never_reach,
1919 )
1920 }
1921}
1922
1923pub fn validate_manifest_capability_grammar(
1928 manifest: &Value,
1929) -> Result<(), CapabilityGrammarError> {
1930 let Some(object) = manifest.as_object() else {
1931 return Ok(());
1932 };
1933
1934 validate_capabilities_value(object.get("capabilities"))?;
1935 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
1936}
1937
1938pub fn validate_hello_capability_grammar(hello: &Value) -> Result<(), CapabilityGrammarError> {
1944 let Some(object) = hello.as_object() else {
1945 return Ok(());
1946 };
1947 if let Some(manifest) = object.get("manifest") {
1948 validate_manifest_capability_grammar(manifest)?;
1949 }
1950 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
1951}
1952
1953pub fn is_valid_capability_identifier(identifier: &str) -> bool {
1955 if identifier.chars().any(char::is_whitespace) {
1956 return false;
1957 }
1958 let Some((name, version)) = identifier.split_once("/v") else {
1959 return false;
1960 };
1961 if name.is_empty() || name.len() > 64 || version.is_empty() {
1962 return false;
1963 }
1964
1965 let name_bytes = name.as_bytes();
1966 if !name_bytes[0].is_ascii_lowercase()
1967 || (name.len() > 1
1968 && !name_bytes[name.len() - 1].is_ascii_lowercase()
1969 && !name_bytes[name.len() - 1].is_ascii_digit())
1970 || name_bytes.windows(2).any(|pair| pair == b"--")
1971 {
1972 return false;
1973 }
1974 if !name_bytes
1975 .iter()
1976 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-')
1977 {
1978 return false;
1979 }
1980
1981 if version.len() > 1 && version.starts_with('0')
1982 || !version.bytes().all(|byte| byte.is_ascii_digit())
1983 {
1984 return false;
1985 }
1986 matches!(
1987 version.parse::<u64>(),
1988 Ok(value) if (1..=u64::from(u32::MAX)).contains(&value)
1989 )
1990}
1991
1992fn validate_capabilities_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
1993 let Some(value) = value else {
1994 return Ok(());
1995 };
1996 let Some(object) = value.as_object() else {
1997 return Err(CapabilityGrammarError::new(
1998 "capabilities",
1999 value_description(value),
2000 ));
2001 };
2002
2003 for (key, value) in object {
2004 if !matches!(key.as_str(), "provides" | "requires" | "must_never_reach") {
2005 return Err(CapabilityGrammarError::new(
2006 field_child("capabilities", key),
2007 value_description(value),
2008 ));
2009 }
2010 }
2011
2012 validate_capability_list_value("capabilities.provides", object.get("provides"))?;
2013 validate_requires_value(object.get("requires"))?;
2014 validate_capability_list_value(
2015 "capabilities.must_never_reach",
2016 object.get("must_never_reach"),
2017 )
2018}
2019
2020fn validate_capability_list_value(
2021 field: &str,
2022 value: Option<&Value>,
2023) -> Result<(), CapabilityGrammarError> {
2024 let Some(value) = value else {
2025 return Ok(());
2026 };
2027 let Some(values) = value.as_array() else {
2028 return Err(CapabilityGrammarError::new(field, value_description(value)));
2029 };
2030
2031 let mut seen = HashSet::new();
2032 for (index, value) in values.iter().enumerate() {
2033 let field = format!("{field}[{index}]");
2034 let Some(identifier) = value.as_str() else {
2035 return Err(CapabilityGrammarError::new(field, value_description(value)));
2036 };
2037 validate_capability_identifier(&field, identifier)?;
2038 if !seen.insert(identifier) {
2039 return Err(CapabilityGrammarError::new(field, identifier));
2040 }
2041 }
2042 Ok(())
2043}
2044
2045fn validate_requires_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
2046 let Some(value) = value else {
2047 return Ok(());
2048 };
2049 let Some(values) = value.as_array() else {
2050 return Err(CapabilityGrammarError::new(
2051 "capabilities.requires",
2052 value_description(value),
2053 ));
2054 };
2055
2056 let mut seen = HashSet::new();
2057 for (index, value) in values.iter().enumerate() {
2058 let entry_field = format!("capabilities.requires[{index}]");
2059 let Some(object) = value.as_object() else {
2060 return Err(CapabilityGrammarError::new(
2061 entry_field,
2062 value_description(value),
2063 ));
2064 };
2065 for (key, value) in object {
2066 if !matches!(key.as_str(), "capability" | "need") {
2067 return Err(CapabilityGrammarError::new(
2068 field_child(&entry_field, key),
2069 value_description(value),
2070 ));
2071 }
2072 }
2073 let capability_field = format!("{entry_field}.capability");
2074 let Some(capability) = object.get("capability").and_then(Value::as_str) else {
2075 return Err(CapabilityGrammarError::new(
2076 capability_field,
2077 object
2078 .get("capability")
2079 .map_or("<missing>".to_string(), value_description),
2080 ));
2081 };
2082 validate_capability_identifier(&capability_field, capability)?;
2083
2084 let need_field = format!("{entry_field}.need");
2085 let Some(need) = object.get("need").and_then(Value::as_str) else {
2086 return Err(CapabilityGrammarError::new(
2087 need_field,
2088 object
2089 .get("need")
2090 .map_or("<missing>".to_string(), value_description),
2091 ));
2092 };
2093 if !matches!(need, "required" | "optional") {
2094 return Err(CapabilityGrammarError::new(need_field, need));
2095 }
2096 if !seen.insert(capability) {
2097 return Err(CapabilityGrammarError::new(entry_field, capability));
2098 }
2099 }
2100 Ok(())
2101}
2102
2103fn validate_capability_list(field: &str, values: &[String]) -> Result<(), CapabilityGrammarError> {
2104 let mut seen = HashSet::new();
2105 for (index, identifier) in values.iter().enumerate() {
2106 let field = format!("{field}[{index}]");
2107 validate_capability_identifier(&field, identifier)?;
2108 if !seen.insert(identifier) {
2109 return Err(CapabilityGrammarError::new(field, identifier));
2110 }
2111 }
2112 Ok(())
2113}
2114
2115fn validate_requires(values: &[CapabilityRequirement]) -> Result<(), CapabilityGrammarError> {
2116 let mut seen = HashSet::new();
2117 for (index, requirement) in values.iter().enumerate() {
2118 let field = format!("capabilities.requires[{index}].capability");
2119 validate_capability_identifier(&field, &requirement.capability)?;
2120 if !seen.insert(&requirement.capability) {
2121 return Err(CapabilityGrammarError::new(
2122 format!("capabilities.requires[{index}]"),
2123 &requirement.capability,
2124 ));
2125 }
2126 }
2127 Ok(())
2128}
2129
2130fn validate_capability_identifier(
2131 field: &str,
2132 identifier: &str,
2133) -> Result<(), CapabilityGrammarError> {
2134 if is_valid_capability_identifier(identifier) {
2135 Ok(())
2136 } else {
2137 Err(CapabilityGrammarError::new(field, identifier))
2138 }
2139}
2140
2141fn validate_runtime_computed(
2142 value: Option<&Value>,
2143 field: &str,
2144) -> Result<(), CapabilityGrammarError> {
2145 let Some(value) = value else {
2146 return Ok(());
2147 };
2148 let Some(pointers) = value.as_array() else {
2149 return Err(CapabilityGrammarError::new(field, value_description(value)));
2150 };
2151
2152 for (index, pointer) in pointers.iter().enumerate() {
2153 let field = format!("{field}[{index}]");
2154 let Some(pointer) = pointer.as_str() else {
2155 return Err(CapabilityGrammarError::new(
2156 field,
2157 value_description(pointer),
2158 ));
2159 };
2160 let Some(tokens) = parse_json_pointer(pointer) else {
2161 return Err(CapabilityGrammarError::new(field, pointer));
2162 };
2163 if tokens.first().is_some_and(|token| token == "capabilities") {
2164 return Err(CapabilityGrammarError::new(field, pointer));
2165 }
2166 }
2167 Ok(())
2168}
2169
2170fn parse_json_pointer(pointer: &str) -> Option<Vec<String>> {
2171 if pointer.is_empty() {
2172 return Some(Vec::new());
2173 }
2174 let raw_tokens = pointer.strip_prefix('/')?;
2175 raw_tokens
2176 .split('/')
2177 .map(unescape_json_pointer_token)
2178 .collect()
2179}
2180
2181fn unescape_json_pointer_token(token: &str) -> Option<String> {
2182 let mut output = String::with_capacity(token.len());
2183 let mut characters = token.chars();
2184 while let Some(character) = characters.next() {
2185 if character != '~' {
2186 output.push(character);
2187 continue;
2188 }
2189 match characters.next()? {
2190 '0' => output.push('~'),
2191 '1' => output.push('/'),
2192 _ => return None,
2193 }
2194 }
2195 Some(output)
2196}
2197
2198fn field_child(parent: &str, child: &str) -> String {
2199 let child = safe_error_value(child);
2200 format!("{parent}.{child}")
2201}
2202
2203fn value_description(value: &Value) -> String {
2204 match value {
2205 Value::String(value) => safe_error_value(value),
2206 Value::Null => "null".to_string(),
2207 Value::Bool(value) => value.to_string(),
2208 Value::Number(value) => value.to_string(),
2209 Value::Array(_) => "<array>".to_string(),
2210 Value::Object(_) => "<object>".to_string(),
2211 }
2212}
2213
2214fn safe_error_value(value: &str) -> String {
2215 let lower = value.to_ascii_lowercase();
2216 if ["secret", "password", "api_key"]
2217 .iter()
2218 .any(|marker| lower.contains(marker))
2219 || lower.starts_with("sk-")
2220 || lower.starts_with("akia")
2221 || lower.starts_with("bearer ")
2222 || lower.starts_with("token=")
2223 || lower.starts_with("credential=")
2224 {
2225 "<redacted>".to_string()
2226 } else {
2227 value.to_string()
2228 }
2229}
2230
2231#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2237#[serde(rename_all = "snake_case")]
2238pub enum TrustTier {
2239 FirstParty,
2240 Reviewed,
2241 Untrusted,
2242}
2243
2244#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2248#[serde(tag = "role", rename_all = "snake_case")]
2249pub enum ProviderRole {
2250 ToolProvider {
2251 tools: Vec<Tool>,
2252 identity_scope: Vec<IdentityScope>,
2260 concurrency: Concurrency,
2261 emits_push: bool,
2262 sub_supervises: bool,
2263 },
2264 PipelineStage {
2265 stage: PipelineStageKind,
2266 applies_to: PipelineAppliesTo,
2267 interface: String,
2268 declares_frozen_floor: bool,
2269 needs_signals: Vec<String>,
2270 conformance_class: String,
2271 },
2272 ManagementSurface {
2273 operations: Vec<ManagementOperation>,
2274 config_schema: Value,
2275 observability: Vec<ObservabilitySurface>,
2276 identity_scope: Vec<IdentityScope>,
2280 #[serde(default)]
2281 concurrency: Concurrency,
2282 },
2283 InternalService {
2284 service_id: String,
2285 transport: InternalTransport,
2286 agent_facing: bool,
2287 operations: Vec<String>,
2288 },
2289}
2290
2291#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2304#[serde(rename_all = "snake_case")]
2305pub enum ExecutionMode {
2306 Pure,
2307 Mutating,
2308 Unfenceable,
2309}
2310
2311#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2313pub struct Tool {
2314 pub name: String,
2315 #[serde(default, skip_serializing_if = "Option::is_none")]
2316 pub description: Option<String>,
2317 pub execution_mode: ExecutionMode,
2322 pub schema: Value,
2323}
2324
2325#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2331#[serde(rename_all = "snake_case")]
2332pub enum Concurrency {
2333 Serial,
2335 ModuleManaged,
2338 StatelessParallel,
2341}
2342
2343#[allow(clippy::derivable_impls)]
2344impl Default for Concurrency {
2355 fn default() -> Self {
2356 Self::ModuleManaged
2357 }
2358}
2359
2360#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2367#[serde(rename_all = "snake_case")]
2368pub enum IdentityScope {
2369 Session,
2370 Project,
2371}
2372
2373#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2375#[serde(rename_all = "snake_case")]
2376pub enum PipelineStageKind {
2377 Transform,
2378 Codec,
2379 Auth,
2380}
2381
2382#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2384pub struct PipelineAppliesTo {
2385 pub provider: String,
2386 pub model: String,
2387}
2388
2389#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2392#[non_exhaustive]
2393pub struct OperationPayload {
2394 max_bytes: usize,
2395}
2396
2397impl OperationPayload {
2398 pub fn new(max_bytes: usize) -> Self {
2399 Self { max_bytes }
2400 }
2401
2402 pub fn max_bytes(&self) -> usize {
2403 self.max_bytes
2404 }
2405}
2406
2407#[derive(Debug, Clone, PartialEq, Eq)]
2409#[non_exhaustive]
2410pub enum OperationPayloadError {
2411 UnknownOperation { operation: String },
2412 WatchOperation { operation: String },
2413 InvalidMaxBytes { operation: String },
2414}
2415
2416impl fmt::Display for OperationPayloadError {
2417 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2418 write!(f, "{self:?}")
2419 }
2420}
2421
2422impl std::error::Error for OperationPayloadError {}
2423
2424impl ModuleManifest {
2425 pub fn validate_operation_payload(&self) -> Result<(), OperationPayloadError> {
2428 for (name, payload) in &self.operation_payload {
2429 if !self.provides.iter().any(|role| match role {
2430 ProviderRole::ManagementSurface { operations, .. } => {
2431 operations.iter().any(|op| op.name == *name)
2432 }
2433 _ => false,
2434 }) {
2435 return Err(OperationPayloadError::UnknownOperation {
2436 operation: name.clone(),
2437 });
2438 }
2439 if self
2440 .operation_delivery
2441 .get(name)
2442 .is_some_and(OperationDelivery::is_watch)
2443 {
2444 return Err(OperationPayloadError::WatchOperation {
2445 operation: name.clone(),
2446 });
2447 }
2448 if !(1..=crate::framed_body::MAX_DECLARED_PAYLOAD_BYTES).contains(&payload.max_bytes) {
2449 return Err(OperationPayloadError::InvalidMaxBytes {
2450 operation: name.clone(),
2451 });
2452 }
2453 }
2454 Ok(())
2455 }
2456}
2457
2458#[derive(Debug, Clone, PartialEq, Eq)]
2463#[non_exhaustive]
2464pub enum FlowOperationsError {
2465 FlowScopesNotDeclared,
2468 NotAList,
2470 TooMany { count: usize },
2472 DuplicateOperation { operation: String },
2474 UnknownOperation { operation: String },
2476}
2477
2478impl fmt::Display for FlowOperationsError {
2479 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2480 match self {
2481 Self::FlowScopesNotDeclared => write!(
2482 f,
2483 "flow_operations requires '{}' or '{}' in capabilities.provides",
2484 crate::scope::FLOW_SCOPES_CAPABILITY,
2485 crate::call_mode::CALL_MODES_CAPABILITY
2486 ),
2487 Self::NotAList => f.write_str("flow_operations must be an array of operation names"),
2488 Self::TooMany { count } => write!(
2489 f,
2490 "flow_operations lists {count} names, more than {MAX_FLOW_OPERATIONS}"
2491 ),
2492 Self::DuplicateOperation { operation } => {
2493 write!(f, "flow_operations names '{operation}' more than once")
2494 }
2495 Self::UnknownOperation { operation } => write!(
2496 f,
2497 "flow_operations names '{operation}', which is not a declared management operation"
2498 ),
2499 }
2500 }
2501}
2502
2503impl std::error::Error for FlowOperationsError {}
2504
2505impl ModuleManifest {
2506 pub fn validate_flow_operations(&self) -> Result<(), FlowOperationsError> {
2511 match &self.flow_operations {
2512 Some(operations) => check_flow_operations(self, operations),
2513 None => Ok(()),
2514 }
2515 }
2516}
2517
2518fn check_flow_operations(
2519 manifest: &ModuleManifest,
2520 operations: &[String],
2521) -> Result<(), FlowOperationsError> {
2522 let admits_flows = manifest.capabilities.as_ref().is_some_and(|capabilities| {
2523 capabilities.provides.iter().any(|capability| {
2524 capability == crate::scope::FLOW_SCOPES_CAPABILITY
2525 || capability == crate::call_mode::CALL_MODES_CAPABILITY
2526 })
2527 });
2528 if !admits_flows {
2529 return Err(FlowOperationsError::FlowScopesNotDeclared);
2530 }
2531 if operations.len() > MAX_FLOW_OPERATIONS {
2532 return Err(FlowOperationsError::TooMany {
2533 count: operations.len(),
2534 });
2535 }
2536 let mut seen = HashSet::new();
2537 for operation in operations {
2538 if !seen.insert(operation.as_str()) {
2539 return Err(FlowOperationsError::DuplicateOperation {
2540 operation: operation.clone(),
2541 });
2542 }
2543 let declared = manifest.provides.iter().any(|role| match role {
2544 ProviderRole::ManagementSurface { operations, .. } => {
2545 operations.iter().any(|op| op.name == *operation)
2546 }
2547 _ => false,
2548 });
2549 if !declared {
2550 return Err(FlowOperationsError::UnknownOperation {
2551 operation: operation.clone(),
2552 });
2553 }
2554 }
2555 Ok(())
2556}
2557
2558fn decode_flow_operations(
2561 manifest: &ModuleManifest,
2562 value: &Value,
2563) -> Result<Vec<String>, FlowOperationsError> {
2564 let operations: Vec<String> =
2565 serde_json::from_value(value.clone()).map_err(|_| FlowOperationsError::NotAList)?;
2566 check_flow_operations(manifest, &operations)?;
2567 Ok(operations)
2568}
2569
2570pub fn validate_hello_flow_operations(hello: &Value) -> Result<(), FlowOperationsError> {
2576 let Some(manifest_value) = hello.get("manifest") else {
2577 return Ok(());
2578 };
2579 let Some(value) = manifest_value
2580 .get("flow_operations")
2581 .filter(|value| !value.is_null())
2582 else {
2583 return Ok(());
2584 };
2585 let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
2586 return Ok(());
2587 };
2588 decode_flow_operations(&manifest, value).map(|_| ())
2589}
2590
2591#[derive(Debug, Clone, PartialEq, Eq)]
2596#[non_exhaustive]
2597pub enum ConfirmOperationsError {
2598 NotAList,
2600 TooMany { count: usize },
2602 DuplicateOperation { operation: String },
2604 UnknownOperation { operation: String },
2606}
2607
2608impl fmt::Display for ConfirmOperationsError {
2609 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2610 match self {
2611 Self::NotAList => {
2612 f.write_str("confirm_operations must be an array of operation names")
2613 }
2614 Self::TooMany { count } => write!(
2615 f,
2616 "confirm_operations lists {count} names, more than {MAX_CONFIRM_OPERATIONS}"
2617 ),
2618 Self::DuplicateOperation { operation } => {
2619 write!(f, "confirm_operations names '{operation}' more than once")
2620 }
2621 Self::UnknownOperation { operation } => write!(
2622 f,
2623 "confirm_operations names '{operation}', which is not a declared management operation"
2624 ),
2625 }
2626 }
2627}
2628
2629impl std::error::Error for ConfirmOperationsError {}
2630
2631impl ModuleManifest {
2632 pub fn validate_confirm_operations(&self) -> Result<(), ConfirmOperationsError> {
2636 match &self.confirm_operations {
2637 Some(operations) => check_confirm_operations(self, operations),
2638 None => Ok(()),
2639 }
2640 }
2641}
2642
2643fn check_confirm_operations(
2644 manifest: &ModuleManifest,
2645 operations: &[String],
2646) -> Result<(), ConfirmOperationsError> {
2647 if operations.len() > MAX_CONFIRM_OPERATIONS {
2648 return Err(ConfirmOperationsError::TooMany {
2649 count: operations.len(),
2650 });
2651 }
2652 let mut seen = HashSet::new();
2653 for operation in operations {
2654 if !seen.insert(operation.as_str()) {
2655 return Err(ConfirmOperationsError::DuplicateOperation {
2656 operation: operation.clone(),
2657 });
2658 }
2659 if !declares_management_operation(manifest, operation) {
2660 return Err(ConfirmOperationsError::UnknownOperation {
2661 operation: operation.clone(),
2662 });
2663 }
2664 }
2665 Ok(())
2666}
2667
2668fn declares_management_operation(manifest: &ModuleManifest, operation: &str) -> bool {
2669 manifest.provides.iter().any(|role| match role {
2670 ProviderRole::ManagementSurface { operations, .. } => {
2671 operations.iter().any(|op| op.name == operation)
2672 }
2673 _ => false,
2674 })
2675}
2676
2677fn decode_confirm_operations(
2680 manifest: &ModuleManifest,
2681 value: &Value,
2682) -> Result<Vec<String>, ConfirmOperationsError> {
2683 let operations: Vec<String> =
2684 serde_json::from_value(value.clone()).map_err(|_| ConfirmOperationsError::NotAList)?;
2685 check_confirm_operations(manifest, &operations)?;
2686 Ok(operations)
2687}
2688
2689pub fn validate_hello_confirm_operations(hello: &Value) -> Result<(), ConfirmOperationsError> {
2695 let Some(manifest_value) = hello.get("manifest") else {
2696 return Ok(());
2697 };
2698 let Some(value) = manifest_value
2699 .get("confirm_operations")
2700 .filter(|value| !value.is_null())
2701 else {
2702 return Ok(());
2703 };
2704 let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
2705 return Ok(());
2706 };
2707 decode_confirm_operations(&manifest, value).map(|_| ())
2708}
2709
2710#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2715pub struct ManagementOperation {
2716 pub name: String,
2717 pub kind: ManagementOperationKind,
2718 #[serde(default, skip_serializing_if = "Option::is_none")]
2719 pub description: Option<String>,
2720}
2721
2722#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2723#[serde(rename_all = "snake_case")]
2724pub enum ManagementOperationKind {
2725 Query,
2726 Mutate,
2727}
2728
2729#[derive(Debug, Clone, PartialEq, Eq)]
2732#[non_exhaustive]
2733pub enum OperationDelivery {
2734 Watch,
2735 Other(String),
2736}
2737
2738impl OperationDelivery {
2739 pub const WATCH: Self = Self::Watch;
2741
2742 pub fn wire_name(&self) -> &str {
2744 match self {
2745 Self::Watch => "watch",
2746 Self::Other(value) => value,
2747 }
2748 }
2749
2750 pub fn is_watch(&self) -> bool {
2752 self.wire_name() == "watch"
2753 }
2754}
2755
2756impl Serialize for OperationDelivery {
2757 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2758 where
2759 S: serde::Serializer,
2760 {
2761 serializer.serialize_str(self.wire_name())
2762 }
2763}
2764
2765impl<'de> Deserialize<'de> for OperationDelivery {
2766 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2767 where
2768 D: Deserializer<'de>,
2769 {
2770 let value = String::deserialize(deserializer)?;
2771 Ok(if value == "watch" {
2772 Self::WATCH
2773 } else {
2774 Self::Other(value)
2775 })
2776 }
2777}
2778
2779#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2781pub struct ObservabilitySurface {
2782 pub name: String,
2783 pub kind: ObservabilityKind,
2784}
2785
2786#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2787#[serde(rename_all = "snake_case")]
2788pub enum ObservabilityKind {
2789 Snapshot,
2790 Stream,
2791}
2792
2793#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2794#[serde(rename_all = "snake_case")]
2795pub enum InternalTransport {
2796 Bulk,
2797}
2798
2799#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2801#[serde(tag = "role", rename_all = "snake_case")]
2802pub enum ConsumerRole {
2803 ToolClient { of: Vec<String> },
2804 LlmClient { via: String, auth: String },
2805 ServiceClient { of: Vec<String> },
2806}
2807
2808#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2810pub struct Bindings {
2811 pub storage: StorageBinding,
2812 pub vault_grants: Vec<VaultGrant>,
2813 pub identity: IdentityBinding,
2814}
2815
2816#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2818pub struct StorageBinding {
2819 pub kind: StorageKind,
2820 pub scope: StorageScope,
2821 pub owns_schema: bool,
2822}
2823
2824#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2825#[serde(rename_all = "snake_case")]
2826pub enum StorageKind {
2827 Sqlite,
2828}
2829
2830#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2831#[serde(rename_all = "snake_case")]
2832pub enum StorageScope {
2833 Project,
2834}
2835
2836#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2837pub struct VaultGrant {
2838 pub secret: String,
2839 pub reason: String,
2840}
2841
2842#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2843pub struct IdentityBinding {
2844 pub requires: Vec<IdentityScope>,
2845 pub optional: Vec<IdentityScope>,
2846}
2847
2848#[cfg(test)]
2849mod tests {
2850 use super::*;
2851 use serde_json::json;
2852
2853 fn aft_manifest_fixture() -> ModuleManifest {
2854 ModuleManifest::builder("aft", "0.39.2")
2855 .trust_tier(Some(TrustTier::FirstParty))
2856 .bindings(Some(Bindings {
2857 storage: StorageBinding {
2858 kind: StorageKind::Sqlite,
2859 scope: StorageScope::Project,
2860 owns_schema: true,
2861 },
2862 vault_grants: vec![VaultGrant {
2863 secret: "provider_api_key".to_string(),
2864 reason: "cortexkit_native auth".to_string(),
2865 }],
2866 identity: IdentityBinding {
2867 requires: vec![IdentityScope::Project],
2868 optional: vec![IdentityScope::Session],
2869 },
2870 }))
2871 .protocol_ver(1)
2872 .provides(vec![ProviderRole::ToolProvider {
2873 tools: vec![
2874 Tool {
2875 name: "read".to_string(),
2876 description: None,
2877 execution_mode: ExecutionMode::Pure,
2878 schema: json!({"type": "object"}),
2879 },
2880 Tool {
2881 name: "grep".to_string(),
2882 description: None,
2883 execution_mode: ExecutionMode::Pure,
2884 schema: json!({"type": "object"}),
2885 },
2886 Tool {
2887 name: "outline".to_string(),
2888 description: None,
2889 execution_mode: ExecutionMode::Pure,
2890 schema: json!({"type": "object"}),
2891 },
2892 Tool {
2893 name: "semantic_search".to_string(),
2894 description: None,
2895 execution_mode: ExecutionMode::Pure,
2896 schema: json!({"type": "object"}),
2897 },
2898 Tool {
2899 name: "edit".to_string(),
2900 description: None,
2901 execution_mode: ExecutionMode::Mutating,
2902 schema: json!({"type": "object"}),
2903 },
2904 Tool {
2905 name: "write".to_string(),
2906 description: None,
2907 execution_mode: ExecutionMode::Mutating,
2908 schema: json!({"type": "object"}),
2909 },
2910 Tool {
2911 name: "bash".to_string(),
2912 description: None,
2913 execution_mode: ExecutionMode::Unfenceable,
2914 schema: json!({"type": "object"}),
2915 },
2916 ],
2917 identity_scope: vec![IdentityScope::Session, IdentityScope::Project],
2918 concurrency: Concurrency::ModuleManaged,
2919 emits_push: true,
2920 sub_supervises: true,
2921 }])
2922 .consumes(vec![ConsumerRole::ServiceClient {
2923 of: vec!["embedding.v2".to_string()],
2924 }])
2925 .build()
2926 }
2927
2928 #[test]
2929 fn serde_round_trips_representative_manifest() {
2930 let manifest = aft_manifest_fixture();
2931 let serialized = serde_json::to_string_pretty(&manifest).unwrap();
2932 let decoded: ModuleManifest = serde_json::from_str(&serialized).unwrap();
2933
2934 assert_eq!(manifest, decoded);
2935 }
2936
2937 #[test]
2938 fn builder_defaults_additions_to_honest_absence_and_round_trips() {
2939 let manifest = ModuleManifest::builder("builder-defaults", "2.0.0").build();
2940
2941 assert_eq!(manifest.module_id, "builder-defaults");
2942 assert_eq!(manifest.module_version, "2.0.0");
2943 assert_eq!(manifest.display_name, None);
2944 assert_eq!(manifest.protocol_ver, PROTOCOL_VERSION);
2945 assert_eq!(manifest.trust_tier, None);
2946 assert!(manifest.provides.is_empty());
2947 assert!(manifest.consumes.is_empty());
2948 assert_eq!(manifest.bindings, None);
2949 assert_eq!(manifest.capabilities, None);
2950 assert_eq!(manifest.self_signals, None);
2951 assert_eq!(manifest.provenance, None);
2952
2953 let encoded = serde_json::to_value(&manifest).expect("builder manifest serializes");
2954 for optional in [
2955 "display_name",
2956 "trust_tier",
2957 "consumes",
2958 "bindings",
2959 "capabilities",
2960 "self_signals",
2961 "provenance",
2962 ] {
2963 assert!(
2964 encoded.get(optional).is_none(),
2965 "an absent {optional} declaration must stay absent on the wire"
2966 );
2967 }
2968 let decoded: ModuleManifest =
2969 serde_json::from_value(encoded).expect("builder manifest round-trips");
2970 assert_eq!(decoded, manifest);
2971 }
2972
2973 #[test]
2974 fn fully_populated_builder_manifest_matches_the_literal_wire_golden() {
2975 let manifest = ModuleManifest::builder("full-builder", "2.0.0")
2976 .display_name(Some("Example".to_string()))
2977 .unwrap()
2978 .trust_tier(Some(TrustTier::Reviewed))
2979 .bindings(Some(Bindings {
2980 storage: StorageBinding {
2981 kind: StorageKind::Sqlite,
2982 scope: StorageScope::Project,
2983 owns_schema: false,
2984 },
2985 vault_grants: Vec::new(),
2986 identity: IdentityBinding {
2987 requires: vec![IdentityScope::Project],
2988 optional: Vec::new(),
2989 },
2990 }))
2991 .provides(vec![ProviderRole::ToolProvider {
2992 tools: vec![Tool {
2993 name: "read".to_string(),
2994 description: None,
2995 execution_mode: ExecutionMode::Pure,
2996 schema: json!({"type": "object"}),
2997 }],
2998 identity_scope: vec![IdentityScope::Project],
2999 concurrency: Concurrency::Serial,
3000 emits_push: false,
3001 sub_supervises: false,
3002 }])
3003 .consumes(vec![ConsumerRole::ServiceClient {
3004 of: vec!["embedding.v2".to_string()],
3005 }])
3006 .capabilities(Some(CapabilityDeclarations {
3007 provides: vec!["embedding/v2".to_string()],
3008 requires: Vec::new(),
3009 must_never_reach: Vec::new(),
3010 }))
3011 .self_signals(Some(vec![SelfSignalDeclaration {
3012 name: "usage_poller".to_string(),
3013 kind: SelfSignalKind::Poller,
3014 effect: SelfSignalEffect::Observe,
3015 anchored_to: SignalAnchor::FixedInterval,
3016 cadence: Some(SignalCadence::Literal {
3017 interval_ms: 60_000,
3018 }),
3019 domain: Some("provider-usage".to_string()),
3020 note: None,
3021 }]))
3022 .provenance(Some(ManifestProvenance {
3023 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
3024 build_git_sha_absence_reason: None,
3025 build_lock_digest: Some(
3026 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
3027 ),
3028 wire_crate_version: Some("0.16.0".to_string()),
3029 store_schema_version: Some("42".to_string()),
3030 launch_nonce_source: None,
3031 }))
3032 .build();
3033
3034 assert_eq!(
3035 serde_json::to_vec(&manifest).expect("builder manifest serializes"),
3036 include_bytes!("../tests/golden/module_manifest_builder_full.json"),
3037 "the builder must match the fully populated manifest wire bytes"
3038 );
3039 }
3040
3041 #[test]
3042 fn display_name_validator_enforces_scalar_bounds_and_safe_text() {
3043 for valid in [
3044 "Routing".to_string(),
3045 "名".repeat(40),
3046 "a".repeat(40),
3047 "e\u{301}".repeat(20),
3048 ] {
3049 assert!(validate_display_name(&valid).is_ok(), "{valid:?}");
3050 }
3051 let mut invalid = vec![
3052 "".to_string(),
3053 "a".repeat(41),
3054 "名".repeat(41),
3055 " Routing".to_string(),
3056 "Routing ".to_string(),
3057 "\u{2003}Routing".to_string(),
3058 "a\nb".to_string(),
3059 "a\u{0085}b".to_string(),
3060 "a\u{007f}b".to_string(),
3061 ];
3062 for code in [0x061c, 0x200e, 0x200f]
3063 .into_iter()
3064 .chain(0x202a..=0x202e)
3065 .chain(0x2066..=0x2069)
3066 {
3067 invalid.push(format!("a{}b", char::from_u32(code).unwrap()));
3068 }
3069 let accepted: Vec<_> = invalid
3070 .iter()
3071 .filter(|value| validate_display_name(value).is_ok())
3072 .collect();
3073 assert!(
3074 accepted.is_empty(),
3075 "invalid display names accepted: {accepted:?}"
3076 );
3077 }
3078
3079 #[test]
3080 fn display_name_builder_refuses_invalid_value() {
3081 let error = ModuleManifest::builder("provider", "1.0.0")
3082 .display_name(Some(" Routing".to_string()))
3083 .unwrap_err();
3084 assert!(error.to_string().contains("display_name"));
3085 }
3086
3087 #[test]
3088 fn display_name_manifest_round_trips_and_keeps_unknown_fields_lenient() {
3089 let manifest = ModuleManifest::builder("provider", "1.0.0")
3090 .display_name(Some("Routing".to_string()))
3091 .unwrap()
3092 .build();
3093 let mut wire = serde_json::to_value(&manifest).unwrap();
3094 assert_eq!(wire["display_name"], "Routing");
3095 wire["future_manifest_field"] = json!(true);
3096 assert_eq!(
3097 serde_json::from_value::<ModuleManifest>(wire.clone()).unwrap(),
3098 manifest
3099 );
3100 wire["display_name"] = json!("bad\nname");
3101 assert!(serde_json::from_value::<ModuleManifest>(wire)
3102 .unwrap_err()
3103 .to_string()
3104 .contains("display_name"));
3105 }
3106
3107 #[test]
3108 fn old_manifest_with_unread_fields_decodes_and_round_trips_verbatim() {
3109 let raw = include_bytes!("../tests/golden/module_manifest_builder_full.json");
3110 let decoded: ModuleManifest =
3111 serde_json::from_slice(raw).expect("old manifest with all unread fields decodes");
3112
3113 assert_eq!(decoded.trust_tier, Some(TrustTier::Reviewed));
3114 assert!(!decoded.consumes.is_empty());
3115 assert!(decoded.bindings.is_some());
3116
3117 let reencoded = serde_json::to_vec(&decoded).expect("re-encode succeeds");
3118 assert_eq!(
3119 reencoded, raw,
3120 "old manifest relay stays byte-for-byte verbatim"
3121 );
3122 }
3123
3124 #[test]
3125 fn new_manifest_omits_unread_fields_on_wire_and_decodes_cleanly() {
3126 let raw = include_bytes!("../tests/golden/module_manifest_diet.json");
3127 let decoded: ModuleManifest =
3128 serde_json::from_slice(raw).expect("new manifest omitting unread fields decodes");
3129
3130 assert_eq!(decoded.trust_tier, None);
3131 assert!(decoded.consumes.is_empty());
3132 assert_eq!(decoded.bindings, None);
3133
3134 let pretty = format!("{}\n", serde_json::to_string_pretty(&decoded).unwrap());
3135 assert_eq!(
3136 pretty.as_bytes(),
3137 raw,
3138 "new manifest matches golden byte-for-byte without unread keys"
3139 );
3140
3141 let as_val: serde_json::Value = serde_json::to_value(&decoded).unwrap();
3142 assert!(
3143 as_val.get("trust_tier").is_none(),
3144 "no trust_tier on wire for new manifest"
3145 );
3146 assert!(
3147 as_val.get("consumes").is_none(),
3148 "no consumes on wire for empty consumes"
3149 );
3150 assert!(
3151 as_val.get("bindings").is_none(),
3152 "no bindings on wire for new manifest"
3153 );
3154 }
3155
3156 #[test]
3157 fn aft_manifest_fixture_matches_v1_contract() {
3158 let manifest = aft_manifest_fixture();
3159
3160 assert_eq!(manifest.module_id, "aft");
3161 let ProviderRole::ToolProvider {
3162 tools,
3163 identity_scope,
3164 concurrency,
3165 emits_push,
3166 sub_supervises,
3167 } = &manifest.provides[0]
3168 else {
3169 panic!("AFT fixture must expose one tool_provider role");
3170 };
3171
3172 assert_eq!(*concurrency, Concurrency::ModuleManaged);
3173 assert!(*emits_push);
3174 assert!(*sub_supervises);
3175 assert_eq!(
3176 identity_scope,
3177 &vec![IdentityScope::Session, IdentityScope::Project]
3178 );
3179 assert_eq!(
3180 tools
3181 .iter()
3182 .map(|tool| (tool.name.as_str(), tool.execution_mode))
3183 .collect::<Vec<_>>(),
3184 vec![
3185 ("read", ExecutionMode::Pure),
3186 ("grep", ExecutionMode::Pure),
3187 ("outline", ExecutionMode::Pure),
3188 ("semantic_search", ExecutionMode::Pure),
3189 ("edit", ExecutionMode::Mutating),
3190 ("write", ExecutionMode::Mutating),
3191 ("bash", ExecutionMode::Unfenceable),
3192 ]
3193 );
3194 }
3195
3196 #[test]
3197 fn tool_provider_role_tag_serializes_as_snake_case() {
3198 let manifest = aft_manifest_fixture();
3199 let value = serde_json::to_value(&manifest).unwrap();
3200
3201 assert_eq!(value["provides"][0]["role"], "tool_provider");
3202 }
3203
3204 #[test]
3205 fn manifest_without_capabilities_preserves_the_existing_wire_shape() {
3206 let manifest = aft_manifest_fixture();
3207 let encoded = serde_json::to_value(&manifest).expect("manifest serializes");
3208 assert!(encoded.get("capabilities").is_none());
3209
3210 let decoded: ModuleManifest =
3211 serde_json::from_value(encoded).expect("legacy manifest parses");
3212 assert_eq!(decoded.capabilities, None);
3213 }
3214
3215 #[test]
3216 fn capability_identifier_lexical_grammar_accepts_only_pinned_forms() {
3217 for identifier in [
3218 "a/v1",
3219 "credentials-provider/v1",
3220 "a1-b2/v4294967295",
3221 "a123456789012345678901234567890123456789012345678901234567890123/v1",
3222 ] {
3223 assert!(
3224 is_valid_capability_identifier(identifier),
3225 "identifier must be accepted: {identifier}"
3226 );
3227 }
3228
3229 for identifier in [
3230 "credentials-Provider/v1",
3231 "credentials-provider/v01",
3232 "credentials-provider-/v1",
3233 "credentials--provider/v1",
3234 "Credentials-provider/v1",
3235 "credentials-provider/1",
3236 "credentials provider/v1",
3237 "credentials-provider/v0",
3238 "credentials-provider/v4294967296",
3239 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/v1",
3240 ] {
3241 assert!(
3242 !is_valid_capability_identifier(identifier),
3243 "identifier must be rejected: {identifier}"
3244 );
3245 }
3246 }
3247
3248 #[test]
3249 fn capability_grammar_errors_redact_secret_shaped_values() {
3250 let error = validate_manifest_capability_grammar(&json!({
3251 "capabilities": { "provides": ["sk-secret-value/v0"] }
3252 }))
3253 .expect_err("secret-shaped capability identifier is malformed");
3254 assert_eq!(error.field(), "capabilities.provides[0]");
3255 assert_eq!(error.value(), "<redacted>");
3256 assert!(!error.to_string().contains("sk-secret-value"));
3257 }
3258
3259 #[test]
3266 fn provenance_builder_sentinels_become_field_omission() {
3267 for sentinel in [
3268 "unknown",
3269 "UNKNOWN",
3270 "Unknown",
3271 "unavailable",
3272 "none",
3273 "None",
3274 " unknown ",
3275 "",
3276 ] {
3277 let p = build_provenance_from_source(
3278 BuildGitShaSource::Git {
3279 revision: sentinel,
3280 tree_state: GitTreeState::Clean,
3281 },
3282 Some(sentinel),
3283 Some(sentinel),
3284 )
3285 .expect("sentinels are omitted before form validation");
3286 assert_eq!(
3287 (
3288 p.build_git_sha,
3289 p.build_git_sha_absence_reason,
3290 p.build_lock_digest,
3291 p.store_schema_version,
3292 ),
3293 (
3294 None,
3295 Some(BuildGitShaAbsenceReason::NeverDerived),
3296 None,
3297 None,
3298 ),
3299 "sentinel {sentinel:?} must be omitted, not published"
3300 );
3301 }
3302 let real = build_provenance_from_source(
3303 BuildGitShaSource::Git {
3304 revision: "0123456789abcdef0123456789abcdef01234567",
3305 tree_state: GitTreeState::Clean,
3306 },
3307 None,
3308 Some("9"),
3309 )
3310 .expect("canonical build revision is accepted");
3311 assert_eq!(
3312 real.build_git_sha.as_deref(),
3313 Some("0123456789abcdef0123456789abcdef01234567")
3314 );
3315 assert_eq!(real.store_schema_version.as_deref(), Some("9"));
3316 assert_eq!(
3320 real.wire_crate_version.as_deref(),
3321 Some(crate::SUBC_PROTOCOL_CRATE_VERSION)
3322 );
3323 }
3324
3325 #[test]
3326 fn build_provenance_accepts_canonical_sha_and_lock_digest() {
3327 let provenance = build_provenance_from_source(
3328 BuildGitShaSource::Git {
3329 revision: " 0123456789abcdef0123456789abcdef01234567 ",
3330 tree_state: GitTreeState::Clean,
3331 },
3332 Some(" abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789 "),
3333 Some(" schema-v3 "),
3334 )
3335 .expect("canonical build facts are accepted");
3336
3337 assert_eq!(
3338 provenance,
3339 ManifestProvenance {
3340 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
3341 build_git_sha_absence_reason: None,
3342 build_lock_digest: Some(
3343 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
3344 ),
3345 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
3346 store_schema_version: Some("schema-v3".to_string()),
3347 launch_nonce_source: None,
3348 }
3349 );
3350 }
3351
3352 #[test]
3353 fn build_provenance_refuses_an_abbreviated_git_sha() {
3354 let error = build_provenance_from_source(
3355 BuildGitShaSource::Git {
3356 revision: "0123456789ab",
3357 tree_state: GitTreeState::Clean,
3358 },
3359 None,
3360 None,
3361 )
3362 .expect_err("a 12-character abbreviation is not canonical");
3363
3364 assert_eq!(error.field(), "build_git_sha");
3365 assert_eq!(error.length(), 12);
3366 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3367 assert_eq!(
3368 error.to_string(),
3369 "invalid manifest provenance form: field build_git_sha has length 12; canonical form is exactly 40 lowercase hexadecimal characters"
3370 );
3371 }
3372
3373 #[test]
3374 fn build_provenance_refuses_an_abbreviated_lock_digest() {
3375 let error = build_provenance_from_source(
3376 BuildGitShaSource::NeverDerived,
3377 Some("0123456789abcdef"),
3378 None,
3379 )
3380 .expect_err("a 16-character digest is not canonical");
3381
3382 assert_eq!(error.field(), "build_lock_digest");
3383 assert_eq!(error.length(), 16);
3384 assert_eq!(error.canonical_form(), BUILD_LOCK_DIGEST_CANONICAL_FORM);
3385 }
3386
3387 #[test]
3388 fn build_provenance_refuses_uppercase_hex() {
3389 let uppercase_sha = "A".repeat(40);
3390 let error = build_provenance_from_source(
3391 BuildGitShaSource::Git {
3392 revision: &uppercase_sha,
3393 tree_state: GitTreeState::Clean,
3394 },
3395 None,
3396 None,
3397 )
3398 .expect_err("uppercase hexadecimal is not canonical");
3399
3400 assert_eq!(error.field(), "build_git_sha");
3401 assert_eq!(error.length(), 40);
3402 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3403 }
3404
3405 #[test]
3406 fn build_provenance_refuses_dirty_revision_stamp_claimed_clean() {
3407 let error = build_provenance_from_source(
3408 BuildGitShaSource::Git {
3409 revision: "0123456789abcdef0123456789abcdef01234567-dirty",
3410 tree_state: GitTreeState::Clean,
3411 },
3412 None,
3413 None,
3414 )
3415 .expect_err("a dirty stamp is not a canonical build revision");
3416
3417 assert_eq!(error.field(), "build_git_sha");
3418 assert_eq!(error.length(), 46);
3419 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3420 }
3421
3422 #[test]
3423 fn build_provenance_keeps_a_lock_digest_when_identity_is_unavailable() {
3424 let provenance = build_provenance_from_source(
3425 BuildGitShaSource::Git {
3426 revision: "unavailable",
3427 tree_state: GitTreeState::Clean,
3428 },
3429 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"),
3430 None,
3431 )
3432 .expect("sentinel SHA is omitted before the valid lock digest is checked");
3433
3434 assert_eq!(provenance.build_git_sha, None);
3435 assert_eq!(
3436 provenance.build_lock_digest,
3437 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string())
3438 );
3439 assert_eq!(
3440 provenance.wire_crate_version,
3441 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
3442 );
3443 }
3444
3445 #[test]
3446 fn build_provenance_omits_fully_unavailable_inputs() {
3447 let provenance = build_provenance_from_source(
3448 BuildGitShaSource::NeverDerived,
3449 Some(" unavailable "),
3450 Some(" "),
3451 )
3452 .expect("omitted and sentinel inputs are not form errors");
3453
3454 assert_eq!(provenance.build_git_sha, None);
3455 assert_eq!(provenance.build_lock_digest, None);
3456 assert_eq!(provenance.store_schema_version, None);
3457 assert_eq!(
3458 provenance.wire_crate_version,
3459 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
3460 );
3461 }
3462
3463 #[test]
3464 fn legacy_build_provenance_keeps_master_wire_bytes_without_an_absence_reason() {
3465 let revision = "0123456789abcdef0123456789abcdef01234567";
3466 for (input, expected) in [
3467 (
3468 Some(revision),
3469 format!(
3470 r#"{{"build_git_sha":"{revision}","wire_crate_version":"{}"}}"#,
3471 crate::SUBC_PROTOCOL_CRATE_VERSION
3472 ),
3473 ),
3474 (
3475 None,
3476 format!(
3477 r#"{{"wire_crate_version":"{}"}}"#,
3478 crate::SUBC_PROTOCOL_CRATE_VERSION
3479 ),
3480 ),
3481 (
3482 Some("unknown"),
3483 format!(
3484 r#"{{"wire_crate_version":"{}"}}"#,
3485 crate::SUBC_PROTOCOL_CRATE_VERSION
3486 ),
3487 ),
3488 ] {
3489 let provenance = build_provenance(input, None, None)
3490 .expect("the legacy build facts remain constructible");
3491 assert_eq!(provenance.build_git_sha_absence_reason, None);
3492 assert_eq!(
3493 serde_json::to_string(&provenance).expect("legacy provenance serializes"),
3494 expected
3495 );
3496 }
3497 }
3498
3499 #[test]
3500 fn build_provenance_derives_git_sha_absence_from_the_stamping_inputs() {
3501 let revision = "0123456789abcdef0123456789abcdef01234567";
3502 let cases = [
3503 (
3504 BuildGitShaSource::Git {
3505 revision,
3506 tree_state: GitTreeState::Clean,
3507 },
3508 Some(revision),
3509 None,
3510 ),
3511 (
3512 BuildGitShaSource::Git {
3513 revision,
3514 tree_state: GitTreeState::Dirty,
3515 },
3516 None,
3517 Some(BuildGitShaAbsenceReason::DeclinedDirty),
3518 ),
3519 (
3520 BuildGitShaSource::NeverDerived,
3521 None,
3522 Some(BuildGitShaAbsenceReason::NeverDerived),
3523 ),
3524 (
3525 BuildGitShaSource::NoGitDir,
3526 None,
3527 Some(BuildGitShaAbsenceReason::NoGitDir),
3528 ),
3529 ];
3530
3531 for (source, expected_sha, expected_reason) in cases {
3532 let provenance = build_provenance_from_source(source, None, None)
3533 .expect("every stamping state constructs honest provenance");
3534 assert_eq!(provenance.build_git_sha.as_deref(), expected_sha);
3535 assert_eq!(provenance.build_git_sha_absence_reason, expected_reason);
3536 }
3537 }
3538
3539 #[test]
3540 fn unknown_git_sha_absence_reason_round_trips_byte_faithfully() {
3541 let wire = format!(
3542 r#"{{"build_git_sha_absence_reason":"future_stamper_state","wire_crate_version":"{}"}}"#,
3543 crate::SUBC_PROTOCOL_CRATE_VERSION
3544 );
3545 let provenance: ManifestProvenance =
3546 serde_json::from_str(&wire).expect("future absence reasons remain readable");
3547
3548 assert_eq!(
3549 provenance.build_git_sha_absence_reason,
3550 Some(BuildGitShaAbsenceReason::ForwardCompatibleUnknown(
3551 "future_stamper_state".to_string()
3552 ))
3553 );
3554 assert_eq!(
3555 serde_json::to_string(&provenance).expect("future absence reason reserializes"),
3556 wire
3557 );
3558 }
3559
3560 #[test]
3561 fn provenance_rejects_an_absence_reason_beside_a_declared_commit() {
3562 let error = serde_json::from_value::<ManifestProvenance>(json!({
3563 "build_git_sha": "0123456789abcdef0123456789abcdef01234567",
3564 "build_git_sha_absence_reason": "declined_dirty"
3565 }))
3566 .expect_err("a declared commit cannot also claim an absence reason");
3567
3568 assert!(error.to_string().contains(
3569 "build_git_sha_absence_reason has must be omitted when build_git_sha is present"
3570 ));
3571 }
3572
3573 #[test]
3574 fn rich_ui_descriptor_is_optional_and_round_trips_when_present() {
3575 let manifest = ModuleManifest::builder("provider", "1.0.0").build();
3576 assert_eq!(
3577 serde_json::to_string(&manifest).unwrap(),
3578 r#"{"module_id":"provider","module_version":"1.0.0","protocol_ver":2,"provides":[]}"#
3579 );
3580
3581 let descriptor = RichUiDescriptor::new(
3582 "ckios.richui.manifest/1",
3583 format!("sha256:{}", "a".repeat(64)),
3584 128,
3585 2,
3586 );
3587 let manifest = ModuleManifest::builder("provider", "1.0.0")
3588 .rich_ui(Some(descriptor.clone()))
3589 .build();
3590 let wire = serde_json::to_string(&manifest).unwrap();
3591 assert!(wire.contains("\"rich_ui\":{\"schema\":\"ckios.richui.manifest/1\""));
3592 assert_eq!(
3593 serde_json::from_str::<ModuleManifest>(&wire)
3594 .unwrap()
3595 .rich_ui,
3596 Some(descriptor)
3597 );
3598 }
3599
3600 #[test]
3601 fn rich_ui_descriptor_validation_names_each_invalid_field() {
3602 let good = json!({
3603 "schema": "ckios.richui.manifest/1",
3604 "manifest_digest": format!("sha256:{}", "a".repeat(64)),
3605 "bytes": 1,
3606 "chunks": 1
3607 });
3608 let hello = json!({"manifest": {"rich_ui": good.clone()}});
3609 assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
3610
3611 for (field, value) in [
3612 ("schema", json!("bad schema")),
3613 (
3614 "manifest_digest",
3615 json!(format!("sha256:{}", "A".repeat(64))),
3616 ),
3617 ("bytes", json!(0)),
3618 ("chunks", json!(1025)),
3619 ] {
3620 let mut invalid = hello.clone();
3621 invalid["manifest"]["rich_ui"][field] = value;
3622 let error = validate_hello_rich_ui_descriptor(&invalid)
3623 .expect_err("an invalid descriptor field must be refused");
3624 assert_eq!(error.field(), format!("rich_ui.{field}"));
3625 }
3626
3627 let mut hello = hello;
3628 hello["manifest"]["rich_ui"] = Value::Null;
3629 let error = validate_hello_rich_ui_descriptor(&hello)
3630 .expect_err("null is not an absent descriptor");
3631 assert_eq!(error.field(), "rich_ui");
3632 }
3633
3634 #[test]
3635 fn rich_ui_descriptor_validation_accepts_inclusive_bounds() {
3636 let hello = json!({"manifest": {"rich_ui": {
3637 "schema": "a".repeat(64),
3638 "manifest_digest": format!("sha256:{}", "f".repeat(64)),
3639 "bytes": 16_777_216,
3640 "chunks": 1024
3641 }}});
3642 assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
3643 }
3644}