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 validate_plain_text(value, 40)
664}
665
666pub fn validate_module_id(module_id: &str) -> Result<(), String> {
668 if module_id.is_empty() {
669 return Err("empty".to_string());
670 }
671 if module_id.contains('/') || module_id.contains('\\') {
672 return Err("contains a path separator".to_string());
673 }
674 if module_id == "." || module_id == ".." {
675 return Err("is a dot path component".to_string());
676 }
677 if module_id.chars().any(|c| c.is_control()) {
678 return Err("contains a control character".to_string());
679 }
680 if module_id.len() > 255 {
681 return Err("is longer than 255 bytes".to_string());
682 }
683 Ok(())
684}
685
686pub(crate) fn validate_plain_text(value: &str, max: usize) -> Result<(), DisplayNameError> {
687 if value.is_empty() || value.chars().count() > max {
688 return Err(DisplayNameError(
689 "text length is outside the permitted bounds",
690 ));
691 }
692 if value.chars().any(|ch| {
693 ch.is_control()
694 || matches!(ch, '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')
695 }) {
696 return Err(DisplayNameError("must not contain control or bidi formatting characters"));
697 }
698 Ok(())
699}
700
701pub fn validate_hello_display_name(hello: &Value) -> Result<(), DisplayNameError> {
703 match hello
704 .get("manifest")
705 .and_then(|manifest| manifest.get("display_name"))
706 {
707 None | Some(Value::Null) => Ok(()),
708 Some(Value::String(value)) => validate_display_name(value),
709 Some(_) => Err(DisplayNameError("must be a string")),
710 }
711}
712
713#[derive(Debug, Clone, PartialEq, Eq)]
715#[non_exhaustive]
716pub struct RichUiDescriptorError {
717 field: String,
718 reason: &'static str,
719}
720
721impl RichUiDescriptorError {
722 fn new(field: impl Into<String>, reason: &'static str) -> Self {
723 Self {
724 field: field.into(),
725 reason,
726 }
727 }
728
729 pub fn field(&self) -> &str {
731 &self.field
732 }
733}
734
735impl fmt::Display for RichUiDescriptorError {
736 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
737 write!(
738 f,
739 "invalid rich_ui descriptor: field {} {}",
740 self.field, self.reason
741 )
742 }
743}
744
745impl std::error::Error for RichUiDescriptorError {}
746
747pub fn validate_hello_rich_ui_descriptor(hello: &Value) -> Result<(), RichUiDescriptorError> {
749 let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
750 return Ok(());
751 };
752 let Some(value) = manifest.get("rich_ui") else {
753 return Ok(());
754 };
755 validate_rich_ui_descriptor_value(value)
756}
757
758fn validate_rich_ui_descriptor_value(value: &Value) -> Result<(), RichUiDescriptorError> {
759 let descriptor = value
760 .as_object()
761 .ok_or_else(|| RichUiDescriptorError::new("rich_ui", "must be an object"))?;
762 let schema = descriptor
763 .get("schema")
764 .and_then(Value::as_str)
765 .ok_or_else(|| RichUiDescriptorError::new("rich_ui.schema", "must be a string"))?;
766 let digest = descriptor
767 .get("manifest_digest")
768 .and_then(Value::as_str)
769 .ok_or_else(|| RichUiDescriptorError::new("rich_ui.manifest_digest", "must be a string"))?;
770 let bytes = descriptor
771 .get("bytes")
772 .and_then(Value::as_u64)
773 .ok_or_else(|| {
774 RichUiDescriptorError::new("rich_ui.bytes", "must be an integer from 1 to 16777216")
775 })?;
776 let chunks = descriptor
777 .get("chunks")
778 .and_then(Value::as_u64)
779 .ok_or_else(|| {
780 RichUiDescriptorError::new("rich_ui.chunks", "must be an integer from 1 to 1024")
781 })?;
782 validate_rich_ui_fields(schema, digest, bytes, chunks)
783}
784
785fn validate_rich_ui_fields(
786 schema: &str,
787 digest: &str,
788 bytes: u64,
789 chunks: u64,
790) -> Result<(), RichUiDescriptorError> {
791 if !(1..=64).contains(&schema.len())
792 || !schema.bytes().all(|byte| {
793 byte.is_ascii_lowercase()
794 || byte.is_ascii_digit()
795 || matches!(byte, b'.' | b'_' | b'/' | b'-')
796 })
797 {
798 return Err(RichUiDescriptorError::new(
799 "rich_ui.schema",
800 "must be 1 to 64 bytes of [a-z0-9._/-]",
801 ));
802 }
803 if !digest.strip_prefix("sha256:").is_some_and(|hex| {
804 hex.len() == 64
805 && hex
806 .bytes()
807 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
808 }) {
809 return Err(RichUiDescriptorError::new(
810 "rich_ui.manifest_digest",
811 "must be sha256: followed by 64 lowercase hexadecimal characters",
812 ));
813 }
814 if !(1..=16_777_216).contains(&bytes) {
815 return Err(RichUiDescriptorError::new(
816 "rich_ui.bytes",
817 "must be an integer from 1 to 16777216",
818 ));
819 }
820 if !(1..=1_024).contains(&chunks) {
821 return Err(RichUiDescriptorError::new(
822 "rich_ui.chunks",
823 "must be an integer from 1 to 1024",
824 ));
825 }
826 Ok(())
827}
828
829pub const CAP_CATALOG_EVENTS_V1: &str = "catalog-events/v1";
835
836pub const CAP_SCOPE_BIND_PROOF_V1: &str = "scope-bind-proof/v1";
840
841pub const CAP_SCOPE_BIND_PROOF_V2: &str = "scope-bind-proof/v2";
845
846pub const CAP_SCOPE_REPLACE_IF_IDLE_V1: &str = "scope-replace-if-idle/v1";
848
849#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
851#[non_exhaustive]
852pub struct EventDeclaration {
853 pub name: String,
860 pub version: u32,
862 pub headers: Vec<String>,
867 #[serde(default, skip_serializing_if = "Option::is_none")]
869 pub summary: Option<String>,
870}
871
872impl EventDeclaration {
873 pub fn new(name: impl Into<String>, version: u32) -> Self {
876 Self {
877 name: name.into(),
878 version,
879 headers: Vec::new(),
880 summary: None,
881 }
882 }
883
884 pub fn with_headers(mut self, headers: Vec<String>) -> Self {
886 self.headers = headers;
887 self
888 }
889
890 pub fn with_summary(mut self, summary: Option<String>) -> Self {
892 self.summary = summary;
893 self
894 }
895}
896
897#[derive(Debug, Clone, PartialEq, Eq)]
899#[non_exhaustive]
900pub struct EventDeclarationError {
901 field: String,
902 reason: &'static str,
903}
904
905impl EventDeclarationError {
906 fn new(field: impl Into<String>, reason: &'static str) -> Self {
907 Self {
908 field: field.into(),
909 reason,
910 }
911 }
912
913 pub fn field(&self) -> &str {
915 &self.field
916 }
917}
918
919impl fmt::Display for EventDeclarationError {
920 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
921 write!(
922 f,
923 "invalid event declaration: field {} {}",
924 self.field, self.reason
925 )
926 }
927}
928
929impl std::error::Error for EventDeclarationError {}
930
931pub fn validate_hello_event_declarations(hello: &Value) -> Result<(), EventDeclarationError> {
933 validate_events_value(
934 hello
935 .get("manifest")
936 .and_then(|manifest| manifest.get("events")),
937 )
938}
939
940fn is_valid_event_name(name: &str) -> bool {
943 let level_count = name.split('.').count();
944 (1..=4).contains(&level_count)
945 && name.split('.').all(|level| {
946 if level.is_empty() {
947 return false;
948 }
949 let first = level.as_bytes()[0];
950 (1..=63).contains(&level.len())
951 && (first.is_ascii_lowercase() || first.is_ascii_digit())
952 && level
953 .bytes()
954 .skip(1)
955 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
956 && !level.strip_prefix('v').is_some_and(|digits| {
957 !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit())
958 })
959 })
960}
961
962fn validate_events_value(value: Option<&Value>) -> Result<(), EventDeclarationError> {
963 let Some(value) = value.filter(|value| !value.is_null()) else {
964 return Ok(());
965 };
966 let entries = value
967 .as_array()
968 .ok_or_else(|| EventDeclarationError::new("events", "must be a list"))?;
969 if entries.len() > 64 {
970 return Err(EventDeclarationError::new(
971 "events",
972 "must contain at most 64 declarations",
973 ));
974 }
975 let mut pairs = HashSet::new();
976 for (index, entry) in entries.iter().enumerate() {
977 let field = format!("events[{index}]");
978 let entry = entry
979 .as_object()
980 .ok_or_else(|| EventDeclarationError::new(&field, "must be an object"))?;
981 let name_field = format!("{field}.name");
982 let name = entry
983 .get("name")
984 .and_then(Value::as_str)
985 .ok_or_else(|| EventDeclarationError::new(&name_field, "must be a string"))?;
986 if !is_valid_event_name(name) {
987 return Err(EventDeclarationError::new(
988 name_field,
989 "must contain one to four valid dot-separated event-name levels",
990 ));
991 }
992 let version = entry
993 .get("version")
994 .and_then(Value::as_u64)
995 .filter(|version| (1..=u32::MAX as u64).contains(version))
996 .ok_or_else(|| {
997 EventDeclarationError::new(
998 format!("{field}.version"),
999 "must be an integer between 1 and u32::MAX",
1000 )
1001 })?;
1002 if !pairs.insert((name, version)) {
1003 return Err(EventDeclarationError::new(
1004 &field,
1005 "duplicates an event (name, version) pair",
1006 ));
1007 }
1008 let headers_field = format!("{field}.headers");
1009 let headers = entry
1010 .get("headers")
1011 .and_then(Value::as_array)
1012 .ok_or_else(|| EventDeclarationError::new(&headers_field, "must be a list"))?;
1013 if headers.len() > 16 {
1014 return Err(EventDeclarationError::new(
1015 headers_field,
1016 "must contain at most 16 headers",
1017 ));
1018 }
1019 let mut names = HashSet::new();
1020 for (header_index, header) in headers.iter().enumerate() {
1021 let header_field = format!("{headers_field}[{header_index}]");
1022 let header = header
1023 .as_str()
1024 .ok_or_else(|| EventDeclarationError::new(&header_field, "must be a string"))?;
1025 if !(1..=32).contains(&header.len())
1026 || !header.as_bytes()[0].is_ascii_lowercase()
1027 || !header
1028 .bytes()
1029 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
1030 {
1031 return Err(EventDeclarationError::new(
1032 header_field,
1033 "must match [a-z][a-z0-9_]{0,31}",
1034 ));
1035 }
1036 if !names.insert(header) {
1037 return Err(EventDeclarationError::new(
1038 header_field,
1039 "duplicates a header name",
1040 ));
1041 }
1042 }
1043 if let Some(summary) = entry.get("summary").filter(|value| !value.is_null()) {
1044 let summary_field = format!("{field}.summary");
1045 let summary = summary
1046 .as_str()
1047 .ok_or_else(|| EventDeclarationError::new(&summary_field, "must be a string"))?;
1048 if summary.chars().count() > 200 || summary.chars().any(char::is_control) {
1049 return Err(EventDeclarationError::new(
1050 summary_field,
1051 "must contain at most 200 characters and no control characters",
1052 ));
1053 }
1054 }
1055 }
1056 Ok(())
1057}
1058
1059#[derive(Debug, Clone, PartialEq, Eq)]
1061pub struct SelfSignalDeclarationError {
1062 module_id: String,
1063 entry_index: usize,
1064 field: &'static str,
1065}
1066
1067impl fmt::Display for SelfSignalDeclarationError {
1068 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1069 write!(
1070 f,
1071 "module_id '{}' self_signals[{}] is missing required field '{}'",
1072 self.module_id.escape_debug(),
1073 self.entry_index,
1074 self.field
1075 )
1076 }
1077}
1078
1079pub fn validate_hello_self_signal_declarations(
1086 hello: &Value,
1087) -> Result<(), SelfSignalDeclarationError> {
1088 let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
1089 return Ok(());
1090 };
1091 let module_id = manifest
1092 .get("module_id")
1093 .and_then(Value::as_str)
1094 .unwrap_or("<unknown>");
1095 let Some(entries) = manifest.get("self_signals").and_then(Value::as_array) else {
1096 return Ok(());
1097 };
1098
1099 for (entry_index, entry) in entries.iter().enumerate() {
1100 let Some(entry) = entry.as_object() else {
1101 continue;
1102 };
1103 for field in ["effect", "anchored_to"] {
1104 if !entry.contains_key(field) {
1105 return Err(SelfSignalDeclarationError {
1106 module_id: module_id.to_string(),
1107 entry_index,
1108 field,
1109 });
1110 }
1111 }
1112 }
1113 Ok(())
1114}
1115
1116#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1118#[serde(deny_unknown_fields)]
1119pub struct CapabilityDeclarations {
1120 #[serde(default)]
1121 pub provides: Vec<String>,
1122 #[serde(default)]
1123 pub requires: Vec<CapabilityRequirement>,
1124 #[serde(default)]
1125 pub must_never_reach: Vec<String>,
1126}
1127
1128#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1130pub struct SelfSignalDeclaration {
1131 pub name: String,
1133 pub kind: SelfSignalKind,
1161 pub effect: SelfSignalEffect,
1163 pub anchored_to: SignalAnchor,
1165 #[serde(default, skip_serializing_if = "Option::is_none")]
1172 pub cadence: Option<SignalCadence>,
1173 #[serde(default, skip_serializing_if = "Option::is_none")]
1175 pub domain: Option<String>,
1176 #[serde(default, skip_serializing_if = "Option::is_none")]
1177 pub note: Option<String>,
1178}
1179
1180#[derive(Debug, Clone, PartialEq, Eq)]
1182pub enum SelfSignalKind {
1183 Keepalive,
1184 Busy,
1186 Poller,
1187 Cron,
1188 Sweep,
1189 Watchdog,
1190 Heartbeat,
1191 Other(String),
1192}
1193
1194impl SelfSignalKind {
1195 fn wire_name(&self) -> &str {
1196 match self {
1197 Self::Keepalive => "keepalive",
1198 Self::Busy => "busy",
1199 Self::Poller => "poller",
1200 Self::Cron => "cron",
1201 Self::Sweep => "sweep",
1202 Self::Watchdog => "watchdog",
1203 Self::Heartbeat => "heartbeat",
1204 Self::Other(value) => value,
1205 }
1206 }
1207}
1208
1209impl Serialize for SelfSignalKind {
1210 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1211 where
1212 S: serde::Serializer,
1213 {
1214 serializer.serialize_str(self.wire_name())
1215 }
1216}
1217
1218impl<'de> Deserialize<'de> for SelfSignalKind {
1219 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1220 where
1221 D: Deserializer<'de>,
1222 {
1223 let value = String::deserialize(deserializer)?;
1224 Ok(match value.as_str() {
1225 "keepalive" => Self::Keepalive,
1226 "busy" => Self::Busy,
1227 "poller" => Self::Poller,
1228 "cron" => Self::Cron,
1229 "sweep" => Self::Sweep,
1230 "watchdog" => Self::Watchdog,
1231 "heartbeat" => Self::Heartbeat,
1232 _ => Self::Other(value),
1233 })
1234 }
1235}
1236
1237#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1239#[serde(rename_all = "lowercase")]
1240pub enum SelfSignalEffect {
1241 Observe,
1242 Mutate,
1243}
1244
1245#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1247#[serde(rename_all = "snake_case")]
1248pub enum SignalAnchor {
1249 FixedInterval,
1252 Event { event: String },
1255 HealthGauges { gauges: Vec<String> },
1257}
1258
1259#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1261#[serde(rename_all = "snake_case")]
1262pub enum SignalCadence {
1263 Literal { interval_ms: u64 },
1264 Derived { source: String },
1265}
1266
1267#[derive(Serialize, Debug, Clone, Default, PartialEq, Eq)]
1344#[non_exhaustive]
1345pub struct ManifestProvenance {
1346 #[serde(default, skip_serializing_if = "Option::is_none")]
1347 pub build_git_sha: Option<String>,
1348 #[serde(default, skip_serializing_if = "Option::is_none")]
1352 pub build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1353 #[serde(default, skip_serializing_if = "Option::is_none")]
1354 pub build_lock_digest: Option<String>,
1355 #[serde(default, skip_serializing_if = "Option::is_none")]
1364 pub wire_crate_version: Option<String>,
1365 #[serde(default, skip_serializing_if = "Option::is_none")]
1366 pub store_schema_version: Option<String>,
1367 #[serde(default, skip_serializing_if = "Option::is_none")]
1373 pub launch_nonce_source: Option<LaunchNonceSource>,
1374}
1375
1376#[derive(Debug, Clone, PartialEq, Eq)]
1383#[non_exhaustive]
1384pub enum LaunchNonceSource {
1385 Fd,
1387 Pipe,
1389 Env,
1391 ForwardCompatibleUnknown(String),
1392}
1393
1394impl LaunchNonceSource {
1395 pub fn wire_name(&self) -> &str {
1397 match self {
1398 Self::Fd => "fd",
1399 Self::Pipe => "pipe",
1400 Self::Env => "env",
1401 Self::ForwardCompatibleUnknown(value) => value,
1402 }
1403 }
1404
1405 pub fn from_wire_name(value: &str) -> Self {
1407 match value {
1408 "fd" => Self::Fd,
1409 "pipe" => Self::Pipe,
1410 "env" => Self::Env,
1411 _ => Self::ForwardCompatibleUnknown(value.to_string()),
1412 }
1413 }
1414}
1415
1416impl Serialize for LaunchNonceSource {
1417 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1418 where
1419 S: serde::Serializer,
1420 {
1421 serializer.serialize_str(self.wire_name())
1422 }
1423}
1424
1425impl<'de> Deserialize<'de> for LaunchNonceSource {
1426 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1427 where
1428 D: serde::Deserializer<'de>,
1429 {
1430 let value = String::deserialize(deserializer)?;
1431 Ok(Self::from_wire_name(&value))
1432 }
1433}
1434
1435#[derive(Debug, Clone, PartialEq, Eq)]
1440pub enum BuildGitShaAbsenceReason {
1441 DeclinedDirty,
1442 NeverDerived,
1443 NoGitDir,
1444 ForwardCompatibleUnknown(String),
1445}
1446
1447impl BuildGitShaAbsenceReason {
1448 fn wire_name(&self) -> &str {
1449 match self {
1450 Self::DeclinedDirty => "declined_dirty",
1451 Self::NeverDerived => "never_derived",
1452 Self::NoGitDir => "no_git_dir",
1453 Self::ForwardCompatibleUnknown(value) => value,
1454 }
1455 }
1456}
1457
1458impl Serialize for BuildGitShaAbsenceReason {
1459 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1460 where
1461 S: serde::Serializer,
1462 {
1463 serializer.serialize_str(self.wire_name())
1464 }
1465}
1466
1467impl<'de> Deserialize<'de> for BuildGitShaAbsenceReason {
1468 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1469 where
1470 D: serde::Deserializer<'de>,
1471 {
1472 let value = String::deserialize(deserializer)?;
1473 Ok(match value.as_str() {
1474 "declined_dirty" => Self::DeclinedDirty,
1475 "never_derived" => Self::NeverDerived,
1476 "no_git_dir" => Self::NoGitDir,
1477 _ => Self::ForwardCompatibleUnknown(value),
1478 })
1479 }
1480}
1481
1482#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1484pub enum GitTreeState {
1485 Clean,
1486 Dirty,
1487}
1488
1489#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1494pub enum BuildGitShaSource<'a> {
1495 Git {
1496 revision: &'a str,
1497 tree_state: GitTreeState,
1498 },
1499 NeverDerived,
1500 NoGitDir,
1501}
1502
1503pub fn attestable_commit(revision: &str, tree_state: GitTreeState) -> Option<&str> {
1507 match tree_state {
1508 GitTreeState::Clean => Some(revision),
1509 GitTreeState::Dirty => None,
1510 }
1511}
1512
1513const MAX_PROVENANCE_VALUE_BYTES: usize = 128;
1514const BUILD_GIT_SHA_CANONICAL_FORM: &str = "exactly 40 lowercase hexadecimal characters";
1515const BUILD_LOCK_DIGEST_CANONICAL_FORM: &str = "exactly 64 lowercase hexadecimal characters";
1516
1517#[derive(Deserialize)]
1518struct ManifestProvenanceWire {
1519 #[serde(default)]
1520 build_git_sha: Option<String>,
1521 #[serde(default)]
1522 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1523 #[serde(default)]
1524 build_lock_digest: Option<String>,
1525 #[serde(default)]
1526 wire_crate_version: Option<String>,
1527 #[serde(default)]
1528 store_schema_version: Option<String>,
1529 #[serde(default)]
1530 launch_nonce_source: Option<LaunchNonceSource>,
1531}
1532
1533impl<'de> Deserialize<'de> for ManifestProvenance {
1534 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1535 where
1536 D: Deserializer<'de>,
1537 {
1538 let wire = ManifestProvenanceWire::deserialize(deserializer)?;
1539 let provenance = Self {
1540 build_git_sha: wire.build_git_sha,
1541 build_git_sha_absence_reason: wire.build_git_sha_absence_reason,
1542 build_lock_digest: wire.build_lock_digest,
1543 wire_crate_version: wire.wire_crate_version,
1544 store_schema_version: wire.store_schema_version,
1545 launch_nonce_source: wire.launch_nonce_source,
1546 };
1547 provenance.validate().map_err(D::Error::custom)?;
1548 Ok(provenance)
1549 }
1550}
1551
1552#[derive(Debug, Clone, PartialEq, Eq)]
1554pub struct ProvenanceFormError {
1555 field: &'static str,
1556 length: usize,
1557 canonical_form: &'static str,
1558}
1559
1560impl ProvenanceFormError {
1561 fn new(field: &'static str, length: usize, canonical_form: &'static str) -> Self {
1562 Self {
1563 field,
1564 length,
1565 canonical_form,
1566 }
1567 }
1568
1569 pub fn field(&self) -> &str {
1571 self.field
1572 }
1573
1574 pub fn length(&self) -> usize {
1576 self.length
1577 }
1578
1579 pub fn canonical_form(&self) -> &str {
1581 self.canonical_form
1582 }
1583}
1584
1585impl fmt::Display for ProvenanceFormError {
1586 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1587 write!(
1588 f,
1589 "invalid manifest provenance form: field {} has length {}; canonical form is {}",
1590 self.field, self.length, self.canonical_form
1591 )
1592 }
1593}
1594
1595impl std::error::Error for ProvenanceFormError {}
1596
1597#[derive(Debug, Clone, PartialEq, Eq)]
1598pub struct ManifestProvenanceError {
1599 field: String,
1600 value: String,
1601 reason: &'static str,
1602}
1603
1604impl ManifestProvenanceError {
1605 fn new(field: &str, value: &str, reason: &'static str) -> Self {
1606 Self {
1607 field: field.to_string(),
1608 value: safe_error_value(value),
1609 reason,
1610 }
1611 }
1612
1613 pub fn field(&self) -> &str {
1614 &self.field
1615 }
1616}
1617
1618impl fmt::Display for ManifestProvenanceError {
1619 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1620 write!(
1621 f,
1622 "invalid manifest provenance: field {} has {} (value {:?})",
1623 self.field, self.reason, self.value
1624 )
1625 }
1626}
1627
1628impl std::error::Error for ManifestProvenanceError {}
1629
1630impl ManifestProvenance {
1631 pub fn new() -> Self {
1633 Self::default()
1634 }
1635
1636 pub fn with_build_git_sha(mut self, value: Option<String>) -> Self {
1637 self.build_git_sha = value;
1638 self
1639 }
1640
1641 pub fn with_build_git_sha_absence_reason(
1642 mut self,
1643 value: Option<BuildGitShaAbsenceReason>,
1644 ) -> Self {
1645 self.build_git_sha_absence_reason = value;
1646 self
1647 }
1648
1649 pub fn with_build_lock_digest(mut self, value: Option<String>) -> Self {
1650 self.build_lock_digest = value;
1651 self
1652 }
1653
1654 pub fn with_wire_crate_version(mut self, value: Option<String>) -> Self {
1655 self.wire_crate_version = value;
1656 self
1657 }
1658
1659 pub fn with_store_schema_version(mut self, value: Option<String>) -> Self {
1660 self.store_schema_version = value;
1661 self
1662 }
1663
1664 pub fn with_launch_nonce_source(mut self, value: Option<LaunchNonceSource>) -> Self {
1669 self.launch_nonce_source = value;
1670 self
1671 }
1672
1673 pub fn validate(&self) -> Result<(), ManifestProvenanceError> {
1674 if let (Some(_), Some(reason)) = (
1675 self.build_git_sha.as_ref(),
1676 self.build_git_sha_absence_reason.as_ref(),
1677 ) {
1678 return Err(ManifestProvenanceError::new(
1679 "build_git_sha_absence_reason",
1680 reason.wire_name(),
1681 "must be omitted when build_git_sha is present",
1682 ));
1683 }
1684 for (field, value) in [
1685 ("build_git_sha", self.build_git_sha.as_deref()),
1686 (
1687 "build_git_sha_absence_reason",
1688 self.build_git_sha_absence_reason
1689 .as_ref()
1690 .map(|reason| reason.wire_name()),
1691 ),
1692 ("build_lock_digest", self.build_lock_digest.as_deref()),
1693 ("wire_crate_version", self.wire_crate_version.as_deref()),
1694 ("store_schema_version", self.store_schema_version.as_deref()),
1695 (
1696 "launch_nonce_source",
1697 self.launch_nonce_source
1698 .as_ref()
1699 .map(|source| source.wire_name()),
1700 ),
1701 ] {
1702 let Some(value) = value else { continue };
1703 if value.is_empty() {
1704 return Err(ManifestProvenanceError::new(
1705 field,
1706 value,
1707 "must not be empty",
1708 ));
1709 }
1710 if value.len() > MAX_PROVENANCE_VALUE_BYTES {
1715 return Err(ManifestProvenanceError::new(
1716 field,
1717 value,
1718 "exceeds the 128-byte maximum",
1719 ));
1720 }
1721 if value.bytes().any(|byte| !(0x20..=0x7e).contains(&byte)) {
1722 return Err(ManifestProvenanceError::new(
1723 field,
1724 value,
1725 "contains non-printable ASCII",
1726 ));
1727 }
1728 }
1729 Ok(())
1730 }
1731}
1732
1733pub fn build_provenance(
1751 build_git_sha: Option<&str>,
1752 build_lock_digest: Option<&str>,
1753 store_schema_version: Option<&str>,
1754) -> Result<ManifestProvenance, ProvenanceFormError> {
1755 let build_git_sha = normalize_and_validate_build_git_sha(build_git_sha)?;
1756 build_provenance_with_build_git_sha(
1757 build_git_sha,
1758 None,
1759 build_lock_digest,
1760 store_schema_version,
1761 )
1762}
1763
1764pub fn build_provenance_from_source(
1780 build_git_sha_source: BuildGitShaSource<'_>,
1781 build_lock_digest: Option<&str>,
1782 store_schema_version: Option<&str>,
1783) -> Result<ManifestProvenance, ProvenanceFormError> {
1784 let (raw_build_git_sha, mut build_git_sha_absence_reason) = match build_git_sha_source {
1785 BuildGitShaSource::Git {
1786 revision,
1787 tree_state,
1788 } => match attestable_commit(revision, tree_state) {
1789 Some(revision) => (Some(revision), None),
1790 None => (None, Some(BuildGitShaAbsenceReason::DeclinedDirty)),
1791 },
1792 BuildGitShaSource::NeverDerived => (None, Some(BuildGitShaAbsenceReason::NeverDerived)),
1793 BuildGitShaSource::NoGitDir => (None, Some(BuildGitShaAbsenceReason::NoGitDir)),
1794 };
1795 let build_git_sha = normalize_and_validate_build_git_sha(raw_build_git_sha)?;
1796 if build_git_sha.is_none() {
1797 build_git_sha_absence_reason.get_or_insert(BuildGitShaAbsenceReason::NeverDerived);
1798 }
1799 build_provenance_with_build_git_sha(
1800 build_git_sha,
1801 build_git_sha_absence_reason,
1802 build_lock_digest,
1803 store_schema_version,
1804 )
1805}
1806
1807fn normalize_and_validate_build_git_sha(
1808 build_git_sha: Option<&str>,
1809) -> Result<Option<String>, ProvenanceFormError> {
1810 let build_git_sha = normalize_provenance_fact(build_git_sha);
1811 validate_provenance_form(
1812 "build_git_sha",
1813 build_git_sha.as_deref(),
1814 BUILD_GIT_SHA_CANONICAL_FORM,
1815 40,
1816 )?;
1817 Ok(build_git_sha)
1818}
1819
1820fn build_provenance_with_build_git_sha(
1821 build_git_sha: Option<String>,
1822 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1823 build_lock_digest: Option<&str>,
1824 store_schema_version: Option<&str>,
1825) -> Result<ManifestProvenance, ProvenanceFormError> {
1826 let build_lock_digest = normalize_provenance_fact(build_lock_digest);
1827 validate_provenance_form(
1828 "build_lock_digest",
1829 build_lock_digest.as_deref(),
1830 BUILD_LOCK_DIGEST_CANONICAL_FORM,
1831 64,
1832 )?;
1833
1834 Ok(ManifestProvenance {
1835 build_git_sha,
1836 build_git_sha_absence_reason,
1837 build_lock_digest,
1838 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
1839 store_schema_version: normalize_provenance_fact(store_schema_version),
1840 launch_nonce_source: None,
1841 })
1842}
1843
1844fn validate_provenance_form(
1845 field: &'static str,
1846 value: Option<&str>,
1847 canonical_form: &'static str,
1848 expected_length: usize,
1849) -> Result<(), ProvenanceFormError> {
1850 let Some(value) = value else { return Ok(()) };
1851 if value.len() != expected_length
1852 || !value
1853 .bytes()
1854 .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
1855 {
1856 return Err(ProvenanceFormError::new(field, value.len(), canonical_form));
1857 }
1858 Ok(())
1859}
1860
1861pub const PROVENANCE_SENTINELS: [&str; 3] = ["unknown", "unavailable", "none"];
1869
1870fn normalize_provenance_fact(value: Option<&str>) -> Option<String> {
1871 let value = value?.trim();
1872 if value.is_empty() {
1873 return None;
1874 }
1875 let lowered = value.to_ascii_lowercase();
1876 if PROVENANCE_SENTINELS.contains(&lowered.as_str()) {
1877 return None;
1878 }
1879 Some(value.to_string())
1880}
1881
1882#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1884#[serde(deny_unknown_fields)]
1885pub struct CapabilityRequirement {
1886 pub capability: String,
1887 pub need: CapabilityNeed,
1888}
1889
1890#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1892#[serde(rename_all = "snake_case")]
1893pub enum CapabilityNeed {
1894 Required,
1895 Optional,
1896}
1897
1898#[derive(Debug, Clone, PartialEq, Eq)]
1900pub struct CapabilityGrammarError {
1901 field: String,
1902 value: String,
1903}
1904
1905impl CapabilityGrammarError {
1906 fn new(field: impl Into<String>, value: impl AsRef<str>) -> Self {
1907 Self {
1908 field: field.into(),
1909 value: safe_error_value(value.as_ref()),
1910 }
1911 }
1912
1913 pub fn field(&self) -> &str {
1915 &self.field
1916 }
1917
1918 pub fn value(&self) -> &str {
1920 &self.value
1921 }
1922}
1923
1924impl fmt::Display for CapabilityGrammarError {
1925 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1926 write!(
1927 f,
1928 "invalid capability grammar: field {} has offending value {:?}",
1929 self.field, self.value
1930 )
1931 }
1932}
1933
1934impl std::error::Error for CapabilityGrammarError {}
1935
1936impl ModuleManifest {
1937 pub fn validate_capability_grammar(&self) -> Result<(), CapabilityGrammarError> {
1939 let Some(capabilities) = &self.capabilities else {
1940 return Ok(());
1941 };
1942
1943 validate_capability_list("capabilities.provides", &capabilities.provides)?;
1944 validate_requires(&capabilities.requires)?;
1945 validate_capability_list(
1946 "capabilities.must_never_reach",
1947 &capabilities.must_never_reach,
1948 )
1949 }
1950}
1951
1952pub fn validate_manifest_capability_grammar(
1957 manifest: &Value,
1958) -> Result<(), CapabilityGrammarError> {
1959 let Some(object) = manifest.as_object() else {
1960 return Ok(());
1961 };
1962
1963 validate_capabilities_value(object.get("capabilities"))?;
1964 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
1965}
1966
1967pub fn validate_hello_capability_grammar(hello: &Value) -> Result<(), CapabilityGrammarError> {
1973 let Some(object) = hello.as_object() else {
1974 return Ok(());
1975 };
1976 if let Some(manifest) = object.get("manifest") {
1977 validate_manifest_capability_grammar(manifest)?;
1978 }
1979 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
1980}
1981
1982pub fn is_valid_capability_identifier(identifier: &str) -> bool {
1984 if identifier.chars().any(char::is_whitespace) {
1985 return false;
1986 }
1987 let Some((name, version)) = identifier.split_once("/v") else {
1988 return false;
1989 };
1990 if name.is_empty() || name.len() > 64 || version.is_empty() {
1991 return false;
1992 }
1993
1994 let name_bytes = name.as_bytes();
1995 if !name_bytes[0].is_ascii_lowercase()
1996 || (name.len() > 1
1997 && !name_bytes[name.len() - 1].is_ascii_lowercase()
1998 && !name_bytes[name.len() - 1].is_ascii_digit())
1999 || name_bytes.windows(2).any(|pair| pair == b"--")
2000 {
2001 return false;
2002 }
2003 if !name_bytes
2004 .iter()
2005 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-')
2006 {
2007 return false;
2008 }
2009
2010 if version.len() > 1 && version.starts_with('0')
2011 || !version.bytes().all(|byte| byte.is_ascii_digit())
2012 {
2013 return false;
2014 }
2015 matches!(
2016 version.parse::<u64>(),
2017 Ok(value) if (1..=u64::from(u32::MAX)).contains(&value)
2018 )
2019}
2020
2021fn validate_capabilities_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
2022 let Some(value) = value else {
2023 return Ok(());
2024 };
2025 let Some(object) = value.as_object() else {
2026 return Err(CapabilityGrammarError::new(
2027 "capabilities",
2028 value_description(value),
2029 ));
2030 };
2031
2032 for (key, value) in object {
2033 if !matches!(key.as_str(), "provides" | "requires" | "must_never_reach") {
2034 return Err(CapabilityGrammarError::new(
2035 field_child("capabilities", key),
2036 value_description(value),
2037 ));
2038 }
2039 }
2040
2041 validate_capability_list_value("capabilities.provides", object.get("provides"))?;
2042 validate_requires_value(object.get("requires"))?;
2043 validate_capability_list_value(
2044 "capabilities.must_never_reach",
2045 object.get("must_never_reach"),
2046 )
2047}
2048
2049fn validate_capability_list_value(
2050 field: &str,
2051 value: Option<&Value>,
2052) -> Result<(), CapabilityGrammarError> {
2053 let Some(value) = value else {
2054 return Ok(());
2055 };
2056 let Some(values) = value.as_array() else {
2057 return Err(CapabilityGrammarError::new(field, value_description(value)));
2058 };
2059
2060 let mut seen = HashSet::new();
2061 for (index, value) in values.iter().enumerate() {
2062 let field = format!("{field}[{index}]");
2063 let Some(identifier) = value.as_str() else {
2064 return Err(CapabilityGrammarError::new(field, value_description(value)));
2065 };
2066 validate_capability_identifier(&field, identifier)?;
2067 if !seen.insert(identifier) {
2068 return Err(CapabilityGrammarError::new(field, identifier));
2069 }
2070 }
2071 Ok(())
2072}
2073
2074fn validate_requires_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
2075 let Some(value) = value else {
2076 return Ok(());
2077 };
2078 let Some(values) = value.as_array() else {
2079 return Err(CapabilityGrammarError::new(
2080 "capabilities.requires",
2081 value_description(value),
2082 ));
2083 };
2084
2085 let mut seen = HashSet::new();
2086 for (index, value) in values.iter().enumerate() {
2087 let entry_field = format!("capabilities.requires[{index}]");
2088 let Some(object) = value.as_object() else {
2089 return Err(CapabilityGrammarError::new(
2090 entry_field,
2091 value_description(value),
2092 ));
2093 };
2094 for (key, value) in object {
2095 if !matches!(key.as_str(), "capability" | "need") {
2096 return Err(CapabilityGrammarError::new(
2097 field_child(&entry_field, key),
2098 value_description(value),
2099 ));
2100 }
2101 }
2102 let capability_field = format!("{entry_field}.capability");
2103 let Some(capability) = object.get("capability").and_then(Value::as_str) else {
2104 return Err(CapabilityGrammarError::new(
2105 capability_field,
2106 object
2107 .get("capability")
2108 .map_or("<missing>".to_string(), value_description),
2109 ));
2110 };
2111 validate_capability_identifier(&capability_field, capability)?;
2112
2113 let need_field = format!("{entry_field}.need");
2114 let Some(need) = object.get("need").and_then(Value::as_str) else {
2115 return Err(CapabilityGrammarError::new(
2116 need_field,
2117 object
2118 .get("need")
2119 .map_or("<missing>".to_string(), value_description),
2120 ));
2121 };
2122 if !matches!(need, "required" | "optional") {
2123 return Err(CapabilityGrammarError::new(need_field, need));
2124 }
2125 if !seen.insert(capability) {
2126 return Err(CapabilityGrammarError::new(entry_field, capability));
2127 }
2128 }
2129 Ok(())
2130}
2131
2132fn validate_capability_list(field: &str, values: &[String]) -> Result<(), CapabilityGrammarError> {
2133 let mut seen = HashSet::new();
2134 for (index, identifier) in values.iter().enumerate() {
2135 let field = format!("{field}[{index}]");
2136 validate_capability_identifier(&field, identifier)?;
2137 if !seen.insert(identifier) {
2138 return Err(CapabilityGrammarError::new(field, identifier));
2139 }
2140 }
2141 Ok(())
2142}
2143
2144fn validate_requires(values: &[CapabilityRequirement]) -> Result<(), CapabilityGrammarError> {
2145 let mut seen = HashSet::new();
2146 for (index, requirement) in values.iter().enumerate() {
2147 let field = format!("capabilities.requires[{index}].capability");
2148 validate_capability_identifier(&field, &requirement.capability)?;
2149 if !seen.insert(&requirement.capability) {
2150 return Err(CapabilityGrammarError::new(
2151 format!("capabilities.requires[{index}]"),
2152 &requirement.capability,
2153 ));
2154 }
2155 }
2156 Ok(())
2157}
2158
2159fn validate_capability_identifier(
2160 field: &str,
2161 identifier: &str,
2162) -> Result<(), CapabilityGrammarError> {
2163 if is_valid_capability_identifier(identifier) {
2164 Ok(())
2165 } else {
2166 Err(CapabilityGrammarError::new(field, identifier))
2167 }
2168}
2169
2170fn validate_runtime_computed(
2171 value: Option<&Value>,
2172 field: &str,
2173) -> Result<(), CapabilityGrammarError> {
2174 let Some(value) = value else {
2175 return Ok(());
2176 };
2177 let Some(pointers) = value.as_array() else {
2178 return Err(CapabilityGrammarError::new(field, value_description(value)));
2179 };
2180
2181 for (index, pointer) in pointers.iter().enumerate() {
2182 let field = format!("{field}[{index}]");
2183 let Some(pointer) = pointer.as_str() else {
2184 return Err(CapabilityGrammarError::new(
2185 field,
2186 value_description(pointer),
2187 ));
2188 };
2189 let Some(tokens) = parse_json_pointer(pointer) else {
2190 return Err(CapabilityGrammarError::new(field, pointer));
2191 };
2192 if tokens.first().is_some_and(|token| token == "capabilities") {
2193 return Err(CapabilityGrammarError::new(field, pointer));
2194 }
2195 }
2196 Ok(())
2197}
2198
2199fn parse_json_pointer(pointer: &str) -> Option<Vec<String>> {
2200 if pointer.is_empty() {
2201 return Some(Vec::new());
2202 }
2203 let raw_tokens = pointer.strip_prefix('/')?;
2204 raw_tokens
2205 .split('/')
2206 .map(unescape_json_pointer_token)
2207 .collect()
2208}
2209
2210fn unescape_json_pointer_token(token: &str) -> Option<String> {
2211 let mut output = String::with_capacity(token.len());
2212 let mut characters = token.chars();
2213 while let Some(character) = characters.next() {
2214 if character != '~' {
2215 output.push(character);
2216 continue;
2217 }
2218 match characters.next()? {
2219 '0' => output.push('~'),
2220 '1' => output.push('/'),
2221 _ => return None,
2222 }
2223 }
2224 Some(output)
2225}
2226
2227fn field_child(parent: &str, child: &str) -> String {
2228 let child = safe_error_value(child);
2229 format!("{parent}.{child}")
2230}
2231
2232fn value_description(value: &Value) -> String {
2233 match value {
2234 Value::String(value) => safe_error_value(value),
2235 Value::Null => "null".to_string(),
2236 Value::Bool(value) => value.to_string(),
2237 Value::Number(value) => value.to_string(),
2238 Value::Array(_) => "<array>".to_string(),
2239 Value::Object(_) => "<object>".to_string(),
2240 }
2241}
2242
2243fn safe_error_value(value: &str) -> String {
2244 let lower = value.to_ascii_lowercase();
2245 if ["secret", "password", "api_key"]
2246 .iter()
2247 .any(|marker| lower.contains(marker))
2248 || lower.starts_with("sk-")
2249 || lower.starts_with("akia")
2250 || lower.starts_with("bearer ")
2251 || lower.starts_with("token=")
2252 || lower.starts_with("credential=")
2253 {
2254 "<redacted>".to_string()
2255 } else {
2256 value.to_string()
2257 }
2258}
2259
2260#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2266#[serde(rename_all = "snake_case")]
2267pub enum TrustTier {
2268 FirstParty,
2269 Reviewed,
2270 Untrusted,
2271}
2272
2273#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2277#[serde(tag = "role", rename_all = "snake_case")]
2278pub enum ProviderRole {
2279 ToolProvider {
2280 tools: Vec<Tool>,
2281 identity_scope: Vec<IdentityScope>,
2289 concurrency: Concurrency,
2290 emits_push: bool,
2291 sub_supervises: bool,
2292 },
2293 PipelineStage {
2294 stage: PipelineStageKind,
2295 applies_to: PipelineAppliesTo,
2296 interface: String,
2297 declares_frozen_floor: bool,
2298 needs_signals: Vec<String>,
2299 conformance_class: String,
2300 },
2301 ManagementSurface {
2302 operations: Vec<ManagementOperation>,
2303 config_schema: Value,
2304 observability: Vec<ObservabilitySurface>,
2305 identity_scope: Vec<IdentityScope>,
2309 #[serde(default)]
2310 concurrency: Concurrency,
2311 },
2312 InternalService {
2313 service_id: String,
2314 transport: InternalTransport,
2315 agent_facing: bool,
2316 operations: Vec<String>,
2317 },
2318}
2319
2320#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2333#[serde(rename_all = "snake_case")]
2334pub enum ExecutionMode {
2335 Pure,
2336 Mutating,
2337 Unfenceable,
2338}
2339
2340#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2342pub struct Tool {
2343 pub name: String,
2344 #[serde(default, skip_serializing_if = "Option::is_none")]
2345 pub description: Option<String>,
2346 pub execution_mode: ExecutionMode,
2351 pub schema: Value,
2352}
2353
2354#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2360#[serde(rename_all = "snake_case")]
2361pub enum Concurrency {
2362 Serial,
2364 ModuleManaged,
2367 StatelessParallel,
2370}
2371
2372#[allow(clippy::derivable_impls)]
2373impl Default for Concurrency {
2384 fn default() -> Self {
2385 Self::ModuleManaged
2386 }
2387}
2388
2389#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2396#[serde(rename_all = "snake_case")]
2397pub enum IdentityScope {
2398 Session,
2399 Project,
2400}
2401
2402#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2404#[serde(rename_all = "snake_case")]
2405pub enum PipelineStageKind {
2406 Transform,
2407 Codec,
2408 Auth,
2409}
2410
2411#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2413pub struct PipelineAppliesTo {
2414 pub provider: String,
2415 pub model: String,
2416}
2417
2418#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2421#[non_exhaustive]
2422pub struct OperationPayload {
2423 max_bytes: usize,
2424}
2425
2426impl OperationPayload {
2427 pub fn new(max_bytes: usize) -> Self {
2428 Self { max_bytes }
2429 }
2430
2431 pub fn max_bytes(&self) -> usize {
2432 self.max_bytes
2433 }
2434}
2435
2436#[derive(Debug, Clone, PartialEq, Eq)]
2438#[non_exhaustive]
2439pub enum OperationPayloadError {
2440 UnknownOperation { operation: String },
2441 WatchOperation { operation: String },
2442 InvalidMaxBytes { operation: String },
2443}
2444
2445impl fmt::Display for OperationPayloadError {
2446 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2447 write!(f, "{self:?}")
2448 }
2449}
2450
2451impl std::error::Error for OperationPayloadError {}
2452
2453impl ModuleManifest {
2454 pub fn validate_operation_payload(&self) -> Result<(), OperationPayloadError> {
2457 for (name, payload) in &self.operation_payload {
2458 if !self.provides.iter().any(|role| match role {
2459 ProviderRole::ManagementSurface { operations, .. } => {
2460 operations.iter().any(|op| op.name == *name)
2461 }
2462 _ => false,
2463 }) {
2464 return Err(OperationPayloadError::UnknownOperation {
2465 operation: name.clone(),
2466 });
2467 }
2468 if self
2469 .operation_delivery
2470 .get(name)
2471 .is_some_and(OperationDelivery::is_watch)
2472 {
2473 return Err(OperationPayloadError::WatchOperation {
2474 operation: name.clone(),
2475 });
2476 }
2477 if !(1..=crate::framed_body::MAX_DECLARED_PAYLOAD_BYTES).contains(&payload.max_bytes) {
2478 return Err(OperationPayloadError::InvalidMaxBytes {
2479 operation: name.clone(),
2480 });
2481 }
2482 }
2483 Ok(())
2484 }
2485}
2486
2487#[derive(Debug, Clone, PartialEq, Eq)]
2492#[non_exhaustive]
2493pub enum FlowOperationsError {
2494 FlowScopesNotDeclared,
2497 NotAList,
2499 TooMany { count: usize },
2501 DuplicateOperation { operation: String },
2503 UnknownOperation { operation: String },
2505}
2506
2507impl fmt::Display for FlowOperationsError {
2508 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2509 match self {
2510 Self::FlowScopesNotDeclared => write!(
2511 f,
2512 "flow_operations requires '{}' or '{}' in capabilities.provides",
2513 crate::scope::FLOW_SCOPES_CAPABILITY,
2514 crate::call_mode::CALL_MODES_CAPABILITY
2515 ),
2516 Self::NotAList => f.write_str("flow_operations must be an array of operation names"),
2517 Self::TooMany { count } => write!(
2518 f,
2519 "flow_operations lists {count} names, more than {MAX_FLOW_OPERATIONS}"
2520 ),
2521 Self::DuplicateOperation { operation } => {
2522 write!(f, "flow_operations names '{operation}' more than once")
2523 }
2524 Self::UnknownOperation { operation } => write!(
2525 f,
2526 "flow_operations names '{operation}', which is not a declared management operation"
2527 ),
2528 }
2529 }
2530}
2531
2532impl std::error::Error for FlowOperationsError {}
2533
2534impl ModuleManifest {
2535 pub fn validate_flow_operations(&self) -> Result<(), FlowOperationsError> {
2540 match &self.flow_operations {
2541 Some(operations) => check_flow_operations(self, operations),
2542 None => Ok(()),
2543 }
2544 }
2545}
2546
2547fn check_flow_operations(
2548 manifest: &ModuleManifest,
2549 operations: &[String],
2550) -> Result<(), FlowOperationsError> {
2551 let admits_flows = manifest.capabilities.as_ref().is_some_and(|capabilities| {
2552 capabilities.provides.iter().any(|capability| {
2553 capability == crate::scope::FLOW_SCOPES_CAPABILITY
2554 || capability == crate::call_mode::CALL_MODES_CAPABILITY
2555 })
2556 });
2557 if !admits_flows {
2558 return Err(FlowOperationsError::FlowScopesNotDeclared);
2559 }
2560 if operations.len() > MAX_FLOW_OPERATIONS {
2561 return Err(FlowOperationsError::TooMany {
2562 count: operations.len(),
2563 });
2564 }
2565 let mut seen = HashSet::new();
2566 for operation in operations {
2567 if !seen.insert(operation.as_str()) {
2568 return Err(FlowOperationsError::DuplicateOperation {
2569 operation: operation.clone(),
2570 });
2571 }
2572 let declared = manifest.provides.iter().any(|role| match role {
2573 ProviderRole::ManagementSurface { operations, .. } => {
2574 operations.iter().any(|op| op.name == *operation)
2575 }
2576 _ => false,
2577 });
2578 if !declared {
2579 return Err(FlowOperationsError::UnknownOperation {
2580 operation: operation.clone(),
2581 });
2582 }
2583 }
2584 Ok(())
2585}
2586
2587fn decode_flow_operations(
2590 manifest: &ModuleManifest,
2591 value: &Value,
2592) -> Result<Vec<String>, FlowOperationsError> {
2593 let operations: Vec<String> =
2594 serde_json::from_value(value.clone()).map_err(|_| FlowOperationsError::NotAList)?;
2595 check_flow_operations(manifest, &operations)?;
2596 Ok(operations)
2597}
2598
2599pub fn validate_hello_flow_operations(hello: &Value) -> Result<(), FlowOperationsError> {
2605 let Some(manifest_value) = hello.get("manifest") else {
2606 return Ok(());
2607 };
2608 let Some(value) = manifest_value
2609 .get("flow_operations")
2610 .filter(|value| !value.is_null())
2611 else {
2612 return Ok(());
2613 };
2614 let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
2615 return Ok(());
2616 };
2617 decode_flow_operations(&manifest, value).map(|_| ())
2618}
2619
2620#[derive(Debug, Clone, PartialEq, Eq)]
2625#[non_exhaustive]
2626pub enum ConfirmOperationsError {
2627 NotAList,
2629 TooMany { count: usize },
2631 DuplicateOperation { operation: String },
2633 UnknownOperation { operation: String },
2635}
2636
2637impl fmt::Display for ConfirmOperationsError {
2638 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2639 match self {
2640 Self::NotAList => {
2641 f.write_str("confirm_operations must be an array of operation names")
2642 }
2643 Self::TooMany { count } => write!(
2644 f,
2645 "confirm_operations lists {count} names, more than {MAX_CONFIRM_OPERATIONS}"
2646 ),
2647 Self::DuplicateOperation { operation } => {
2648 write!(f, "confirm_operations names '{operation}' more than once")
2649 }
2650 Self::UnknownOperation { operation } => write!(
2651 f,
2652 "confirm_operations names '{operation}', which is not a declared management operation"
2653 ),
2654 }
2655 }
2656}
2657
2658impl std::error::Error for ConfirmOperationsError {}
2659
2660impl ModuleManifest {
2661 pub fn validate_confirm_operations(&self) -> Result<(), ConfirmOperationsError> {
2665 match &self.confirm_operations {
2666 Some(operations) => check_confirm_operations(self, operations),
2667 None => Ok(()),
2668 }
2669 }
2670}
2671
2672fn check_confirm_operations(
2673 manifest: &ModuleManifest,
2674 operations: &[String],
2675) -> Result<(), ConfirmOperationsError> {
2676 if operations.len() > MAX_CONFIRM_OPERATIONS {
2677 return Err(ConfirmOperationsError::TooMany {
2678 count: operations.len(),
2679 });
2680 }
2681 let mut seen = HashSet::new();
2682 for operation in operations {
2683 if !seen.insert(operation.as_str()) {
2684 return Err(ConfirmOperationsError::DuplicateOperation {
2685 operation: operation.clone(),
2686 });
2687 }
2688 if !declares_management_operation(manifest, operation) {
2689 return Err(ConfirmOperationsError::UnknownOperation {
2690 operation: operation.clone(),
2691 });
2692 }
2693 }
2694 Ok(())
2695}
2696
2697fn declares_management_operation(manifest: &ModuleManifest, operation: &str) -> bool {
2698 manifest.provides.iter().any(|role| match role {
2699 ProviderRole::ManagementSurface { operations, .. } => {
2700 operations.iter().any(|op| op.name == operation)
2701 }
2702 _ => false,
2703 })
2704}
2705
2706fn decode_confirm_operations(
2709 manifest: &ModuleManifest,
2710 value: &Value,
2711) -> Result<Vec<String>, ConfirmOperationsError> {
2712 let operations: Vec<String> =
2713 serde_json::from_value(value.clone()).map_err(|_| ConfirmOperationsError::NotAList)?;
2714 check_confirm_operations(manifest, &operations)?;
2715 Ok(operations)
2716}
2717
2718pub fn validate_hello_confirm_operations(hello: &Value) -> Result<(), ConfirmOperationsError> {
2724 let Some(manifest_value) = hello.get("manifest") else {
2725 return Ok(());
2726 };
2727 let Some(value) = manifest_value
2728 .get("confirm_operations")
2729 .filter(|value| !value.is_null())
2730 else {
2731 return Ok(());
2732 };
2733 let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
2734 return Ok(());
2735 };
2736 decode_confirm_operations(&manifest, value).map(|_| ())
2737}
2738
2739#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2744pub struct ManagementOperation {
2745 pub name: String,
2746 pub kind: ManagementOperationKind,
2747 #[serde(default, skip_serializing_if = "Option::is_none")]
2748 pub description: Option<String>,
2749}
2750
2751#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2752#[serde(rename_all = "snake_case")]
2753pub enum ManagementOperationKind {
2754 Query,
2755 Mutate,
2756}
2757
2758#[derive(Debug, Clone, PartialEq, Eq)]
2761#[non_exhaustive]
2762pub enum OperationDelivery {
2763 Watch,
2764 Other(String),
2765}
2766
2767impl OperationDelivery {
2768 pub const WATCH: Self = Self::Watch;
2770
2771 pub fn wire_name(&self) -> &str {
2773 match self {
2774 Self::Watch => "watch",
2775 Self::Other(value) => value,
2776 }
2777 }
2778
2779 pub fn is_watch(&self) -> bool {
2781 self.wire_name() == "watch"
2782 }
2783}
2784
2785impl Serialize for OperationDelivery {
2786 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2787 where
2788 S: serde::Serializer,
2789 {
2790 serializer.serialize_str(self.wire_name())
2791 }
2792}
2793
2794impl<'de> Deserialize<'de> for OperationDelivery {
2795 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2796 where
2797 D: Deserializer<'de>,
2798 {
2799 let value = String::deserialize(deserializer)?;
2800 Ok(if value == "watch" {
2801 Self::WATCH
2802 } else {
2803 Self::Other(value)
2804 })
2805 }
2806}
2807
2808#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2810pub struct ObservabilitySurface {
2811 pub name: String,
2812 pub kind: ObservabilityKind,
2813}
2814
2815#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2816#[serde(rename_all = "snake_case")]
2817pub enum ObservabilityKind {
2818 Snapshot,
2819 Stream,
2820}
2821
2822#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2823#[serde(rename_all = "snake_case")]
2824pub enum InternalTransport {
2825 Bulk,
2826}
2827
2828#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2830#[serde(tag = "role", rename_all = "snake_case")]
2831pub enum ConsumerRole {
2832 ToolClient { of: Vec<String> },
2833 LlmClient { via: String, auth: String },
2834 ServiceClient { of: Vec<String> },
2835}
2836
2837#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2839pub struct Bindings {
2840 pub storage: StorageBinding,
2841 pub vault_grants: Vec<VaultGrant>,
2842 pub identity: IdentityBinding,
2843}
2844
2845#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2847pub struct StorageBinding {
2848 pub kind: StorageKind,
2849 pub scope: StorageScope,
2850 pub owns_schema: bool,
2851}
2852
2853#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2854#[serde(rename_all = "snake_case")]
2855pub enum StorageKind {
2856 Sqlite,
2857}
2858
2859#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2860#[serde(rename_all = "snake_case")]
2861pub enum StorageScope {
2862 Project,
2863}
2864
2865#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2866pub struct VaultGrant {
2867 pub secret: String,
2868 pub reason: String,
2869}
2870
2871#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2872pub struct IdentityBinding {
2873 pub requires: Vec<IdentityScope>,
2874 pub optional: Vec<IdentityScope>,
2875}
2876
2877#[cfg(test)]
2878mod tests {
2879 use super::*;
2880 use serde_json::json;
2881
2882 fn aft_manifest_fixture() -> ModuleManifest {
2883 ModuleManifest::builder("aft", "0.39.2")
2884 .trust_tier(Some(TrustTier::FirstParty))
2885 .bindings(Some(Bindings {
2886 storage: StorageBinding {
2887 kind: StorageKind::Sqlite,
2888 scope: StorageScope::Project,
2889 owns_schema: true,
2890 },
2891 vault_grants: vec![VaultGrant {
2892 secret: "provider_api_key".to_string(),
2893 reason: "cortexkit_native auth".to_string(),
2894 }],
2895 identity: IdentityBinding {
2896 requires: vec![IdentityScope::Project],
2897 optional: vec![IdentityScope::Session],
2898 },
2899 }))
2900 .protocol_ver(1)
2901 .provides(vec![ProviderRole::ToolProvider {
2902 tools: vec![
2903 Tool {
2904 name: "read".to_string(),
2905 description: None,
2906 execution_mode: ExecutionMode::Pure,
2907 schema: json!({"type": "object"}),
2908 },
2909 Tool {
2910 name: "grep".to_string(),
2911 description: None,
2912 execution_mode: ExecutionMode::Pure,
2913 schema: json!({"type": "object"}),
2914 },
2915 Tool {
2916 name: "outline".to_string(),
2917 description: None,
2918 execution_mode: ExecutionMode::Pure,
2919 schema: json!({"type": "object"}),
2920 },
2921 Tool {
2922 name: "semantic_search".to_string(),
2923 description: None,
2924 execution_mode: ExecutionMode::Pure,
2925 schema: json!({"type": "object"}),
2926 },
2927 Tool {
2928 name: "edit".to_string(),
2929 description: None,
2930 execution_mode: ExecutionMode::Mutating,
2931 schema: json!({"type": "object"}),
2932 },
2933 Tool {
2934 name: "write".to_string(),
2935 description: None,
2936 execution_mode: ExecutionMode::Mutating,
2937 schema: json!({"type": "object"}),
2938 },
2939 Tool {
2940 name: "bash".to_string(),
2941 description: None,
2942 execution_mode: ExecutionMode::Unfenceable,
2943 schema: json!({"type": "object"}),
2944 },
2945 ],
2946 identity_scope: vec![IdentityScope::Session, IdentityScope::Project],
2947 concurrency: Concurrency::ModuleManaged,
2948 emits_push: true,
2949 sub_supervises: true,
2950 }])
2951 .consumes(vec![ConsumerRole::ServiceClient {
2952 of: vec!["embedding.v2".to_string()],
2953 }])
2954 .build()
2955 }
2956
2957 #[test]
2958 fn serde_round_trips_representative_manifest() {
2959 let manifest = aft_manifest_fixture();
2960 let serialized = serde_json::to_string_pretty(&manifest).unwrap();
2961 let decoded: ModuleManifest = serde_json::from_str(&serialized).unwrap();
2962
2963 assert_eq!(manifest, decoded);
2964 }
2965
2966 #[test]
2967 fn builder_defaults_additions_to_honest_absence_and_round_trips() {
2968 let manifest = ModuleManifest::builder("builder-defaults", "2.0.0").build();
2969
2970 assert_eq!(manifest.module_id, "builder-defaults");
2971 assert_eq!(manifest.module_version, "2.0.0");
2972 assert_eq!(manifest.display_name, None);
2973 assert_eq!(manifest.protocol_ver, PROTOCOL_VERSION);
2974 assert_eq!(manifest.trust_tier, None);
2975 assert!(manifest.provides.is_empty());
2976 assert!(manifest.consumes.is_empty());
2977 assert_eq!(manifest.bindings, None);
2978 assert_eq!(manifest.capabilities, None);
2979 assert_eq!(manifest.self_signals, None);
2980 assert_eq!(manifest.provenance, None);
2981
2982 let encoded = serde_json::to_value(&manifest).expect("builder manifest serializes");
2983 for optional in [
2984 "display_name",
2985 "trust_tier",
2986 "consumes",
2987 "bindings",
2988 "capabilities",
2989 "self_signals",
2990 "provenance",
2991 ] {
2992 assert!(
2993 encoded.get(optional).is_none(),
2994 "an absent {optional} declaration must stay absent on the wire"
2995 );
2996 }
2997 let decoded: ModuleManifest =
2998 serde_json::from_value(encoded).expect("builder manifest round-trips");
2999 assert_eq!(decoded, manifest);
3000 }
3001
3002 #[test]
3003 fn fully_populated_builder_manifest_matches_the_literal_wire_golden() {
3004 let manifest = ModuleManifest::builder("full-builder", "2.0.0")
3005 .display_name(Some("Example".to_string()))
3006 .unwrap()
3007 .trust_tier(Some(TrustTier::Reviewed))
3008 .bindings(Some(Bindings {
3009 storage: StorageBinding {
3010 kind: StorageKind::Sqlite,
3011 scope: StorageScope::Project,
3012 owns_schema: false,
3013 },
3014 vault_grants: Vec::new(),
3015 identity: IdentityBinding {
3016 requires: vec![IdentityScope::Project],
3017 optional: Vec::new(),
3018 },
3019 }))
3020 .provides(vec![ProviderRole::ToolProvider {
3021 tools: vec![Tool {
3022 name: "read".to_string(),
3023 description: None,
3024 execution_mode: ExecutionMode::Pure,
3025 schema: json!({"type": "object"}),
3026 }],
3027 identity_scope: vec![IdentityScope::Project],
3028 concurrency: Concurrency::Serial,
3029 emits_push: false,
3030 sub_supervises: false,
3031 }])
3032 .consumes(vec![ConsumerRole::ServiceClient {
3033 of: vec!["embedding.v2".to_string()],
3034 }])
3035 .capabilities(Some(CapabilityDeclarations {
3036 provides: vec!["embedding/v2".to_string()],
3037 requires: Vec::new(),
3038 must_never_reach: Vec::new(),
3039 }))
3040 .self_signals(Some(vec![SelfSignalDeclaration {
3041 name: "usage_poller".to_string(),
3042 kind: SelfSignalKind::Poller,
3043 effect: SelfSignalEffect::Observe,
3044 anchored_to: SignalAnchor::FixedInterval,
3045 cadence: Some(SignalCadence::Literal {
3046 interval_ms: 60_000,
3047 }),
3048 domain: Some("provider-usage".to_string()),
3049 note: None,
3050 }]))
3051 .provenance(Some(ManifestProvenance {
3052 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
3053 build_git_sha_absence_reason: None,
3054 build_lock_digest: Some(
3055 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
3056 ),
3057 wire_crate_version: Some("0.16.0".to_string()),
3058 store_schema_version: Some("42".to_string()),
3059 launch_nonce_source: None,
3060 }))
3061 .build();
3062
3063 assert_eq!(
3064 serde_json::to_vec(&manifest).expect("builder manifest serializes"),
3065 include_bytes!("../tests/golden/module_manifest_builder_full.json"),
3066 "the builder must match the fully populated manifest wire bytes"
3067 );
3068 }
3069
3070 #[test]
3071 fn display_name_validator_enforces_scalar_bounds_and_safe_text() {
3072 for valid in [
3073 "Routing".to_string(),
3074 "名".repeat(40),
3075 "a".repeat(40),
3076 "e\u{301}".repeat(20),
3077 ] {
3078 assert!(validate_display_name(&valid).is_ok(), "{valid:?}");
3079 }
3080 let mut invalid = vec![
3081 "".to_string(),
3082 "a".repeat(41),
3083 "名".repeat(41),
3084 " Routing".to_string(),
3085 "Routing ".to_string(),
3086 "\u{2003}Routing".to_string(),
3087 "a\nb".to_string(),
3088 "a\u{0085}b".to_string(),
3089 "a\u{007f}b".to_string(),
3090 ];
3091 for code in [0x061c, 0x200e, 0x200f]
3092 .into_iter()
3093 .chain(0x202a..=0x202e)
3094 .chain(0x2066..=0x2069)
3095 {
3096 invalid.push(format!("a{}b", char::from_u32(code).unwrap()));
3097 }
3098 let accepted: Vec<_> = invalid
3099 .iter()
3100 .filter(|value| validate_display_name(value).is_ok())
3101 .collect();
3102 assert!(
3103 accepted.is_empty(),
3104 "invalid display names accepted: {accepted:?}"
3105 );
3106 }
3107
3108 #[test]
3109 fn display_name_builder_refuses_invalid_value() {
3110 let error = ModuleManifest::builder("provider", "1.0.0")
3111 .display_name(Some(" Routing".to_string()))
3112 .unwrap_err();
3113 assert!(error.to_string().contains("display_name"));
3114 }
3115
3116 #[test]
3117 fn display_name_manifest_round_trips_and_keeps_unknown_fields_lenient() {
3118 let manifest = ModuleManifest::builder("provider", "1.0.0")
3119 .display_name(Some("Routing".to_string()))
3120 .unwrap()
3121 .build();
3122 let mut wire = serde_json::to_value(&manifest).unwrap();
3123 assert_eq!(wire["display_name"], "Routing");
3124 wire["future_manifest_field"] = json!(true);
3125 assert_eq!(
3126 serde_json::from_value::<ModuleManifest>(wire.clone()).unwrap(),
3127 manifest
3128 );
3129 wire["display_name"] = json!("bad\nname");
3130 assert!(serde_json::from_value::<ModuleManifest>(wire)
3131 .unwrap_err()
3132 .to_string()
3133 .contains("display_name"));
3134 }
3135
3136 #[test]
3137 fn old_manifest_with_unread_fields_decodes_and_round_trips_verbatim() {
3138 let raw = include_bytes!("../tests/golden/module_manifest_builder_full.json");
3139 let decoded: ModuleManifest =
3140 serde_json::from_slice(raw).expect("old manifest with all unread fields decodes");
3141
3142 assert_eq!(decoded.trust_tier, Some(TrustTier::Reviewed));
3143 assert!(!decoded.consumes.is_empty());
3144 assert!(decoded.bindings.is_some());
3145
3146 let reencoded = serde_json::to_vec(&decoded).expect("re-encode succeeds");
3147 assert_eq!(
3148 reencoded, raw,
3149 "old manifest relay stays byte-for-byte verbatim"
3150 );
3151 }
3152
3153 #[test]
3154 fn new_manifest_omits_unread_fields_on_wire_and_decodes_cleanly() {
3155 let raw = include_bytes!("../tests/golden/module_manifest_diet.json");
3156 let decoded: ModuleManifest =
3157 serde_json::from_slice(raw).expect("new manifest omitting unread fields decodes");
3158
3159 assert_eq!(decoded.trust_tier, None);
3160 assert!(decoded.consumes.is_empty());
3161 assert_eq!(decoded.bindings, None);
3162
3163 let pretty = format!("{}\n", serde_json::to_string_pretty(&decoded).unwrap());
3164 assert_eq!(
3165 pretty.as_bytes(),
3166 raw,
3167 "new manifest matches golden byte-for-byte without unread keys"
3168 );
3169
3170 let as_val: serde_json::Value = serde_json::to_value(&decoded).unwrap();
3171 assert!(
3172 as_val.get("trust_tier").is_none(),
3173 "no trust_tier on wire for new manifest"
3174 );
3175 assert!(
3176 as_val.get("consumes").is_none(),
3177 "no consumes on wire for empty consumes"
3178 );
3179 assert!(
3180 as_val.get("bindings").is_none(),
3181 "no bindings on wire for new manifest"
3182 );
3183 }
3184
3185 #[test]
3186 fn aft_manifest_fixture_matches_v1_contract() {
3187 let manifest = aft_manifest_fixture();
3188
3189 assert_eq!(manifest.module_id, "aft");
3190 let ProviderRole::ToolProvider {
3191 tools,
3192 identity_scope,
3193 concurrency,
3194 emits_push,
3195 sub_supervises,
3196 } = &manifest.provides[0]
3197 else {
3198 panic!("AFT fixture must expose one tool_provider role");
3199 };
3200
3201 assert_eq!(*concurrency, Concurrency::ModuleManaged);
3202 assert!(*emits_push);
3203 assert!(*sub_supervises);
3204 assert_eq!(
3205 identity_scope,
3206 &vec![IdentityScope::Session, IdentityScope::Project]
3207 );
3208 assert_eq!(
3209 tools
3210 .iter()
3211 .map(|tool| (tool.name.as_str(), tool.execution_mode))
3212 .collect::<Vec<_>>(),
3213 vec![
3214 ("read", ExecutionMode::Pure),
3215 ("grep", ExecutionMode::Pure),
3216 ("outline", ExecutionMode::Pure),
3217 ("semantic_search", ExecutionMode::Pure),
3218 ("edit", ExecutionMode::Mutating),
3219 ("write", ExecutionMode::Mutating),
3220 ("bash", ExecutionMode::Unfenceable),
3221 ]
3222 );
3223 }
3224
3225 #[test]
3226 fn tool_provider_role_tag_serializes_as_snake_case() {
3227 let manifest = aft_manifest_fixture();
3228 let value = serde_json::to_value(&manifest).unwrap();
3229
3230 assert_eq!(value["provides"][0]["role"], "tool_provider");
3231 }
3232
3233 #[test]
3234 fn manifest_without_capabilities_preserves_the_existing_wire_shape() {
3235 let manifest = aft_manifest_fixture();
3236 let encoded = serde_json::to_value(&manifest).expect("manifest serializes");
3237 assert!(encoded.get("capabilities").is_none());
3238
3239 let decoded: ModuleManifest =
3240 serde_json::from_value(encoded).expect("legacy manifest parses");
3241 assert_eq!(decoded.capabilities, None);
3242 }
3243
3244 #[test]
3245 fn capability_identifier_lexical_grammar_accepts_only_pinned_forms() {
3246 for identifier in [
3247 "a/v1",
3248 "credentials-provider/v1",
3249 "a1-b2/v4294967295",
3250 "a123456789012345678901234567890123456789012345678901234567890123/v1",
3251 ] {
3252 assert!(
3253 is_valid_capability_identifier(identifier),
3254 "identifier must be accepted: {identifier}"
3255 );
3256 }
3257
3258 for identifier in [
3259 "credentials-Provider/v1",
3260 "credentials-provider/v01",
3261 "credentials-provider-/v1",
3262 "credentials--provider/v1",
3263 "Credentials-provider/v1",
3264 "credentials-provider/1",
3265 "credentials provider/v1",
3266 "credentials-provider/v0",
3267 "credentials-provider/v4294967296",
3268 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/v1",
3269 ] {
3270 assert!(
3271 !is_valid_capability_identifier(identifier),
3272 "identifier must be rejected: {identifier}"
3273 );
3274 }
3275 }
3276
3277 #[test]
3278 fn capability_grammar_errors_redact_secret_shaped_values() {
3279 let error = validate_manifest_capability_grammar(&json!({
3280 "capabilities": { "provides": ["sk-secret-value/v0"] }
3281 }))
3282 .expect_err("secret-shaped capability identifier is malformed");
3283 assert_eq!(error.field(), "capabilities.provides[0]");
3284 assert_eq!(error.value(), "<redacted>");
3285 assert!(!error.to_string().contains("sk-secret-value"));
3286 }
3287
3288 #[test]
3295 fn provenance_builder_sentinels_become_field_omission() {
3296 for sentinel in [
3297 "unknown",
3298 "UNKNOWN",
3299 "Unknown",
3300 "unavailable",
3301 "none",
3302 "None",
3303 " unknown ",
3304 "",
3305 ] {
3306 let p = build_provenance_from_source(
3307 BuildGitShaSource::Git {
3308 revision: sentinel,
3309 tree_state: GitTreeState::Clean,
3310 },
3311 Some(sentinel),
3312 Some(sentinel),
3313 )
3314 .expect("sentinels are omitted before form validation");
3315 assert_eq!(
3316 (
3317 p.build_git_sha,
3318 p.build_git_sha_absence_reason,
3319 p.build_lock_digest,
3320 p.store_schema_version,
3321 ),
3322 (
3323 None,
3324 Some(BuildGitShaAbsenceReason::NeverDerived),
3325 None,
3326 None,
3327 ),
3328 "sentinel {sentinel:?} must be omitted, not published"
3329 );
3330 }
3331 let real = build_provenance_from_source(
3332 BuildGitShaSource::Git {
3333 revision: "0123456789abcdef0123456789abcdef01234567",
3334 tree_state: GitTreeState::Clean,
3335 },
3336 None,
3337 Some("9"),
3338 )
3339 .expect("canonical build revision is accepted");
3340 assert_eq!(
3341 real.build_git_sha.as_deref(),
3342 Some("0123456789abcdef0123456789abcdef01234567")
3343 );
3344 assert_eq!(real.store_schema_version.as_deref(), Some("9"));
3345 assert_eq!(
3349 real.wire_crate_version.as_deref(),
3350 Some(crate::SUBC_PROTOCOL_CRATE_VERSION)
3351 );
3352 }
3353
3354 #[test]
3355 fn build_provenance_accepts_canonical_sha_and_lock_digest() {
3356 let provenance = build_provenance_from_source(
3357 BuildGitShaSource::Git {
3358 revision: " 0123456789abcdef0123456789abcdef01234567 ",
3359 tree_state: GitTreeState::Clean,
3360 },
3361 Some(" abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789 "),
3362 Some(" schema-v3 "),
3363 )
3364 .expect("canonical build facts are accepted");
3365
3366 assert_eq!(
3367 provenance,
3368 ManifestProvenance {
3369 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
3370 build_git_sha_absence_reason: None,
3371 build_lock_digest: Some(
3372 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
3373 ),
3374 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
3375 store_schema_version: Some("schema-v3".to_string()),
3376 launch_nonce_source: None,
3377 }
3378 );
3379 }
3380
3381 #[test]
3382 fn build_provenance_refuses_an_abbreviated_git_sha() {
3383 let error = build_provenance_from_source(
3384 BuildGitShaSource::Git {
3385 revision: "0123456789ab",
3386 tree_state: GitTreeState::Clean,
3387 },
3388 None,
3389 None,
3390 )
3391 .expect_err("a 12-character abbreviation is not canonical");
3392
3393 assert_eq!(error.field(), "build_git_sha");
3394 assert_eq!(error.length(), 12);
3395 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3396 assert_eq!(
3397 error.to_string(),
3398 "invalid manifest provenance form: field build_git_sha has length 12; canonical form is exactly 40 lowercase hexadecimal characters"
3399 );
3400 }
3401
3402 #[test]
3403 fn build_provenance_refuses_an_abbreviated_lock_digest() {
3404 let error = build_provenance_from_source(
3405 BuildGitShaSource::NeverDerived,
3406 Some("0123456789abcdef"),
3407 None,
3408 )
3409 .expect_err("a 16-character digest is not canonical");
3410
3411 assert_eq!(error.field(), "build_lock_digest");
3412 assert_eq!(error.length(), 16);
3413 assert_eq!(error.canonical_form(), BUILD_LOCK_DIGEST_CANONICAL_FORM);
3414 }
3415
3416 #[test]
3417 fn build_provenance_refuses_uppercase_hex() {
3418 let uppercase_sha = "A".repeat(40);
3419 let error = build_provenance_from_source(
3420 BuildGitShaSource::Git {
3421 revision: &uppercase_sha,
3422 tree_state: GitTreeState::Clean,
3423 },
3424 None,
3425 None,
3426 )
3427 .expect_err("uppercase hexadecimal is not canonical");
3428
3429 assert_eq!(error.field(), "build_git_sha");
3430 assert_eq!(error.length(), 40);
3431 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3432 }
3433
3434 #[test]
3435 fn build_provenance_refuses_dirty_revision_stamp_claimed_clean() {
3436 let error = build_provenance_from_source(
3437 BuildGitShaSource::Git {
3438 revision: "0123456789abcdef0123456789abcdef01234567-dirty",
3439 tree_state: GitTreeState::Clean,
3440 },
3441 None,
3442 None,
3443 )
3444 .expect_err("a dirty stamp is not a canonical build revision");
3445
3446 assert_eq!(error.field(), "build_git_sha");
3447 assert_eq!(error.length(), 46);
3448 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3449 }
3450
3451 #[test]
3452 fn build_provenance_keeps_a_lock_digest_when_identity_is_unavailable() {
3453 let provenance = build_provenance_from_source(
3454 BuildGitShaSource::Git {
3455 revision: "unavailable",
3456 tree_state: GitTreeState::Clean,
3457 },
3458 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"),
3459 None,
3460 )
3461 .expect("sentinel SHA is omitted before the valid lock digest is checked");
3462
3463 assert_eq!(provenance.build_git_sha, None);
3464 assert_eq!(
3465 provenance.build_lock_digest,
3466 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string())
3467 );
3468 assert_eq!(
3469 provenance.wire_crate_version,
3470 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
3471 );
3472 }
3473
3474 #[test]
3475 fn build_provenance_omits_fully_unavailable_inputs() {
3476 let provenance = build_provenance_from_source(
3477 BuildGitShaSource::NeverDerived,
3478 Some(" unavailable "),
3479 Some(" "),
3480 )
3481 .expect("omitted and sentinel inputs are not form errors");
3482
3483 assert_eq!(provenance.build_git_sha, None);
3484 assert_eq!(provenance.build_lock_digest, None);
3485 assert_eq!(provenance.store_schema_version, None);
3486 assert_eq!(
3487 provenance.wire_crate_version,
3488 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
3489 );
3490 }
3491
3492 #[test]
3493 fn legacy_build_provenance_keeps_master_wire_bytes_without_an_absence_reason() {
3494 let revision = "0123456789abcdef0123456789abcdef01234567";
3495 for (input, expected) in [
3496 (
3497 Some(revision),
3498 format!(
3499 r#"{{"build_git_sha":"{revision}","wire_crate_version":"{}"}}"#,
3500 crate::SUBC_PROTOCOL_CRATE_VERSION
3501 ),
3502 ),
3503 (
3504 None,
3505 format!(
3506 r#"{{"wire_crate_version":"{}"}}"#,
3507 crate::SUBC_PROTOCOL_CRATE_VERSION
3508 ),
3509 ),
3510 (
3511 Some("unknown"),
3512 format!(
3513 r#"{{"wire_crate_version":"{}"}}"#,
3514 crate::SUBC_PROTOCOL_CRATE_VERSION
3515 ),
3516 ),
3517 ] {
3518 let provenance = build_provenance(input, None, None)
3519 .expect("the legacy build facts remain constructible");
3520 assert_eq!(provenance.build_git_sha_absence_reason, None);
3521 assert_eq!(
3522 serde_json::to_string(&provenance).expect("legacy provenance serializes"),
3523 expected
3524 );
3525 }
3526 }
3527
3528 #[test]
3529 fn build_provenance_derives_git_sha_absence_from_the_stamping_inputs() {
3530 let revision = "0123456789abcdef0123456789abcdef01234567";
3531 let cases = [
3532 (
3533 BuildGitShaSource::Git {
3534 revision,
3535 tree_state: GitTreeState::Clean,
3536 },
3537 Some(revision),
3538 None,
3539 ),
3540 (
3541 BuildGitShaSource::Git {
3542 revision,
3543 tree_state: GitTreeState::Dirty,
3544 },
3545 None,
3546 Some(BuildGitShaAbsenceReason::DeclinedDirty),
3547 ),
3548 (
3549 BuildGitShaSource::NeverDerived,
3550 None,
3551 Some(BuildGitShaAbsenceReason::NeverDerived),
3552 ),
3553 (
3554 BuildGitShaSource::NoGitDir,
3555 None,
3556 Some(BuildGitShaAbsenceReason::NoGitDir),
3557 ),
3558 ];
3559
3560 for (source, expected_sha, expected_reason) in cases {
3561 let provenance = build_provenance_from_source(source, None, None)
3562 .expect("every stamping state constructs honest provenance");
3563 assert_eq!(provenance.build_git_sha.as_deref(), expected_sha);
3564 assert_eq!(provenance.build_git_sha_absence_reason, expected_reason);
3565 }
3566 }
3567
3568 #[test]
3569 fn unknown_git_sha_absence_reason_round_trips_byte_faithfully() {
3570 let wire = format!(
3571 r#"{{"build_git_sha_absence_reason":"future_stamper_state","wire_crate_version":"{}"}}"#,
3572 crate::SUBC_PROTOCOL_CRATE_VERSION
3573 );
3574 let provenance: ManifestProvenance =
3575 serde_json::from_str(&wire).expect("future absence reasons remain readable");
3576
3577 assert_eq!(
3578 provenance.build_git_sha_absence_reason,
3579 Some(BuildGitShaAbsenceReason::ForwardCompatibleUnknown(
3580 "future_stamper_state".to_string()
3581 ))
3582 );
3583 assert_eq!(
3584 serde_json::to_string(&provenance).expect("future absence reason reserializes"),
3585 wire
3586 );
3587 }
3588
3589 #[test]
3590 fn provenance_rejects_an_absence_reason_beside_a_declared_commit() {
3591 let error = serde_json::from_value::<ManifestProvenance>(json!({
3592 "build_git_sha": "0123456789abcdef0123456789abcdef01234567",
3593 "build_git_sha_absence_reason": "declined_dirty"
3594 }))
3595 .expect_err("a declared commit cannot also claim an absence reason");
3596
3597 assert!(error.to_string().contains(
3598 "build_git_sha_absence_reason has must be omitted when build_git_sha is present"
3599 ));
3600 }
3601
3602 #[test]
3603 fn rich_ui_descriptor_is_optional_and_round_trips_when_present() {
3604 let manifest = ModuleManifest::builder("provider", "1.0.0").build();
3605 assert_eq!(
3606 serde_json::to_string(&manifest).unwrap(),
3607 r#"{"module_id":"provider","module_version":"1.0.0","protocol_ver":2,"provides":[]}"#
3608 );
3609
3610 let descriptor = RichUiDescriptor::new(
3611 "ckios.richui.manifest/1",
3612 format!("sha256:{}", "a".repeat(64)),
3613 128,
3614 2,
3615 );
3616 let manifest = ModuleManifest::builder("provider", "1.0.0")
3617 .rich_ui(Some(descriptor.clone()))
3618 .build();
3619 let wire = serde_json::to_string(&manifest).unwrap();
3620 assert!(wire.contains("\"rich_ui\":{\"schema\":\"ckios.richui.manifest/1\""));
3621 assert_eq!(
3622 serde_json::from_str::<ModuleManifest>(&wire)
3623 .unwrap()
3624 .rich_ui,
3625 Some(descriptor)
3626 );
3627 }
3628
3629 #[test]
3630 fn rich_ui_descriptor_validation_names_each_invalid_field() {
3631 let good = json!({
3632 "schema": "ckios.richui.manifest/1",
3633 "manifest_digest": format!("sha256:{}", "a".repeat(64)),
3634 "bytes": 1,
3635 "chunks": 1
3636 });
3637 let hello = json!({"manifest": {"rich_ui": good.clone()}});
3638 assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
3639
3640 for (field, value) in [
3641 ("schema", json!("bad schema")),
3642 (
3643 "manifest_digest",
3644 json!(format!("sha256:{}", "A".repeat(64))),
3645 ),
3646 ("bytes", json!(0)),
3647 ("chunks", json!(1025)),
3648 ] {
3649 let mut invalid = hello.clone();
3650 invalid["manifest"]["rich_ui"][field] = value;
3651 let error = validate_hello_rich_ui_descriptor(&invalid)
3652 .expect_err("an invalid descriptor field must be refused");
3653 assert_eq!(error.field(), format!("rich_ui.{field}"));
3654 }
3655
3656 let mut hello = hello;
3657 hello["manifest"]["rich_ui"] = Value::Null;
3658 let error = validate_hello_rich_ui_descriptor(&hello)
3659 .expect_err("null is not an absent descriptor");
3660 assert_eq!(error.field(), "rich_ui");
3661 }
3662
3663 #[test]
3664 fn rich_ui_descriptor_validation_accepts_inclusive_bounds() {
3665 let hello = json!({"manifest": {"rich_ui": {
3666 "schema": "a".repeat(64),
3667 "manifest_digest": format!("sha256:{}", "f".repeat(64)),
3668 "bytes": 16_777_216,
3669 "chunks": 1024
3670 }}});
3671 assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
3672 }
3673}