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