1use std::{
10 collections::{BTreeMap, HashSet},
11 fmt,
12};
13
14use serde::{de::Error as _, Deserialize, Deserializer, Serialize};
15use serde_json::Value;
16
17use crate::PROTOCOL_VERSION;
18
19pub const MAX_ROLE_DECLARATIONS_BYTES: usize = 16_384;
21
22pub const MAX_FLOW_OPERATIONS: usize = 256;
24
25pub const MAX_CONFIRM_OPERATIONS: usize = 256;
27
28#[derive(Serialize, Debug, Clone, PartialEq)]
35#[non_exhaustive]
36pub struct ModuleManifest {
37 pub module_id: String,
38 #[serde(default, skip_serializing_if = "Option::is_none")]
40 pub display_name: Option<String>,
41 pub module_version: String,
42 pub protocol_ver: u8,
43 #[serde(default, skip_serializing_if = "Option::is_none")]
44 pub trust_tier: Option<TrustTier>,
45 #[serde(default, skip_serializing_if = "Option::is_none")]
52 pub ready: Option<bool>,
53 pub provides: Vec<ProviderRole>,
56 #[serde(default, skip_serializing_if = "Vec::is_empty")]
57 pub consumes: Vec<ConsumerRole>,
58 #[serde(default, skip_serializing_if = "Option::is_none")]
59 pub bindings: Option<Bindings>,
60 #[serde(default, skip_serializing_if = "Option::is_none")]
66 pub capabilities: Option<CapabilityDeclarations>,
67 #[serde(default, skip_serializing_if = "Option::is_none")]
81 pub events: Option<Vec<EventDeclaration>>,
82 #[serde(default, skip_serializing_if = "Option::is_none")]
117 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
118 #[serde(default, skip_serializing_if = "Option::is_none")]
119 pub provenance: Option<ManifestProvenance>,
120 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
125 pub operation_delivery: BTreeMap<String, OperationDelivery>,
126 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
129 pub operation_payload: BTreeMap<String, OperationPayload>,
130 #[serde(default, skip_serializing_if = "Option::is_none")]
149 pub flow_operations: Option<Vec<String>>,
150 #[serde(default, skip_serializing_if = "Option::is_none")]
154 pub operation_deferral: Option<BTreeMap<String, bool>>,
155 #[serde(default, skip_serializing_if = "Option::is_none")]
172 pub confirm_operations: Option<Vec<String>>,
173 #[serde(default, skip_serializing_if = "Option::is_none")]
178 pub rich_ui: Option<RichUiDescriptor>,
179 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
188 pub role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
189}
190
191#[derive(Debug, Clone)]
193pub struct ModuleManifestBuilder {
194 module_id: String,
195 display_name: Option<String>,
196 module_version: String,
197 protocol_ver: u8,
198 trust_tier: Option<TrustTier>,
199 ready: Option<bool>,
200 provides: Vec<ProviderRole>,
201 consumes: Vec<ConsumerRole>,
202 bindings: Option<Bindings>,
203 capabilities: Option<CapabilityDeclarations>,
204 events: Option<Vec<EventDeclaration>>,
205 self_signals: Option<Vec<SelfSignalDeclaration>>,
206 provenance: Option<ManifestProvenance>,
207 operation_delivery: BTreeMap<String, OperationDelivery>,
208 operation_payload: BTreeMap<String, OperationPayload>,
209 flow_operations: Option<Vec<String>>,
210 operation_deferral: Option<BTreeMap<String, bool>>,
211 confirm_operations: Option<Vec<String>>,
212 rich_ui: Option<RichUiDescriptor>,
213 role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
214}
215
216impl ModuleManifest {
217 pub fn builder(
225 module_id: impl Into<String>,
226 module_version: impl Into<String>,
227 ) -> ModuleManifestBuilder {
228 ModuleManifestBuilder {
229 module_id: module_id.into(),
230 display_name: None,
231 module_version: module_version.into(),
232 protocol_ver: PROTOCOL_VERSION,
233 trust_tier: None,
234 ready: None,
235 provides: Vec::new(),
236 consumes: Vec::new(),
237 bindings: None,
238 capabilities: None,
239 events: None,
240 self_signals: None,
241 provenance: None,
242 operation_delivery: BTreeMap::new(),
243 operation_payload: BTreeMap::new(),
244 flow_operations: None,
245 operation_deferral: None,
246 confirm_operations: None,
247 rich_ui: None,
248 role_declarations: BTreeMap::new(),
249 }
250 }
251
252 pub fn is_watch_operation(&self, name: &str) -> bool {
257 self.operation_delivery
258 .get(name)
259 .is_some_and(OperationDelivery::is_watch)
260 && self.provides.iter().any(|role| match role {
261 ProviderRole::ManagementSurface { operations, .. } => operations
262 .iter()
263 .any(|op| op.name == name && op.kind == ManagementOperationKind::Query),
264 _ => false,
265 })
266 }
267}
268
269impl ModuleManifestBuilder {
270 pub fn display_name(mut self, display_name: Option<String>) -> Result<Self, DisplayNameError> {
272 if let Some(value) = &display_name {
273 validate_display_name(value)?;
274 }
275 self.display_name = display_name;
276 Ok(self)
277 }
278
279 pub fn protocol_ver(mut self, protocol_ver: u8) -> Self {
281 self.protocol_ver = protocol_ver;
282 self
283 }
284
285 pub fn trust_tier(mut self, trust_tier: Option<TrustTier>) -> Self {
289 self.trust_tier = trust_tier;
290 self
291 }
292
293 pub fn ready(mut self, ready: bool) -> Self {
295 self.ready = Some(ready);
296 self
297 }
298
299 pub fn provides(mut self, provides: Vec<ProviderRole>) -> Self {
301 self.provides = provides;
302 self
303 }
304
305 pub fn consumes(mut self, consumes: Vec<ConsumerRole>) -> Self {
307 self.consumes = consumes;
308 self
309 }
310
311 pub fn bindings(mut self, bindings: Option<Bindings>) -> Self {
315 self.bindings = bindings;
316 self
317 }
318
319 pub fn capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
321 self.capabilities = capabilities;
322 self
323 }
324
325 pub fn events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
327 self.events = events;
328 self
329 }
330
331 pub fn self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
333 self.self_signals = self_signals;
334 self
335 }
336
337 pub fn provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
339 self.provenance = provenance;
340 self
341 }
342
343 pub fn operation_delivery(
345 mut self,
346 operation_delivery: BTreeMap<String, OperationDelivery>,
347 ) -> Self {
348 self.operation_delivery = operation_delivery;
349 self
350 }
351
352 pub fn operation_payload(
354 mut self,
355 operation_payload: BTreeMap<String, OperationPayload>,
356 ) -> Self {
357 self.operation_payload = operation_payload;
358 self
359 }
360
361 pub fn flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
368 self.flow_operations = flow_operations;
369 self
370 }
371
372 pub fn operation_deferral(mut self, operations: Option<BTreeMap<String, bool>>) -> Self {
374 self.operation_deferral = operations;
375 self
376 }
377
378 pub fn confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
385 self.confirm_operations = confirm_operations;
386 self
387 }
388
389 pub fn rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
391 self.rich_ui = rich_ui;
392 self
393 }
394
395 pub fn role_declarations(
397 mut self,
398 role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
399 ) -> Self {
400 self.role_declarations = role_declarations;
401 self
402 }
403
404 pub fn build(self) -> ModuleManifest {
406 ModuleManifest {
407 module_id: self.module_id,
408 display_name: self.display_name,
409 module_version: self.module_version,
410 protocol_ver: self.protocol_ver,
411 trust_tier: self.trust_tier,
412 ready: self.ready,
413 provides: self.provides,
414 consumes: self.consumes,
415 bindings: self.bindings,
416 capabilities: self.capabilities,
417 events: self.events,
418 self_signals: self.self_signals,
419 provenance: self.provenance,
420 operation_delivery: self.operation_delivery,
421 operation_payload: self.operation_payload,
422 flow_operations: self.flow_operations,
423 operation_deferral: self.operation_deferral,
424 confirm_operations: self.confirm_operations,
425 rich_ui: self.rich_ui,
426 role_declarations: self.role_declarations,
427 }
428 }
429}
430
431#[derive(Deserialize)]
451struct ModuleManifestWire {
452 module_id: String,
453 #[serde(default)]
454 display_name: Option<String>,
455 module_version: String,
456 protocol_ver: u8,
457 #[serde(default)]
458 trust_tier: Option<TrustTier>,
459 #[serde(default)]
460 ready: Option<bool>,
461 provides: Vec<ProviderRole>,
462 #[serde(default)]
463 consumes: Vec<ConsumerRole>,
464 #[serde(default)]
465 bindings: Option<Bindings>,
466 #[serde(default)]
467 capabilities: Option<CapabilityDeclarations>,
468 #[serde(default)]
469 events: Option<Value>,
470 #[serde(default)]
471 self_signals: Option<Vec<SelfSignalDeclaration>>,
472 #[serde(default)]
473 provenance: Option<ManifestProvenance>,
474 #[serde(default)]
475 operation_delivery: Option<Value>,
476 #[serde(default)]
477 operation_payload: BTreeMap<String, OperationPayload>,
478 #[serde(default)]
480 flow_operations: Option<Value>,
481 #[serde(default)]
482 operation_deferral: Option<Value>,
483 #[serde(default)]
485 confirm_operations: Option<Value>,
486 #[serde(default)]
487 rich_ui: Option<RichUiDescriptor>,
488 #[serde(default)]
492 runtime_computed: Option<Value>,
493 #[serde(default)]
494 role_declarations: Option<Value>,
495}
496
497impl<'de> Deserialize<'de> for ModuleManifest {
498 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
499 where
500 D: Deserializer<'de>,
501 {
502 let wire = ModuleManifestWire::deserialize(deserializer)?;
503 validate_runtime_computed(wire.runtime_computed.as_ref(), "runtime_computed")
504 .map_err(D::Error::custom)?;
505 validate_events_value(wire.events.as_ref()).map_err(D::Error::custom)?;
506 let events = wire
507 .events
508 .map(serde_json::from_value)
509 .transpose()
510 .map_err(D::Error::custom)?;
511 let mut builder = Self::builder(wire.module_id, wire.module_version)
512 .display_name(wire.display_name)
513 .map_err(D::Error::custom)?
514 .protocol_ver(wire.protocol_ver)
515 .trust_tier(wire.trust_tier);
516 if let Some(ready) = wire.ready {
517 builder = builder.ready(ready);
518 }
519 let mut manifest = builder
520 .provides(wire.provides)
521 .consumes(wire.consumes)
522 .bindings(wire.bindings)
523 .capabilities(wire.capabilities)
524 .events(events)
525 .self_signals(wire.self_signals)
526 .provenance(wire.provenance)
527 .operation_delivery(
528 wire.operation_delivery
529 .and_then(|value| serde_json::from_value(value).ok())
530 .unwrap_or_default(),
531 )
532 .rich_ui(wire.rich_ui)
533 .role_declarations(
534 wire.role_declarations
535 .filter(|value| validate_role_declarations_value(Some(value)).is_ok())
536 .and_then(|value| serde_json::from_value(value).ok())
537 .unwrap_or_default(),
538 )
539 .operation_payload(wire.operation_payload)
540 .build();
541 manifest
542 .validate_operation_payload()
543 .map_err(D::Error::custom)?;
544 manifest.flow_operations = wire
547 .flow_operations
548 .and_then(|value| decode_flow_operations(&manifest, &value).ok());
549 manifest.operation_deferral = wire
550 .operation_deferral
551 .and_then(|value| decode_operation_deferral(&manifest, &value).ok());
552 manifest.confirm_operations = wire
553 .confirm_operations
554 .and_then(|value| decode_confirm_operations(&manifest, &value).ok());
555 manifest
556 .validate_capability_grammar()
557 .map_err(D::Error::custom)?;
558 if let Some(rich_ui) = &manifest.rich_ui {
559 rich_ui.validate().map_err(D::Error::custom)?;
560 }
561 Ok(manifest)
562 }
563}
564
565#[derive(Debug, Clone, PartialEq, Eq)]
567pub struct RoleDeclarationsError(&'static str);
568
569impl fmt::Display for RoleDeclarationsError {
570 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
571 f.write_str(self.0)
572 }
573}
574
575impl std::error::Error for RoleDeclarationsError {}
576
577pub fn validate_hello_role_declarations(hello: &Value) -> Result<(), RoleDeclarationsError> {
579 validate_role_declarations_value(
580 hello
581 .get("manifest")
582 .and_then(|manifest| manifest.get("role_declarations")),
583 )
584}
585
586fn validate_role_declarations_value(value: Option<&Value>) -> Result<(), RoleDeclarationsError> {
587 let Some(value) = value else {
588 return Ok(());
589 };
590 let map = value
591 .as_object()
592 .ok_or(RoleDeclarationsError("role_declarations must be an object"))?;
593 for (role, declaration) in map {
594 if !is_valid_capability_identifier(role) {
595 return Err(RoleDeclarationsError(
596 "role_declarations key must use capability-name grammar",
597 ));
598 }
599 if !declaration.is_object() {
600 return Err(RoleDeclarationsError(
601 "role_declarations values must be objects",
602 ));
603 }
604 }
605 let bytes = serde_json::to_vec(value)
606 .map_err(|_| RoleDeclarationsError("role_declarations could not be serialized"))?;
607 if bytes.len() > MAX_ROLE_DECLARATIONS_BYTES {
608 return Err(RoleDeclarationsError(
609 "role_declarations exceeds 16384 compact JSON bytes",
610 ));
611 }
612 Ok(())
613}
614
615#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
621#[non_exhaustive]
622pub struct RichUiDescriptor {
623 pub schema: String,
625 pub manifest_digest: String,
627 pub bytes: u64,
629 pub chunks: u32,
631}
632
633impl RichUiDescriptor {
634 pub fn new(
636 schema: impl Into<String>,
637 manifest_digest: impl Into<String>,
638 bytes: u64,
639 chunks: u32,
640 ) -> Self {
641 Self {
642 schema: schema.into(),
643 manifest_digest: manifest_digest.into(),
644 bytes,
645 chunks,
646 }
647 }
648
649 pub fn validate(&self) -> Result<(), RichUiDescriptorError> {
651 validate_rich_ui_fields(
652 &self.schema,
653 &self.manifest_digest,
654 self.bytes,
655 u64::from(self.chunks),
656 )
657 }
658}
659
660#[derive(Debug, Clone, PartialEq, Eq)]
662pub struct DisplayNameError(&'static str);
663
664impl fmt::Display for DisplayNameError {
665 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
666 write!(f, "invalid manifest display_name: {}", self.0)
667 }
668}
669
670impl std::error::Error for DisplayNameError {}
671
672pub fn validate_display_name(value: &str) -> Result<(), DisplayNameError> {
677 if value.trim() != value || !(1..=40).contains(&value.chars().count()) {
678 return Err(DisplayNameError(
679 "must be trimmed text of 1 to 40 characters",
680 ));
681 }
682 validate_plain_text(value, 40)
683}
684
685pub fn validate_module_id(module_id: &str) -> Result<(), String> {
687 if module_id.is_empty() {
688 return Err("empty".to_string());
689 }
690 if module_id.contains('/') || module_id.contains('\\') {
691 return Err("contains a path separator".to_string());
692 }
693 if module_id == "." || module_id == ".." {
694 return Err("is a dot path component".to_string());
695 }
696 if module_id.chars().any(|c| c.is_control()) {
697 return Err("contains a control character".to_string());
698 }
699 if module_id.len() > 255 {
700 return Err("is longer than 255 bytes".to_string());
701 }
702 Ok(())
703}
704
705pub(crate) fn validate_plain_text(value: &str, max: usize) -> Result<(), DisplayNameError> {
706 if value.is_empty() || value.chars().count() > max {
707 return Err(DisplayNameError(
708 "text length is outside the permitted bounds",
709 ));
710 }
711 if value.chars().any(|ch| {
712 ch.is_control()
713 || matches!(ch, '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')
714 }) {
715 return Err(DisplayNameError("must not contain control or bidi formatting characters"));
716 }
717 Ok(())
718}
719
720pub fn validate_hello_display_name(hello: &Value) -> Result<(), DisplayNameError> {
722 match hello
723 .get("manifest")
724 .and_then(|manifest| manifest.get("display_name"))
725 {
726 None | Some(Value::Null) => Ok(()),
727 Some(Value::String(value)) => validate_display_name(value),
728 Some(_) => Err(DisplayNameError("must be a string")),
729 }
730}
731
732#[derive(Debug, Clone, PartialEq, Eq)]
734#[non_exhaustive]
735pub struct RichUiDescriptorError {
736 field: String,
737 reason: &'static str,
738}
739
740impl RichUiDescriptorError {
741 fn new(field: impl Into<String>, reason: &'static str) -> Self {
742 Self {
743 field: field.into(),
744 reason,
745 }
746 }
747
748 pub fn field(&self) -> &str {
750 &self.field
751 }
752}
753
754impl fmt::Display for RichUiDescriptorError {
755 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
756 write!(
757 f,
758 "invalid rich_ui descriptor: field {} {}",
759 self.field, self.reason
760 )
761 }
762}
763
764impl std::error::Error for RichUiDescriptorError {}
765
766pub fn validate_hello_rich_ui_descriptor(hello: &Value) -> Result<(), RichUiDescriptorError> {
768 let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
769 return Ok(());
770 };
771 let Some(value) = manifest.get("rich_ui") else {
772 return Ok(());
773 };
774 validate_rich_ui_descriptor_value(value)
775}
776
777fn validate_rich_ui_descriptor_value(value: &Value) -> Result<(), RichUiDescriptorError> {
778 let descriptor = value
779 .as_object()
780 .ok_or_else(|| RichUiDescriptorError::new("rich_ui", "must be an object"))?;
781 let schema = descriptor
782 .get("schema")
783 .and_then(Value::as_str)
784 .ok_or_else(|| RichUiDescriptorError::new("rich_ui.schema", "must be a string"))?;
785 let digest = descriptor
786 .get("manifest_digest")
787 .and_then(Value::as_str)
788 .ok_or_else(|| RichUiDescriptorError::new("rich_ui.manifest_digest", "must be a string"))?;
789 let bytes = descriptor
790 .get("bytes")
791 .and_then(Value::as_u64)
792 .ok_or_else(|| {
793 RichUiDescriptorError::new("rich_ui.bytes", "must be an integer from 1 to 16777216")
794 })?;
795 let chunks = descriptor
796 .get("chunks")
797 .and_then(Value::as_u64)
798 .ok_or_else(|| {
799 RichUiDescriptorError::new("rich_ui.chunks", "must be an integer from 1 to 1024")
800 })?;
801 validate_rich_ui_fields(schema, digest, bytes, chunks)
802}
803
804fn validate_rich_ui_fields(
805 schema: &str,
806 digest: &str,
807 bytes: u64,
808 chunks: u64,
809) -> Result<(), RichUiDescriptorError> {
810 if !(1..=64).contains(&schema.len())
811 || !schema.bytes().all(|byte| {
812 byte.is_ascii_lowercase()
813 || byte.is_ascii_digit()
814 || matches!(byte, b'.' | b'_' | b'/' | b'-')
815 })
816 {
817 return Err(RichUiDescriptorError::new(
818 "rich_ui.schema",
819 "must be 1 to 64 bytes of [a-z0-9._/-]",
820 ));
821 }
822 if !digest.strip_prefix("sha256:").is_some_and(|hex| {
823 hex.len() == 64
824 && hex
825 .bytes()
826 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
827 }) {
828 return Err(RichUiDescriptorError::new(
829 "rich_ui.manifest_digest",
830 "must be sha256: followed by 64 lowercase hexadecimal characters",
831 ));
832 }
833 if !(1..=16_777_216).contains(&bytes) {
834 return Err(RichUiDescriptorError::new(
835 "rich_ui.bytes",
836 "must be an integer from 1 to 16777216",
837 ));
838 }
839 if !(1..=1_024).contains(&chunks) {
840 return Err(RichUiDescriptorError::new(
841 "rich_ui.chunks",
842 "must be an integer from 1 to 1024",
843 ));
844 }
845 Ok(())
846}
847
848pub const CAP_CATALOG_EVENTS_V1: &str = "catalog-events/v1";
854
855pub const CAP_SCOPE_BIND_PROOF_V1: &str = "scope-bind-proof/v1";
859
860pub const CAP_SCOPE_BIND_PROOF_V2: &str = "scope-bind-proof/v2";
864
865pub const CAP_SCOPE_REPLACE_IF_IDLE_V1: &str = "scope-replace-if-idle/v1";
867
868#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
870#[non_exhaustive]
871pub struct EventDeclaration {
872 pub name: String,
879 pub version: u32,
881 pub headers: Vec<String>,
886 #[serde(default, skip_serializing_if = "Option::is_none")]
888 pub summary: Option<String>,
889}
890
891impl EventDeclaration {
892 pub fn new(name: impl Into<String>, version: u32) -> Self {
895 Self {
896 name: name.into(),
897 version,
898 headers: Vec::new(),
899 summary: None,
900 }
901 }
902
903 pub fn with_headers(mut self, headers: Vec<String>) -> Self {
905 self.headers = headers;
906 self
907 }
908
909 pub fn with_summary(mut self, summary: Option<String>) -> Self {
911 self.summary = summary;
912 self
913 }
914}
915
916#[derive(Debug, Clone, PartialEq, Eq)]
918#[non_exhaustive]
919pub struct EventDeclarationError {
920 field: String,
921 reason: &'static str,
922}
923
924impl EventDeclarationError {
925 fn new(field: impl Into<String>, reason: &'static str) -> Self {
926 Self {
927 field: field.into(),
928 reason,
929 }
930 }
931
932 pub fn field(&self) -> &str {
934 &self.field
935 }
936}
937
938impl fmt::Display for EventDeclarationError {
939 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
940 write!(
941 f,
942 "invalid event declaration: field {} {}",
943 self.field, self.reason
944 )
945 }
946}
947
948impl std::error::Error for EventDeclarationError {}
949
950pub fn validate_hello_event_declarations(hello: &Value) -> Result<(), EventDeclarationError> {
952 validate_events_value(
953 hello
954 .get("manifest")
955 .and_then(|manifest| manifest.get("events")),
956 )
957}
958
959fn is_valid_event_name(name: &str) -> bool {
962 let level_count = name.split('.').count();
963 (1..=4).contains(&level_count)
964 && name.split('.').all(|level| {
965 if level.is_empty() {
966 return false;
967 }
968 let first = level.as_bytes()[0];
969 (1..=63).contains(&level.len())
970 && (first.is_ascii_lowercase() || first.is_ascii_digit())
971 && level
972 .bytes()
973 .skip(1)
974 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
975 && !level.strip_prefix('v').is_some_and(|digits| {
976 !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit())
977 })
978 })
979}
980
981fn validate_events_value(value: Option<&Value>) -> Result<(), EventDeclarationError> {
982 let Some(value) = value.filter(|value| !value.is_null()) else {
983 return Ok(());
984 };
985 let entries = value
986 .as_array()
987 .ok_or_else(|| EventDeclarationError::new("events", "must be a list"))?;
988 if entries.len() > 64 {
989 return Err(EventDeclarationError::new(
990 "events",
991 "must contain at most 64 declarations",
992 ));
993 }
994 let mut pairs = HashSet::new();
995 for (index, entry) in entries.iter().enumerate() {
996 let field = format!("events[{index}]");
997 let entry = entry
998 .as_object()
999 .ok_or_else(|| EventDeclarationError::new(&field, "must be an object"))?;
1000 let name_field = format!("{field}.name");
1001 let name = entry
1002 .get("name")
1003 .and_then(Value::as_str)
1004 .ok_or_else(|| EventDeclarationError::new(&name_field, "must be a string"))?;
1005 if !is_valid_event_name(name) {
1006 return Err(EventDeclarationError::new(
1007 name_field,
1008 "must contain one to four valid dot-separated event-name levels",
1009 ));
1010 }
1011 let version = entry
1012 .get("version")
1013 .and_then(Value::as_u64)
1014 .filter(|version| (1..=u32::MAX as u64).contains(version))
1015 .ok_or_else(|| {
1016 EventDeclarationError::new(
1017 format!("{field}.version"),
1018 "must be an integer between 1 and u32::MAX",
1019 )
1020 })?;
1021 if !pairs.insert((name, version)) {
1022 return Err(EventDeclarationError::new(
1023 &field,
1024 "duplicates an event (name, version) pair",
1025 ));
1026 }
1027 let headers_field = format!("{field}.headers");
1028 let headers = entry
1029 .get("headers")
1030 .and_then(Value::as_array)
1031 .ok_or_else(|| EventDeclarationError::new(&headers_field, "must be a list"))?;
1032 if headers.len() > 16 {
1033 return Err(EventDeclarationError::new(
1034 headers_field,
1035 "must contain at most 16 headers",
1036 ));
1037 }
1038 let mut names = HashSet::new();
1039 for (header_index, header) in headers.iter().enumerate() {
1040 let header_field = format!("{headers_field}[{header_index}]");
1041 let header = header
1042 .as_str()
1043 .ok_or_else(|| EventDeclarationError::new(&header_field, "must be a string"))?;
1044 if !(1..=32).contains(&header.len())
1045 || !header.as_bytes()[0].is_ascii_lowercase()
1046 || !header
1047 .bytes()
1048 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
1049 {
1050 return Err(EventDeclarationError::new(
1051 header_field,
1052 "must match [a-z][a-z0-9_]{0,31}",
1053 ));
1054 }
1055 if !names.insert(header) {
1056 return Err(EventDeclarationError::new(
1057 header_field,
1058 "duplicates a header name",
1059 ));
1060 }
1061 }
1062 if let Some(summary) = entry.get("summary").filter(|value| !value.is_null()) {
1063 let summary_field = format!("{field}.summary");
1064 let summary = summary
1065 .as_str()
1066 .ok_or_else(|| EventDeclarationError::new(&summary_field, "must be a string"))?;
1067 if summary.chars().count() > 200 || summary.chars().any(char::is_control) {
1068 return Err(EventDeclarationError::new(
1069 summary_field,
1070 "must contain at most 200 characters and no control characters",
1071 ));
1072 }
1073 }
1074 }
1075 Ok(())
1076}
1077
1078#[derive(Debug, Clone, PartialEq, Eq)]
1080pub struct SelfSignalDeclarationError {
1081 module_id: String,
1082 entry_index: usize,
1083 field: &'static str,
1084}
1085
1086impl fmt::Display for SelfSignalDeclarationError {
1087 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1088 write!(
1089 f,
1090 "module_id '{}' self_signals[{}] is missing required field '{}'",
1091 self.module_id.escape_debug(),
1092 self.entry_index,
1093 self.field
1094 )
1095 }
1096}
1097
1098pub fn validate_hello_self_signal_declarations(
1105 hello: &Value,
1106) -> Result<(), SelfSignalDeclarationError> {
1107 let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
1108 return Ok(());
1109 };
1110 let module_id = manifest
1111 .get("module_id")
1112 .and_then(Value::as_str)
1113 .unwrap_or("<unknown>");
1114 let Some(entries) = manifest.get("self_signals").and_then(Value::as_array) else {
1115 return Ok(());
1116 };
1117
1118 for (entry_index, entry) in entries.iter().enumerate() {
1119 let Some(entry) = entry.as_object() else {
1120 continue;
1121 };
1122 for field in ["effect", "anchored_to"] {
1123 if !entry.contains_key(field) {
1124 return Err(SelfSignalDeclarationError {
1125 module_id: module_id.to_string(),
1126 entry_index,
1127 field,
1128 });
1129 }
1130 }
1131 }
1132 Ok(())
1133}
1134
1135#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1137#[serde(deny_unknown_fields)]
1138pub struct CapabilityDeclarations {
1139 #[serde(default)]
1140 pub provides: Vec<String>,
1141 #[serde(default)]
1142 pub requires: Vec<CapabilityRequirement>,
1143 #[serde(default)]
1144 pub must_never_reach: Vec<String>,
1145}
1146
1147#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1149pub struct SelfSignalDeclaration {
1150 pub name: String,
1152 pub kind: SelfSignalKind,
1180 pub effect: SelfSignalEffect,
1182 pub anchored_to: SignalAnchor,
1184 #[serde(default, skip_serializing_if = "Option::is_none")]
1191 pub cadence: Option<SignalCadence>,
1192 #[serde(default, skip_serializing_if = "Option::is_none")]
1194 pub domain: Option<String>,
1195 #[serde(default, skip_serializing_if = "Option::is_none")]
1196 pub note: Option<String>,
1197}
1198
1199#[derive(Debug, Clone, PartialEq, Eq)]
1201pub enum SelfSignalKind {
1202 Keepalive,
1203 Busy,
1205 Poller,
1206 Cron,
1207 Sweep,
1208 Watchdog,
1209 Heartbeat,
1210 Other(String),
1211}
1212
1213impl SelfSignalKind {
1214 fn wire_name(&self) -> &str {
1215 match self {
1216 Self::Keepalive => "keepalive",
1217 Self::Busy => "busy",
1218 Self::Poller => "poller",
1219 Self::Cron => "cron",
1220 Self::Sweep => "sweep",
1221 Self::Watchdog => "watchdog",
1222 Self::Heartbeat => "heartbeat",
1223 Self::Other(value) => value,
1224 }
1225 }
1226}
1227
1228impl Serialize for SelfSignalKind {
1229 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1230 where
1231 S: serde::Serializer,
1232 {
1233 serializer.serialize_str(self.wire_name())
1234 }
1235}
1236
1237impl<'de> Deserialize<'de> for SelfSignalKind {
1238 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1239 where
1240 D: Deserializer<'de>,
1241 {
1242 let value = String::deserialize(deserializer)?;
1243 Ok(match value.as_str() {
1244 "keepalive" => Self::Keepalive,
1245 "busy" => Self::Busy,
1246 "poller" => Self::Poller,
1247 "cron" => Self::Cron,
1248 "sweep" => Self::Sweep,
1249 "watchdog" => Self::Watchdog,
1250 "heartbeat" => Self::Heartbeat,
1251 _ => Self::Other(value),
1252 })
1253 }
1254}
1255
1256#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1258#[serde(rename_all = "lowercase")]
1259pub enum SelfSignalEffect {
1260 Observe,
1261 Mutate,
1262}
1263
1264#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1266#[serde(rename_all = "snake_case")]
1267pub enum SignalAnchor {
1268 FixedInterval,
1271 Event { event: String },
1274 HealthGauges { gauges: Vec<String> },
1276}
1277
1278#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1280#[serde(rename_all = "snake_case")]
1281pub enum SignalCadence {
1282 Literal { interval_ms: u64 },
1283 Derived { source: String },
1284}
1285
1286#[derive(Serialize, Debug, Clone, Default, PartialEq, Eq)]
1363#[non_exhaustive]
1364pub struct ManifestProvenance {
1365 #[serde(default, skip_serializing_if = "Option::is_none")]
1366 pub build_git_sha: Option<String>,
1367 #[serde(default, skip_serializing_if = "Option::is_none")]
1371 pub build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1372 #[serde(default, skip_serializing_if = "Option::is_none")]
1373 pub build_lock_digest: Option<String>,
1374 #[serde(default, skip_serializing_if = "Option::is_none")]
1383 pub wire_crate_version: Option<String>,
1384 #[serde(default, skip_serializing_if = "Option::is_none")]
1385 pub store_schema_version: Option<String>,
1386 #[serde(default, skip_serializing_if = "Option::is_none")]
1392 pub launch_nonce_source: Option<LaunchNonceSource>,
1393}
1394
1395#[derive(Debug, Clone, PartialEq, Eq)]
1402#[non_exhaustive]
1403pub enum LaunchNonceSource {
1404 Fd,
1406 Pipe,
1408 Env,
1410 ForwardCompatibleUnknown(String),
1411}
1412
1413impl LaunchNonceSource {
1414 pub fn wire_name(&self) -> &str {
1416 match self {
1417 Self::Fd => "fd",
1418 Self::Pipe => "pipe",
1419 Self::Env => "env",
1420 Self::ForwardCompatibleUnknown(value) => value,
1421 }
1422 }
1423
1424 pub fn from_wire_name(value: &str) -> Self {
1426 match value {
1427 "fd" => Self::Fd,
1428 "pipe" => Self::Pipe,
1429 "env" => Self::Env,
1430 _ => Self::ForwardCompatibleUnknown(value.to_string()),
1431 }
1432 }
1433}
1434
1435impl Serialize for LaunchNonceSource {
1436 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1437 where
1438 S: serde::Serializer,
1439 {
1440 serializer.serialize_str(self.wire_name())
1441 }
1442}
1443
1444impl<'de> Deserialize<'de> for LaunchNonceSource {
1445 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1446 where
1447 D: serde::Deserializer<'de>,
1448 {
1449 let value = String::deserialize(deserializer)?;
1450 Ok(Self::from_wire_name(&value))
1451 }
1452}
1453
1454#[derive(Debug, Clone, PartialEq, Eq)]
1459pub enum BuildGitShaAbsenceReason {
1460 DeclinedDirty,
1461 NeverDerived,
1462 NoGitDir,
1463 ForwardCompatibleUnknown(String),
1464}
1465
1466impl BuildGitShaAbsenceReason {
1467 fn wire_name(&self) -> &str {
1468 match self {
1469 Self::DeclinedDirty => "declined_dirty",
1470 Self::NeverDerived => "never_derived",
1471 Self::NoGitDir => "no_git_dir",
1472 Self::ForwardCompatibleUnknown(value) => value,
1473 }
1474 }
1475}
1476
1477impl Serialize for BuildGitShaAbsenceReason {
1478 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1479 where
1480 S: serde::Serializer,
1481 {
1482 serializer.serialize_str(self.wire_name())
1483 }
1484}
1485
1486impl<'de> Deserialize<'de> for BuildGitShaAbsenceReason {
1487 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1488 where
1489 D: serde::Deserializer<'de>,
1490 {
1491 let value = String::deserialize(deserializer)?;
1492 Ok(match value.as_str() {
1493 "declined_dirty" => Self::DeclinedDirty,
1494 "never_derived" => Self::NeverDerived,
1495 "no_git_dir" => Self::NoGitDir,
1496 _ => Self::ForwardCompatibleUnknown(value),
1497 })
1498 }
1499}
1500
1501#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1503pub enum GitTreeState {
1504 Clean,
1505 Dirty,
1506}
1507
1508#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1513pub enum BuildGitShaSource<'a> {
1514 Git {
1515 revision: &'a str,
1516 tree_state: GitTreeState,
1517 },
1518 NeverDerived,
1519 NoGitDir,
1520}
1521
1522pub fn attestable_commit(revision: &str, tree_state: GitTreeState) -> Option<&str> {
1526 match tree_state {
1527 GitTreeState::Clean => Some(revision),
1528 GitTreeState::Dirty => None,
1529 }
1530}
1531
1532const MAX_PROVENANCE_VALUE_BYTES: usize = 128;
1533const BUILD_GIT_SHA_CANONICAL_FORM: &str = "exactly 40 lowercase hexadecimal characters";
1534const BUILD_LOCK_DIGEST_CANONICAL_FORM: &str = "exactly 64 lowercase hexadecimal characters";
1535
1536#[derive(Deserialize)]
1537struct ManifestProvenanceWire {
1538 #[serde(default)]
1539 build_git_sha: Option<String>,
1540 #[serde(default)]
1541 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1542 #[serde(default)]
1543 build_lock_digest: Option<String>,
1544 #[serde(default)]
1545 wire_crate_version: Option<String>,
1546 #[serde(default)]
1547 store_schema_version: Option<String>,
1548 #[serde(default)]
1549 launch_nonce_source: Option<LaunchNonceSource>,
1550}
1551
1552impl<'de> Deserialize<'de> for ManifestProvenance {
1553 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1554 where
1555 D: Deserializer<'de>,
1556 {
1557 let wire = ManifestProvenanceWire::deserialize(deserializer)?;
1558 let provenance = Self {
1559 build_git_sha: wire.build_git_sha,
1560 build_git_sha_absence_reason: wire.build_git_sha_absence_reason,
1561 build_lock_digest: wire.build_lock_digest,
1562 wire_crate_version: wire.wire_crate_version,
1563 store_schema_version: wire.store_schema_version,
1564 launch_nonce_source: wire.launch_nonce_source,
1565 };
1566 provenance.validate().map_err(D::Error::custom)?;
1567 Ok(provenance)
1568 }
1569}
1570
1571#[derive(Debug, Clone, PartialEq, Eq)]
1573pub struct ProvenanceFormError {
1574 field: &'static str,
1575 length: usize,
1576 canonical_form: &'static str,
1577}
1578
1579impl ProvenanceFormError {
1580 fn new(field: &'static str, length: usize, canonical_form: &'static str) -> Self {
1581 Self {
1582 field,
1583 length,
1584 canonical_form,
1585 }
1586 }
1587
1588 pub fn field(&self) -> &str {
1590 self.field
1591 }
1592
1593 pub fn length(&self) -> usize {
1595 self.length
1596 }
1597
1598 pub fn canonical_form(&self) -> &str {
1600 self.canonical_form
1601 }
1602}
1603
1604impl fmt::Display for ProvenanceFormError {
1605 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1606 write!(
1607 f,
1608 "invalid manifest provenance form: field {} has length {}; canonical form is {}",
1609 self.field, self.length, self.canonical_form
1610 )
1611 }
1612}
1613
1614impl std::error::Error for ProvenanceFormError {}
1615
1616#[derive(Debug, Clone, PartialEq, Eq)]
1617pub struct ManifestProvenanceError {
1618 field: String,
1619 value: String,
1620 reason: &'static str,
1621}
1622
1623impl ManifestProvenanceError {
1624 fn new(field: &str, value: &str, reason: &'static str) -> Self {
1625 Self {
1626 field: field.to_string(),
1627 value: safe_error_value(value),
1628 reason,
1629 }
1630 }
1631
1632 pub fn field(&self) -> &str {
1633 &self.field
1634 }
1635}
1636
1637impl fmt::Display for ManifestProvenanceError {
1638 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1639 write!(
1640 f,
1641 "invalid manifest provenance: field {} has {} (value {:?})",
1642 self.field, self.reason, self.value
1643 )
1644 }
1645}
1646
1647impl std::error::Error for ManifestProvenanceError {}
1648
1649impl ManifestProvenance {
1650 pub fn new() -> Self {
1652 Self::default()
1653 }
1654
1655 pub fn with_build_git_sha(mut self, value: Option<String>) -> Self {
1656 self.build_git_sha = value;
1657 self
1658 }
1659
1660 pub fn with_build_git_sha_absence_reason(
1661 mut self,
1662 value: Option<BuildGitShaAbsenceReason>,
1663 ) -> Self {
1664 self.build_git_sha_absence_reason = value;
1665 self
1666 }
1667
1668 pub fn with_build_lock_digest(mut self, value: Option<String>) -> Self {
1669 self.build_lock_digest = value;
1670 self
1671 }
1672
1673 pub fn with_wire_crate_version(mut self, value: Option<String>) -> Self {
1674 self.wire_crate_version = value;
1675 self
1676 }
1677
1678 pub fn with_store_schema_version(mut self, value: Option<String>) -> Self {
1679 self.store_schema_version = value;
1680 self
1681 }
1682
1683 pub fn with_launch_nonce_source(mut self, value: Option<LaunchNonceSource>) -> Self {
1688 self.launch_nonce_source = value;
1689 self
1690 }
1691
1692 pub fn validate(&self) -> Result<(), ManifestProvenanceError> {
1693 if let (Some(_), Some(reason)) = (
1694 self.build_git_sha.as_ref(),
1695 self.build_git_sha_absence_reason.as_ref(),
1696 ) {
1697 return Err(ManifestProvenanceError::new(
1698 "build_git_sha_absence_reason",
1699 reason.wire_name(),
1700 "must be omitted when build_git_sha is present",
1701 ));
1702 }
1703 for (field, value) in [
1704 ("build_git_sha", self.build_git_sha.as_deref()),
1705 (
1706 "build_git_sha_absence_reason",
1707 self.build_git_sha_absence_reason
1708 .as_ref()
1709 .map(|reason| reason.wire_name()),
1710 ),
1711 ("build_lock_digest", self.build_lock_digest.as_deref()),
1712 ("wire_crate_version", self.wire_crate_version.as_deref()),
1713 ("store_schema_version", self.store_schema_version.as_deref()),
1714 (
1715 "launch_nonce_source",
1716 self.launch_nonce_source
1717 .as_ref()
1718 .map(|source| source.wire_name()),
1719 ),
1720 ] {
1721 let Some(value) = value else { continue };
1722 if value.is_empty() {
1723 return Err(ManifestProvenanceError::new(
1724 field,
1725 value,
1726 "must not be empty",
1727 ));
1728 }
1729 if value.len() > MAX_PROVENANCE_VALUE_BYTES {
1734 return Err(ManifestProvenanceError::new(
1735 field,
1736 value,
1737 "exceeds the 128-byte maximum",
1738 ));
1739 }
1740 if value.bytes().any(|byte| !(0x20..=0x7e).contains(&byte)) {
1741 return Err(ManifestProvenanceError::new(
1742 field,
1743 value,
1744 "contains non-printable ASCII",
1745 ));
1746 }
1747 }
1748 Ok(())
1749 }
1750}
1751
1752pub fn build_provenance(
1770 build_git_sha: Option<&str>,
1771 build_lock_digest: Option<&str>,
1772 store_schema_version: Option<&str>,
1773) -> Result<ManifestProvenance, ProvenanceFormError> {
1774 let build_git_sha = normalize_and_validate_build_git_sha(build_git_sha)?;
1775 build_provenance_with_build_git_sha(
1776 build_git_sha,
1777 None,
1778 build_lock_digest,
1779 store_schema_version,
1780 )
1781}
1782
1783pub fn build_provenance_from_source(
1799 build_git_sha_source: BuildGitShaSource<'_>,
1800 build_lock_digest: Option<&str>,
1801 store_schema_version: Option<&str>,
1802) -> Result<ManifestProvenance, ProvenanceFormError> {
1803 let (raw_build_git_sha, mut build_git_sha_absence_reason) = match build_git_sha_source {
1804 BuildGitShaSource::Git {
1805 revision,
1806 tree_state,
1807 } => match attestable_commit(revision, tree_state) {
1808 Some(revision) => (Some(revision), None),
1809 None => (None, Some(BuildGitShaAbsenceReason::DeclinedDirty)),
1810 },
1811 BuildGitShaSource::NeverDerived => (None, Some(BuildGitShaAbsenceReason::NeverDerived)),
1812 BuildGitShaSource::NoGitDir => (None, Some(BuildGitShaAbsenceReason::NoGitDir)),
1813 };
1814 let build_git_sha = normalize_and_validate_build_git_sha(raw_build_git_sha)?;
1815 if build_git_sha.is_none() {
1816 build_git_sha_absence_reason.get_or_insert(BuildGitShaAbsenceReason::NeverDerived);
1817 }
1818 build_provenance_with_build_git_sha(
1819 build_git_sha,
1820 build_git_sha_absence_reason,
1821 build_lock_digest,
1822 store_schema_version,
1823 )
1824}
1825
1826fn normalize_and_validate_build_git_sha(
1827 build_git_sha: Option<&str>,
1828) -> Result<Option<String>, ProvenanceFormError> {
1829 let build_git_sha = normalize_provenance_fact(build_git_sha);
1830 validate_provenance_form(
1831 "build_git_sha",
1832 build_git_sha.as_deref(),
1833 BUILD_GIT_SHA_CANONICAL_FORM,
1834 40,
1835 )?;
1836 Ok(build_git_sha)
1837}
1838
1839fn build_provenance_with_build_git_sha(
1840 build_git_sha: Option<String>,
1841 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1842 build_lock_digest: Option<&str>,
1843 store_schema_version: Option<&str>,
1844) -> Result<ManifestProvenance, ProvenanceFormError> {
1845 let build_lock_digest = normalize_provenance_fact(build_lock_digest);
1846 validate_provenance_form(
1847 "build_lock_digest",
1848 build_lock_digest.as_deref(),
1849 BUILD_LOCK_DIGEST_CANONICAL_FORM,
1850 64,
1851 )?;
1852
1853 Ok(ManifestProvenance {
1854 build_git_sha,
1855 build_git_sha_absence_reason,
1856 build_lock_digest,
1857 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
1858 store_schema_version: normalize_provenance_fact(store_schema_version),
1859 launch_nonce_source: None,
1860 })
1861}
1862
1863fn validate_provenance_form(
1864 field: &'static str,
1865 value: Option<&str>,
1866 canonical_form: &'static str,
1867 expected_length: usize,
1868) -> Result<(), ProvenanceFormError> {
1869 let Some(value) = value else { return Ok(()) };
1870 if value.len() != expected_length
1871 || !value
1872 .bytes()
1873 .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
1874 {
1875 return Err(ProvenanceFormError::new(field, value.len(), canonical_form));
1876 }
1877 Ok(())
1878}
1879
1880pub const PROVENANCE_SENTINELS: [&str; 3] = ["unknown", "unavailable", "none"];
1888
1889fn normalize_provenance_fact(value: Option<&str>) -> Option<String> {
1890 let value = value?.trim();
1891 if value.is_empty() {
1892 return None;
1893 }
1894 let lowered = value.to_ascii_lowercase();
1895 if PROVENANCE_SENTINELS.contains(&lowered.as_str()) {
1896 return None;
1897 }
1898 Some(value.to_string())
1899}
1900
1901#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1903#[serde(deny_unknown_fields)]
1904pub struct CapabilityRequirement {
1905 pub capability: String,
1906 pub need: CapabilityNeed,
1907}
1908
1909#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1911#[serde(rename_all = "snake_case")]
1912pub enum CapabilityNeed {
1913 Required,
1914 Optional,
1915}
1916
1917#[derive(Debug, Clone, PartialEq, Eq)]
1919pub struct CapabilityGrammarError {
1920 field: String,
1921 value: String,
1922}
1923
1924impl CapabilityGrammarError {
1925 fn new(field: impl Into<String>, value: impl AsRef<str>) -> Self {
1926 Self {
1927 field: field.into(),
1928 value: safe_error_value(value.as_ref()),
1929 }
1930 }
1931
1932 pub fn field(&self) -> &str {
1934 &self.field
1935 }
1936
1937 pub fn value(&self) -> &str {
1939 &self.value
1940 }
1941}
1942
1943impl fmt::Display for CapabilityGrammarError {
1944 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1945 write!(
1946 f,
1947 "invalid capability grammar: field {} has offending value {:?}",
1948 self.field, self.value
1949 )
1950 }
1951}
1952
1953impl std::error::Error for CapabilityGrammarError {}
1954
1955impl ModuleManifest {
1956 pub fn validate_capability_grammar(&self) -> Result<(), CapabilityGrammarError> {
1958 let Some(capabilities) = &self.capabilities else {
1959 return Ok(());
1960 };
1961
1962 validate_capability_list("capabilities.provides", &capabilities.provides)?;
1963 validate_requires(&capabilities.requires)?;
1964 validate_capability_list(
1965 "capabilities.must_never_reach",
1966 &capabilities.must_never_reach,
1967 )
1968 }
1969}
1970
1971pub fn validate_manifest_capability_grammar(
1976 manifest: &Value,
1977) -> Result<(), CapabilityGrammarError> {
1978 let Some(object) = manifest.as_object() else {
1979 return Ok(());
1980 };
1981
1982 validate_capabilities_value(object.get("capabilities"))?;
1983 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
1984}
1985
1986pub fn validate_hello_capability_grammar(hello: &Value) -> Result<(), CapabilityGrammarError> {
1992 let Some(object) = hello.as_object() else {
1993 return Ok(());
1994 };
1995 if let Some(manifest) = object.get("manifest") {
1996 validate_manifest_capability_grammar(manifest)?;
1997 }
1998 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
1999}
2000
2001pub fn is_valid_capability_identifier(identifier: &str) -> bool {
2003 if identifier.chars().any(char::is_whitespace) {
2004 return false;
2005 }
2006 let Some((name, version)) = identifier.split_once("/v") else {
2007 return false;
2008 };
2009 if name.is_empty() || name.len() > 64 || version.is_empty() {
2010 return false;
2011 }
2012
2013 let name_bytes = name.as_bytes();
2014 if !name_bytes[0].is_ascii_lowercase()
2015 || (name.len() > 1
2016 && !name_bytes[name.len() - 1].is_ascii_lowercase()
2017 && !name_bytes[name.len() - 1].is_ascii_digit())
2018 || name_bytes.windows(2).any(|pair| pair == b"--")
2019 {
2020 return false;
2021 }
2022 if !name_bytes
2023 .iter()
2024 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-')
2025 {
2026 return false;
2027 }
2028
2029 if version.len() > 1 && version.starts_with('0')
2030 || !version.bytes().all(|byte| byte.is_ascii_digit())
2031 {
2032 return false;
2033 }
2034 matches!(
2035 version.parse::<u64>(),
2036 Ok(value) if (1..=u64::from(u32::MAX)).contains(&value)
2037 )
2038}
2039
2040fn validate_capabilities_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
2041 let Some(value) = value else {
2042 return Ok(());
2043 };
2044 let Some(object) = value.as_object() else {
2045 return Err(CapabilityGrammarError::new(
2046 "capabilities",
2047 value_description(value),
2048 ));
2049 };
2050
2051 for (key, value) in object {
2052 if !matches!(key.as_str(), "provides" | "requires" | "must_never_reach") {
2053 return Err(CapabilityGrammarError::new(
2054 field_child("capabilities", key),
2055 value_description(value),
2056 ));
2057 }
2058 }
2059
2060 validate_capability_list_value("capabilities.provides", object.get("provides"))?;
2061 validate_requires_value(object.get("requires"))?;
2062 validate_capability_list_value(
2063 "capabilities.must_never_reach",
2064 object.get("must_never_reach"),
2065 )
2066}
2067
2068fn validate_capability_list_value(
2069 field: &str,
2070 value: Option<&Value>,
2071) -> Result<(), CapabilityGrammarError> {
2072 let Some(value) = value else {
2073 return Ok(());
2074 };
2075 let Some(values) = value.as_array() else {
2076 return Err(CapabilityGrammarError::new(field, value_description(value)));
2077 };
2078
2079 let mut seen = HashSet::new();
2080 for (index, value) in values.iter().enumerate() {
2081 let field = format!("{field}[{index}]");
2082 let Some(identifier) = value.as_str() else {
2083 return Err(CapabilityGrammarError::new(field, value_description(value)));
2084 };
2085 validate_capability_identifier(&field, identifier)?;
2086 if !seen.insert(identifier) {
2087 return Err(CapabilityGrammarError::new(field, identifier));
2088 }
2089 }
2090 Ok(())
2091}
2092
2093fn validate_requires_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
2094 let Some(value) = value else {
2095 return Ok(());
2096 };
2097 let Some(values) = value.as_array() else {
2098 return Err(CapabilityGrammarError::new(
2099 "capabilities.requires",
2100 value_description(value),
2101 ));
2102 };
2103
2104 let mut seen = HashSet::new();
2105 for (index, value) in values.iter().enumerate() {
2106 let entry_field = format!("capabilities.requires[{index}]");
2107 let Some(object) = value.as_object() else {
2108 return Err(CapabilityGrammarError::new(
2109 entry_field,
2110 value_description(value),
2111 ));
2112 };
2113 for (key, value) in object {
2114 if !matches!(key.as_str(), "capability" | "need") {
2115 return Err(CapabilityGrammarError::new(
2116 field_child(&entry_field, key),
2117 value_description(value),
2118 ));
2119 }
2120 }
2121 let capability_field = format!("{entry_field}.capability");
2122 let Some(capability) = object.get("capability").and_then(Value::as_str) else {
2123 return Err(CapabilityGrammarError::new(
2124 capability_field,
2125 object
2126 .get("capability")
2127 .map_or("<missing>".to_string(), value_description),
2128 ));
2129 };
2130 validate_capability_identifier(&capability_field, capability)?;
2131
2132 let need_field = format!("{entry_field}.need");
2133 let Some(need) = object.get("need").and_then(Value::as_str) else {
2134 return Err(CapabilityGrammarError::new(
2135 need_field,
2136 object
2137 .get("need")
2138 .map_or("<missing>".to_string(), value_description),
2139 ));
2140 };
2141 if !matches!(need, "required" | "optional") {
2142 return Err(CapabilityGrammarError::new(need_field, need));
2143 }
2144 if !seen.insert(capability) {
2145 return Err(CapabilityGrammarError::new(entry_field, capability));
2146 }
2147 }
2148 Ok(())
2149}
2150
2151fn validate_capability_list(field: &str, values: &[String]) -> Result<(), CapabilityGrammarError> {
2152 let mut seen = HashSet::new();
2153 for (index, identifier) in values.iter().enumerate() {
2154 let field = format!("{field}[{index}]");
2155 validate_capability_identifier(&field, identifier)?;
2156 if !seen.insert(identifier) {
2157 return Err(CapabilityGrammarError::new(field, identifier));
2158 }
2159 }
2160 Ok(())
2161}
2162
2163fn validate_requires(values: &[CapabilityRequirement]) -> Result<(), CapabilityGrammarError> {
2164 let mut seen = HashSet::new();
2165 for (index, requirement) in values.iter().enumerate() {
2166 let field = format!("capabilities.requires[{index}].capability");
2167 validate_capability_identifier(&field, &requirement.capability)?;
2168 if !seen.insert(&requirement.capability) {
2169 return Err(CapabilityGrammarError::new(
2170 format!("capabilities.requires[{index}]"),
2171 &requirement.capability,
2172 ));
2173 }
2174 }
2175 Ok(())
2176}
2177
2178fn validate_capability_identifier(
2179 field: &str,
2180 identifier: &str,
2181) -> Result<(), CapabilityGrammarError> {
2182 if is_valid_capability_identifier(identifier) {
2183 Ok(())
2184 } else {
2185 Err(CapabilityGrammarError::new(field, identifier))
2186 }
2187}
2188
2189fn validate_runtime_computed(
2190 value: Option<&Value>,
2191 field: &str,
2192) -> Result<(), CapabilityGrammarError> {
2193 let Some(value) = value else {
2194 return Ok(());
2195 };
2196 let Some(pointers) = value.as_array() else {
2197 return Err(CapabilityGrammarError::new(field, value_description(value)));
2198 };
2199
2200 for (index, pointer) in pointers.iter().enumerate() {
2201 let field = format!("{field}[{index}]");
2202 let Some(pointer) = pointer.as_str() else {
2203 return Err(CapabilityGrammarError::new(
2204 field,
2205 value_description(pointer),
2206 ));
2207 };
2208 let Some(tokens) = parse_json_pointer(pointer) else {
2209 return Err(CapabilityGrammarError::new(field, pointer));
2210 };
2211 if tokens.first().is_some_and(|token| token == "capabilities") {
2212 return Err(CapabilityGrammarError::new(field, pointer));
2213 }
2214 }
2215 Ok(())
2216}
2217
2218fn parse_json_pointer(pointer: &str) -> Option<Vec<String>> {
2219 if pointer.is_empty() {
2220 return Some(Vec::new());
2221 }
2222 let raw_tokens = pointer.strip_prefix('/')?;
2223 raw_tokens
2224 .split('/')
2225 .map(unescape_json_pointer_token)
2226 .collect()
2227}
2228
2229fn unescape_json_pointer_token(token: &str) -> Option<String> {
2230 let mut output = String::with_capacity(token.len());
2231 let mut characters = token.chars();
2232 while let Some(character) = characters.next() {
2233 if character != '~' {
2234 output.push(character);
2235 continue;
2236 }
2237 match characters.next()? {
2238 '0' => output.push('~'),
2239 '1' => output.push('/'),
2240 _ => return None,
2241 }
2242 }
2243 Some(output)
2244}
2245
2246fn field_child(parent: &str, child: &str) -> String {
2247 let child = safe_error_value(child);
2248 format!("{parent}.{child}")
2249}
2250
2251fn value_description(value: &Value) -> String {
2252 match value {
2253 Value::String(value) => safe_error_value(value),
2254 Value::Null => "null".to_string(),
2255 Value::Bool(value) => value.to_string(),
2256 Value::Number(value) => value.to_string(),
2257 Value::Array(_) => "<array>".to_string(),
2258 Value::Object(_) => "<object>".to_string(),
2259 }
2260}
2261
2262fn safe_error_value(value: &str) -> String {
2263 let lower = value.to_ascii_lowercase();
2264 if ["secret", "password", "api_key"]
2265 .iter()
2266 .any(|marker| lower.contains(marker))
2267 || lower.starts_with("sk-")
2268 || lower.starts_with("akia")
2269 || lower.starts_with("bearer ")
2270 || lower.starts_with("token=")
2271 || lower.starts_with("credential=")
2272 {
2273 "<redacted>".to_string()
2274 } else {
2275 value.to_string()
2276 }
2277}
2278
2279#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2285#[serde(rename_all = "snake_case")]
2286pub enum TrustTier {
2287 FirstParty,
2288 Reviewed,
2289 Untrusted,
2290}
2291
2292#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2296#[serde(tag = "role", rename_all = "snake_case")]
2297pub enum ProviderRole {
2298 ToolProvider {
2299 tools: Vec<Tool>,
2300 identity_scope: Vec<IdentityScope>,
2308 concurrency: Concurrency,
2309 emits_push: bool,
2310 sub_supervises: bool,
2311 },
2312 PipelineStage {
2313 stage: PipelineStageKind,
2314 applies_to: PipelineAppliesTo,
2315 interface: String,
2316 declares_frozen_floor: bool,
2317 needs_signals: Vec<String>,
2318 conformance_class: String,
2319 },
2320 ManagementSurface {
2321 operations: Vec<ManagementOperation>,
2322 config_schema: Value,
2323 observability: Vec<ObservabilitySurface>,
2324 identity_scope: Vec<IdentityScope>,
2328 #[serde(default)]
2329 concurrency: Concurrency,
2330 },
2331 InternalService {
2332 service_id: String,
2333 transport: InternalTransport,
2334 agent_facing: bool,
2335 operations: Vec<String>,
2336 },
2337}
2338
2339#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2352#[serde(rename_all = "snake_case")]
2353pub enum ExecutionMode {
2354 Pure,
2355 Mutating,
2356 Unfenceable,
2357}
2358
2359#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2361pub struct Tool {
2362 pub name: String,
2363 #[serde(default, skip_serializing_if = "Option::is_none")]
2364 pub description: Option<String>,
2365 pub execution_mode: ExecutionMode,
2370 pub schema: Value,
2371}
2372
2373#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2379#[serde(rename_all = "snake_case")]
2380pub enum Concurrency {
2381 Serial,
2383 ModuleManaged,
2386 StatelessParallel,
2389}
2390
2391#[allow(clippy::derivable_impls)]
2392impl Default for Concurrency {
2403 fn default() -> Self {
2404 Self::ModuleManaged
2405 }
2406}
2407
2408#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2415#[serde(rename_all = "snake_case")]
2416pub enum IdentityScope {
2417 Session,
2418 Project,
2419}
2420
2421#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2423#[serde(rename_all = "snake_case")]
2424pub enum PipelineStageKind {
2425 Transform,
2426 Codec,
2427 Auth,
2428}
2429
2430#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2432pub struct PipelineAppliesTo {
2433 pub provider: String,
2434 pub model: String,
2435}
2436
2437#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2440#[non_exhaustive]
2441pub struct OperationPayload {
2442 max_bytes: usize,
2443}
2444
2445impl OperationPayload {
2446 pub fn new(max_bytes: usize) -> Self {
2447 Self { max_bytes }
2448 }
2449
2450 pub fn max_bytes(&self) -> usize {
2451 self.max_bytes
2452 }
2453}
2454
2455#[derive(Debug, Clone, PartialEq, Eq)]
2457#[non_exhaustive]
2458pub enum OperationPayloadError {
2459 UnknownOperation { operation: String },
2460 WatchOperation { operation: String },
2461 InvalidMaxBytes { operation: String },
2462}
2463
2464impl fmt::Display for OperationPayloadError {
2465 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2466 write!(f, "{self:?}")
2467 }
2468}
2469
2470impl std::error::Error for OperationPayloadError {}
2471
2472impl ModuleManifest {
2473 pub fn validate_operation_payload(&self) -> Result<(), OperationPayloadError> {
2476 for (name, payload) in &self.operation_payload {
2477 if !self.provides.iter().any(|role| match role {
2478 ProviderRole::ManagementSurface { operations, .. } => {
2479 operations.iter().any(|op| op.name == *name)
2480 }
2481 _ => false,
2482 }) {
2483 return Err(OperationPayloadError::UnknownOperation {
2484 operation: name.clone(),
2485 });
2486 }
2487 if self
2488 .operation_delivery
2489 .get(name)
2490 .is_some_and(OperationDelivery::is_watch)
2491 {
2492 return Err(OperationPayloadError::WatchOperation {
2493 operation: name.clone(),
2494 });
2495 }
2496 if !(1..=crate::framed_body::MAX_DECLARED_PAYLOAD_BYTES).contains(&payload.max_bytes) {
2497 return Err(OperationPayloadError::InvalidMaxBytes {
2498 operation: name.clone(),
2499 });
2500 }
2501 }
2502 Ok(())
2503 }
2504}
2505
2506#[derive(Debug, Clone, PartialEq, Eq)]
2511#[non_exhaustive]
2512pub enum FlowOperationsError {
2513 FlowScopesNotDeclared,
2516 NotAList,
2518 TooMany { count: usize },
2520 DuplicateOperation { operation: String },
2522 UnknownOperation { operation: String },
2524}
2525
2526impl fmt::Display for FlowOperationsError {
2527 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2528 match self {
2529 Self::FlowScopesNotDeclared => write!(
2530 f,
2531 "flow_operations requires '{}' or '{}' in capabilities.provides",
2532 crate::scope::FLOW_SCOPES_CAPABILITY,
2533 crate::call_mode::CALL_MODES_CAPABILITY
2534 ),
2535 Self::NotAList => f.write_str("flow_operations must be an array of operation names"),
2536 Self::TooMany { count } => write!(
2537 f,
2538 "flow_operations lists {count} names, more than {MAX_FLOW_OPERATIONS}"
2539 ),
2540 Self::DuplicateOperation { operation } => {
2541 write!(f, "flow_operations names '{operation}' more than once")
2542 }
2543 Self::UnknownOperation { operation } => write!(
2544 f,
2545 "flow_operations names '{operation}', which is not a declared management operation"
2546 ),
2547 }
2548 }
2549}
2550
2551impl std::error::Error for FlowOperationsError {}
2552
2553impl ModuleManifest {
2554 pub fn validate_flow_operations(&self) -> Result<(), FlowOperationsError> {
2559 match &self.flow_operations {
2560 Some(operations) => check_flow_operations(self, operations),
2561 None => Ok(()),
2562 }
2563 }
2564}
2565
2566fn check_flow_operations(
2567 manifest: &ModuleManifest,
2568 operations: &[String],
2569) -> Result<(), FlowOperationsError> {
2570 let admits_flows = manifest.capabilities.as_ref().is_some_and(|capabilities| {
2571 capabilities.provides.iter().any(|capability| {
2572 capability == crate::scope::FLOW_SCOPES_CAPABILITY
2573 || capability == crate::call_mode::CALL_MODES_CAPABILITY
2574 })
2575 });
2576 if !admits_flows {
2577 return Err(FlowOperationsError::FlowScopesNotDeclared);
2578 }
2579 if operations.len() > MAX_FLOW_OPERATIONS {
2580 return Err(FlowOperationsError::TooMany {
2581 count: operations.len(),
2582 });
2583 }
2584 let mut seen = HashSet::new();
2585 for operation in operations {
2586 if !seen.insert(operation.as_str()) {
2587 return Err(FlowOperationsError::DuplicateOperation {
2588 operation: operation.clone(),
2589 });
2590 }
2591 let declared = manifest.provides.iter().any(|role| match role {
2592 ProviderRole::ManagementSurface { operations, .. } => {
2593 operations.iter().any(|op| op.name == *operation)
2594 }
2595 _ => false,
2596 });
2597 if !declared {
2598 return Err(FlowOperationsError::UnknownOperation {
2599 operation: operation.clone(),
2600 });
2601 }
2602 }
2603 Ok(())
2604}
2605
2606fn decode_flow_operations(
2609 manifest: &ModuleManifest,
2610 value: &Value,
2611) -> Result<Vec<String>, FlowOperationsError> {
2612 let operations: Vec<String> =
2613 serde_json::from_value(value.clone()).map_err(|_| FlowOperationsError::NotAList)?;
2614 check_flow_operations(manifest, &operations)?;
2615 Ok(operations)
2616}
2617
2618pub fn validate_hello_flow_operations(hello: &Value) -> Result<(), FlowOperationsError> {
2624 let Some(manifest_value) = hello.get("manifest") else {
2625 return Ok(());
2626 };
2627 let Some(value) = manifest_value
2628 .get("flow_operations")
2629 .filter(|value| !value.is_null())
2630 else {
2631 return Ok(());
2632 };
2633 let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
2634 return Ok(());
2635 };
2636 decode_flow_operations(&manifest, value).map(|_| ())
2637}
2638
2639pub const MAX_OPERATION_DEFERRAL: usize = 256;
2641
2642fn decode_operation_deferral(
2643 manifest: &ModuleManifest,
2644 value: &Value,
2645) -> Result<BTreeMap<String, bool>, String> {
2646 if !manifest.capabilities.as_ref().is_some_and(|caps| {
2647 caps.provides
2648 .iter()
2649 .any(|cap| cap == crate::scope::SCOPE_FEDERATED_CAPABILITY)
2650 }) {
2651 return Err("operation_deferral requires scope-federated/v1".into());
2652 }
2653 let operations = value
2654 .as_object()
2655 .ok_or("operation_deferral must be an object")?;
2656 if operations.len() > MAX_OPERATION_DEFERRAL {
2657 return Err(format!(
2658 "operation_deferral exceeds {MAX_OPERATION_DEFERRAL} entries"
2659 ));
2660 }
2661 for (key, value) in operations {
2662 let (surface, name) = key
2663 .split_once(':')
2664 .ok_or("operation_deferral keys require a surface prefix")?;
2665 if !matches!(surface, "tool" | "management")
2668 || name.is_empty()
2669 || name.len() > 128
2670 || !name
2671 .bytes()
2672 .all(|b| (0x21..=0x7e).contains(&b) && b != b':')
2673 {
2674 return Err(format!("invalid operation_deferral key '{key}'"));
2675 }
2676 if value != &Value::Bool(true) {
2677 return Err(format!("operation_deferral value for '{key}' must be true"));
2678 }
2679 if surface == "management" && !manifest.provides.iter().any(|role| matches!(role,
2680 ProviderRole::ManagementSurface { operations, .. } if operations.iter().any(|op| op.name == name))) {
2681 return Err(format!("operation_deferral names undeclared management operation '{name}'"));
2682 }
2683 }
2684 Ok(operations.keys().map(|key| (key.clone(), true)).collect())
2685}
2686
2687impl ModuleManifest {
2688 pub fn validate_operation_deferral(&self) -> Result<(), String> {
2690 match &self.operation_deferral {
2691 Some(operations) => decode_operation_deferral(
2692 self,
2693 &serde_json::to_value(operations).expect("serializable map"),
2694 )
2695 .map(|_| ()),
2696 None => Ok(()),
2697 }
2698 }
2699}
2700
2701pub fn validate_hello_operation_deferral(hello: &Value) -> Result<(), String> {
2703 let Some(manifest_value) = hello.get("manifest") else {
2704 return Ok(());
2705 };
2706 let Some(value) = manifest_value
2707 .get("operation_deferral")
2708 .filter(|v| !v.is_null())
2709 else {
2710 return Ok(());
2711 };
2712 let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
2713 return Ok(());
2714 };
2715 decode_operation_deferral(&manifest, value).map(|_| ())
2716}
2717
2718#[derive(Debug, Clone, PartialEq, Eq)]
2723#[non_exhaustive]
2724pub enum ConfirmOperationsError {
2725 NotAList,
2727 TooMany { count: usize },
2729 DuplicateOperation { operation: String },
2731 UnknownOperation { operation: String },
2733}
2734
2735impl fmt::Display for ConfirmOperationsError {
2736 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2737 match self {
2738 Self::NotAList => {
2739 f.write_str("confirm_operations must be an array of operation names")
2740 }
2741 Self::TooMany { count } => write!(
2742 f,
2743 "confirm_operations lists {count} names, more than {MAX_CONFIRM_OPERATIONS}"
2744 ),
2745 Self::DuplicateOperation { operation } => {
2746 write!(f, "confirm_operations names '{operation}' more than once")
2747 }
2748 Self::UnknownOperation { operation } => write!(
2749 f,
2750 "confirm_operations names '{operation}', which is not a declared management operation"
2751 ),
2752 }
2753 }
2754}
2755
2756impl std::error::Error for ConfirmOperationsError {}
2757
2758impl ModuleManifest {
2759 pub fn validate_confirm_operations(&self) -> Result<(), ConfirmOperationsError> {
2763 match &self.confirm_operations {
2764 Some(operations) => check_confirm_operations(self, operations),
2765 None => Ok(()),
2766 }
2767 }
2768}
2769
2770fn check_confirm_operations(
2771 manifest: &ModuleManifest,
2772 operations: &[String],
2773) -> Result<(), ConfirmOperationsError> {
2774 if operations.len() > MAX_CONFIRM_OPERATIONS {
2775 return Err(ConfirmOperationsError::TooMany {
2776 count: operations.len(),
2777 });
2778 }
2779 let mut seen = HashSet::new();
2780 for operation in operations {
2781 if !seen.insert(operation.as_str()) {
2782 return Err(ConfirmOperationsError::DuplicateOperation {
2783 operation: operation.clone(),
2784 });
2785 }
2786 if !declares_management_operation(manifest, operation) {
2787 return Err(ConfirmOperationsError::UnknownOperation {
2788 operation: operation.clone(),
2789 });
2790 }
2791 }
2792 Ok(())
2793}
2794
2795fn declares_management_operation(manifest: &ModuleManifest, operation: &str) -> bool {
2796 manifest.provides.iter().any(|role| match role {
2797 ProviderRole::ManagementSurface { operations, .. } => {
2798 operations.iter().any(|op| op.name == operation)
2799 }
2800 _ => false,
2801 })
2802}
2803
2804fn decode_confirm_operations(
2807 manifest: &ModuleManifest,
2808 value: &Value,
2809) -> Result<Vec<String>, ConfirmOperationsError> {
2810 let operations: Vec<String> =
2811 serde_json::from_value(value.clone()).map_err(|_| ConfirmOperationsError::NotAList)?;
2812 check_confirm_operations(manifest, &operations)?;
2813 Ok(operations)
2814}
2815
2816pub fn validate_hello_confirm_operations(hello: &Value) -> Result<(), ConfirmOperationsError> {
2822 let Some(manifest_value) = hello.get("manifest") else {
2823 return Ok(());
2824 };
2825 let Some(value) = manifest_value
2826 .get("confirm_operations")
2827 .filter(|value| !value.is_null())
2828 else {
2829 return Ok(());
2830 };
2831 let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
2832 return Ok(());
2833 };
2834 decode_confirm_operations(&manifest, value).map(|_| ())
2835}
2836
2837#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2842pub struct ManagementOperation {
2843 pub name: String,
2844 pub kind: ManagementOperationKind,
2845 #[serde(default, skip_serializing_if = "Option::is_none")]
2846 pub description: Option<String>,
2847}
2848
2849#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2850#[serde(rename_all = "snake_case")]
2851pub enum ManagementOperationKind {
2852 Query,
2853 Mutate,
2854}
2855
2856#[derive(Debug, Clone, PartialEq, Eq)]
2859#[non_exhaustive]
2860pub enum OperationDelivery {
2861 Watch,
2862 Other(String),
2863}
2864
2865impl OperationDelivery {
2866 pub const WATCH: Self = Self::Watch;
2868
2869 pub fn wire_name(&self) -> &str {
2871 match self {
2872 Self::Watch => "watch",
2873 Self::Other(value) => value,
2874 }
2875 }
2876
2877 pub fn is_watch(&self) -> bool {
2879 self.wire_name() == "watch"
2880 }
2881}
2882
2883impl Serialize for OperationDelivery {
2884 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2885 where
2886 S: serde::Serializer,
2887 {
2888 serializer.serialize_str(self.wire_name())
2889 }
2890}
2891
2892impl<'de> Deserialize<'de> for OperationDelivery {
2893 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2894 where
2895 D: Deserializer<'de>,
2896 {
2897 let value = String::deserialize(deserializer)?;
2898 Ok(if value == "watch" {
2899 Self::WATCH
2900 } else {
2901 Self::Other(value)
2902 })
2903 }
2904}
2905
2906#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2908pub struct ObservabilitySurface {
2909 pub name: String,
2910 pub kind: ObservabilityKind,
2911}
2912
2913#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2914#[serde(rename_all = "snake_case")]
2915pub enum ObservabilityKind {
2916 Snapshot,
2917 Stream,
2918}
2919
2920#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2921#[serde(rename_all = "snake_case")]
2922pub enum InternalTransport {
2923 Bulk,
2924}
2925
2926#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2928#[serde(tag = "role", rename_all = "snake_case")]
2929pub enum ConsumerRole {
2930 ToolClient { of: Vec<String> },
2931 LlmClient { via: String, auth: String },
2932 ServiceClient { of: Vec<String> },
2933}
2934
2935#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2937pub struct Bindings {
2938 pub storage: StorageBinding,
2939 pub vault_grants: Vec<VaultGrant>,
2940 pub identity: IdentityBinding,
2941}
2942
2943#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2945pub struct StorageBinding {
2946 pub kind: StorageKind,
2947 pub scope: StorageScope,
2948 pub owns_schema: bool,
2949}
2950
2951#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2952#[serde(rename_all = "snake_case")]
2953pub enum StorageKind {
2954 Sqlite,
2955}
2956
2957#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2958#[serde(rename_all = "snake_case")]
2959pub enum StorageScope {
2960 Project,
2961}
2962
2963#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2964pub struct VaultGrant {
2965 pub secret: String,
2966 pub reason: String,
2967}
2968
2969#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2970pub struct IdentityBinding {
2971 pub requires: Vec<IdentityScope>,
2972 pub optional: Vec<IdentityScope>,
2973}
2974
2975#[cfg(test)]
2976mod tests {
2977 use super::*;
2978 use serde_json::json;
2979
2980 fn aft_manifest_fixture() -> ModuleManifest {
2981 ModuleManifest::builder("aft", "0.39.2")
2982 .trust_tier(Some(TrustTier::FirstParty))
2983 .bindings(Some(Bindings {
2984 storage: StorageBinding {
2985 kind: StorageKind::Sqlite,
2986 scope: StorageScope::Project,
2987 owns_schema: true,
2988 },
2989 vault_grants: vec![VaultGrant {
2990 secret: "provider_api_key".to_string(),
2991 reason: "cortexkit_native auth".to_string(),
2992 }],
2993 identity: IdentityBinding {
2994 requires: vec![IdentityScope::Project],
2995 optional: vec![IdentityScope::Session],
2996 },
2997 }))
2998 .protocol_ver(1)
2999 .provides(vec![ProviderRole::ToolProvider {
3000 tools: vec![
3001 Tool {
3002 name: "read".to_string(),
3003 description: None,
3004 execution_mode: ExecutionMode::Pure,
3005 schema: json!({"type": "object"}),
3006 },
3007 Tool {
3008 name: "grep".to_string(),
3009 description: None,
3010 execution_mode: ExecutionMode::Pure,
3011 schema: json!({"type": "object"}),
3012 },
3013 Tool {
3014 name: "outline".to_string(),
3015 description: None,
3016 execution_mode: ExecutionMode::Pure,
3017 schema: json!({"type": "object"}),
3018 },
3019 Tool {
3020 name: "semantic_search".to_string(),
3021 description: None,
3022 execution_mode: ExecutionMode::Pure,
3023 schema: json!({"type": "object"}),
3024 },
3025 Tool {
3026 name: "edit".to_string(),
3027 description: None,
3028 execution_mode: ExecutionMode::Mutating,
3029 schema: json!({"type": "object"}),
3030 },
3031 Tool {
3032 name: "write".to_string(),
3033 description: None,
3034 execution_mode: ExecutionMode::Mutating,
3035 schema: json!({"type": "object"}),
3036 },
3037 Tool {
3038 name: "bash".to_string(),
3039 description: None,
3040 execution_mode: ExecutionMode::Unfenceable,
3041 schema: json!({"type": "object"}),
3042 },
3043 ],
3044 identity_scope: vec![IdentityScope::Session, IdentityScope::Project],
3045 concurrency: Concurrency::ModuleManaged,
3046 emits_push: true,
3047 sub_supervises: true,
3048 }])
3049 .consumes(vec![ConsumerRole::ServiceClient {
3050 of: vec!["embedding.v2".to_string()],
3051 }])
3052 .build()
3053 }
3054
3055 #[test]
3056 fn serde_round_trips_representative_manifest() {
3057 let manifest = aft_manifest_fixture();
3058 let serialized = serde_json::to_string_pretty(&manifest).unwrap();
3059 let decoded: ModuleManifest = serde_json::from_str(&serialized).unwrap();
3060
3061 assert_eq!(manifest, decoded);
3062 }
3063
3064 #[test]
3065 fn builder_defaults_additions_to_honest_absence_and_round_trips() {
3066 let manifest = ModuleManifest::builder("builder-defaults", "2.0.0").build();
3067
3068 assert_eq!(manifest.module_id, "builder-defaults");
3069 assert_eq!(manifest.module_version, "2.0.0");
3070 assert_eq!(manifest.display_name, None);
3071 assert_eq!(manifest.protocol_ver, PROTOCOL_VERSION);
3072 assert_eq!(manifest.trust_tier, None);
3073 assert!(manifest.provides.is_empty());
3074 assert!(manifest.consumes.is_empty());
3075 assert_eq!(manifest.bindings, None);
3076 assert_eq!(manifest.capabilities, None);
3077 assert_eq!(manifest.self_signals, None);
3078 assert_eq!(manifest.provenance, None);
3079
3080 let encoded = serde_json::to_value(&manifest).expect("builder manifest serializes");
3081 for optional in [
3082 "display_name",
3083 "trust_tier",
3084 "consumes",
3085 "bindings",
3086 "capabilities",
3087 "self_signals",
3088 "provenance",
3089 ] {
3090 assert!(
3091 encoded.get(optional).is_none(),
3092 "an absent {optional} declaration must stay absent on the wire"
3093 );
3094 }
3095 let decoded: ModuleManifest =
3096 serde_json::from_value(encoded).expect("builder manifest round-trips");
3097 assert_eq!(decoded, manifest);
3098 }
3099
3100 #[test]
3101 fn fully_populated_builder_manifest_matches_the_literal_wire_golden() {
3102 let manifest = ModuleManifest::builder("full-builder", "2.0.0")
3103 .display_name(Some("Example".to_string()))
3104 .unwrap()
3105 .trust_tier(Some(TrustTier::Reviewed))
3106 .bindings(Some(Bindings {
3107 storage: StorageBinding {
3108 kind: StorageKind::Sqlite,
3109 scope: StorageScope::Project,
3110 owns_schema: false,
3111 },
3112 vault_grants: Vec::new(),
3113 identity: IdentityBinding {
3114 requires: vec![IdentityScope::Project],
3115 optional: Vec::new(),
3116 },
3117 }))
3118 .provides(vec![ProviderRole::ToolProvider {
3119 tools: vec![Tool {
3120 name: "read".to_string(),
3121 description: None,
3122 execution_mode: ExecutionMode::Pure,
3123 schema: json!({"type": "object"}),
3124 }],
3125 identity_scope: vec![IdentityScope::Project],
3126 concurrency: Concurrency::Serial,
3127 emits_push: false,
3128 sub_supervises: false,
3129 }])
3130 .consumes(vec![ConsumerRole::ServiceClient {
3131 of: vec!["embedding.v2".to_string()],
3132 }])
3133 .capabilities(Some(CapabilityDeclarations {
3134 provides: vec!["embedding/v2".to_string()],
3135 requires: Vec::new(),
3136 must_never_reach: Vec::new(),
3137 }))
3138 .self_signals(Some(vec![SelfSignalDeclaration {
3139 name: "usage_poller".to_string(),
3140 kind: SelfSignalKind::Poller,
3141 effect: SelfSignalEffect::Observe,
3142 anchored_to: SignalAnchor::FixedInterval,
3143 cadence: Some(SignalCadence::Literal {
3144 interval_ms: 60_000,
3145 }),
3146 domain: Some("provider-usage".to_string()),
3147 note: None,
3148 }]))
3149 .provenance(Some(ManifestProvenance {
3150 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
3151 build_git_sha_absence_reason: None,
3152 build_lock_digest: Some(
3153 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
3154 ),
3155 wire_crate_version: Some("0.16.0".to_string()),
3156 store_schema_version: Some("42".to_string()),
3157 launch_nonce_source: None,
3158 }))
3159 .build();
3160
3161 assert_eq!(
3162 serde_json::to_vec(&manifest).expect("builder manifest serializes"),
3163 include_bytes!("../tests/golden/module_manifest_builder_full.json"),
3164 "the builder must match the fully populated manifest wire bytes"
3165 );
3166 }
3167
3168 #[test]
3169 fn display_name_validator_enforces_scalar_bounds_and_safe_text() {
3170 for valid in [
3171 "Routing".to_string(),
3172 "名".repeat(40),
3173 "a".repeat(40),
3174 "e\u{301}".repeat(20),
3175 ] {
3176 assert!(validate_display_name(&valid).is_ok(), "{valid:?}");
3177 }
3178 let mut invalid = vec![
3179 "".to_string(),
3180 "a".repeat(41),
3181 "名".repeat(41),
3182 " Routing".to_string(),
3183 "Routing ".to_string(),
3184 "\u{2003}Routing".to_string(),
3185 "a\nb".to_string(),
3186 "a\u{0085}b".to_string(),
3187 "a\u{007f}b".to_string(),
3188 ];
3189 for code in [0x061c, 0x200e, 0x200f]
3190 .into_iter()
3191 .chain(0x202a..=0x202e)
3192 .chain(0x2066..=0x2069)
3193 {
3194 invalid.push(format!("a{}b", char::from_u32(code).unwrap()));
3195 }
3196 let accepted: Vec<_> = invalid
3197 .iter()
3198 .filter(|value| validate_display_name(value).is_ok())
3199 .collect();
3200 assert!(
3201 accepted.is_empty(),
3202 "invalid display names accepted: {accepted:?}"
3203 );
3204 }
3205
3206 #[test]
3207 fn display_name_builder_refuses_invalid_value() {
3208 let error = ModuleManifest::builder("provider", "1.0.0")
3209 .display_name(Some(" Routing".to_string()))
3210 .unwrap_err();
3211 assert!(error.to_string().contains("display_name"));
3212 }
3213
3214 #[test]
3215 fn display_name_manifest_round_trips_and_keeps_unknown_fields_lenient() {
3216 let manifest = ModuleManifest::builder("provider", "1.0.0")
3217 .display_name(Some("Routing".to_string()))
3218 .unwrap()
3219 .build();
3220 let mut wire = serde_json::to_value(&manifest).unwrap();
3221 assert_eq!(wire["display_name"], "Routing");
3222 wire["future_manifest_field"] = json!(true);
3223 assert_eq!(
3224 serde_json::from_value::<ModuleManifest>(wire.clone()).unwrap(),
3225 manifest
3226 );
3227 wire["display_name"] = json!("bad\nname");
3228 assert!(serde_json::from_value::<ModuleManifest>(wire)
3229 .unwrap_err()
3230 .to_string()
3231 .contains("display_name"));
3232 }
3233
3234 #[test]
3235 fn old_manifest_with_unread_fields_decodes_and_round_trips_verbatim() {
3236 let raw = include_bytes!("../tests/golden/module_manifest_builder_full.json");
3237 let decoded: ModuleManifest =
3238 serde_json::from_slice(raw).expect("old manifest with all unread fields decodes");
3239
3240 assert_eq!(decoded.trust_tier, Some(TrustTier::Reviewed));
3241 assert!(!decoded.consumes.is_empty());
3242 assert!(decoded.bindings.is_some());
3243
3244 let reencoded = serde_json::to_vec(&decoded).expect("re-encode succeeds");
3245 assert_eq!(
3246 reencoded, raw,
3247 "old manifest relay stays byte-for-byte verbatim"
3248 );
3249 }
3250
3251 #[test]
3252 fn new_manifest_omits_unread_fields_on_wire_and_decodes_cleanly() {
3253 let raw = include_bytes!("../tests/golden/module_manifest_diet.json");
3254 let decoded: ModuleManifest =
3255 serde_json::from_slice(raw).expect("new manifest omitting unread fields decodes");
3256
3257 assert_eq!(decoded.trust_tier, None);
3258 assert!(decoded.consumes.is_empty());
3259 assert_eq!(decoded.bindings, None);
3260
3261 let pretty = format!("{}\n", serde_json::to_string_pretty(&decoded).unwrap());
3262 assert_eq!(
3263 pretty.as_bytes(),
3264 raw,
3265 "new manifest matches golden byte-for-byte without unread keys"
3266 );
3267
3268 let as_val: serde_json::Value = serde_json::to_value(&decoded).unwrap();
3269 assert!(
3270 as_val.get("trust_tier").is_none(),
3271 "no trust_tier on wire for new manifest"
3272 );
3273 assert!(
3274 as_val.get("consumes").is_none(),
3275 "no consumes on wire for empty consumes"
3276 );
3277 assert!(
3278 as_val.get("bindings").is_none(),
3279 "no bindings on wire for new manifest"
3280 );
3281 }
3282
3283 #[test]
3284 fn aft_manifest_fixture_matches_v1_contract() {
3285 let manifest = aft_manifest_fixture();
3286
3287 assert_eq!(manifest.module_id, "aft");
3288 let ProviderRole::ToolProvider {
3289 tools,
3290 identity_scope,
3291 concurrency,
3292 emits_push,
3293 sub_supervises,
3294 } = &manifest.provides[0]
3295 else {
3296 panic!("AFT fixture must expose one tool_provider role");
3297 };
3298
3299 assert_eq!(*concurrency, Concurrency::ModuleManaged);
3300 assert!(*emits_push);
3301 assert!(*sub_supervises);
3302 assert_eq!(
3303 identity_scope,
3304 &vec![IdentityScope::Session, IdentityScope::Project]
3305 );
3306 assert_eq!(
3307 tools
3308 .iter()
3309 .map(|tool| (tool.name.as_str(), tool.execution_mode))
3310 .collect::<Vec<_>>(),
3311 vec![
3312 ("read", ExecutionMode::Pure),
3313 ("grep", ExecutionMode::Pure),
3314 ("outline", ExecutionMode::Pure),
3315 ("semantic_search", ExecutionMode::Pure),
3316 ("edit", ExecutionMode::Mutating),
3317 ("write", ExecutionMode::Mutating),
3318 ("bash", ExecutionMode::Unfenceable),
3319 ]
3320 );
3321 }
3322
3323 #[test]
3324 fn tool_provider_role_tag_serializes_as_snake_case() {
3325 let manifest = aft_manifest_fixture();
3326 let value = serde_json::to_value(&manifest).unwrap();
3327
3328 assert_eq!(value["provides"][0]["role"], "tool_provider");
3329 }
3330
3331 #[test]
3332 fn manifest_without_capabilities_preserves_the_existing_wire_shape() {
3333 let manifest = aft_manifest_fixture();
3334 let encoded = serde_json::to_value(&manifest).expect("manifest serializes");
3335 assert!(encoded.get("capabilities").is_none());
3336
3337 let decoded: ModuleManifest =
3338 serde_json::from_value(encoded).expect("legacy manifest parses");
3339 assert_eq!(decoded.capabilities, None);
3340 }
3341
3342 #[test]
3343 fn capability_identifier_lexical_grammar_accepts_only_pinned_forms() {
3344 for identifier in [
3345 "a/v1",
3346 "credentials-provider/v1",
3347 "a1-b2/v4294967295",
3348 "a123456789012345678901234567890123456789012345678901234567890123/v1",
3349 ] {
3350 assert!(
3351 is_valid_capability_identifier(identifier),
3352 "identifier must be accepted: {identifier}"
3353 );
3354 }
3355
3356 for identifier in [
3357 "credentials-Provider/v1",
3358 "credentials-provider/v01",
3359 "credentials-provider-/v1",
3360 "credentials--provider/v1",
3361 "Credentials-provider/v1",
3362 "credentials-provider/1",
3363 "credentials provider/v1",
3364 "credentials-provider/v0",
3365 "credentials-provider/v4294967296",
3366 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/v1",
3367 ] {
3368 assert!(
3369 !is_valid_capability_identifier(identifier),
3370 "identifier must be rejected: {identifier}"
3371 );
3372 }
3373 }
3374
3375 #[test]
3376 fn capability_grammar_errors_redact_secret_shaped_values() {
3377 let error = validate_manifest_capability_grammar(&json!({
3378 "capabilities": { "provides": ["sk-secret-value/v0"] }
3379 }))
3380 .expect_err("secret-shaped capability identifier is malformed");
3381 assert_eq!(error.field(), "capabilities.provides[0]");
3382 assert_eq!(error.value(), "<redacted>");
3383 assert!(!error.to_string().contains("sk-secret-value"));
3384 }
3385
3386 #[test]
3393 fn provenance_builder_sentinels_become_field_omission() {
3394 for sentinel in [
3395 "unknown",
3396 "UNKNOWN",
3397 "Unknown",
3398 "unavailable",
3399 "none",
3400 "None",
3401 " unknown ",
3402 "",
3403 ] {
3404 let p = build_provenance_from_source(
3405 BuildGitShaSource::Git {
3406 revision: sentinel,
3407 tree_state: GitTreeState::Clean,
3408 },
3409 Some(sentinel),
3410 Some(sentinel),
3411 )
3412 .expect("sentinels are omitted before form validation");
3413 assert_eq!(
3414 (
3415 p.build_git_sha,
3416 p.build_git_sha_absence_reason,
3417 p.build_lock_digest,
3418 p.store_schema_version,
3419 ),
3420 (
3421 None,
3422 Some(BuildGitShaAbsenceReason::NeverDerived),
3423 None,
3424 None,
3425 ),
3426 "sentinel {sentinel:?} must be omitted, not published"
3427 );
3428 }
3429 let real = build_provenance_from_source(
3430 BuildGitShaSource::Git {
3431 revision: "0123456789abcdef0123456789abcdef01234567",
3432 tree_state: GitTreeState::Clean,
3433 },
3434 None,
3435 Some("9"),
3436 )
3437 .expect("canonical build revision is accepted");
3438 assert_eq!(
3439 real.build_git_sha.as_deref(),
3440 Some("0123456789abcdef0123456789abcdef01234567")
3441 );
3442 assert_eq!(real.store_schema_version.as_deref(), Some("9"));
3443 assert_eq!(
3447 real.wire_crate_version.as_deref(),
3448 Some(crate::SUBC_PROTOCOL_CRATE_VERSION)
3449 );
3450 }
3451
3452 #[test]
3453 fn build_provenance_accepts_canonical_sha_and_lock_digest() {
3454 let provenance = build_provenance_from_source(
3455 BuildGitShaSource::Git {
3456 revision: " 0123456789abcdef0123456789abcdef01234567 ",
3457 tree_state: GitTreeState::Clean,
3458 },
3459 Some(" abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789 "),
3460 Some(" schema-v3 "),
3461 )
3462 .expect("canonical build facts are accepted");
3463
3464 assert_eq!(
3465 provenance,
3466 ManifestProvenance {
3467 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
3468 build_git_sha_absence_reason: None,
3469 build_lock_digest: Some(
3470 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
3471 ),
3472 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
3473 store_schema_version: Some("schema-v3".to_string()),
3474 launch_nonce_source: None,
3475 }
3476 );
3477 }
3478
3479 #[test]
3480 fn build_provenance_refuses_an_abbreviated_git_sha() {
3481 let error = build_provenance_from_source(
3482 BuildGitShaSource::Git {
3483 revision: "0123456789ab",
3484 tree_state: GitTreeState::Clean,
3485 },
3486 None,
3487 None,
3488 )
3489 .expect_err("a 12-character abbreviation is not canonical");
3490
3491 assert_eq!(error.field(), "build_git_sha");
3492 assert_eq!(error.length(), 12);
3493 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3494 assert_eq!(
3495 error.to_string(),
3496 "invalid manifest provenance form: field build_git_sha has length 12; canonical form is exactly 40 lowercase hexadecimal characters"
3497 );
3498 }
3499
3500 #[test]
3501 fn build_provenance_refuses_an_abbreviated_lock_digest() {
3502 let error = build_provenance_from_source(
3503 BuildGitShaSource::NeverDerived,
3504 Some("0123456789abcdef"),
3505 None,
3506 )
3507 .expect_err("a 16-character digest is not canonical");
3508
3509 assert_eq!(error.field(), "build_lock_digest");
3510 assert_eq!(error.length(), 16);
3511 assert_eq!(error.canonical_form(), BUILD_LOCK_DIGEST_CANONICAL_FORM);
3512 }
3513
3514 #[test]
3515 fn build_provenance_refuses_uppercase_hex() {
3516 let uppercase_sha = "A".repeat(40);
3517 let error = build_provenance_from_source(
3518 BuildGitShaSource::Git {
3519 revision: &uppercase_sha,
3520 tree_state: GitTreeState::Clean,
3521 },
3522 None,
3523 None,
3524 )
3525 .expect_err("uppercase hexadecimal is not canonical");
3526
3527 assert_eq!(error.field(), "build_git_sha");
3528 assert_eq!(error.length(), 40);
3529 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3530 }
3531
3532 #[test]
3533 fn build_provenance_refuses_dirty_revision_stamp_claimed_clean() {
3534 let error = build_provenance_from_source(
3535 BuildGitShaSource::Git {
3536 revision: "0123456789abcdef0123456789abcdef01234567-dirty",
3537 tree_state: GitTreeState::Clean,
3538 },
3539 None,
3540 None,
3541 )
3542 .expect_err("a dirty stamp is not a canonical build revision");
3543
3544 assert_eq!(error.field(), "build_git_sha");
3545 assert_eq!(error.length(), 46);
3546 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3547 }
3548
3549 #[test]
3550 fn build_provenance_keeps_a_lock_digest_when_identity_is_unavailable() {
3551 let provenance = build_provenance_from_source(
3552 BuildGitShaSource::Git {
3553 revision: "unavailable",
3554 tree_state: GitTreeState::Clean,
3555 },
3556 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"),
3557 None,
3558 )
3559 .expect("sentinel SHA is omitted before the valid lock digest is checked");
3560
3561 assert_eq!(provenance.build_git_sha, None);
3562 assert_eq!(
3563 provenance.build_lock_digest,
3564 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string())
3565 );
3566 assert_eq!(
3567 provenance.wire_crate_version,
3568 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
3569 );
3570 }
3571
3572 #[test]
3573 fn build_provenance_omits_fully_unavailable_inputs() {
3574 let provenance = build_provenance_from_source(
3575 BuildGitShaSource::NeverDerived,
3576 Some(" unavailable "),
3577 Some(" "),
3578 )
3579 .expect("omitted and sentinel inputs are not form errors");
3580
3581 assert_eq!(provenance.build_git_sha, None);
3582 assert_eq!(provenance.build_lock_digest, None);
3583 assert_eq!(provenance.store_schema_version, None);
3584 assert_eq!(
3585 provenance.wire_crate_version,
3586 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
3587 );
3588 }
3589
3590 #[test]
3591 fn legacy_build_provenance_keeps_master_wire_bytes_without_an_absence_reason() {
3592 let revision = "0123456789abcdef0123456789abcdef01234567";
3593 for (input, expected) in [
3594 (
3595 Some(revision),
3596 format!(
3597 r#"{{"build_git_sha":"{revision}","wire_crate_version":"{}"}}"#,
3598 crate::SUBC_PROTOCOL_CRATE_VERSION
3599 ),
3600 ),
3601 (
3602 None,
3603 format!(
3604 r#"{{"wire_crate_version":"{}"}}"#,
3605 crate::SUBC_PROTOCOL_CRATE_VERSION
3606 ),
3607 ),
3608 (
3609 Some("unknown"),
3610 format!(
3611 r#"{{"wire_crate_version":"{}"}}"#,
3612 crate::SUBC_PROTOCOL_CRATE_VERSION
3613 ),
3614 ),
3615 ] {
3616 let provenance = build_provenance(input, None, None)
3617 .expect("the legacy build facts remain constructible");
3618 assert_eq!(provenance.build_git_sha_absence_reason, None);
3619 assert_eq!(
3620 serde_json::to_string(&provenance).expect("legacy provenance serializes"),
3621 expected
3622 );
3623 }
3624 }
3625
3626 #[test]
3627 fn build_provenance_derives_git_sha_absence_from_the_stamping_inputs() {
3628 let revision = "0123456789abcdef0123456789abcdef01234567";
3629 let cases = [
3630 (
3631 BuildGitShaSource::Git {
3632 revision,
3633 tree_state: GitTreeState::Clean,
3634 },
3635 Some(revision),
3636 None,
3637 ),
3638 (
3639 BuildGitShaSource::Git {
3640 revision,
3641 tree_state: GitTreeState::Dirty,
3642 },
3643 None,
3644 Some(BuildGitShaAbsenceReason::DeclinedDirty),
3645 ),
3646 (
3647 BuildGitShaSource::NeverDerived,
3648 None,
3649 Some(BuildGitShaAbsenceReason::NeverDerived),
3650 ),
3651 (
3652 BuildGitShaSource::NoGitDir,
3653 None,
3654 Some(BuildGitShaAbsenceReason::NoGitDir),
3655 ),
3656 ];
3657
3658 for (source, expected_sha, expected_reason) in cases {
3659 let provenance = build_provenance_from_source(source, None, None)
3660 .expect("every stamping state constructs honest provenance");
3661 assert_eq!(provenance.build_git_sha.as_deref(), expected_sha);
3662 assert_eq!(provenance.build_git_sha_absence_reason, expected_reason);
3663 }
3664 }
3665
3666 #[test]
3667 fn unknown_git_sha_absence_reason_round_trips_byte_faithfully() {
3668 let wire = format!(
3669 r#"{{"build_git_sha_absence_reason":"future_stamper_state","wire_crate_version":"{}"}}"#,
3670 crate::SUBC_PROTOCOL_CRATE_VERSION
3671 );
3672 let provenance: ManifestProvenance =
3673 serde_json::from_str(&wire).expect("future absence reasons remain readable");
3674
3675 assert_eq!(
3676 provenance.build_git_sha_absence_reason,
3677 Some(BuildGitShaAbsenceReason::ForwardCompatibleUnknown(
3678 "future_stamper_state".to_string()
3679 ))
3680 );
3681 assert_eq!(
3682 serde_json::to_string(&provenance).expect("future absence reason reserializes"),
3683 wire
3684 );
3685 }
3686
3687 #[test]
3688 fn provenance_rejects_an_absence_reason_beside_a_declared_commit() {
3689 let error = serde_json::from_value::<ManifestProvenance>(json!({
3690 "build_git_sha": "0123456789abcdef0123456789abcdef01234567",
3691 "build_git_sha_absence_reason": "declined_dirty"
3692 }))
3693 .expect_err("a declared commit cannot also claim an absence reason");
3694
3695 assert!(error.to_string().contains(
3696 "build_git_sha_absence_reason has must be omitted when build_git_sha is present"
3697 ));
3698 }
3699
3700 #[test]
3701 fn rich_ui_descriptor_is_optional_and_round_trips_when_present() {
3702 let manifest = ModuleManifest::builder("provider", "1.0.0").build();
3703 assert_eq!(
3704 serde_json::to_string(&manifest).unwrap(),
3705 r#"{"module_id":"provider","module_version":"1.0.0","protocol_ver":2,"provides":[]}"#
3706 );
3707
3708 let descriptor = RichUiDescriptor::new(
3709 "ckios.richui.manifest/1",
3710 format!("sha256:{}", "a".repeat(64)),
3711 128,
3712 2,
3713 );
3714 let manifest = ModuleManifest::builder("provider", "1.0.0")
3715 .rich_ui(Some(descriptor.clone()))
3716 .build();
3717 let wire = serde_json::to_string(&manifest).unwrap();
3718 assert!(wire.contains("\"rich_ui\":{\"schema\":\"ckios.richui.manifest/1\""));
3719 assert_eq!(
3720 serde_json::from_str::<ModuleManifest>(&wire)
3721 .unwrap()
3722 .rich_ui,
3723 Some(descriptor)
3724 );
3725 }
3726
3727 #[test]
3728 fn rich_ui_descriptor_validation_names_each_invalid_field() {
3729 let good = json!({
3730 "schema": "ckios.richui.manifest/1",
3731 "manifest_digest": format!("sha256:{}", "a".repeat(64)),
3732 "bytes": 1,
3733 "chunks": 1
3734 });
3735 let hello = json!({"manifest": {"rich_ui": good.clone()}});
3736 assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
3737
3738 for (field, value) in [
3739 ("schema", json!("bad schema")),
3740 (
3741 "manifest_digest",
3742 json!(format!("sha256:{}", "A".repeat(64))),
3743 ),
3744 ("bytes", json!(0)),
3745 ("chunks", json!(1025)),
3746 ] {
3747 let mut invalid = hello.clone();
3748 invalid["manifest"]["rich_ui"][field] = value;
3749 let error = validate_hello_rich_ui_descriptor(&invalid)
3750 .expect_err("an invalid descriptor field must be refused");
3751 assert_eq!(error.field(), format!("rich_ui.{field}"));
3752 }
3753
3754 let mut hello = hello;
3755 hello["manifest"]["rich_ui"] = Value::Null;
3756 let error = validate_hello_rich_ui_descriptor(&hello)
3757 .expect_err("null is not an absent descriptor");
3758 assert_eq!(error.field(), "rich_ui");
3759 }
3760
3761 #[test]
3762 fn rich_ui_descriptor_validation_accepts_inclusive_bounds() {
3763 let hello = json!({"manifest": {"rich_ui": {
3764 "schema": "a".repeat(64),
3765 "manifest_digest": format!("sha256:{}", "f".repeat(64)),
3766 "bytes": 16_777_216,
3767 "chunks": 1024
3768 }}});
3769 assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
3770 }
3771}