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