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