1use std::{
10 collections::{BTreeMap, HashSet},
11 fmt,
12};
13
14use serde::{de::Error as _, Deserialize, Deserializer, Serialize};
15use serde_json::Value;
16
17use crate::provider_declarations::{deserialize_provider_declarations, ProviderDeclarations};
18use crate::PROTOCOL_VERSION;
19
20pub use crate::provider_declarations::{
21 validate_hello_provider_declarations, ProviderDeclarationsError,
22};
23
24pub const MAX_ROLE_DECLARATIONS_BYTES: usize = 16_384;
26
27pub const MAX_FLOW_OPERATIONS: usize = 256;
29
30pub const MAX_CONFIRM_OPERATIONS: usize = 256;
32
33pub const DOCTOR_CAPABILITY: &str = "doctor/v1";
35
36#[derive(Serialize, Debug, Clone, PartialEq)]
43#[non_exhaustive]
44pub struct ModuleManifest {
45 pub module_id: String,
46 #[serde(default, skip_serializing_if = "Option::is_none")]
48 pub display_name: Option<String>,
49 pub module_version: String,
50 pub protocol_ver: u8,
51 #[serde(default, skip_serializing_if = "Option::is_none")]
52 pub trust_tier: Option<TrustTier>,
53 #[serde(default, skip_serializing_if = "Option::is_none")]
60 pub ready: Option<bool>,
61 #[serde(default, skip_serializing_if = "Option::is_none")]
65 pub registration_channel: Option<bool>,
66 pub provides: Vec<ProviderRole>,
69 #[serde(default, skip_serializing_if = "Vec::is_empty")]
70 pub consumes: Vec<ConsumerRole>,
71 #[serde(default, skip_serializing_if = "Option::is_none")]
72 pub bindings: Option<Bindings>,
73 #[serde(default, skip_serializing_if = "Option::is_none")]
79 pub capabilities: Option<CapabilityDeclarations>,
80 #[serde(default, skip_serializing_if = "Option::is_none")]
94 pub events: Option<Vec<EventDeclaration>>,
95 #[serde(default, skip_serializing_if = "Option::is_none")]
130 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
131 #[serde(default, skip_serializing_if = "Option::is_none")]
132 pub provenance: Option<ManifestProvenance>,
133 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
138 pub operation_delivery: BTreeMap<String, OperationDelivery>,
139 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
142 pub operation_payload: BTreeMap<String, OperationPayload>,
143 #[serde(default, skip_serializing_if = "Option::is_none")]
162 pub flow_operations: Option<Vec<String>>,
163 #[serde(default, skip_serializing_if = "Option::is_none")]
167 pub operation_deferral: Option<BTreeMap<String, bool>>,
168 #[serde(default, skip_serializing_if = "Option::is_none")]
185 pub confirm_operations: Option<Vec<String>>,
186 #[serde(default, skip_serializing_if = "Option::is_none")]
191 pub rich_ui: Option<RichUiDescriptor>,
192 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
201 pub role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
202 #[serde(default, skip_serializing_if = "Option::is_none")]
205 pub provider_declarations: Option<ProviderDeclarations>,
206}
207
208#[derive(Debug, Clone)]
210pub struct ModuleManifestBuilder {
211 module_id: String,
212 display_name: Option<String>,
213 module_version: String,
214 protocol_ver: u8,
215 trust_tier: Option<TrustTier>,
216 ready: Option<bool>,
217 registration_channel: Option<bool>,
218 provides: Vec<ProviderRole>,
219 consumes: Vec<ConsumerRole>,
220 bindings: Option<Bindings>,
221 capabilities: Option<CapabilityDeclarations>,
222 events: Option<Vec<EventDeclaration>>,
223 self_signals: Option<Vec<SelfSignalDeclaration>>,
224 provenance: Option<ManifestProvenance>,
225 operation_delivery: BTreeMap<String, OperationDelivery>,
226 operation_payload: BTreeMap<String, OperationPayload>,
227 flow_operations: Option<Vec<String>>,
228 operation_deferral: Option<BTreeMap<String, bool>>,
229 confirm_operations: Option<Vec<String>>,
230 rich_ui: Option<RichUiDescriptor>,
231 role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
232 provider_declarations: Option<ProviderDeclarations>,
233}
234
235impl ModuleManifest {
236 pub fn builder(
244 module_id: impl Into<String>,
245 module_version: impl Into<String>,
246 ) -> ModuleManifestBuilder {
247 ModuleManifestBuilder {
248 module_id: module_id.into(),
249 display_name: None,
250 module_version: module_version.into(),
251 protocol_ver: PROTOCOL_VERSION,
252 trust_tier: None,
253 ready: None,
254 registration_channel: None,
255 provides: Vec::new(),
256 consumes: Vec::new(),
257 bindings: None,
258 capabilities: None,
259 events: None,
260 self_signals: None,
261 provenance: None,
262 operation_delivery: BTreeMap::new(),
263 operation_payload: BTreeMap::new(),
264 flow_operations: None,
265 operation_deferral: None,
266 confirm_operations: None,
267 rich_ui: None,
268 role_declarations: BTreeMap::new(),
269 provider_declarations: None,
270 }
271 }
272
273 pub fn is_watch_operation(&self, name: &str) -> bool {
278 self.operation_delivery
279 .get(name)
280 .is_some_and(OperationDelivery::is_watch)
281 && self.provides.iter().any(|role| match role {
282 ProviderRole::ManagementSurface { operations, .. } => operations
283 .iter()
284 .any(|op| op.name == name && op.kind == ManagementOperationKind::Query),
285 _ => false,
286 })
287 }
288}
289
290impl ModuleManifestBuilder {
291 pub fn display_name(mut self, display_name: Option<String>) -> Result<Self, DisplayNameError> {
293 if let Some(value) = &display_name {
294 validate_display_name(value)?;
295 }
296 self.display_name = display_name;
297 Ok(self)
298 }
299
300 pub fn protocol_ver(mut self, protocol_ver: u8) -> Self {
302 self.protocol_ver = protocol_ver;
303 self
304 }
305
306 pub fn trust_tier(mut self, trust_tier: Option<TrustTier>) -> Self {
310 self.trust_tier = trust_tier;
311 self
312 }
313
314 pub fn ready(mut self, ready: bool) -> Self {
316 self.ready = Some(ready);
317 self
318 }
319
320 pub fn registration_channel(mut self, supported: bool) -> Self {
322 self.registration_channel = Some(supported);
323 self
324 }
325
326 pub fn provides(mut self, provides: Vec<ProviderRole>) -> Self {
328 self.provides = provides;
329 self
330 }
331
332 pub fn consumes(mut self, consumes: Vec<ConsumerRole>) -> Self {
334 self.consumes = consumes;
335 self
336 }
337
338 pub fn bindings(mut self, bindings: Option<Bindings>) -> Self {
342 self.bindings = bindings;
343 self
344 }
345
346 pub fn capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
348 self.capabilities = capabilities;
349 self
350 }
351
352 pub fn events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
354 self.events = events;
355 self
356 }
357
358 pub fn self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
360 self.self_signals = self_signals;
361 self
362 }
363
364 pub fn provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
366 self.provenance = provenance;
367 self
368 }
369
370 pub fn operation_delivery(
372 mut self,
373 operation_delivery: BTreeMap<String, OperationDelivery>,
374 ) -> Self {
375 self.operation_delivery = operation_delivery;
376 self
377 }
378
379 pub fn operation_payload(
381 mut self,
382 operation_payload: BTreeMap<String, OperationPayload>,
383 ) -> Self {
384 self.operation_payload = operation_payload;
385 self
386 }
387
388 pub fn flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
395 self.flow_operations = flow_operations;
396 self
397 }
398
399 pub fn operation_deferral(mut self, operations: Option<BTreeMap<String, bool>>) -> Self {
401 self.operation_deferral = operations;
402 self
403 }
404
405 pub fn confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
412 self.confirm_operations = confirm_operations;
413 self
414 }
415
416 pub fn rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
418 self.rich_ui = rich_ui;
419 self
420 }
421
422 pub fn role_declarations(
424 mut self,
425 role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
426 ) -> Self {
427 self.role_declarations = role_declarations;
428 self
429 }
430
431 pub fn provider_declarations(mut self, declarations: Option<ProviderDeclarations>) -> Self {
434 self.provider_declarations = declarations;
435 self
436 }
437
438 pub fn build(self) -> ModuleManifest {
440 ModuleManifest {
441 module_id: self.module_id,
442 display_name: self.display_name,
443 module_version: self.module_version,
444 protocol_ver: self.protocol_ver,
445 trust_tier: self.trust_tier,
446 ready: self.ready,
447 registration_channel: self.registration_channel,
448 provides: self.provides,
449 consumes: self.consumes,
450 bindings: self.bindings,
451 capabilities: self.capabilities,
452 events: self.events,
453 self_signals: self.self_signals,
454 provenance: self.provenance,
455 operation_delivery: self.operation_delivery,
456 operation_payload: self.operation_payload,
457 flow_operations: self.flow_operations,
458 operation_deferral: self.operation_deferral,
459 confirm_operations: self.confirm_operations,
460 rich_ui: self.rich_ui,
461 role_declarations: self.role_declarations,
462 provider_declarations: self.provider_declarations,
463 }
464 }
465}
466
467#[derive(Deserialize)]
487struct ModuleManifestWire {
488 module_id: String,
489 #[serde(default)]
490 display_name: Option<String>,
491 module_version: String,
492 protocol_ver: u8,
493 #[serde(default)]
494 trust_tier: Option<TrustTier>,
495 #[serde(default)]
496 ready: Option<bool>,
497 #[serde(default)]
498 registration_channel: Option<bool>,
499 provides: Vec<ProviderRole>,
500 #[serde(default)]
501 consumes: Vec<ConsumerRole>,
502 #[serde(default)]
503 bindings: Option<Bindings>,
504 #[serde(default)]
505 capabilities: Option<CapabilityDeclarations>,
506 #[serde(default)]
507 events: Option<Value>,
508 #[serde(default)]
509 self_signals: Option<Vec<SelfSignalDeclaration>>,
510 #[serde(default)]
511 provenance: Option<ManifestProvenance>,
512 #[serde(default)]
513 operation_delivery: Option<Value>,
514 #[serde(default)]
515 operation_payload: BTreeMap<String, OperationPayload>,
516 #[serde(default)]
518 flow_operations: Option<Value>,
519 #[serde(default)]
520 operation_deferral: Option<Value>,
521 #[serde(default)]
523 confirm_operations: Option<Value>,
524 #[serde(default)]
525 rich_ui: Option<RichUiDescriptor>,
526 #[serde(default)]
530 runtime_computed: Option<Value>,
531 #[serde(default)]
532 role_declarations: Option<Value>,
533 #[serde(default, deserialize_with = "deserialize_provider_declarations")]
534 provider_declarations: Option<ProviderDeclarations>,
535}
536
537impl<'de> Deserialize<'de> for ModuleManifest {
538 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
539 where
540 D: Deserializer<'de>,
541 {
542 let wire = ModuleManifestWire::deserialize(deserializer)?;
543 validate_runtime_computed(wire.runtime_computed.as_ref(), "runtime_computed")
544 .map_err(D::Error::custom)?;
545 validate_events_value(wire.events.as_ref()).map_err(D::Error::custom)?;
546 let events = wire
547 .events
548 .map(serde_json::from_value)
549 .transpose()
550 .map_err(D::Error::custom)?;
551 let mut builder = Self::builder(wire.module_id, wire.module_version)
552 .display_name(wire.display_name)
553 .map_err(D::Error::custom)?
554 .protocol_ver(wire.protocol_ver)
555 .trust_tier(wire.trust_tier);
556 if let Some(ready) = wire.ready {
557 builder = builder.ready(ready);
558 }
559 if let Some(supported) = wire.registration_channel {
560 builder = builder.registration_channel(supported);
561 }
562 let mut manifest = builder
563 .provides(wire.provides)
564 .consumes(wire.consumes)
565 .bindings(wire.bindings)
566 .capabilities(wire.capabilities)
567 .events(events)
568 .self_signals(wire.self_signals)
569 .provenance(wire.provenance)
570 .operation_delivery(
571 wire.operation_delivery
572 .and_then(|value| serde_json::from_value(value).ok())
573 .unwrap_or_default(),
574 )
575 .rich_ui(wire.rich_ui)
576 .role_declarations(
577 wire.role_declarations
578 .filter(|value| validate_role_declarations_value(Some(value)).is_ok())
579 .and_then(|value| serde_json::from_value(value).ok())
580 .unwrap_or_default(),
581 )
582 .operation_payload(wire.operation_payload)
583 .provider_declarations(wire.provider_declarations)
584 .build();
585 manifest
586 .validate_operation_payload()
587 .map_err(D::Error::custom)?;
588 manifest.flow_operations = wire
591 .flow_operations
592 .and_then(|value| decode_flow_operations(&manifest, &value).ok());
593 manifest.operation_deferral = wire
594 .operation_deferral
595 .and_then(|value| decode_operation_deferral(&manifest, &value).ok());
596 manifest.confirm_operations = wire
597 .confirm_operations
598 .and_then(|value| decode_confirm_operations(&manifest, &value).ok());
599 manifest
600 .validate_capability_grammar()
601 .map_err(D::Error::custom)?;
602 if let Some(rich_ui) = &manifest.rich_ui {
603 rich_ui.validate().map_err(D::Error::custom)?;
604 }
605 Ok(manifest)
606 }
607}
608
609#[derive(Debug, Clone, PartialEq, Eq)]
611pub struct RoleDeclarationsError(&'static str);
612
613impl fmt::Display for RoleDeclarationsError {
614 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
615 f.write_str(self.0)
616 }
617}
618
619impl std::error::Error for RoleDeclarationsError {}
620
621pub fn validate_hello_role_declarations(hello: &Value) -> Result<(), RoleDeclarationsError> {
623 validate_role_declarations_value(
624 hello
625 .get("manifest")
626 .and_then(|manifest| manifest.get("role_declarations")),
627 )
628}
629
630pub fn validate_role_declarations_value(
633 value: Option<&Value>,
634) -> Result<(), RoleDeclarationsError> {
635 let Some(value) = value else {
636 return Ok(());
637 };
638 let map = value
639 .as_object()
640 .ok_or(RoleDeclarationsError("role_declarations must be an object"))?;
641 for (role, declaration) in map {
642 if !is_valid_capability_identifier(role) {
643 return Err(RoleDeclarationsError(
644 "role_declarations key must use capability-name grammar",
645 ));
646 }
647 if !declaration.is_object() {
648 return Err(RoleDeclarationsError(
649 "role_declarations values must be objects",
650 ));
651 }
652 }
653 let bytes = serde_json::to_vec(value)
654 .map_err(|_| RoleDeclarationsError("role_declarations could not be serialized"))?;
655 if bytes.len() > MAX_ROLE_DECLARATIONS_BYTES {
656 return Err(RoleDeclarationsError(
657 "role_declarations exceeds 16384 compact JSON bytes",
658 ));
659 }
660 Ok(())
661}
662
663#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
669#[non_exhaustive]
670pub struct RichUiDescriptor {
671 pub schema: String,
673 pub manifest_digest: String,
675 pub bytes: u64,
677 pub chunks: u32,
679}
680
681impl RichUiDescriptor {
682 pub fn new(
684 schema: impl Into<String>,
685 manifest_digest: impl Into<String>,
686 bytes: u64,
687 chunks: u32,
688 ) -> Self {
689 Self {
690 schema: schema.into(),
691 manifest_digest: manifest_digest.into(),
692 bytes,
693 chunks,
694 }
695 }
696
697 pub fn validate(&self) -> Result<(), RichUiDescriptorError> {
699 validate_rich_ui_fields(
700 &self.schema,
701 &self.manifest_digest,
702 self.bytes,
703 u64::from(self.chunks),
704 )
705 }
706}
707
708#[derive(Debug, Clone, PartialEq, Eq)]
710pub struct DisplayNameError(&'static str);
711
712impl fmt::Display for DisplayNameError {
713 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
714 write!(f, "invalid manifest display_name: {}", self.0)
715 }
716}
717
718impl std::error::Error for DisplayNameError {}
719
720pub fn validate_display_name(value: &str) -> Result<(), DisplayNameError> {
725 if value.trim() != value || !(1..=40).contains(&value.chars().count()) {
726 return Err(DisplayNameError(
727 "must be trimmed text of 1 to 40 characters",
728 ));
729 }
730 validate_plain_text(value, 40)
731}
732
733pub fn validate_module_id(module_id: &str) -> Result<(), String> {
735 if module_id.is_empty() {
736 return Err("empty".to_string());
737 }
738 if module_id.contains('/') || module_id.contains('\\') {
739 return Err("contains a path separator".to_string());
740 }
741 if module_id == "." || module_id == ".." {
742 return Err("is a dot path component".to_string());
743 }
744 if module_id.chars().any(|c| c.is_control()) {
745 return Err("contains a control character".to_string());
746 }
747 if module_id.len() > 255 {
748 return Err("is longer than 255 bytes".to_string());
749 }
750 Ok(())
751}
752
753pub(crate) fn validate_plain_text(value: &str, max: usize) -> Result<(), DisplayNameError> {
754 if value.is_empty() || value.chars().count() > max {
755 return Err(DisplayNameError(
756 "text length is outside the permitted bounds",
757 ));
758 }
759 if value.chars().any(|ch| {
760 ch.is_control()
761 || matches!(ch, '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')
762 }) {
763 return Err(DisplayNameError("must not contain control or bidi formatting characters"));
764 }
765 Ok(())
766}
767
768pub fn validate_hello_display_name(hello: &Value) -> Result<(), DisplayNameError> {
770 match hello
771 .get("manifest")
772 .and_then(|manifest| manifest.get("display_name"))
773 {
774 None | Some(Value::Null) => Ok(()),
775 Some(Value::String(value)) => validate_display_name(value),
776 Some(_) => Err(DisplayNameError("must be a string")),
777 }
778}
779
780#[derive(Debug, Clone, PartialEq, Eq)]
782#[non_exhaustive]
783pub struct RichUiDescriptorError {
784 field: String,
785 reason: &'static str,
786}
787
788impl RichUiDescriptorError {
789 fn new(field: impl Into<String>, reason: &'static str) -> Self {
790 Self {
791 field: field.into(),
792 reason,
793 }
794 }
795
796 pub fn field(&self) -> &str {
798 &self.field
799 }
800}
801
802impl fmt::Display for RichUiDescriptorError {
803 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
804 write!(
805 f,
806 "invalid rich_ui descriptor: field {} {}",
807 self.field, self.reason
808 )
809 }
810}
811
812impl std::error::Error for RichUiDescriptorError {}
813
814pub fn validate_hello_rich_ui_descriptor(hello: &Value) -> Result<(), RichUiDescriptorError> {
816 let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
817 return Ok(());
818 };
819 let Some(value) = manifest.get("rich_ui") else {
820 return Ok(());
821 };
822 validate_rich_ui_descriptor_value(value)
823}
824
825fn validate_rich_ui_descriptor_value(value: &Value) -> Result<(), RichUiDescriptorError> {
826 let descriptor = value
827 .as_object()
828 .ok_or_else(|| RichUiDescriptorError::new("rich_ui", "must be an object"))?;
829 let schema = descriptor
830 .get("schema")
831 .and_then(Value::as_str)
832 .ok_or_else(|| RichUiDescriptorError::new("rich_ui.schema", "must be a string"))?;
833 let digest = descriptor
834 .get("manifest_digest")
835 .and_then(Value::as_str)
836 .ok_or_else(|| RichUiDescriptorError::new("rich_ui.manifest_digest", "must be a string"))?;
837 let bytes = descriptor
838 .get("bytes")
839 .and_then(Value::as_u64)
840 .ok_or_else(|| {
841 RichUiDescriptorError::new("rich_ui.bytes", "must be an integer from 1 to 16777216")
842 })?;
843 let chunks = descriptor
844 .get("chunks")
845 .and_then(Value::as_u64)
846 .ok_or_else(|| {
847 RichUiDescriptorError::new("rich_ui.chunks", "must be an integer from 1 to 1024")
848 })?;
849 validate_rich_ui_fields(schema, digest, bytes, chunks)
850}
851
852fn validate_rich_ui_fields(
853 schema: &str,
854 digest: &str,
855 bytes: u64,
856 chunks: u64,
857) -> Result<(), RichUiDescriptorError> {
858 if !(1..=64).contains(&schema.len())
859 || !schema.bytes().all(|byte| {
860 byte.is_ascii_lowercase()
861 || byte.is_ascii_digit()
862 || matches!(byte, b'.' | b'_' | b'/' | b'-')
863 })
864 {
865 return Err(RichUiDescriptorError::new(
866 "rich_ui.schema",
867 "must be 1 to 64 bytes of [a-z0-9._/-]",
868 ));
869 }
870 if !digest.strip_prefix("sha256:").is_some_and(|hex| {
871 hex.len() == 64
872 && hex
873 .bytes()
874 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
875 }) {
876 return Err(RichUiDescriptorError::new(
877 "rich_ui.manifest_digest",
878 "must be sha256: followed by 64 lowercase hexadecimal characters",
879 ));
880 }
881 if !(1..=16_777_216).contains(&bytes) {
882 return Err(RichUiDescriptorError::new(
883 "rich_ui.bytes",
884 "must be an integer from 1 to 16777216",
885 ));
886 }
887 if !(1..=1_024).contains(&chunks) {
888 return Err(RichUiDescriptorError::new(
889 "rich_ui.chunks",
890 "must be an integer from 1 to 1024",
891 ));
892 }
893 Ok(())
894}
895
896pub const CAP_CATALOG_EVENTS_V1: &str = "catalog-events/v1";
902
903pub const CAP_SCOPE_BIND_PROOF_V1: &str = "scope-bind-proof/v1";
907
908pub const CAP_SCOPE_BIND_PROOF_V2: &str = "scope-bind-proof/v2";
912
913pub const CAP_SCOPE_REPLACE_IF_IDLE_V1: &str = "scope-replace-if-idle/v1";
915
916#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
918#[non_exhaustive]
919pub struct EventDeclaration {
920 pub name: String,
927 pub version: u32,
929 pub headers: Vec<String>,
934 #[serde(default, skip_serializing_if = "Option::is_none")]
936 pub summary: Option<String>,
937}
938
939impl EventDeclaration {
940 pub fn new(name: impl Into<String>, version: u32) -> Self {
943 Self {
944 name: name.into(),
945 version,
946 headers: Vec::new(),
947 summary: None,
948 }
949 }
950
951 pub fn with_headers(mut self, headers: Vec<String>) -> Self {
953 self.headers = headers;
954 self
955 }
956
957 pub fn with_summary(mut self, summary: Option<String>) -> Self {
959 self.summary = summary;
960 self
961 }
962}
963
964#[derive(Debug, Clone, PartialEq, Eq)]
966#[non_exhaustive]
967pub struct EventDeclarationError {
968 field: String,
969 reason: &'static str,
970}
971
972impl EventDeclarationError {
973 fn new(field: impl Into<String>, reason: &'static str) -> Self {
974 Self {
975 field: field.into(),
976 reason,
977 }
978 }
979
980 pub fn field(&self) -> &str {
982 &self.field
983 }
984}
985
986impl fmt::Display for EventDeclarationError {
987 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
988 write!(
989 f,
990 "invalid event declaration: field {} {}",
991 self.field, self.reason
992 )
993 }
994}
995
996impl std::error::Error for EventDeclarationError {}
997
998pub fn validate_hello_event_declarations(hello: &Value) -> Result<(), EventDeclarationError> {
1000 validate_events_value(
1001 hello
1002 .get("manifest")
1003 .and_then(|manifest| manifest.get("events")),
1004 )
1005}
1006
1007fn is_valid_event_name(name: &str) -> bool {
1010 let level_count = name.split('.').count();
1011 (1..=4).contains(&level_count)
1012 && name.split('.').all(|level| {
1013 if level.is_empty() {
1014 return false;
1015 }
1016 let first = level.as_bytes()[0];
1017 (1..=63).contains(&level.len())
1018 && (first.is_ascii_lowercase() || first.is_ascii_digit())
1019 && level
1020 .bytes()
1021 .skip(1)
1022 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
1023 && !level.strip_prefix('v').is_some_and(|digits| {
1024 !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit())
1025 })
1026 })
1027}
1028
1029fn validate_events_value(value: Option<&Value>) -> Result<(), EventDeclarationError> {
1030 let Some(value) = value.filter(|value| !value.is_null()) else {
1031 return Ok(());
1032 };
1033 let entries = value
1034 .as_array()
1035 .ok_or_else(|| EventDeclarationError::new("events", "must be a list"))?;
1036 if entries.len() > 64 {
1037 return Err(EventDeclarationError::new(
1038 "events",
1039 "must contain at most 64 declarations",
1040 ));
1041 }
1042 let mut pairs = HashSet::new();
1043 for (index, entry) in entries.iter().enumerate() {
1044 let field = format!("events[{index}]");
1045 let entry = entry
1046 .as_object()
1047 .ok_or_else(|| EventDeclarationError::new(&field, "must be an object"))?;
1048 let name_field = format!("{field}.name");
1049 let name = entry
1050 .get("name")
1051 .and_then(Value::as_str)
1052 .ok_or_else(|| EventDeclarationError::new(&name_field, "must be a string"))?;
1053 if !is_valid_event_name(name) {
1054 return Err(EventDeclarationError::new(
1055 name_field,
1056 "must contain one to four valid dot-separated event-name levels",
1057 ));
1058 }
1059 let version = entry
1060 .get("version")
1061 .and_then(Value::as_u64)
1062 .filter(|version| (1..=u32::MAX as u64).contains(version))
1063 .ok_or_else(|| {
1064 EventDeclarationError::new(
1065 format!("{field}.version"),
1066 "must be an integer between 1 and u32::MAX",
1067 )
1068 })?;
1069 if !pairs.insert((name, version)) {
1070 return Err(EventDeclarationError::new(
1071 &field,
1072 "duplicates an event (name, version) pair",
1073 ));
1074 }
1075 let headers_field = format!("{field}.headers");
1076 let headers = entry
1077 .get("headers")
1078 .and_then(Value::as_array)
1079 .ok_or_else(|| EventDeclarationError::new(&headers_field, "must be a list"))?;
1080 if headers.len() > 16 {
1081 return Err(EventDeclarationError::new(
1082 headers_field,
1083 "must contain at most 16 headers",
1084 ));
1085 }
1086 let mut names = HashSet::new();
1087 for (header_index, header) in headers.iter().enumerate() {
1088 let header_field = format!("{headers_field}[{header_index}]");
1089 let header = header
1090 .as_str()
1091 .ok_or_else(|| EventDeclarationError::new(&header_field, "must be a string"))?;
1092 if !(1..=32).contains(&header.len())
1093 || !header.as_bytes()[0].is_ascii_lowercase()
1094 || !header
1095 .bytes()
1096 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
1097 {
1098 return Err(EventDeclarationError::new(
1099 header_field,
1100 "must match [a-z][a-z0-9_]{0,31}",
1101 ));
1102 }
1103 if !names.insert(header) {
1104 return Err(EventDeclarationError::new(
1105 header_field,
1106 "duplicates a header name",
1107 ));
1108 }
1109 }
1110 if let Some(summary) = entry.get("summary").filter(|value| !value.is_null()) {
1111 let summary_field = format!("{field}.summary");
1112 let summary = summary
1113 .as_str()
1114 .ok_or_else(|| EventDeclarationError::new(&summary_field, "must be a string"))?;
1115 if summary.chars().count() > 200 || summary.chars().any(char::is_control) {
1116 return Err(EventDeclarationError::new(
1117 summary_field,
1118 "must contain at most 200 characters and no control characters",
1119 ));
1120 }
1121 }
1122 }
1123 Ok(())
1124}
1125
1126#[derive(Debug, Clone, PartialEq, Eq)]
1128pub struct SelfSignalDeclarationError {
1129 module_id: String,
1130 entry_index: usize,
1131 field: &'static str,
1132}
1133
1134impl fmt::Display for SelfSignalDeclarationError {
1135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1136 write!(
1137 f,
1138 "module_id '{}' self_signals[{}] is missing required field '{}'",
1139 self.module_id.escape_debug(),
1140 self.entry_index,
1141 self.field
1142 )
1143 }
1144}
1145
1146pub fn validate_hello_self_signal_declarations(
1153 hello: &Value,
1154) -> Result<(), SelfSignalDeclarationError> {
1155 let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
1156 return Ok(());
1157 };
1158 let module_id = manifest
1159 .get("module_id")
1160 .and_then(Value::as_str)
1161 .unwrap_or("<unknown>");
1162 let Some(entries) = manifest.get("self_signals").and_then(Value::as_array) else {
1163 return Ok(());
1164 };
1165
1166 for (entry_index, entry) in entries.iter().enumerate() {
1167 let Some(entry) = entry.as_object() else {
1168 continue;
1169 };
1170 for field in ["effect", "anchored_to"] {
1171 if !entry.contains_key(field) {
1172 return Err(SelfSignalDeclarationError {
1173 module_id: module_id.to_string(),
1174 entry_index,
1175 field,
1176 });
1177 }
1178 }
1179 }
1180 Ok(())
1181}
1182
1183#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1185#[serde(deny_unknown_fields)]
1186pub struct CapabilityDeclarations {
1187 #[serde(default)]
1188 pub provides: Vec<String>,
1189 #[serde(default)]
1190 pub requires: Vec<CapabilityRequirement>,
1191 #[serde(default)]
1192 pub must_never_reach: Vec<String>,
1193}
1194
1195#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1197pub struct SelfSignalDeclaration {
1198 pub name: String,
1200 pub kind: SelfSignalKind,
1228 pub effect: SelfSignalEffect,
1230 pub anchored_to: SignalAnchor,
1232 #[serde(default, skip_serializing_if = "Option::is_none")]
1239 pub cadence: Option<SignalCadence>,
1240 #[serde(default, skip_serializing_if = "Option::is_none")]
1242 pub domain: Option<String>,
1243 #[serde(default, skip_serializing_if = "Option::is_none")]
1244 pub note: Option<String>,
1245}
1246
1247#[derive(Debug, Clone, PartialEq, Eq)]
1249pub enum SelfSignalKind {
1250 Keepalive,
1251 Busy,
1253 Poller,
1254 Cron,
1255 Sweep,
1256 Watchdog,
1257 Heartbeat,
1258 Other(String),
1259}
1260
1261impl SelfSignalKind {
1262 fn wire_name(&self) -> &str {
1263 match self {
1264 Self::Keepalive => "keepalive",
1265 Self::Busy => "busy",
1266 Self::Poller => "poller",
1267 Self::Cron => "cron",
1268 Self::Sweep => "sweep",
1269 Self::Watchdog => "watchdog",
1270 Self::Heartbeat => "heartbeat",
1271 Self::Other(value) => value,
1272 }
1273 }
1274}
1275
1276impl Serialize for SelfSignalKind {
1277 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1278 where
1279 S: serde::Serializer,
1280 {
1281 serializer.serialize_str(self.wire_name())
1282 }
1283}
1284
1285impl<'de> Deserialize<'de> for SelfSignalKind {
1286 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1287 where
1288 D: Deserializer<'de>,
1289 {
1290 let value = String::deserialize(deserializer)?;
1291 Ok(match value.as_str() {
1292 "keepalive" => Self::Keepalive,
1293 "busy" => Self::Busy,
1294 "poller" => Self::Poller,
1295 "cron" => Self::Cron,
1296 "sweep" => Self::Sweep,
1297 "watchdog" => Self::Watchdog,
1298 "heartbeat" => Self::Heartbeat,
1299 _ => Self::Other(value),
1300 })
1301 }
1302}
1303
1304#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1306#[serde(rename_all = "lowercase")]
1307pub enum SelfSignalEffect {
1308 Observe,
1309 Mutate,
1310}
1311
1312#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1314#[serde(rename_all = "snake_case")]
1315pub enum SignalAnchor {
1316 FixedInterval,
1319 Event { event: String },
1322 HealthGauges { gauges: Vec<String> },
1324}
1325
1326#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1328#[serde(rename_all = "snake_case")]
1329pub enum SignalCadence {
1330 Literal { interval_ms: u64 },
1331 Derived { source: String },
1332}
1333
1334#[derive(Serialize, Debug, Clone, Default, PartialEq, Eq)]
1411#[non_exhaustive]
1412pub struct ManifestProvenance {
1413 #[serde(default, skip_serializing_if = "Option::is_none")]
1414 pub build_git_sha: Option<String>,
1415 #[serde(default, skip_serializing_if = "Option::is_none")]
1419 pub build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1420 #[serde(default, skip_serializing_if = "Option::is_none")]
1421 pub build_lock_digest: Option<String>,
1422 #[serde(default, skip_serializing_if = "Option::is_none")]
1431 pub wire_crate_version: Option<String>,
1432 #[serde(default, skip_serializing_if = "Option::is_none")]
1433 pub store_schema_version: Option<String>,
1434 #[serde(default, skip_serializing_if = "Option::is_none")]
1440 pub launch_nonce_source: Option<LaunchNonceSource>,
1441}
1442
1443#[derive(Debug, Clone, PartialEq, Eq)]
1450#[non_exhaustive]
1451pub enum LaunchNonceSource {
1452 Fd,
1454 Pipe,
1456 Env,
1458 ForwardCompatibleUnknown(String),
1459}
1460
1461impl LaunchNonceSource {
1462 pub fn wire_name(&self) -> &str {
1464 match self {
1465 Self::Fd => "fd",
1466 Self::Pipe => "pipe",
1467 Self::Env => "env",
1468 Self::ForwardCompatibleUnknown(value) => value,
1469 }
1470 }
1471
1472 pub fn from_wire_name(value: &str) -> Self {
1474 match value {
1475 "fd" => Self::Fd,
1476 "pipe" => Self::Pipe,
1477 "env" => Self::Env,
1478 _ => Self::ForwardCompatibleUnknown(value.to_string()),
1479 }
1480 }
1481}
1482
1483impl Serialize for LaunchNonceSource {
1484 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1485 where
1486 S: serde::Serializer,
1487 {
1488 serializer.serialize_str(self.wire_name())
1489 }
1490}
1491
1492impl<'de> Deserialize<'de> for LaunchNonceSource {
1493 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1494 where
1495 D: serde::Deserializer<'de>,
1496 {
1497 let value = String::deserialize(deserializer)?;
1498 Ok(Self::from_wire_name(&value))
1499 }
1500}
1501
1502#[derive(Debug, Clone, PartialEq, Eq)]
1507pub enum BuildGitShaAbsenceReason {
1508 DeclinedDirty,
1509 NeverDerived,
1510 NoGitDir,
1511 ForwardCompatibleUnknown(String),
1512}
1513
1514impl BuildGitShaAbsenceReason {
1515 fn wire_name(&self) -> &str {
1516 match self {
1517 Self::DeclinedDirty => "declined_dirty",
1518 Self::NeverDerived => "never_derived",
1519 Self::NoGitDir => "no_git_dir",
1520 Self::ForwardCompatibleUnknown(value) => value,
1521 }
1522 }
1523}
1524
1525impl Serialize for BuildGitShaAbsenceReason {
1526 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1527 where
1528 S: serde::Serializer,
1529 {
1530 serializer.serialize_str(self.wire_name())
1531 }
1532}
1533
1534impl<'de> Deserialize<'de> for BuildGitShaAbsenceReason {
1535 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1536 where
1537 D: serde::Deserializer<'de>,
1538 {
1539 let value = String::deserialize(deserializer)?;
1540 Ok(match value.as_str() {
1541 "declined_dirty" => Self::DeclinedDirty,
1542 "never_derived" => Self::NeverDerived,
1543 "no_git_dir" => Self::NoGitDir,
1544 _ => Self::ForwardCompatibleUnknown(value),
1545 })
1546 }
1547}
1548
1549#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1551pub enum GitTreeState {
1552 Clean,
1553 Dirty,
1554}
1555
1556#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1561pub enum BuildGitShaSource<'a> {
1562 Git {
1563 revision: &'a str,
1564 tree_state: GitTreeState,
1565 },
1566 NeverDerived,
1567 NoGitDir,
1568}
1569
1570pub fn attestable_commit(revision: &str, tree_state: GitTreeState) -> Option<&str> {
1574 match tree_state {
1575 GitTreeState::Clean => Some(revision),
1576 GitTreeState::Dirty => None,
1577 }
1578}
1579
1580const MAX_PROVENANCE_VALUE_BYTES: usize = 128;
1581const BUILD_GIT_SHA_CANONICAL_FORM: &str = "exactly 40 lowercase hexadecimal characters";
1582const BUILD_LOCK_DIGEST_CANONICAL_FORM: &str = "exactly 64 lowercase hexadecimal characters";
1583
1584#[derive(Deserialize)]
1585struct ManifestProvenanceWire {
1586 #[serde(default)]
1587 build_git_sha: Option<String>,
1588 #[serde(default)]
1589 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1590 #[serde(default)]
1591 build_lock_digest: Option<String>,
1592 #[serde(default)]
1593 wire_crate_version: Option<String>,
1594 #[serde(default)]
1595 store_schema_version: Option<String>,
1596 #[serde(default)]
1597 launch_nonce_source: Option<LaunchNonceSource>,
1598}
1599
1600impl<'de> Deserialize<'de> for ManifestProvenance {
1601 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1602 where
1603 D: Deserializer<'de>,
1604 {
1605 let wire = ManifestProvenanceWire::deserialize(deserializer)?;
1606 let provenance = Self {
1607 build_git_sha: wire.build_git_sha,
1608 build_git_sha_absence_reason: wire.build_git_sha_absence_reason,
1609 build_lock_digest: wire.build_lock_digest,
1610 wire_crate_version: wire.wire_crate_version,
1611 store_schema_version: wire.store_schema_version,
1612 launch_nonce_source: wire.launch_nonce_source,
1613 };
1614 provenance.validate().map_err(D::Error::custom)?;
1615 Ok(provenance)
1616 }
1617}
1618
1619#[derive(Debug, Clone, PartialEq, Eq)]
1621pub struct ProvenanceFormError {
1622 field: &'static str,
1623 length: usize,
1624 canonical_form: &'static str,
1625}
1626
1627impl ProvenanceFormError {
1628 fn new(field: &'static str, length: usize, canonical_form: &'static str) -> Self {
1629 Self {
1630 field,
1631 length,
1632 canonical_form,
1633 }
1634 }
1635
1636 pub fn field(&self) -> &str {
1638 self.field
1639 }
1640
1641 pub fn length(&self) -> usize {
1643 self.length
1644 }
1645
1646 pub fn canonical_form(&self) -> &str {
1648 self.canonical_form
1649 }
1650}
1651
1652impl fmt::Display for ProvenanceFormError {
1653 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1654 write!(
1655 f,
1656 "invalid manifest provenance form: field {} has length {}; canonical form is {}",
1657 self.field, self.length, self.canonical_form
1658 )
1659 }
1660}
1661
1662impl std::error::Error for ProvenanceFormError {}
1663
1664#[derive(Debug, Clone, PartialEq, Eq)]
1665pub struct ManifestProvenanceError {
1666 field: String,
1667 value: String,
1668 reason: &'static str,
1669}
1670
1671impl ManifestProvenanceError {
1672 fn new(field: &str, value: &str, reason: &'static str) -> Self {
1673 Self {
1674 field: field.to_string(),
1675 value: safe_error_value(value),
1676 reason,
1677 }
1678 }
1679
1680 pub fn field(&self) -> &str {
1681 &self.field
1682 }
1683}
1684
1685impl fmt::Display for ManifestProvenanceError {
1686 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1687 write!(
1688 f,
1689 "invalid manifest provenance: field {} has {} (value {:?})",
1690 self.field, self.reason, self.value
1691 )
1692 }
1693}
1694
1695impl std::error::Error for ManifestProvenanceError {}
1696
1697impl ManifestProvenance {
1698 pub fn new() -> Self {
1700 Self::default()
1701 }
1702
1703 pub fn with_build_git_sha(mut self, value: Option<String>) -> Self {
1704 self.build_git_sha = value;
1705 self
1706 }
1707
1708 pub fn with_build_git_sha_absence_reason(
1709 mut self,
1710 value: Option<BuildGitShaAbsenceReason>,
1711 ) -> Self {
1712 self.build_git_sha_absence_reason = value;
1713 self
1714 }
1715
1716 pub fn with_build_lock_digest(mut self, value: Option<String>) -> Self {
1717 self.build_lock_digest = value;
1718 self
1719 }
1720
1721 pub fn with_wire_crate_version(mut self, value: Option<String>) -> Self {
1722 self.wire_crate_version = value;
1723 self
1724 }
1725
1726 pub fn with_store_schema_version(mut self, value: Option<String>) -> Self {
1727 self.store_schema_version = value;
1728 self
1729 }
1730
1731 pub fn with_launch_nonce_source(mut self, value: Option<LaunchNonceSource>) -> Self {
1736 self.launch_nonce_source = value;
1737 self
1738 }
1739
1740 pub fn validate(&self) -> Result<(), ManifestProvenanceError> {
1741 if let (Some(_), Some(reason)) = (
1742 self.build_git_sha.as_ref(),
1743 self.build_git_sha_absence_reason.as_ref(),
1744 ) {
1745 return Err(ManifestProvenanceError::new(
1746 "build_git_sha_absence_reason",
1747 reason.wire_name(),
1748 "must be omitted when build_git_sha is present",
1749 ));
1750 }
1751 for (field, value) in [
1752 ("build_git_sha", self.build_git_sha.as_deref()),
1753 (
1754 "build_git_sha_absence_reason",
1755 self.build_git_sha_absence_reason
1756 .as_ref()
1757 .map(|reason| reason.wire_name()),
1758 ),
1759 ("build_lock_digest", self.build_lock_digest.as_deref()),
1760 ("wire_crate_version", self.wire_crate_version.as_deref()),
1761 ("store_schema_version", self.store_schema_version.as_deref()),
1762 (
1763 "launch_nonce_source",
1764 self.launch_nonce_source
1765 .as_ref()
1766 .map(|source| source.wire_name()),
1767 ),
1768 ] {
1769 let Some(value) = value else { continue };
1770 if value.is_empty() {
1771 return Err(ManifestProvenanceError::new(
1772 field,
1773 value,
1774 "must not be empty",
1775 ));
1776 }
1777 if value.len() > MAX_PROVENANCE_VALUE_BYTES {
1782 return Err(ManifestProvenanceError::new(
1783 field,
1784 value,
1785 "exceeds the 128-byte maximum",
1786 ));
1787 }
1788 if value.bytes().any(|byte| !(0x20..=0x7e).contains(&byte)) {
1789 return Err(ManifestProvenanceError::new(
1790 field,
1791 value,
1792 "contains non-printable ASCII",
1793 ));
1794 }
1795 }
1796 Ok(())
1797 }
1798}
1799
1800pub fn build_provenance(
1818 build_git_sha: Option<&str>,
1819 build_lock_digest: Option<&str>,
1820 store_schema_version: Option<&str>,
1821) -> Result<ManifestProvenance, ProvenanceFormError> {
1822 let build_git_sha = normalize_and_validate_build_git_sha(build_git_sha)?;
1823 build_provenance_with_build_git_sha(
1824 build_git_sha,
1825 None,
1826 build_lock_digest,
1827 store_schema_version,
1828 )
1829}
1830
1831pub fn build_provenance_from_source(
1847 build_git_sha_source: BuildGitShaSource<'_>,
1848 build_lock_digest: Option<&str>,
1849 store_schema_version: Option<&str>,
1850) -> Result<ManifestProvenance, ProvenanceFormError> {
1851 let (raw_build_git_sha, mut build_git_sha_absence_reason) = match build_git_sha_source {
1852 BuildGitShaSource::Git {
1853 revision,
1854 tree_state,
1855 } => match attestable_commit(revision, tree_state) {
1856 Some(revision) => (Some(revision), None),
1857 None => (None, Some(BuildGitShaAbsenceReason::DeclinedDirty)),
1858 },
1859 BuildGitShaSource::NeverDerived => (None, Some(BuildGitShaAbsenceReason::NeverDerived)),
1860 BuildGitShaSource::NoGitDir => (None, Some(BuildGitShaAbsenceReason::NoGitDir)),
1861 };
1862 let build_git_sha = normalize_and_validate_build_git_sha(raw_build_git_sha)?;
1863 if build_git_sha.is_none() {
1864 build_git_sha_absence_reason.get_or_insert(BuildGitShaAbsenceReason::NeverDerived);
1865 }
1866 build_provenance_with_build_git_sha(
1867 build_git_sha,
1868 build_git_sha_absence_reason,
1869 build_lock_digest,
1870 store_schema_version,
1871 )
1872}
1873
1874fn normalize_and_validate_build_git_sha(
1875 build_git_sha: Option<&str>,
1876) -> Result<Option<String>, ProvenanceFormError> {
1877 let build_git_sha = normalize_provenance_fact(build_git_sha);
1878 validate_provenance_form(
1879 "build_git_sha",
1880 build_git_sha.as_deref(),
1881 BUILD_GIT_SHA_CANONICAL_FORM,
1882 40,
1883 )?;
1884 Ok(build_git_sha)
1885}
1886
1887fn build_provenance_with_build_git_sha(
1888 build_git_sha: Option<String>,
1889 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1890 build_lock_digest: Option<&str>,
1891 store_schema_version: Option<&str>,
1892) -> Result<ManifestProvenance, ProvenanceFormError> {
1893 let build_lock_digest = normalize_provenance_fact(build_lock_digest);
1894 validate_provenance_form(
1895 "build_lock_digest",
1896 build_lock_digest.as_deref(),
1897 BUILD_LOCK_DIGEST_CANONICAL_FORM,
1898 64,
1899 )?;
1900
1901 Ok(ManifestProvenance {
1902 build_git_sha,
1903 build_git_sha_absence_reason,
1904 build_lock_digest,
1905 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
1906 store_schema_version: normalize_provenance_fact(store_schema_version),
1907 launch_nonce_source: None,
1908 })
1909}
1910
1911fn validate_provenance_form(
1912 field: &'static str,
1913 value: Option<&str>,
1914 canonical_form: &'static str,
1915 expected_length: usize,
1916) -> Result<(), ProvenanceFormError> {
1917 let Some(value) = value else { return Ok(()) };
1918 if value.len() != expected_length
1919 || !value
1920 .bytes()
1921 .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
1922 {
1923 return Err(ProvenanceFormError::new(field, value.len(), canonical_form));
1924 }
1925 Ok(())
1926}
1927
1928pub const PROVENANCE_SENTINELS: [&str; 3] = ["unknown", "unavailable", "none"];
1936
1937fn normalize_provenance_fact(value: Option<&str>) -> Option<String> {
1938 let value = value?.trim();
1939 if value.is_empty() {
1940 return None;
1941 }
1942 let lowered = value.to_ascii_lowercase();
1943 if PROVENANCE_SENTINELS.contains(&lowered.as_str()) {
1944 return None;
1945 }
1946 Some(value.to_string())
1947}
1948
1949#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1951#[serde(deny_unknown_fields)]
1952pub struct CapabilityRequirement {
1953 pub capability: String,
1954 pub need: CapabilityNeed,
1955}
1956
1957#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1959#[serde(rename_all = "snake_case")]
1960pub enum CapabilityNeed {
1961 Required,
1962 Optional,
1963}
1964
1965#[derive(Debug, Clone, PartialEq, Eq)]
1967pub struct CapabilityGrammarError {
1968 field: String,
1969 value: String,
1970}
1971
1972impl CapabilityGrammarError {
1973 fn new(field: impl Into<String>, value: impl AsRef<str>) -> Self {
1974 Self {
1975 field: field.into(),
1976 value: safe_error_value(value.as_ref()),
1977 }
1978 }
1979
1980 pub fn field(&self) -> &str {
1982 &self.field
1983 }
1984
1985 pub fn value(&self) -> &str {
1987 &self.value
1988 }
1989}
1990
1991impl fmt::Display for CapabilityGrammarError {
1992 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1993 write!(
1994 f,
1995 "invalid capability grammar: field {} has offending value {:?}",
1996 self.field, self.value
1997 )
1998 }
1999}
2000
2001impl std::error::Error for CapabilityGrammarError {}
2002
2003impl ModuleManifest {
2004 pub fn validate_capability_grammar(&self) -> Result<(), CapabilityGrammarError> {
2006 let Some(capabilities) = &self.capabilities else {
2007 return Ok(());
2008 };
2009
2010 validate_capability_list("capabilities.provides", &capabilities.provides)?;
2011 validate_requires(&capabilities.requires)?;
2012 validate_capability_list(
2013 "capabilities.must_never_reach",
2014 &capabilities.must_never_reach,
2015 )
2016 }
2017}
2018
2019pub fn validate_manifest_capability_grammar(
2024 manifest: &Value,
2025) -> Result<(), CapabilityGrammarError> {
2026 let Some(object) = manifest.as_object() else {
2027 return Ok(());
2028 };
2029
2030 validate_capabilities_value(object.get("capabilities"))?;
2031 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
2032}
2033
2034pub fn validate_hello_capability_grammar(hello: &Value) -> Result<(), CapabilityGrammarError> {
2040 let Some(object) = hello.as_object() else {
2041 return Ok(());
2042 };
2043 if let Some(manifest) = object.get("manifest") {
2044 validate_manifest_capability_grammar(manifest)?;
2045 }
2046 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
2047}
2048
2049pub fn is_valid_capability_identifier(identifier: &str) -> bool {
2051 if identifier.chars().any(char::is_whitespace) {
2052 return false;
2053 }
2054 let Some((name, version)) = identifier.split_once("/v") else {
2055 return false;
2056 };
2057 if name.is_empty() || name.len() > 64 || version.is_empty() {
2058 return false;
2059 }
2060
2061 let name_bytes = name.as_bytes();
2062 if !name_bytes[0].is_ascii_lowercase()
2063 || (name.len() > 1
2064 && !name_bytes[name.len() - 1].is_ascii_lowercase()
2065 && !name_bytes[name.len() - 1].is_ascii_digit())
2066 || name_bytes.windows(2).any(|pair| pair == b"--")
2067 {
2068 return false;
2069 }
2070 if !name_bytes
2071 .iter()
2072 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-')
2073 {
2074 return false;
2075 }
2076
2077 if version.len() > 1 && version.starts_with('0')
2078 || !version.bytes().all(|byte| byte.is_ascii_digit())
2079 {
2080 return false;
2081 }
2082 matches!(
2083 version.parse::<u64>(),
2084 Ok(value) if (1..=u64::from(u32::MAX)).contains(&value)
2085 )
2086}
2087
2088fn validate_capabilities_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
2089 let Some(value) = value else {
2090 return Ok(());
2091 };
2092 let Some(object) = value.as_object() else {
2093 return Err(CapabilityGrammarError::new(
2094 "capabilities",
2095 value_description(value),
2096 ));
2097 };
2098
2099 for (key, value) in object {
2100 if !matches!(key.as_str(), "provides" | "requires" | "must_never_reach") {
2101 return Err(CapabilityGrammarError::new(
2102 field_child("capabilities", key),
2103 value_description(value),
2104 ));
2105 }
2106 }
2107
2108 validate_capability_list_value("capabilities.provides", object.get("provides"))?;
2109 validate_requires_value(object.get("requires"))?;
2110 validate_capability_list_value(
2111 "capabilities.must_never_reach",
2112 object.get("must_never_reach"),
2113 )
2114}
2115
2116fn validate_capability_list_value(
2117 field: &str,
2118 value: Option<&Value>,
2119) -> Result<(), CapabilityGrammarError> {
2120 let Some(value) = value else {
2121 return Ok(());
2122 };
2123 let Some(values) = value.as_array() else {
2124 return Err(CapabilityGrammarError::new(field, value_description(value)));
2125 };
2126
2127 let mut seen = HashSet::new();
2128 for (index, value) in values.iter().enumerate() {
2129 let field = format!("{field}[{index}]");
2130 let Some(identifier) = value.as_str() else {
2131 return Err(CapabilityGrammarError::new(field, value_description(value)));
2132 };
2133 validate_capability_identifier(&field, identifier)?;
2134 if !seen.insert(identifier) {
2135 return Err(CapabilityGrammarError::new(field, identifier));
2136 }
2137 }
2138 Ok(())
2139}
2140
2141fn validate_requires_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
2142 let Some(value) = value else {
2143 return Ok(());
2144 };
2145 let Some(values) = value.as_array() else {
2146 return Err(CapabilityGrammarError::new(
2147 "capabilities.requires",
2148 value_description(value),
2149 ));
2150 };
2151
2152 let mut seen = HashSet::new();
2153 for (index, value) in values.iter().enumerate() {
2154 let entry_field = format!("capabilities.requires[{index}]");
2155 let Some(object) = value.as_object() else {
2156 return Err(CapabilityGrammarError::new(
2157 entry_field,
2158 value_description(value),
2159 ));
2160 };
2161 for (key, value) in object {
2162 if !matches!(key.as_str(), "capability" | "need") {
2163 return Err(CapabilityGrammarError::new(
2164 field_child(&entry_field, key),
2165 value_description(value),
2166 ));
2167 }
2168 }
2169 let capability_field = format!("{entry_field}.capability");
2170 let Some(capability) = object.get("capability").and_then(Value::as_str) else {
2171 return Err(CapabilityGrammarError::new(
2172 capability_field,
2173 object
2174 .get("capability")
2175 .map_or("<missing>".to_string(), value_description),
2176 ));
2177 };
2178 validate_capability_identifier(&capability_field, capability)?;
2179
2180 let need_field = format!("{entry_field}.need");
2181 let Some(need) = object.get("need").and_then(Value::as_str) else {
2182 return Err(CapabilityGrammarError::new(
2183 need_field,
2184 object
2185 .get("need")
2186 .map_or("<missing>".to_string(), value_description),
2187 ));
2188 };
2189 if !matches!(need, "required" | "optional") {
2190 return Err(CapabilityGrammarError::new(need_field, need));
2191 }
2192 if !seen.insert(capability) {
2193 return Err(CapabilityGrammarError::new(entry_field, capability));
2194 }
2195 }
2196 Ok(())
2197}
2198
2199fn validate_capability_list(field: &str, values: &[String]) -> Result<(), CapabilityGrammarError> {
2200 let mut seen = HashSet::new();
2201 for (index, identifier) in values.iter().enumerate() {
2202 let field = format!("{field}[{index}]");
2203 validate_capability_identifier(&field, identifier)?;
2204 if !seen.insert(identifier) {
2205 return Err(CapabilityGrammarError::new(field, identifier));
2206 }
2207 }
2208 Ok(())
2209}
2210
2211fn validate_requires(values: &[CapabilityRequirement]) -> Result<(), CapabilityGrammarError> {
2212 let mut seen = HashSet::new();
2213 for (index, requirement) in values.iter().enumerate() {
2214 let field = format!("capabilities.requires[{index}].capability");
2215 validate_capability_identifier(&field, &requirement.capability)?;
2216 if !seen.insert(&requirement.capability) {
2217 return Err(CapabilityGrammarError::new(
2218 format!("capabilities.requires[{index}]"),
2219 &requirement.capability,
2220 ));
2221 }
2222 }
2223 Ok(())
2224}
2225
2226fn validate_capability_identifier(
2227 field: &str,
2228 identifier: &str,
2229) -> Result<(), CapabilityGrammarError> {
2230 if is_valid_capability_identifier(identifier) {
2231 Ok(())
2232 } else {
2233 Err(CapabilityGrammarError::new(field, identifier))
2234 }
2235}
2236
2237fn validate_runtime_computed(
2238 value: Option<&Value>,
2239 field: &str,
2240) -> Result<(), CapabilityGrammarError> {
2241 let Some(value) = value else {
2242 return Ok(());
2243 };
2244 let Some(pointers) = value.as_array() else {
2245 return Err(CapabilityGrammarError::new(field, value_description(value)));
2246 };
2247
2248 for (index, pointer) in pointers.iter().enumerate() {
2249 let field = format!("{field}[{index}]");
2250 let Some(pointer) = pointer.as_str() else {
2251 return Err(CapabilityGrammarError::new(
2252 field,
2253 value_description(pointer),
2254 ));
2255 };
2256 let Some(tokens) = parse_json_pointer(pointer) else {
2257 return Err(CapabilityGrammarError::new(field, pointer));
2258 };
2259 if tokens.first().is_some_and(|token| token == "capabilities") {
2260 return Err(CapabilityGrammarError::new(field, pointer));
2261 }
2262 }
2263 Ok(())
2264}
2265
2266fn parse_json_pointer(pointer: &str) -> Option<Vec<String>> {
2267 if pointer.is_empty() {
2268 return Some(Vec::new());
2269 }
2270 let raw_tokens = pointer.strip_prefix('/')?;
2271 raw_tokens
2272 .split('/')
2273 .map(unescape_json_pointer_token)
2274 .collect()
2275}
2276
2277fn unescape_json_pointer_token(token: &str) -> Option<String> {
2278 let mut output = String::with_capacity(token.len());
2279 let mut characters = token.chars();
2280 while let Some(character) = characters.next() {
2281 if character != '~' {
2282 output.push(character);
2283 continue;
2284 }
2285 match characters.next()? {
2286 '0' => output.push('~'),
2287 '1' => output.push('/'),
2288 _ => return None,
2289 }
2290 }
2291 Some(output)
2292}
2293
2294fn field_child(parent: &str, child: &str) -> String {
2295 let child = safe_error_value(child);
2296 format!("{parent}.{child}")
2297}
2298
2299fn value_description(value: &Value) -> String {
2300 match value {
2301 Value::String(value) => safe_error_value(value),
2302 Value::Null => "null".to_string(),
2303 Value::Bool(value) => value.to_string(),
2304 Value::Number(value) => value.to_string(),
2305 Value::Array(_) => "<array>".to_string(),
2306 Value::Object(_) => "<object>".to_string(),
2307 }
2308}
2309
2310fn safe_error_value(value: &str) -> String {
2311 let lower = value.to_ascii_lowercase();
2312 if ["secret", "password", "api_key"]
2313 .iter()
2314 .any(|marker| lower.contains(marker))
2315 || lower.starts_with("sk-")
2316 || lower.starts_with("akia")
2317 || lower.starts_with("bearer ")
2318 || lower.starts_with("token=")
2319 || lower.starts_with("credential=")
2320 {
2321 "<redacted>".to_string()
2322 } else {
2323 value.to_string()
2324 }
2325}
2326
2327#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2333#[serde(rename_all = "snake_case")]
2334pub enum TrustTier {
2335 FirstParty,
2336 Reviewed,
2337 Untrusted,
2338}
2339
2340#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2344#[serde(tag = "role", rename_all = "snake_case")]
2345pub enum ProviderRole {
2346 ToolProvider {
2347 tools: Vec<Tool>,
2348 identity_scope: Vec<IdentityScope>,
2356 concurrency: Concurrency,
2357 emits_push: bool,
2358 sub_supervises: bool,
2359 },
2360 PipelineStage {
2361 stage: PipelineStageKind,
2362 applies_to: PipelineAppliesTo,
2363 interface: String,
2364 declares_frozen_floor: bool,
2365 needs_signals: Vec<String>,
2366 conformance_class: String,
2367 },
2368 ManagementSurface {
2369 operations: Vec<ManagementOperation>,
2370 config_schema: Value,
2371 observability: Vec<ObservabilitySurface>,
2372 identity_scope: Vec<IdentityScope>,
2376 #[serde(default)]
2377 concurrency: Concurrency,
2378 },
2379 InternalService {
2380 service_id: String,
2381 transport: InternalTransport,
2382 agent_facing: bool,
2383 operations: Vec<String>,
2384 },
2385}
2386
2387#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2400#[serde(rename_all = "snake_case")]
2401pub enum ExecutionMode {
2402 Pure,
2403 Mutating,
2404 Unfenceable,
2405}
2406
2407#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2409pub struct Tool {
2410 pub name: String,
2411 #[serde(default, skip_serializing_if = "Option::is_none")]
2412 pub description: Option<String>,
2413 pub execution_mode: ExecutionMode,
2418 pub schema: Value,
2419}
2420
2421#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2427#[serde(rename_all = "snake_case")]
2428pub enum Concurrency {
2429 Serial,
2431 ModuleManaged,
2434 StatelessParallel,
2437}
2438
2439#[allow(clippy::derivable_impls)]
2440impl Default for Concurrency {
2451 fn default() -> Self {
2452 Self::ModuleManaged
2453 }
2454}
2455
2456#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2463#[serde(rename_all = "snake_case")]
2464pub enum IdentityScope {
2465 Session,
2466 Project,
2467}
2468
2469#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2471#[serde(rename_all = "snake_case")]
2472pub enum PipelineStageKind {
2473 Transform,
2474 Codec,
2475 Auth,
2476}
2477
2478#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2480pub struct PipelineAppliesTo {
2481 pub provider: String,
2482 pub model: String,
2483}
2484
2485#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2488#[non_exhaustive]
2489pub struct OperationPayload {
2490 max_bytes: usize,
2491}
2492
2493impl OperationPayload {
2494 pub fn new(max_bytes: usize) -> Self {
2495 Self { max_bytes }
2496 }
2497
2498 pub fn max_bytes(&self) -> usize {
2499 self.max_bytes
2500 }
2501}
2502
2503#[derive(Debug, Clone, PartialEq, Eq)]
2505#[non_exhaustive]
2506pub enum OperationPayloadError {
2507 UnknownOperation { operation: String },
2508 WatchOperation { operation: String },
2509 InvalidMaxBytes { operation: String },
2510}
2511
2512impl fmt::Display for OperationPayloadError {
2513 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2514 write!(f, "{self:?}")
2515 }
2516}
2517
2518impl std::error::Error for OperationPayloadError {}
2519
2520impl ModuleManifest {
2521 pub fn validate_operation_payload(&self) -> Result<(), OperationPayloadError> {
2524 for (name, payload) in &self.operation_payload {
2525 if !self.provides.iter().any(|role| match role {
2526 ProviderRole::ManagementSurface { operations, .. } => {
2527 operations.iter().any(|op| op.name == *name)
2528 }
2529 _ => false,
2530 }) {
2531 return Err(OperationPayloadError::UnknownOperation {
2532 operation: name.clone(),
2533 });
2534 }
2535 if self
2536 .operation_delivery
2537 .get(name)
2538 .is_some_and(OperationDelivery::is_watch)
2539 {
2540 return Err(OperationPayloadError::WatchOperation {
2541 operation: name.clone(),
2542 });
2543 }
2544 if !(1..=crate::framed_body::MAX_DECLARED_PAYLOAD_BYTES).contains(&payload.max_bytes) {
2545 return Err(OperationPayloadError::InvalidMaxBytes {
2546 operation: name.clone(),
2547 });
2548 }
2549 }
2550 Ok(())
2551 }
2552}
2553
2554#[derive(Debug, Clone, PartialEq, Eq)]
2559#[non_exhaustive]
2560pub enum FlowOperationsError {
2561 FlowScopesNotDeclared,
2564 NotAList,
2566 TooMany { count: usize },
2568 DuplicateOperation { operation: String },
2570 UnknownOperation { operation: String },
2572}
2573
2574impl fmt::Display for FlowOperationsError {
2575 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2576 match self {
2577 Self::FlowScopesNotDeclared => write!(
2578 f,
2579 "flow_operations requires '{}' or '{}' in capabilities.provides",
2580 crate::scope::FLOW_SCOPES_CAPABILITY,
2581 crate::call_mode::CALL_MODES_CAPABILITY
2582 ),
2583 Self::NotAList => f.write_str("flow_operations must be an array of operation names"),
2584 Self::TooMany { count } => write!(
2585 f,
2586 "flow_operations lists {count} names, more than {MAX_FLOW_OPERATIONS}"
2587 ),
2588 Self::DuplicateOperation { operation } => {
2589 write!(f, "flow_operations names '{operation}' more than once")
2590 }
2591 Self::UnknownOperation { operation } => write!(
2592 f,
2593 "flow_operations names '{operation}', which is not a declared management operation"
2594 ),
2595 }
2596 }
2597}
2598
2599impl std::error::Error for FlowOperationsError {}
2600
2601impl ModuleManifest {
2602 pub fn validate_flow_operations(&self) -> Result<(), FlowOperationsError> {
2607 match &self.flow_operations {
2608 Some(operations) => check_flow_operations(self, operations),
2609 None => Ok(()),
2610 }
2611 }
2612}
2613
2614fn check_flow_operations(
2615 manifest: &ModuleManifest,
2616 operations: &[String],
2617) -> Result<(), FlowOperationsError> {
2618 let admits_flows = manifest.capabilities.as_ref().is_some_and(|capabilities| {
2619 capabilities.provides.iter().any(|capability| {
2620 capability == crate::scope::FLOW_SCOPES_CAPABILITY
2621 || capability == crate::call_mode::CALL_MODES_CAPABILITY
2622 })
2623 });
2624 if !admits_flows {
2625 return Err(FlowOperationsError::FlowScopesNotDeclared);
2626 }
2627 if operations.len() > MAX_FLOW_OPERATIONS {
2628 return Err(FlowOperationsError::TooMany {
2629 count: operations.len(),
2630 });
2631 }
2632 let mut seen = HashSet::new();
2633 for operation in operations {
2634 if !seen.insert(operation.as_str()) {
2635 return Err(FlowOperationsError::DuplicateOperation {
2636 operation: operation.clone(),
2637 });
2638 }
2639 let declared = manifest.provides.iter().any(|role| match role {
2640 ProviderRole::ManagementSurface { operations, .. } => {
2641 operations.iter().any(|op| op.name == *operation)
2642 }
2643 _ => false,
2644 });
2645 if !declared {
2646 return Err(FlowOperationsError::UnknownOperation {
2647 operation: operation.clone(),
2648 });
2649 }
2650 }
2651 Ok(())
2652}
2653
2654fn decode_flow_operations(
2657 manifest: &ModuleManifest,
2658 value: &Value,
2659) -> Result<Vec<String>, FlowOperationsError> {
2660 let operations: Vec<String> =
2661 serde_json::from_value(value.clone()).map_err(|_| FlowOperationsError::NotAList)?;
2662 check_flow_operations(manifest, &operations)?;
2663 Ok(operations)
2664}
2665
2666pub fn validate_hello_flow_operations(hello: &Value) -> Result<(), FlowOperationsError> {
2672 let Some(manifest_value) = hello.get("manifest") else {
2673 return Ok(());
2674 };
2675 let Some(value) = manifest_value
2676 .get("flow_operations")
2677 .filter(|value| !value.is_null())
2678 else {
2679 return Ok(());
2680 };
2681 let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
2682 return Ok(());
2683 };
2684 decode_flow_operations(&manifest, value).map(|_| ())
2685}
2686
2687pub const MAX_OPERATION_DEFERRAL: usize = 256;
2689
2690fn decode_operation_deferral(
2691 manifest: &ModuleManifest,
2692 value: &Value,
2693) -> Result<BTreeMap<String, bool>, String> {
2694 if !manifest.capabilities.as_ref().is_some_and(|caps| {
2695 caps.provides
2696 .iter()
2697 .any(|cap| cap == crate::scope::SCOPE_FEDERATED_CAPABILITY)
2698 }) {
2699 return Err("operation_deferral requires scope-federated/v1".into());
2700 }
2701 let operations = value
2702 .as_object()
2703 .ok_or("operation_deferral must be an object")?;
2704 if operations.len() > MAX_OPERATION_DEFERRAL {
2705 return Err(format!(
2706 "operation_deferral exceeds {MAX_OPERATION_DEFERRAL} entries"
2707 ));
2708 }
2709 for (key, value) in operations {
2710 let (surface, name) = key
2711 .split_once(':')
2712 .ok_or("operation_deferral keys require a surface prefix")?;
2713 if !matches!(surface, "tool" | "management")
2716 || name.is_empty()
2717 || name.len() > 128
2718 || !name
2719 .bytes()
2720 .all(|b| (0x21..=0x7e).contains(&b) && b != b':')
2721 {
2722 return Err(format!("invalid operation_deferral key '{key}'"));
2723 }
2724 if value != &Value::Bool(true) {
2725 return Err(format!("operation_deferral value for '{key}' must be true"));
2726 }
2727 if surface == "management" && !manifest.provides.iter().any(|role| matches!(role,
2728 ProviderRole::ManagementSurface { operations, .. } if operations.iter().any(|op| op.name == name))) {
2729 return Err(format!("operation_deferral names undeclared management operation '{name}'"));
2730 }
2731 }
2732 Ok(operations.keys().map(|key| (key.clone(), true)).collect())
2733}
2734
2735impl ModuleManifest {
2736 pub fn validate_operation_deferral(&self) -> Result<(), String> {
2738 match &self.operation_deferral {
2739 Some(operations) => decode_operation_deferral(
2740 self,
2741 &serde_json::to_value(operations).expect("serializable map"),
2742 )
2743 .map(|_| ()),
2744 None => Ok(()),
2745 }
2746 }
2747}
2748
2749pub fn validate_hello_operation_deferral(hello: &Value) -> Result<(), String> {
2751 let Some(manifest_value) = hello.get("manifest") else {
2752 return Ok(());
2753 };
2754 let Some(value) = manifest_value
2755 .get("operation_deferral")
2756 .filter(|v| !v.is_null())
2757 else {
2758 return Ok(());
2759 };
2760 let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
2761 return Ok(());
2762 };
2763 decode_operation_deferral(&manifest, value).map(|_| ())
2764}
2765
2766#[derive(Debug, Clone, PartialEq, Eq)]
2771#[non_exhaustive]
2772pub enum ConfirmOperationsError {
2773 NotAList,
2775 TooMany { count: usize },
2777 DuplicateOperation { operation: String },
2779 UnknownOperation { operation: String },
2781}
2782
2783impl fmt::Display for ConfirmOperationsError {
2784 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2785 match self {
2786 Self::NotAList => {
2787 f.write_str("confirm_operations must be an array of operation names")
2788 }
2789 Self::TooMany { count } => write!(
2790 f,
2791 "confirm_operations lists {count} names, more than {MAX_CONFIRM_OPERATIONS}"
2792 ),
2793 Self::DuplicateOperation { operation } => {
2794 write!(f, "confirm_operations names '{operation}' more than once")
2795 }
2796 Self::UnknownOperation { operation } => write!(
2797 f,
2798 "confirm_operations names '{operation}', which is not a declared management operation"
2799 ),
2800 }
2801 }
2802}
2803
2804impl std::error::Error for ConfirmOperationsError {}
2805
2806impl ModuleManifest {
2807 pub fn validate_confirm_operations(&self) -> Result<(), ConfirmOperationsError> {
2811 match &self.confirm_operations {
2812 Some(operations) => check_confirm_operations(self, operations),
2813 None => Ok(()),
2814 }
2815 }
2816}
2817
2818fn check_confirm_operations(
2819 manifest: &ModuleManifest,
2820 operations: &[String],
2821) -> Result<(), ConfirmOperationsError> {
2822 if operations.len() > MAX_CONFIRM_OPERATIONS {
2823 return Err(ConfirmOperationsError::TooMany {
2824 count: operations.len(),
2825 });
2826 }
2827 let mut seen = HashSet::new();
2828 for operation in operations {
2829 if !seen.insert(operation.as_str()) {
2830 return Err(ConfirmOperationsError::DuplicateOperation {
2831 operation: operation.clone(),
2832 });
2833 }
2834 if !declares_management_operation(manifest, operation) {
2835 return Err(ConfirmOperationsError::UnknownOperation {
2836 operation: operation.clone(),
2837 });
2838 }
2839 }
2840 Ok(())
2841}
2842
2843fn declares_management_operation(manifest: &ModuleManifest, operation: &str) -> bool {
2844 manifest.provides.iter().any(|role| match role {
2845 ProviderRole::ManagementSurface { operations, .. } => {
2846 operations.iter().any(|op| op.name == operation)
2847 }
2848 _ => false,
2849 })
2850}
2851
2852fn decode_confirm_operations(
2855 manifest: &ModuleManifest,
2856 value: &Value,
2857) -> Result<Vec<String>, ConfirmOperationsError> {
2858 let operations: Vec<String> =
2859 serde_json::from_value(value.clone()).map_err(|_| ConfirmOperationsError::NotAList)?;
2860 check_confirm_operations(manifest, &operations)?;
2861 Ok(operations)
2862}
2863
2864pub fn validate_hello_confirm_operations(hello: &Value) -> Result<(), ConfirmOperationsError> {
2870 let Some(manifest_value) = hello.get("manifest") else {
2871 return Ok(());
2872 };
2873 let Some(value) = manifest_value
2874 .get("confirm_operations")
2875 .filter(|value| !value.is_null())
2876 else {
2877 return Ok(());
2878 };
2879 let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
2880 return Ok(());
2881 };
2882 decode_confirm_operations(&manifest, value).map(|_| ())
2883}
2884
2885#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2890pub struct ManagementOperation {
2891 pub name: String,
2892 pub kind: ManagementOperationKind,
2893 #[serde(default, skip_serializing_if = "Option::is_none")]
2894 pub description: Option<String>,
2895}
2896
2897#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2898#[serde(rename_all = "snake_case")]
2899pub enum ManagementOperationKind {
2900 Query,
2901 Mutate,
2902}
2903
2904#[derive(Debug, Clone, PartialEq, Eq)]
2907#[non_exhaustive]
2908pub enum OperationDelivery {
2909 Watch,
2910 Other(String),
2911}
2912
2913impl OperationDelivery {
2914 pub const WATCH: Self = Self::Watch;
2916
2917 pub fn wire_name(&self) -> &str {
2919 match self {
2920 Self::Watch => "watch",
2921 Self::Other(value) => value,
2922 }
2923 }
2924
2925 pub fn is_watch(&self) -> bool {
2927 self.wire_name() == "watch"
2928 }
2929}
2930
2931impl Serialize for OperationDelivery {
2932 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2933 where
2934 S: serde::Serializer,
2935 {
2936 serializer.serialize_str(self.wire_name())
2937 }
2938}
2939
2940impl<'de> Deserialize<'de> for OperationDelivery {
2941 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2942 where
2943 D: Deserializer<'de>,
2944 {
2945 let value = String::deserialize(deserializer)?;
2946 Ok(if value == "watch" {
2947 Self::WATCH
2948 } else {
2949 Self::Other(value)
2950 })
2951 }
2952}
2953
2954#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2956pub struct ObservabilitySurface {
2957 pub name: String,
2958 pub kind: ObservabilityKind,
2959}
2960
2961#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2962#[serde(rename_all = "snake_case")]
2963pub enum ObservabilityKind {
2964 Snapshot,
2965 Stream,
2966}
2967
2968#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2969#[serde(rename_all = "snake_case")]
2970pub enum InternalTransport {
2971 Bulk,
2972}
2973
2974#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2976#[serde(tag = "role", rename_all = "snake_case")]
2977pub enum ConsumerRole {
2978 ToolClient { of: Vec<String> },
2979 LlmClient { via: String, auth: String },
2980 ServiceClient { of: Vec<String> },
2981}
2982
2983#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2985pub struct Bindings {
2986 pub storage: StorageBinding,
2987 pub vault_grants: Vec<VaultGrant>,
2988 pub identity: IdentityBinding,
2989}
2990
2991#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2993pub struct StorageBinding {
2994 pub kind: StorageKind,
2995 pub scope: StorageScope,
2996 pub owns_schema: bool,
2997}
2998
2999#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3000#[serde(rename_all = "snake_case")]
3001pub enum StorageKind {
3002 Sqlite,
3003}
3004
3005#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3006#[serde(rename_all = "snake_case")]
3007pub enum StorageScope {
3008 Project,
3009}
3010
3011#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3012pub struct VaultGrant {
3013 pub secret: String,
3014 pub reason: String,
3015}
3016
3017#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3018pub struct IdentityBinding {
3019 pub requires: Vec<IdentityScope>,
3020 pub optional: Vec<IdentityScope>,
3021}
3022
3023#[cfg(test)]
3024mod tests {
3025 use super::*;
3026 use serde_json::json;
3027
3028 fn aft_manifest_fixture() -> ModuleManifest {
3029 ModuleManifest::builder("aft", "0.39.2")
3030 .trust_tier(Some(TrustTier::FirstParty))
3031 .bindings(Some(Bindings {
3032 storage: StorageBinding {
3033 kind: StorageKind::Sqlite,
3034 scope: StorageScope::Project,
3035 owns_schema: true,
3036 },
3037 vault_grants: vec![VaultGrant {
3038 secret: "provider_api_key".to_string(),
3039 reason: "cortexkit_native auth".to_string(),
3040 }],
3041 identity: IdentityBinding {
3042 requires: vec![IdentityScope::Project],
3043 optional: vec![IdentityScope::Session],
3044 },
3045 }))
3046 .protocol_ver(1)
3047 .provides(vec![ProviderRole::ToolProvider {
3048 tools: vec![
3049 Tool {
3050 name: "read".to_string(),
3051 description: None,
3052 execution_mode: ExecutionMode::Pure,
3053 schema: json!({"type": "object"}),
3054 },
3055 Tool {
3056 name: "grep".to_string(),
3057 description: None,
3058 execution_mode: ExecutionMode::Pure,
3059 schema: json!({"type": "object"}),
3060 },
3061 Tool {
3062 name: "outline".to_string(),
3063 description: None,
3064 execution_mode: ExecutionMode::Pure,
3065 schema: json!({"type": "object"}),
3066 },
3067 Tool {
3068 name: "semantic_search".to_string(),
3069 description: None,
3070 execution_mode: ExecutionMode::Pure,
3071 schema: json!({"type": "object"}),
3072 },
3073 Tool {
3074 name: "edit".to_string(),
3075 description: None,
3076 execution_mode: ExecutionMode::Mutating,
3077 schema: json!({"type": "object"}),
3078 },
3079 Tool {
3080 name: "write".to_string(),
3081 description: None,
3082 execution_mode: ExecutionMode::Mutating,
3083 schema: json!({"type": "object"}),
3084 },
3085 Tool {
3086 name: "bash".to_string(),
3087 description: None,
3088 execution_mode: ExecutionMode::Unfenceable,
3089 schema: json!({"type": "object"}),
3090 },
3091 ],
3092 identity_scope: vec![IdentityScope::Session, IdentityScope::Project],
3093 concurrency: Concurrency::ModuleManaged,
3094 emits_push: true,
3095 sub_supervises: true,
3096 }])
3097 .consumes(vec![ConsumerRole::ServiceClient {
3098 of: vec!["embedding.v2".to_string()],
3099 }])
3100 .build()
3101 }
3102
3103 #[test]
3104 fn serde_round_trips_representative_manifest() {
3105 let manifest = aft_manifest_fixture();
3106 let serialized = serde_json::to_string_pretty(&manifest).unwrap();
3107 let decoded: ModuleManifest = serde_json::from_str(&serialized).unwrap();
3108
3109 assert_eq!(manifest, decoded);
3110 }
3111
3112 #[test]
3113 fn builder_defaults_additions_to_honest_absence_and_round_trips() {
3114 let manifest = ModuleManifest::builder("builder-defaults", "2.0.0").build();
3115
3116 assert_eq!(manifest.module_id, "builder-defaults");
3117 assert_eq!(manifest.module_version, "2.0.0");
3118 assert_eq!(manifest.display_name, None);
3119 assert_eq!(manifest.protocol_ver, PROTOCOL_VERSION);
3120 assert_eq!(manifest.trust_tier, None);
3121 assert!(manifest.provides.is_empty());
3122 assert!(manifest.consumes.is_empty());
3123 assert_eq!(manifest.bindings, None);
3124 assert_eq!(manifest.capabilities, None);
3125 assert_eq!(manifest.self_signals, None);
3126 assert_eq!(manifest.provenance, None);
3127
3128 let encoded = serde_json::to_value(&manifest).expect("builder manifest serializes");
3129 for optional in [
3130 "display_name",
3131 "trust_tier",
3132 "consumes",
3133 "bindings",
3134 "capabilities",
3135 "self_signals",
3136 "provenance",
3137 ] {
3138 assert!(
3139 encoded.get(optional).is_none(),
3140 "an absent {optional} declaration must stay absent on the wire"
3141 );
3142 }
3143 let decoded: ModuleManifest =
3144 serde_json::from_value(encoded).expect("builder manifest round-trips");
3145 assert_eq!(decoded, manifest);
3146 }
3147
3148 #[test]
3149 fn fully_populated_builder_manifest_matches_the_literal_wire_golden() {
3150 let manifest = ModuleManifest::builder("full-builder", "2.0.0")
3151 .display_name(Some("Example".to_string()))
3152 .unwrap()
3153 .trust_tier(Some(TrustTier::Reviewed))
3154 .bindings(Some(Bindings {
3155 storage: StorageBinding {
3156 kind: StorageKind::Sqlite,
3157 scope: StorageScope::Project,
3158 owns_schema: false,
3159 },
3160 vault_grants: Vec::new(),
3161 identity: IdentityBinding {
3162 requires: vec![IdentityScope::Project],
3163 optional: Vec::new(),
3164 },
3165 }))
3166 .provides(vec![ProviderRole::ToolProvider {
3167 tools: vec![Tool {
3168 name: "read".to_string(),
3169 description: None,
3170 execution_mode: ExecutionMode::Pure,
3171 schema: json!({"type": "object"}),
3172 }],
3173 identity_scope: vec![IdentityScope::Project],
3174 concurrency: Concurrency::Serial,
3175 emits_push: false,
3176 sub_supervises: false,
3177 }])
3178 .consumes(vec![ConsumerRole::ServiceClient {
3179 of: vec!["embedding.v2".to_string()],
3180 }])
3181 .capabilities(Some(CapabilityDeclarations {
3182 provides: vec!["embedding/v2".to_string()],
3183 requires: Vec::new(),
3184 must_never_reach: Vec::new(),
3185 }))
3186 .self_signals(Some(vec![SelfSignalDeclaration {
3187 name: "usage_poller".to_string(),
3188 kind: SelfSignalKind::Poller,
3189 effect: SelfSignalEffect::Observe,
3190 anchored_to: SignalAnchor::FixedInterval,
3191 cadence: Some(SignalCadence::Literal {
3192 interval_ms: 60_000,
3193 }),
3194 domain: Some("provider-usage".to_string()),
3195 note: None,
3196 }]))
3197 .provenance(Some(ManifestProvenance {
3198 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
3199 build_git_sha_absence_reason: None,
3200 build_lock_digest: Some(
3201 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
3202 ),
3203 wire_crate_version: Some("0.16.0".to_string()),
3204 store_schema_version: Some("42".to_string()),
3205 launch_nonce_source: None,
3206 }))
3207 .build();
3208
3209 assert_eq!(
3210 serde_json::to_vec(&manifest).expect("builder manifest serializes"),
3211 include_bytes!("../tests/golden/module_manifest_builder_full.json"),
3212 "the builder must match the fully populated manifest wire bytes"
3213 );
3214 }
3215
3216 #[test]
3217 fn display_name_validator_enforces_scalar_bounds_and_safe_text() {
3218 for valid in [
3219 "Routing".to_string(),
3220 "名".repeat(40),
3221 "a".repeat(40),
3222 "e\u{301}".repeat(20),
3223 ] {
3224 assert!(validate_display_name(&valid).is_ok(), "{valid:?}");
3225 }
3226 let mut invalid = vec![
3227 "".to_string(),
3228 "a".repeat(41),
3229 "名".repeat(41),
3230 " Routing".to_string(),
3231 "Routing ".to_string(),
3232 "\u{2003}Routing".to_string(),
3233 "a\nb".to_string(),
3234 "a\u{0085}b".to_string(),
3235 "a\u{007f}b".to_string(),
3236 ];
3237 for code in [0x061c, 0x200e, 0x200f]
3238 .into_iter()
3239 .chain(0x202a..=0x202e)
3240 .chain(0x2066..=0x2069)
3241 {
3242 invalid.push(format!("a{}b", char::from_u32(code).unwrap()));
3243 }
3244 let accepted: Vec<_> = invalid
3245 .iter()
3246 .filter(|value| validate_display_name(value).is_ok())
3247 .collect();
3248 assert!(
3249 accepted.is_empty(),
3250 "invalid display names accepted: {accepted:?}"
3251 );
3252 }
3253
3254 #[test]
3255 fn display_name_builder_refuses_invalid_value() {
3256 let error = ModuleManifest::builder("provider", "1.0.0")
3257 .display_name(Some(" Routing".to_string()))
3258 .unwrap_err();
3259 assert!(error.to_string().contains("display_name"));
3260 }
3261
3262 #[test]
3263 fn display_name_manifest_round_trips_and_keeps_unknown_fields_lenient() {
3264 let manifest = ModuleManifest::builder("provider", "1.0.0")
3265 .display_name(Some("Routing".to_string()))
3266 .unwrap()
3267 .build();
3268 let mut wire = serde_json::to_value(&manifest).unwrap();
3269 assert_eq!(wire["display_name"], "Routing");
3270 wire["future_manifest_field"] = json!(true);
3271 assert_eq!(
3272 serde_json::from_value::<ModuleManifest>(wire.clone()).unwrap(),
3273 manifest
3274 );
3275 wire["display_name"] = json!("bad\nname");
3276 assert!(serde_json::from_value::<ModuleManifest>(wire)
3277 .unwrap_err()
3278 .to_string()
3279 .contains("display_name"));
3280 }
3281
3282 #[test]
3283 fn old_manifest_with_unread_fields_decodes_and_round_trips_verbatim() {
3284 let raw = include_bytes!("../tests/golden/module_manifest_builder_full.json");
3285 let decoded: ModuleManifest =
3286 serde_json::from_slice(raw).expect("old manifest with all unread fields decodes");
3287
3288 assert_eq!(decoded.trust_tier, Some(TrustTier::Reviewed));
3289 assert!(!decoded.consumes.is_empty());
3290 assert!(decoded.bindings.is_some());
3291
3292 let reencoded = serde_json::to_vec(&decoded).expect("re-encode succeeds");
3293 assert_eq!(
3294 reencoded, raw,
3295 "old manifest relay stays byte-for-byte verbatim"
3296 );
3297 }
3298
3299 #[test]
3300 fn new_manifest_omits_unread_fields_on_wire_and_decodes_cleanly() {
3301 let raw = include_bytes!("../tests/golden/module_manifest_diet.json");
3302 let decoded: ModuleManifest =
3303 serde_json::from_slice(raw).expect("new manifest omitting unread fields decodes");
3304
3305 assert_eq!(decoded.trust_tier, None);
3306 assert!(decoded.consumes.is_empty());
3307 assert_eq!(decoded.bindings, None);
3308
3309 let pretty = format!("{}\n", serde_json::to_string_pretty(&decoded).unwrap());
3310 assert_eq!(
3311 pretty.as_bytes(),
3312 raw,
3313 "new manifest matches golden byte-for-byte without unread keys"
3314 );
3315
3316 let as_val: serde_json::Value = serde_json::to_value(&decoded).unwrap();
3317 assert!(
3318 as_val.get("trust_tier").is_none(),
3319 "no trust_tier on wire for new manifest"
3320 );
3321 assert!(
3322 as_val.get("consumes").is_none(),
3323 "no consumes on wire for empty consumes"
3324 );
3325 assert!(
3326 as_val.get("bindings").is_none(),
3327 "no bindings on wire for new manifest"
3328 );
3329 }
3330
3331 #[test]
3332 fn aft_manifest_fixture_matches_v1_contract() {
3333 let manifest = aft_manifest_fixture();
3334
3335 assert_eq!(manifest.module_id, "aft");
3336 let ProviderRole::ToolProvider {
3337 tools,
3338 identity_scope,
3339 concurrency,
3340 emits_push,
3341 sub_supervises,
3342 } = &manifest.provides[0]
3343 else {
3344 panic!("AFT fixture must expose one tool_provider role");
3345 };
3346
3347 assert_eq!(*concurrency, Concurrency::ModuleManaged);
3348 assert!(*emits_push);
3349 assert!(*sub_supervises);
3350 assert_eq!(
3351 identity_scope,
3352 &vec![IdentityScope::Session, IdentityScope::Project]
3353 );
3354 assert_eq!(
3355 tools
3356 .iter()
3357 .map(|tool| (tool.name.as_str(), tool.execution_mode))
3358 .collect::<Vec<_>>(),
3359 vec![
3360 ("read", ExecutionMode::Pure),
3361 ("grep", ExecutionMode::Pure),
3362 ("outline", ExecutionMode::Pure),
3363 ("semantic_search", ExecutionMode::Pure),
3364 ("edit", ExecutionMode::Mutating),
3365 ("write", ExecutionMode::Mutating),
3366 ("bash", ExecutionMode::Unfenceable),
3367 ]
3368 );
3369 }
3370
3371 #[test]
3372 fn tool_provider_role_tag_serializes_as_snake_case() {
3373 let manifest = aft_manifest_fixture();
3374 let value = serde_json::to_value(&manifest).unwrap();
3375
3376 assert_eq!(value["provides"][0]["role"], "tool_provider");
3377 }
3378
3379 #[test]
3380 fn manifest_without_capabilities_preserves_the_existing_wire_shape() {
3381 let manifest = aft_manifest_fixture();
3382 let encoded = serde_json::to_value(&manifest).expect("manifest serializes");
3383 assert!(encoded.get("capabilities").is_none());
3384
3385 let decoded: ModuleManifest =
3386 serde_json::from_value(encoded).expect("legacy manifest parses");
3387 assert_eq!(decoded.capabilities, None);
3388 }
3389
3390 #[test]
3391 fn capability_identifier_lexical_grammar_accepts_only_pinned_forms() {
3392 for identifier in [
3393 "a/v1",
3394 "credentials-provider/v1",
3395 "a1-b2/v4294967295",
3396 "a123456789012345678901234567890123456789012345678901234567890123/v1",
3397 ] {
3398 assert!(
3399 is_valid_capability_identifier(identifier),
3400 "identifier must be accepted: {identifier}"
3401 );
3402 }
3403
3404 for identifier in [
3405 "credentials-Provider/v1",
3406 "credentials-provider/v01",
3407 "credentials-provider-/v1",
3408 "credentials--provider/v1",
3409 "Credentials-provider/v1",
3410 "credentials-provider/1",
3411 "credentials provider/v1",
3412 "credentials-provider/v0",
3413 "credentials-provider/v4294967296",
3414 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/v1",
3415 ] {
3416 assert!(
3417 !is_valid_capability_identifier(identifier),
3418 "identifier must be rejected: {identifier}"
3419 );
3420 }
3421 }
3422
3423 #[test]
3424 fn capability_grammar_errors_redact_secret_shaped_values() {
3425 let error = validate_manifest_capability_grammar(&json!({
3426 "capabilities": { "provides": ["sk-secret-value/v0"] }
3427 }))
3428 .expect_err("secret-shaped capability identifier is malformed");
3429 assert_eq!(error.field(), "capabilities.provides[0]");
3430 assert_eq!(error.value(), "<redacted>");
3431 assert!(!error.to_string().contains("sk-secret-value"));
3432 }
3433
3434 #[test]
3441 fn provenance_builder_sentinels_become_field_omission() {
3442 for sentinel in [
3443 "unknown",
3444 "UNKNOWN",
3445 "Unknown",
3446 "unavailable",
3447 "none",
3448 "None",
3449 " unknown ",
3450 "",
3451 ] {
3452 let p = build_provenance_from_source(
3453 BuildGitShaSource::Git {
3454 revision: sentinel,
3455 tree_state: GitTreeState::Clean,
3456 },
3457 Some(sentinel),
3458 Some(sentinel),
3459 )
3460 .expect("sentinels are omitted before form validation");
3461 assert_eq!(
3462 (
3463 p.build_git_sha,
3464 p.build_git_sha_absence_reason,
3465 p.build_lock_digest,
3466 p.store_schema_version,
3467 ),
3468 (
3469 None,
3470 Some(BuildGitShaAbsenceReason::NeverDerived),
3471 None,
3472 None,
3473 ),
3474 "sentinel {sentinel:?} must be omitted, not published"
3475 );
3476 }
3477 let real = build_provenance_from_source(
3478 BuildGitShaSource::Git {
3479 revision: "0123456789abcdef0123456789abcdef01234567",
3480 tree_state: GitTreeState::Clean,
3481 },
3482 None,
3483 Some("9"),
3484 )
3485 .expect("canonical build revision is accepted");
3486 assert_eq!(
3487 real.build_git_sha.as_deref(),
3488 Some("0123456789abcdef0123456789abcdef01234567")
3489 );
3490 assert_eq!(real.store_schema_version.as_deref(), Some("9"));
3491 assert_eq!(
3495 real.wire_crate_version.as_deref(),
3496 Some(crate::SUBC_PROTOCOL_CRATE_VERSION)
3497 );
3498 }
3499
3500 #[test]
3501 fn build_provenance_accepts_canonical_sha_and_lock_digest() {
3502 let provenance = build_provenance_from_source(
3503 BuildGitShaSource::Git {
3504 revision: " 0123456789abcdef0123456789abcdef01234567 ",
3505 tree_state: GitTreeState::Clean,
3506 },
3507 Some(" abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789 "),
3508 Some(" schema-v3 "),
3509 )
3510 .expect("canonical build facts are accepted");
3511
3512 assert_eq!(
3513 provenance,
3514 ManifestProvenance {
3515 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
3516 build_git_sha_absence_reason: None,
3517 build_lock_digest: Some(
3518 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
3519 ),
3520 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
3521 store_schema_version: Some("schema-v3".to_string()),
3522 launch_nonce_source: None,
3523 }
3524 );
3525 }
3526
3527 #[test]
3528 fn build_provenance_refuses_an_abbreviated_git_sha() {
3529 let error = build_provenance_from_source(
3530 BuildGitShaSource::Git {
3531 revision: "0123456789ab",
3532 tree_state: GitTreeState::Clean,
3533 },
3534 None,
3535 None,
3536 )
3537 .expect_err("a 12-character abbreviation is not canonical");
3538
3539 assert_eq!(error.field(), "build_git_sha");
3540 assert_eq!(error.length(), 12);
3541 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3542 assert_eq!(
3543 error.to_string(),
3544 "invalid manifest provenance form: field build_git_sha has length 12; canonical form is exactly 40 lowercase hexadecimal characters"
3545 );
3546 }
3547
3548 #[test]
3549 fn build_provenance_refuses_an_abbreviated_lock_digest() {
3550 let error = build_provenance_from_source(
3551 BuildGitShaSource::NeverDerived,
3552 Some("0123456789abcdef"),
3553 None,
3554 )
3555 .expect_err("a 16-character digest is not canonical");
3556
3557 assert_eq!(error.field(), "build_lock_digest");
3558 assert_eq!(error.length(), 16);
3559 assert_eq!(error.canonical_form(), BUILD_LOCK_DIGEST_CANONICAL_FORM);
3560 }
3561
3562 #[test]
3563 fn build_provenance_refuses_uppercase_hex() {
3564 let uppercase_sha = "A".repeat(40);
3565 let error = build_provenance_from_source(
3566 BuildGitShaSource::Git {
3567 revision: &uppercase_sha,
3568 tree_state: GitTreeState::Clean,
3569 },
3570 None,
3571 None,
3572 )
3573 .expect_err("uppercase hexadecimal is not canonical");
3574
3575 assert_eq!(error.field(), "build_git_sha");
3576 assert_eq!(error.length(), 40);
3577 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3578 }
3579
3580 #[test]
3581 fn build_provenance_refuses_dirty_revision_stamp_claimed_clean() {
3582 let error = build_provenance_from_source(
3583 BuildGitShaSource::Git {
3584 revision: "0123456789abcdef0123456789abcdef01234567-dirty",
3585 tree_state: GitTreeState::Clean,
3586 },
3587 None,
3588 None,
3589 )
3590 .expect_err("a dirty stamp is not a canonical build revision");
3591
3592 assert_eq!(error.field(), "build_git_sha");
3593 assert_eq!(error.length(), 46);
3594 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3595 }
3596
3597 #[test]
3598 fn build_provenance_keeps_a_lock_digest_when_identity_is_unavailable() {
3599 let provenance = build_provenance_from_source(
3600 BuildGitShaSource::Git {
3601 revision: "unavailable",
3602 tree_state: GitTreeState::Clean,
3603 },
3604 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"),
3605 None,
3606 )
3607 .expect("sentinel SHA is omitted before the valid lock digest is checked");
3608
3609 assert_eq!(provenance.build_git_sha, None);
3610 assert_eq!(
3611 provenance.build_lock_digest,
3612 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string())
3613 );
3614 assert_eq!(
3615 provenance.wire_crate_version,
3616 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
3617 );
3618 }
3619
3620 #[test]
3621 fn build_provenance_omits_fully_unavailable_inputs() {
3622 let provenance = build_provenance_from_source(
3623 BuildGitShaSource::NeverDerived,
3624 Some(" unavailable "),
3625 Some(" "),
3626 )
3627 .expect("omitted and sentinel inputs are not form errors");
3628
3629 assert_eq!(provenance.build_git_sha, None);
3630 assert_eq!(provenance.build_lock_digest, None);
3631 assert_eq!(provenance.store_schema_version, None);
3632 assert_eq!(
3633 provenance.wire_crate_version,
3634 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
3635 );
3636 }
3637
3638 #[test]
3639 fn legacy_build_provenance_keeps_master_wire_bytes_without_an_absence_reason() {
3640 let revision = "0123456789abcdef0123456789abcdef01234567";
3641 for (input, expected) in [
3642 (
3643 Some(revision),
3644 format!(
3645 r#"{{"build_git_sha":"{revision}","wire_crate_version":"{}"}}"#,
3646 crate::SUBC_PROTOCOL_CRATE_VERSION
3647 ),
3648 ),
3649 (
3650 None,
3651 format!(
3652 r#"{{"wire_crate_version":"{}"}}"#,
3653 crate::SUBC_PROTOCOL_CRATE_VERSION
3654 ),
3655 ),
3656 (
3657 Some("unknown"),
3658 format!(
3659 r#"{{"wire_crate_version":"{}"}}"#,
3660 crate::SUBC_PROTOCOL_CRATE_VERSION
3661 ),
3662 ),
3663 ] {
3664 let provenance = build_provenance(input, None, None)
3665 .expect("the legacy build facts remain constructible");
3666 assert_eq!(provenance.build_git_sha_absence_reason, None);
3667 assert_eq!(
3668 serde_json::to_string(&provenance).expect("legacy provenance serializes"),
3669 expected
3670 );
3671 }
3672 }
3673
3674 #[test]
3675 fn build_provenance_derives_git_sha_absence_from_the_stamping_inputs() {
3676 let revision = "0123456789abcdef0123456789abcdef01234567";
3677 let cases = [
3678 (
3679 BuildGitShaSource::Git {
3680 revision,
3681 tree_state: GitTreeState::Clean,
3682 },
3683 Some(revision),
3684 None,
3685 ),
3686 (
3687 BuildGitShaSource::Git {
3688 revision,
3689 tree_state: GitTreeState::Dirty,
3690 },
3691 None,
3692 Some(BuildGitShaAbsenceReason::DeclinedDirty),
3693 ),
3694 (
3695 BuildGitShaSource::NeverDerived,
3696 None,
3697 Some(BuildGitShaAbsenceReason::NeverDerived),
3698 ),
3699 (
3700 BuildGitShaSource::NoGitDir,
3701 None,
3702 Some(BuildGitShaAbsenceReason::NoGitDir),
3703 ),
3704 ];
3705
3706 for (source, expected_sha, expected_reason) in cases {
3707 let provenance = build_provenance_from_source(source, None, None)
3708 .expect("every stamping state constructs honest provenance");
3709 assert_eq!(provenance.build_git_sha.as_deref(), expected_sha);
3710 assert_eq!(provenance.build_git_sha_absence_reason, expected_reason);
3711 }
3712 }
3713
3714 #[test]
3715 fn unknown_git_sha_absence_reason_round_trips_byte_faithfully() {
3716 let wire = format!(
3717 r#"{{"build_git_sha_absence_reason":"future_stamper_state","wire_crate_version":"{}"}}"#,
3718 crate::SUBC_PROTOCOL_CRATE_VERSION
3719 );
3720 let provenance: ManifestProvenance =
3721 serde_json::from_str(&wire).expect("future absence reasons remain readable");
3722
3723 assert_eq!(
3724 provenance.build_git_sha_absence_reason,
3725 Some(BuildGitShaAbsenceReason::ForwardCompatibleUnknown(
3726 "future_stamper_state".to_string()
3727 ))
3728 );
3729 assert_eq!(
3730 serde_json::to_string(&provenance).expect("future absence reason reserializes"),
3731 wire
3732 );
3733 }
3734
3735 #[test]
3736 fn provenance_rejects_an_absence_reason_beside_a_declared_commit() {
3737 let error = serde_json::from_value::<ManifestProvenance>(json!({
3738 "build_git_sha": "0123456789abcdef0123456789abcdef01234567",
3739 "build_git_sha_absence_reason": "declined_dirty"
3740 }))
3741 .expect_err("a declared commit cannot also claim an absence reason");
3742
3743 assert!(error.to_string().contains(
3744 "build_git_sha_absence_reason has must be omitted when build_git_sha is present"
3745 ));
3746 }
3747
3748 #[test]
3749 fn rich_ui_descriptor_is_optional_and_round_trips_when_present() {
3750 let manifest = ModuleManifest::builder("provider", "1.0.0").build();
3751 assert_eq!(
3752 serde_json::to_string(&manifest).unwrap(),
3753 r#"{"module_id":"provider","module_version":"1.0.0","protocol_ver":2,"provides":[]}"#
3754 );
3755
3756 let descriptor = RichUiDescriptor::new(
3757 "ckios.richui.manifest/1",
3758 format!("sha256:{}", "a".repeat(64)),
3759 128,
3760 2,
3761 );
3762 let manifest = ModuleManifest::builder("provider", "1.0.0")
3763 .rich_ui(Some(descriptor.clone()))
3764 .build();
3765 let wire = serde_json::to_string(&manifest).unwrap();
3766 assert!(wire.contains("\"rich_ui\":{\"schema\":\"ckios.richui.manifest/1\""));
3767 assert_eq!(
3768 serde_json::from_str::<ModuleManifest>(&wire)
3769 .unwrap()
3770 .rich_ui,
3771 Some(descriptor)
3772 );
3773 }
3774
3775 #[test]
3776 fn rich_ui_descriptor_validation_names_each_invalid_field() {
3777 let good = json!({
3778 "schema": "ckios.richui.manifest/1",
3779 "manifest_digest": format!("sha256:{}", "a".repeat(64)),
3780 "bytes": 1,
3781 "chunks": 1
3782 });
3783 let hello = json!({"manifest": {"rich_ui": good.clone()}});
3784 assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
3785
3786 for (field, value) in [
3787 ("schema", json!("bad schema")),
3788 (
3789 "manifest_digest",
3790 json!(format!("sha256:{}", "A".repeat(64))),
3791 ),
3792 ("bytes", json!(0)),
3793 ("chunks", json!(1025)),
3794 ] {
3795 let mut invalid = hello.clone();
3796 invalid["manifest"]["rich_ui"][field] = value;
3797 let error = validate_hello_rich_ui_descriptor(&invalid)
3798 .expect_err("an invalid descriptor field must be refused");
3799 assert_eq!(error.field(), format!("rich_ui.{field}"));
3800 }
3801
3802 let mut hello = hello;
3803 hello["manifest"]["rich_ui"] = Value::Null;
3804 let error = validate_hello_rich_ui_descriptor(&hello)
3805 .expect_err("null is not an absent descriptor");
3806 assert_eq!(error.field(), "rich_ui");
3807 }
3808
3809 #[test]
3810 fn rich_ui_descriptor_validation_accepts_inclusive_bounds() {
3811 let hello = json!({"manifest": {"rich_ui": {
3812 "schema": "a".repeat(64),
3813 "manifest_digest": format!("sha256:{}", "f".repeat(64)),
3814 "bytes": 16_777_216,
3815 "chunks": 1024
3816 }}});
3817 assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
3818 }
3819}