1use std::{
10 collections::{BTreeMap, HashSet},
11 fmt,
12};
13
14use serde::{de::Error as _, Deserialize, Deserializer, Serialize};
15use serde_json::Value;
16
17use crate::PROTOCOL_VERSION;
18
19pub const MAX_ROLE_DECLARATIONS_BYTES: usize = 16_384;
21
22pub const MAX_FLOW_OPERATIONS: usize = 256;
24
25#[derive(Serialize, Debug, Clone, PartialEq)]
32#[non_exhaustive]
33pub struct ModuleManifest {
34 pub module_id: String,
35 pub module_version: String,
36 pub protocol_ver: u8,
37 #[serde(default, skip_serializing_if = "Option::is_none")]
38 pub trust_tier: Option<TrustTier>,
39 #[serde(default, skip_serializing_if = "Option::is_none")]
46 pub ready: Option<bool>,
47 pub provides: Vec<ProviderRole>,
50 #[serde(default, skip_serializing_if = "Vec::is_empty")]
51 pub consumes: Vec<ConsumerRole>,
52 #[serde(default, skip_serializing_if = "Option::is_none")]
53 pub bindings: Option<Bindings>,
54 #[serde(default, skip_serializing_if = "Option::is_none")]
60 pub capabilities: Option<CapabilityDeclarations>,
61 #[serde(default, skip_serializing_if = "Option::is_none")]
75 pub events: Option<Vec<EventDeclaration>>,
76 #[serde(default, skip_serializing_if = "Option::is_none")]
111 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
112 #[serde(default, skip_serializing_if = "Option::is_none")]
113 pub provenance: Option<ManifestProvenance>,
114 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
119 pub operation_delivery: BTreeMap<String, OperationDelivery>,
120 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
123 pub operation_payload: BTreeMap<String, OperationPayload>,
124 #[serde(default, skip_serializing_if = "Option::is_none")]
143 pub flow_operations: Option<Vec<String>>,
144 #[serde(default, skip_serializing_if = "Option::is_none")]
149 pub rich_ui: Option<RichUiDescriptor>,
150 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
159 pub role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
160}
161
162#[derive(Debug, Clone)]
164pub struct ModuleManifestBuilder {
165 module_id: String,
166 module_version: String,
167 protocol_ver: u8,
168 trust_tier: Option<TrustTier>,
169 ready: Option<bool>,
170 provides: Vec<ProviderRole>,
171 consumes: Vec<ConsumerRole>,
172 bindings: Option<Bindings>,
173 capabilities: Option<CapabilityDeclarations>,
174 events: Option<Vec<EventDeclaration>>,
175 self_signals: Option<Vec<SelfSignalDeclaration>>,
176 provenance: Option<ManifestProvenance>,
177 operation_delivery: BTreeMap<String, OperationDelivery>,
178 operation_payload: BTreeMap<String, OperationPayload>,
179 flow_operations: Option<Vec<String>>,
180 rich_ui: Option<RichUiDescriptor>,
181 role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
182}
183
184impl ModuleManifest {
185 pub fn builder(
193 module_id: impl Into<String>,
194 module_version: impl Into<String>,
195 ) -> ModuleManifestBuilder {
196 ModuleManifestBuilder {
197 module_id: module_id.into(),
198 module_version: module_version.into(),
199 protocol_ver: PROTOCOL_VERSION,
200 trust_tier: None,
201 ready: None,
202 provides: Vec::new(),
203 consumes: Vec::new(),
204 bindings: None,
205 capabilities: None,
206 events: None,
207 self_signals: None,
208 provenance: None,
209 operation_delivery: BTreeMap::new(),
210 operation_payload: BTreeMap::new(),
211 flow_operations: None,
212 rich_ui: None,
213 role_declarations: BTreeMap::new(),
214 }
215 }
216
217 pub fn is_watch_operation(&self, name: &str) -> bool {
222 self.operation_delivery
223 .get(name)
224 .is_some_and(OperationDelivery::is_watch)
225 && self.provides.iter().any(|role| match role {
226 ProviderRole::ManagementSurface { operations, .. } => operations
227 .iter()
228 .any(|op| op.name == name && op.kind == ManagementOperationKind::Query),
229 _ => false,
230 })
231 }
232}
233
234impl ModuleManifestBuilder {
235 pub fn protocol_ver(mut self, protocol_ver: u8) -> Self {
237 self.protocol_ver = protocol_ver;
238 self
239 }
240
241 pub fn trust_tier(mut self, trust_tier: Option<TrustTier>) -> Self {
245 self.trust_tier = trust_tier;
246 self
247 }
248
249 pub fn ready(mut self, ready: bool) -> Self {
251 self.ready = Some(ready);
252 self
253 }
254
255 pub fn provides(mut self, provides: Vec<ProviderRole>) -> Self {
257 self.provides = provides;
258 self
259 }
260
261 pub fn consumes(mut self, consumes: Vec<ConsumerRole>) -> Self {
263 self.consumes = consumes;
264 self
265 }
266
267 pub fn bindings(mut self, bindings: Option<Bindings>) -> Self {
271 self.bindings = bindings;
272 self
273 }
274
275 pub fn capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
277 self.capabilities = capabilities;
278 self
279 }
280
281 pub fn events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
283 self.events = events;
284 self
285 }
286
287 pub fn self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
289 self.self_signals = self_signals;
290 self
291 }
292
293 pub fn provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
295 self.provenance = provenance;
296 self
297 }
298
299 pub fn operation_delivery(
301 mut self,
302 operation_delivery: BTreeMap<String, OperationDelivery>,
303 ) -> Self {
304 self.operation_delivery = operation_delivery;
305 self
306 }
307
308 pub fn operation_payload(
310 mut self,
311 operation_payload: BTreeMap<String, OperationPayload>,
312 ) -> Self {
313 self.operation_payload = operation_payload;
314 self
315 }
316
317 pub fn flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
324 self.flow_operations = flow_operations;
325 self
326 }
327
328 pub fn rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
330 self.rich_ui = rich_ui;
331 self
332 }
333
334 pub fn role_declarations(
336 mut self,
337 role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
338 ) -> Self {
339 self.role_declarations = role_declarations;
340 self
341 }
342
343 pub fn build(self) -> ModuleManifest {
345 ModuleManifest {
346 module_id: self.module_id,
347 module_version: self.module_version,
348 protocol_ver: self.protocol_ver,
349 trust_tier: self.trust_tier,
350 ready: self.ready,
351 provides: self.provides,
352 consumes: self.consumes,
353 bindings: self.bindings,
354 capabilities: self.capabilities,
355 events: self.events,
356 self_signals: self.self_signals,
357 provenance: self.provenance,
358 operation_delivery: self.operation_delivery,
359 operation_payload: self.operation_payload,
360 flow_operations: self.flow_operations,
361 rich_ui: self.rich_ui,
362 role_declarations: self.role_declarations,
363 }
364 }
365}
366
367#[derive(Deserialize)]
387struct ModuleManifestWire {
388 module_id: String,
389 module_version: String,
390 protocol_ver: u8,
391 #[serde(default)]
392 trust_tier: Option<TrustTier>,
393 #[serde(default)]
394 ready: Option<bool>,
395 provides: Vec<ProviderRole>,
396 #[serde(default)]
397 consumes: Vec<ConsumerRole>,
398 #[serde(default)]
399 bindings: Option<Bindings>,
400 #[serde(default)]
401 capabilities: Option<CapabilityDeclarations>,
402 #[serde(default)]
403 events: Option<Value>,
404 #[serde(default)]
405 self_signals: Option<Vec<SelfSignalDeclaration>>,
406 #[serde(default)]
407 provenance: Option<ManifestProvenance>,
408 #[serde(default)]
409 operation_delivery: Option<Value>,
410 #[serde(default)]
411 operation_payload: BTreeMap<String, OperationPayload>,
412 #[serde(default)]
414 flow_operations: Option<Value>,
415 #[serde(default)]
416 rich_ui: Option<RichUiDescriptor>,
417 #[serde(default)]
421 runtime_computed: Option<Value>,
422 #[serde(default)]
423 role_declarations: Option<Value>,
424}
425
426impl<'de> Deserialize<'de> for ModuleManifest {
427 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
428 where
429 D: Deserializer<'de>,
430 {
431 let wire = ModuleManifestWire::deserialize(deserializer)?;
432 validate_runtime_computed(wire.runtime_computed.as_ref(), "runtime_computed")
433 .map_err(D::Error::custom)?;
434 validate_events_value(wire.events.as_ref()).map_err(D::Error::custom)?;
435 let events = wire
436 .events
437 .map(serde_json::from_value)
438 .transpose()
439 .map_err(D::Error::custom)?;
440 let mut builder = Self::builder(wire.module_id, wire.module_version)
441 .protocol_ver(wire.protocol_ver)
442 .trust_tier(wire.trust_tier);
443 if let Some(ready) = wire.ready {
444 builder = builder.ready(ready);
445 }
446 let mut manifest = builder
447 .provides(wire.provides)
448 .consumes(wire.consumes)
449 .bindings(wire.bindings)
450 .capabilities(wire.capabilities)
451 .events(events)
452 .self_signals(wire.self_signals)
453 .provenance(wire.provenance)
454 .operation_delivery(
455 wire.operation_delivery
456 .and_then(|value| serde_json::from_value(value).ok())
457 .unwrap_or_default(),
458 )
459 .rich_ui(wire.rich_ui)
460 .role_declarations(
461 wire.role_declarations
462 .filter(|value| validate_role_declarations_value(Some(value)).is_ok())
463 .and_then(|value| serde_json::from_value(value).ok())
464 .unwrap_or_default(),
465 )
466 .operation_payload(wire.operation_payload)
467 .build();
468 manifest
469 .validate_operation_payload()
470 .map_err(D::Error::custom)?;
471 manifest.flow_operations = wire
474 .flow_operations
475 .and_then(|value| decode_flow_operations(&manifest, &value).ok());
476 manifest
477 .validate_capability_grammar()
478 .map_err(D::Error::custom)?;
479 if let Some(rich_ui) = &manifest.rich_ui {
480 rich_ui.validate().map_err(D::Error::custom)?;
481 }
482 Ok(manifest)
483 }
484}
485
486#[derive(Debug, Clone, PartialEq, Eq)]
488pub struct RoleDeclarationsError(&'static str);
489
490impl fmt::Display for RoleDeclarationsError {
491 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
492 f.write_str(self.0)
493 }
494}
495
496impl std::error::Error for RoleDeclarationsError {}
497
498pub fn validate_hello_role_declarations(hello: &Value) -> Result<(), RoleDeclarationsError> {
500 validate_role_declarations_value(
501 hello
502 .get("manifest")
503 .and_then(|manifest| manifest.get("role_declarations")),
504 )
505}
506
507fn validate_role_declarations_value(value: Option<&Value>) -> Result<(), RoleDeclarationsError> {
508 let Some(value) = value else {
509 return Ok(());
510 };
511 let map = value
512 .as_object()
513 .ok_or(RoleDeclarationsError("role_declarations must be an object"))?;
514 for (role, declaration) in map {
515 if !is_valid_capability_identifier(role) {
516 return Err(RoleDeclarationsError(
517 "role_declarations key must use capability-name grammar",
518 ));
519 }
520 if !declaration.is_object() {
521 return Err(RoleDeclarationsError(
522 "role_declarations values must be objects",
523 ));
524 }
525 }
526 let bytes = serde_json::to_vec(value)
527 .map_err(|_| RoleDeclarationsError("role_declarations could not be serialized"))?;
528 if bytes.len() > MAX_ROLE_DECLARATIONS_BYTES {
529 return Err(RoleDeclarationsError(
530 "role_declarations exceeds 16384 compact JSON bytes",
531 ));
532 }
533 Ok(())
534}
535
536#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
542#[non_exhaustive]
543pub struct RichUiDescriptor {
544 pub schema: String,
546 pub manifest_digest: String,
548 pub bytes: u64,
550 pub chunks: u32,
552}
553
554impl RichUiDescriptor {
555 pub fn new(
557 schema: impl Into<String>,
558 manifest_digest: impl Into<String>,
559 bytes: u64,
560 chunks: u32,
561 ) -> Self {
562 Self {
563 schema: schema.into(),
564 manifest_digest: manifest_digest.into(),
565 bytes,
566 chunks,
567 }
568 }
569
570 pub fn validate(&self) -> Result<(), RichUiDescriptorError> {
572 validate_rich_ui_fields(
573 &self.schema,
574 &self.manifest_digest,
575 self.bytes,
576 u64::from(self.chunks),
577 )
578 }
579}
580
581#[derive(Debug, Clone, PartialEq, Eq)]
583#[non_exhaustive]
584pub struct RichUiDescriptorError {
585 field: String,
586 reason: &'static str,
587}
588
589impl RichUiDescriptorError {
590 fn new(field: impl Into<String>, reason: &'static str) -> Self {
591 Self {
592 field: field.into(),
593 reason,
594 }
595 }
596
597 pub fn field(&self) -> &str {
599 &self.field
600 }
601}
602
603impl fmt::Display for RichUiDescriptorError {
604 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
605 write!(
606 f,
607 "invalid rich_ui descriptor: field {} {}",
608 self.field, self.reason
609 )
610 }
611}
612
613impl std::error::Error for RichUiDescriptorError {}
614
615pub fn validate_hello_rich_ui_descriptor(hello: &Value) -> Result<(), RichUiDescriptorError> {
617 let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
618 return Ok(());
619 };
620 let Some(value) = manifest.get("rich_ui") else {
621 return Ok(());
622 };
623 validate_rich_ui_descriptor_value(value)
624}
625
626fn validate_rich_ui_descriptor_value(value: &Value) -> Result<(), RichUiDescriptorError> {
627 let descriptor = value
628 .as_object()
629 .ok_or_else(|| RichUiDescriptorError::new("rich_ui", "must be an object"))?;
630 let schema = descriptor
631 .get("schema")
632 .and_then(Value::as_str)
633 .ok_or_else(|| RichUiDescriptorError::new("rich_ui.schema", "must be a string"))?;
634 let digest = descriptor
635 .get("manifest_digest")
636 .and_then(Value::as_str)
637 .ok_or_else(|| RichUiDescriptorError::new("rich_ui.manifest_digest", "must be a string"))?;
638 let bytes = descriptor
639 .get("bytes")
640 .and_then(Value::as_u64)
641 .ok_or_else(|| {
642 RichUiDescriptorError::new("rich_ui.bytes", "must be an integer from 1 to 16777216")
643 })?;
644 let chunks = descriptor
645 .get("chunks")
646 .and_then(Value::as_u64)
647 .ok_or_else(|| {
648 RichUiDescriptorError::new("rich_ui.chunks", "must be an integer from 1 to 1024")
649 })?;
650 validate_rich_ui_fields(schema, digest, bytes, chunks)
651}
652
653fn validate_rich_ui_fields(
654 schema: &str,
655 digest: &str,
656 bytes: u64,
657 chunks: u64,
658) -> Result<(), RichUiDescriptorError> {
659 if !(1..=64).contains(&schema.len())
660 || !schema.bytes().all(|byte| {
661 byte.is_ascii_lowercase()
662 || byte.is_ascii_digit()
663 || matches!(byte, b'.' | b'_' | b'/' | b'-')
664 })
665 {
666 return Err(RichUiDescriptorError::new(
667 "rich_ui.schema",
668 "must be 1 to 64 bytes of [a-z0-9._/-]",
669 ));
670 }
671 if !digest.strip_prefix("sha256:").is_some_and(|hex| {
672 hex.len() == 64
673 && hex
674 .bytes()
675 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
676 }) {
677 return Err(RichUiDescriptorError::new(
678 "rich_ui.manifest_digest",
679 "must be sha256: followed by 64 lowercase hexadecimal characters",
680 ));
681 }
682 if !(1..=16_777_216).contains(&bytes) {
683 return Err(RichUiDescriptorError::new(
684 "rich_ui.bytes",
685 "must be an integer from 1 to 16777216",
686 ));
687 }
688 if !(1..=1_024).contains(&chunks) {
689 return Err(RichUiDescriptorError::new(
690 "rich_ui.chunks",
691 "must be an integer from 1 to 1024",
692 ));
693 }
694 Ok(())
695}
696
697pub const CAP_CATALOG_EVENTS_V1: &str = "catalog-events/v1";
703
704pub const CAP_SCOPE_BIND_PROOF_V1: &str = "scope-bind-proof/v1";
708
709pub const CAP_SCOPE_BIND_PROOF_V2: &str = "scope-bind-proof/v2";
713
714pub const CAP_SCOPE_REPLACE_IF_IDLE_V1: &str = "scope-replace-if-idle/v1";
716
717#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
719#[non_exhaustive]
720pub struct EventDeclaration {
721 pub name: String,
728 pub version: u32,
730 pub headers: Vec<String>,
733 #[serde(default, skip_serializing_if = "Option::is_none")]
735 pub summary: Option<String>,
736}
737
738impl EventDeclaration {
739 pub fn new(name: impl Into<String>, version: u32) -> Self {
742 Self {
743 name: name.into(),
744 version,
745 headers: Vec::new(),
746 summary: None,
747 }
748 }
749
750 pub fn with_headers(mut self, headers: Vec<String>) -> Self {
752 self.headers = headers;
753 self
754 }
755
756 pub fn with_summary(mut self, summary: Option<String>) -> Self {
758 self.summary = summary;
759 self
760 }
761}
762
763#[derive(Debug, Clone, PartialEq, Eq)]
765#[non_exhaustive]
766pub struct EventDeclarationError {
767 field: String,
768 reason: &'static str,
769}
770
771impl EventDeclarationError {
772 fn new(field: impl Into<String>, reason: &'static str) -> Self {
773 Self {
774 field: field.into(),
775 reason,
776 }
777 }
778
779 pub fn field(&self) -> &str {
781 &self.field
782 }
783}
784
785impl fmt::Display for EventDeclarationError {
786 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
787 write!(
788 f,
789 "invalid event declaration: field {} {}",
790 self.field, self.reason
791 )
792 }
793}
794
795impl std::error::Error for EventDeclarationError {}
796
797pub fn validate_hello_event_declarations(hello: &Value) -> Result<(), EventDeclarationError> {
799 validate_events_value(
800 hello
801 .get("manifest")
802 .and_then(|manifest| manifest.get("events")),
803 )
804}
805
806fn is_valid_event_name(name: &str) -> bool {
809 let level_count = name.split('.').count();
810 (1..=4).contains(&level_count)
811 && name.split('.').all(|level| {
812 if level.is_empty() {
813 return false;
814 }
815 let first = level.as_bytes()[0];
816 (1..=63).contains(&level.len())
817 && (first.is_ascii_lowercase() || first.is_ascii_digit())
818 && level
819 .bytes()
820 .skip(1)
821 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
822 && !level.strip_prefix('v').is_some_and(|digits| {
823 !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit())
824 })
825 })
826}
827
828fn validate_events_value(value: Option<&Value>) -> Result<(), EventDeclarationError> {
829 let Some(value) = value.filter(|value| !value.is_null()) else {
830 return Ok(());
831 };
832 let entries = value
833 .as_array()
834 .ok_or_else(|| EventDeclarationError::new("events", "must be a list"))?;
835 if entries.len() > 64 {
836 return Err(EventDeclarationError::new(
837 "events",
838 "must contain at most 64 declarations",
839 ));
840 }
841 let mut pairs = HashSet::new();
842 for (index, entry) in entries.iter().enumerate() {
843 let field = format!("events[{index}]");
844 let entry = entry
845 .as_object()
846 .ok_or_else(|| EventDeclarationError::new(&field, "must be an object"))?;
847 let name_field = format!("{field}.name");
848 let name = entry
849 .get("name")
850 .and_then(Value::as_str)
851 .ok_or_else(|| EventDeclarationError::new(&name_field, "must be a string"))?;
852 if !is_valid_event_name(name) {
853 return Err(EventDeclarationError::new(
854 name_field,
855 "must contain one to four valid dot-separated event-name levels",
856 ));
857 }
858 let version = entry
859 .get("version")
860 .and_then(Value::as_u64)
861 .filter(|version| (1..=u32::MAX as u64).contains(version))
862 .ok_or_else(|| {
863 EventDeclarationError::new(
864 format!("{field}.version"),
865 "must be an integer between 1 and u32::MAX",
866 )
867 })?;
868 if !pairs.insert((name, version)) {
869 return Err(EventDeclarationError::new(
870 &field,
871 "duplicates an event (name, version) pair",
872 ));
873 }
874 let headers_field = format!("{field}.headers");
875 let headers = entry
876 .get("headers")
877 .and_then(Value::as_array)
878 .ok_or_else(|| EventDeclarationError::new(&headers_field, "must be a list"))?;
879 if headers.len() > 16 {
880 return Err(EventDeclarationError::new(
881 headers_field,
882 "must contain at most 16 headers",
883 ));
884 }
885 let mut names = HashSet::new();
886 for (header_index, header) in headers.iter().enumerate() {
887 let header_field = format!("{headers_field}[{header_index}]");
888 let header = header
889 .as_str()
890 .ok_or_else(|| EventDeclarationError::new(&header_field, "must be a string"))?;
891 if !(1..=32).contains(&header.len())
892 || !header.as_bytes()[0].is_ascii_lowercase()
893 || !header
894 .bytes()
895 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
896 {
897 return Err(EventDeclarationError::new(
898 header_field,
899 "must match [a-z][a-z0-9_]{0,31}",
900 ));
901 }
902 if !names.insert(header) {
903 return Err(EventDeclarationError::new(
904 header_field,
905 "duplicates a header name",
906 ));
907 }
908 }
909 if let Some(summary) = entry.get("summary").filter(|value| !value.is_null()) {
910 let summary_field = format!("{field}.summary");
911 let summary = summary
912 .as_str()
913 .ok_or_else(|| EventDeclarationError::new(&summary_field, "must be a string"))?;
914 if summary.chars().count() > 200 || summary.chars().any(char::is_control) {
915 return Err(EventDeclarationError::new(
916 summary_field,
917 "must contain at most 200 characters and no control characters",
918 ));
919 }
920 }
921 }
922 Ok(())
923}
924
925#[derive(Debug, Clone, PartialEq, Eq)]
927pub struct SelfSignalDeclarationError {
928 module_id: String,
929 entry_index: usize,
930 field: &'static str,
931}
932
933impl fmt::Display for SelfSignalDeclarationError {
934 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
935 write!(
936 f,
937 "module_id '{}' self_signals[{}] is missing required field '{}'",
938 self.module_id.escape_debug(),
939 self.entry_index,
940 self.field
941 )
942 }
943}
944
945pub fn validate_hello_self_signal_declarations(
952 hello: &Value,
953) -> Result<(), SelfSignalDeclarationError> {
954 let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
955 return Ok(());
956 };
957 let module_id = manifest
958 .get("module_id")
959 .and_then(Value::as_str)
960 .unwrap_or("<unknown>");
961 let Some(entries) = manifest.get("self_signals").and_then(Value::as_array) else {
962 return Ok(());
963 };
964
965 for (entry_index, entry) in entries.iter().enumerate() {
966 let Some(entry) = entry.as_object() else {
967 continue;
968 };
969 for field in ["effect", "anchored_to"] {
970 if !entry.contains_key(field) {
971 return Err(SelfSignalDeclarationError {
972 module_id: module_id.to_string(),
973 entry_index,
974 field,
975 });
976 }
977 }
978 }
979 Ok(())
980}
981
982#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
984#[serde(deny_unknown_fields)]
985pub struct CapabilityDeclarations {
986 #[serde(default)]
987 pub provides: Vec<String>,
988 #[serde(default)]
989 pub requires: Vec<CapabilityRequirement>,
990 #[serde(default)]
991 pub must_never_reach: Vec<String>,
992}
993
994#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
996pub struct SelfSignalDeclaration {
997 pub name: String,
999 pub kind: SelfSignalKind,
1027 pub effect: SelfSignalEffect,
1029 pub anchored_to: SignalAnchor,
1031 #[serde(default, skip_serializing_if = "Option::is_none")]
1038 pub cadence: Option<SignalCadence>,
1039 #[serde(default, skip_serializing_if = "Option::is_none")]
1041 pub domain: Option<String>,
1042 #[serde(default, skip_serializing_if = "Option::is_none")]
1043 pub note: Option<String>,
1044}
1045
1046#[derive(Debug, Clone, PartialEq, Eq)]
1048pub enum SelfSignalKind {
1049 Keepalive,
1050 Busy,
1052 Poller,
1053 Cron,
1054 Sweep,
1055 Watchdog,
1056 Heartbeat,
1057 Other(String),
1058}
1059
1060impl SelfSignalKind {
1061 fn wire_name(&self) -> &str {
1062 match self {
1063 Self::Keepalive => "keepalive",
1064 Self::Busy => "busy",
1065 Self::Poller => "poller",
1066 Self::Cron => "cron",
1067 Self::Sweep => "sweep",
1068 Self::Watchdog => "watchdog",
1069 Self::Heartbeat => "heartbeat",
1070 Self::Other(value) => value,
1071 }
1072 }
1073}
1074
1075impl Serialize for SelfSignalKind {
1076 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1077 where
1078 S: serde::Serializer,
1079 {
1080 serializer.serialize_str(self.wire_name())
1081 }
1082}
1083
1084impl<'de> Deserialize<'de> for SelfSignalKind {
1085 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1086 where
1087 D: Deserializer<'de>,
1088 {
1089 let value = String::deserialize(deserializer)?;
1090 Ok(match value.as_str() {
1091 "keepalive" => Self::Keepalive,
1092 "busy" => Self::Busy,
1093 "poller" => Self::Poller,
1094 "cron" => Self::Cron,
1095 "sweep" => Self::Sweep,
1096 "watchdog" => Self::Watchdog,
1097 "heartbeat" => Self::Heartbeat,
1098 _ => Self::Other(value),
1099 })
1100 }
1101}
1102
1103#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1105#[serde(rename_all = "lowercase")]
1106pub enum SelfSignalEffect {
1107 Observe,
1108 Mutate,
1109}
1110
1111#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1113#[serde(rename_all = "snake_case")]
1114pub enum SignalAnchor {
1115 FixedInterval,
1118 Event { event: String },
1121 HealthGauges { gauges: Vec<String> },
1123}
1124
1125#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1127#[serde(rename_all = "snake_case")]
1128pub enum SignalCadence {
1129 Literal { interval_ms: u64 },
1130 Derived { source: String },
1131}
1132
1133#[derive(Serialize, Debug, Clone, Default, PartialEq, Eq)]
1210#[non_exhaustive]
1211pub struct ManifestProvenance {
1212 #[serde(default, skip_serializing_if = "Option::is_none")]
1213 pub build_git_sha: Option<String>,
1214 #[serde(default, skip_serializing_if = "Option::is_none")]
1218 pub build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1219 #[serde(default, skip_serializing_if = "Option::is_none")]
1220 pub build_lock_digest: Option<String>,
1221 #[serde(default, skip_serializing_if = "Option::is_none")]
1230 pub wire_crate_version: Option<String>,
1231 #[serde(default, skip_serializing_if = "Option::is_none")]
1232 pub store_schema_version: Option<String>,
1233 #[serde(default, skip_serializing_if = "Option::is_none")]
1239 pub launch_nonce_source: Option<LaunchNonceSource>,
1240}
1241
1242#[derive(Debug, Clone, PartialEq, Eq)]
1249#[non_exhaustive]
1250pub enum LaunchNonceSource {
1251 Fd,
1253 Pipe,
1255 Env,
1257 ForwardCompatibleUnknown(String),
1258}
1259
1260impl LaunchNonceSource {
1261 pub fn wire_name(&self) -> &str {
1263 match self {
1264 Self::Fd => "fd",
1265 Self::Pipe => "pipe",
1266 Self::Env => "env",
1267 Self::ForwardCompatibleUnknown(value) => value,
1268 }
1269 }
1270
1271 pub fn from_wire_name(value: &str) -> Self {
1273 match value {
1274 "fd" => Self::Fd,
1275 "pipe" => Self::Pipe,
1276 "env" => Self::Env,
1277 _ => Self::ForwardCompatibleUnknown(value.to_string()),
1278 }
1279 }
1280}
1281
1282impl Serialize for LaunchNonceSource {
1283 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1284 where
1285 S: serde::Serializer,
1286 {
1287 serializer.serialize_str(self.wire_name())
1288 }
1289}
1290
1291impl<'de> Deserialize<'de> for LaunchNonceSource {
1292 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1293 where
1294 D: serde::Deserializer<'de>,
1295 {
1296 let value = String::deserialize(deserializer)?;
1297 Ok(Self::from_wire_name(&value))
1298 }
1299}
1300
1301#[derive(Debug, Clone, PartialEq, Eq)]
1306pub enum BuildGitShaAbsenceReason {
1307 DeclinedDirty,
1308 NeverDerived,
1309 NoGitDir,
1310 ForwardCompatibleUnknown(String),
1311}
1312
1313impl BuildGitShaAbsenceReason {
1314 fn wire_name(&self) -> &str {
1315 match self {
1316 Self::DeclinedDirty => "declined_dirty",
1317 Self::NeverDerived => "never_derived",
1318 Self::NoGitDir => "no_git_dir",
1319 Self::ForwardCompatibleUnknown(value) => value,
1320 }
1321 }
1322}
1323
1324impl Serialize for BuildGitShaAbsenceReason {
1325 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1326 where
1327 S: serde::Serializer,
1328 {
1329 serializer.serialize_str(self.wire_name())
1330 }
1331}
1332
1333impl<'de> Deserialize<'de> for BuildGitShaAbsenceReason {
1334 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1335 where
1336 D: serde::Deserializer<'de>,
1337 {
1338 let value = String::deserialize(deserializer)?;
1339 Ok(match value.as_str() {
1340 "declined_dirty" => Self::DeclinedDirty,
1341 "never_derived" => Self::NeverDerived,
1342 "no_git_dir" => Self::NoGitDir,
1343 _ => Self::ForwardCompatibleUnknown(value),
1344 })
1345 }
1346}
1347
1348#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1350pub enum GitTreeState {
1351 Clean,
1352 Dirty,
1353}
1354
1355#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1360pub enum BuildGitShaSource<'a> {
1361 Git {
1362 revision: &'a str,
1363 tree_state: GitTreeState,
1364 },
1365 NeverDerived,
1366 NoGitDir,
1367}
1368
1369pub fn attestable_commit(revision: &str, tree_state: GitTreeState) -> Option<&str> {
1373 match tree_state {
1374 GitTreeState::Clean => Some(revision),
1375 GitTreeState::Dirty => None,
1376 }
1377}
1378
1379const MAX_PROVENANCE_VALUE_BYTES: usize = 128;
1380const BUILD_GIT_SHA_CANONICAL_FORM: &str = "exactly 40 lowercase hexadecimal characters";
1381const BUILD_LOCK_DIGEST_CANONICAL_FORM: &str = "exactly 64 lowercase hexadecimal characters";
1382
1383#[derive(Deserialize)]
1384struct ManifestProvenanceWire {
1385 #[serde(default)]
1386 build_git_sha: Option<String>,
1387 #[serde(default)]
1388 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1389 #[serde(default)]
1390 build_lock_digest: Option<String>,
1391 #[serde(default)]
1392 wire_crate_version: Option<String>,
1393 #[serde(default)]
1394 store_schema_version: Option<String>,
1395 #[serde(default)]
1396 launch_nonce_source: Option<LaunchNonceSource>,
1397}
1398
1399impl<'de> Deserialize<'de> for ManifestProvenance {
1400 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1401 where
1402 D: Deserializer<'de>,
1403 {
1404 let wire = ManifestProvenanceWire::deserialize(deserializer)?;
1405 let provenance = Self {
1406 build_git_sha: wire.build_git_sha,
1407 build_git_sha_absence_reason: wire.build_git_sha_absence_reason,
1408 build_lock_digest: wire.build_lock_digest,
1409 wire_crate_version: wire.wire_crate_version,
1410 store_schema_version: wire.store_schema_version,
1411 launch_nonce_source: wire.launch_nonce_source,
1412 };
1413 provenance.validate().map_err(D::Error::custom)?;
1414 Ok(provenance)
1415 }
1416}
1417
1418#[derive(Debug, Clone, PartialEq, Eq)]
1420pub struct ProvenanceFormError {
1421 field: &'static str,
1422 length: usize,
1423 canonical_form: &'static str,
1424}
1425
1426impl ProvenanceFormError {
1427 fn new(field: &'static str, length: usize, canonical_form: &'static str) -> Self {
1428 Self {
1429 field,
1430 length,
1431 canonical_form,
1432 }
1433 }
1434
1435 pub fn field(&self) -> &str {
1437 self.field
1438 }
1439
1440 pub fn length(&self) -> usize {
1442 self.length
1443 }
1444
1445 pub fn canonical_form(&self) -> &str {
1447 self.canonical_form
1448 }
1449}
1450
1451impl fmt::Display for ProvenanceFormError {
1452 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1453 write!(
1454 f,
1455 "invalid manifest provenance form: field {} has length {}; canonical form is {}",
1456 self.field, self.length, self.canonical_form
1457 )
1458 }
1459}
1460
1461impl std::error::Error for ProvenanceFormError {}
1462
1463#[derive(Debug, Clone, PartialEq, Eq)]
1464pub struct ManifestProvenanceError {
1465 field: String,
1466 value: String,
1467 reason: &'static str,
1468}
1469
1470impl ManifestProvenanceError {
1471 fn new(field: &str, value: &str, reason: &'static str) -> Self {
1472 Self {
1473 field: field.to_string(),
1474 value: safe_error_value(value),
1475 reason,
1476 }
1477 }
1478
1479 pub fn field(&self) -> &str {
1480 &self.field
1481 }
1482}
1483
1484impl fmt::Display for ManifestProvenanceError {
1485 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1486 write!(
1487 f,
1488 "invalid manifest provenance: field {} has {} (value {:?})",
1489 self.field, self.reason, self.value
1490 )
1491 }
1492}
1493
1494impl std::error::Error for ManifestProvenanceError {}
1495
1496impl ManifestProvenance {
1497 pub fn new() -> Self {
1499 Self::default()
1500 }
1501
1502 pub fn with_build_git_sha(mut self, value: Option<String>) -> Self {
1503 self.build_git_sha = value;
1504 self
1505 }
1506
1507 pub fn with_build_git_sha_absence_reason(
1508 mut self,
1509 value: Option<BuildGitShaAbsenceReason>,
1510 ) -> Self {
1511 self.build_git_sha_absence_reason = value;
1512 self
1513 }
1514
1515 pub fn with_build_lock_digest(mut self, value: Option<String>) -> Self {
1516 self.build_lock_digest = value;
1517 self
1518 }
1519
1520 pub fn with_wire_crate_version(mut self, value: Option<String>) -> Self {
1521 self.wire_crate_version = value;
1522 self
1523 }
1524
1525 pub fn with_store_schema_version(mut self, value: Option<String>) -> Self {
1526 self.store_schema_version = value;
1527 self
1528 }
1529
1530 pub fn with_launch_nonce_source(mut self, value: Option<LaunchNonceSource>) -> Self {
1535 self.launch_nonce_source = value;
1536 self
1537 }
1538
1539 pub fn validate(&self) -> Result<(), ManifestProvenanceError> {
1540 if let (Some(_), Some(reason)) = (
1541 self.build_git_sha.as_ref(),
1542 self.build_git_sha_absence_reason.as_ref(),
1543 ) {
1544 return Err(ManifestProvenanceError::new(
1545 "build_git_sha_absence_reason",
1546 reason.wire_name(),
1547 "must be omitted when build_git_sha is present",
1548 ));
1549 }
1550 for (field, value) in [
1551 ("build_git_sha", self.build_git_sha.as_deref()),
1552 (
1553 "build_git_sha_absence_reason",
1554 self.build_git_sha_absence_reason
1555 .as_ref()
1556 .map(|reason| reason.wire_name()),
1557 ),
1558 ("build_lock_digest", self.build_lock_digest.as_deref()),
1559 ("wire_crate_version", self.wire_crate_version.as_deref()),
1560 ("store_schema_version", self.store_schema_version.as_deref()),
1561 (
1562 "launch_nonce_source",
1563 self.launch_nonce_source
1564 .as_ref()
1565 .map(|source| source.wire_name()),
1566 ),
1567 ] {
1568 let Some(value) = value else { continue };
1569 if value.is_empty() {
1570 return Err(ManifestProvenanceError::new(
1571 field,
1572 value,
1573 "must not be empty",
1574 ));
1575 }
1576 if value.len() > MAX_PROVENANCE_VALUE_BYTES {
1581 return Err(ManifestProvenanceError::new(
1582 field,
1583 value,
1584 "exceeds the 128-byte maximum",
1585 ));
1586 }
1587 if value.bytes().any(|byte| !(0x20..=0x7e).contains(&byte)) {
1588 return Err(ManifestProvenanceError::new(
1589 field,
1590 value,
1591 "contains non-printable ASCII",
1592 ));
1593 }
1594 }
1595 Ok(())
1596 }
1597}
1598
1599pub fn build_provenance(
1617 build_git_sha: Option<&str>,
1618 build_lock_digest: Option<&str>,
1619 store_schema_version: Option<&str>,
1620) -> Result<ManifestProvenance, ProvenanceFormError> {
1621 let build_git_sha = normalize_and_validate_build_git_sha(build_git_sha)?;
1622 build_provenance_with_build_git_sha(
1623 build_git_sha,
1624 None,
1625 build_lock_digest,
1626 store_schema_version,
1627 )
1628}
1629
1630pub fn build_provenance_from_source(
1646 build_git_sha_source: BuildGitShaSource<'_>,
1647 build_lock_digest: Option<&str>,
1648 store_schema_version: Option<&str>,
1649) -> Result<ManifestProvenance, ProvenanceFormError> {
1650 let (raw_build_git_sha, mut build_git_sha_absence_reason) = match build_git_sha_source {
1651 BuildGitShaSource::Git {
1652 revision,
1653 tree_state,
1654 } => match attestable_commit(revision, tree_state) {
1655 Some(revision) => (Some(revision), None),
1656 None => (None, Some(BuildGitShaAbsenceReason::DeclinedDirty)),
1657 },
1658 BuildGitShaSource::NeverDerived => (None, Some(BuildGitShaAbsenceReason::NeverDerived)),
1659 BuildGitShaSource::NoGitDir => (None, Some(BuildGitShaAbsenceReason::NoGitDir)),
1660 };
1661 let build_git_sha = normalize_and_validate_build_git_sha(raw_build_git_sha)?;
1662 if build_git_sha.is_none() {
1663 build_git_sha_absence_reason.get_or_insert(BuildGitShaAbsenceReason::NeverDerived);
1664 }
1665 build_provenance_with_build_git_sha(
1666 build_git_sha,
1667 build_git_sha_absence_reason,
1668 build_lock_digest,
1669 store_schema_version,
1670 )
1671}
1672
1673fn normalize_and_validate_build_git_sha(
1674 build_git_sha: Option<&str>,
1675) -> Result<Option<String>, ProvenanceFormError> {
1676 let build_git_sha = normalize_provenance_fact(build_git_sha);
1677 validate_provenance_form(
1678 "build_git_sha",
1679 build_git_sha.as_deref(),
1680 BUILD_GIT_SHA_CANONICAL_FORM,
1681 40,
1682 )?;
1683 Ok(build_git_sha)
1684}
1685
1686fn build_provenance_with_build_git_sha(
1687 build_git_sha: Option<String>,
1688 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1689 build_lock_digest: Option<&str>,
1690 store_schema_version: Option<&str>,
1691) -> Result<ManifestProvenance, ProvenanceFormError> {
1692 let build_lock_digest = normalize_provenance_fact(build_lock_digest);
1693 validate_provenance_form(
1694 "build_lock_digest",
1695 build_lock_digest.as_deref(),
1696 BUILD_LOCK_DIGEST_CANONICAL_FORM,
1697 64,
1698 )?;
1699
1700 Ok(ManifestProvenance {
1701 build_git_sha,
1702 build_git_sha_absence_reason,
1703 build_lock_digest,
1704 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
1705 store_schema_version: normalize_provenance_fact(store_schema_version),
1706 launch_nonce_source: None,
1707 })
1708}
1709
1710fn validate_provenance_form(
1711 field: &'static str,
1712 value: Option<&str>,
1713 canonical_form: &'static str,
1714 expected_length: usize,
1715) -> Result<(), ProvenanceFormError> {
1716 let Some(value) = value else { return Ok(()) };
1717 if value.len() != expected_length
1718 || !value
1719 .bytes()
1720 .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
1721 {
1722 return Err(ProvenanceFormError::new(field, value.len(), canonical_form));
1723 }
1724 Ok(())
1725}
1726
1727pub const PROVENANCE_SENTINELS: [&str; 3] = ["unknown", "unavailable", "none"];
1735
1736fn normalize_provenance_fact(value: Option<&str>) -> Option<String> {
1737 let value = value?.trim();
1738 if value.is_empty() {
1739 return None;
1740 }
1741 let lowered = value.to_ascii_lowercase();
1742 if PROVENANCE_SENTINELS.contains(&lowered.as_str()) {
1743 return None;
1744 }
1745 Some(value.to_string())
1746}
1747
1748#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1750#[serde(deny_unknown_fields)]
1751pub struct CapabilityRequirement {
1752 pub capability: String,
1753 pub need: CapabilityNeed,
1754}
1755
1756#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1758#[serde(rename_all = "snake_case")]
1759pub enum CapabilityNeed {
1760 Required,
1761 Optional,
1762}
1763
1764#[derive(Debug, Clone, PartialEq, Eq)]
1766pub struct CapabilityGrammarError {
1767 field: String,
1768 value: String,
1769}
1770
1771impl CapabilityGrammarError {
1772 fn new(field: impl Into<String>, value: impl AsRef<str>) -> Self {
1773 Self {
1774 field: field.into(),
1775 value: safe_error_value(value.as_ref()),
1776 }
1777 }
1778
1779 pub fn field(&self) -> &str {
1781 &self.field
1782 }
1783
1784 pub fn value(&self) -> &str {
1786 &self.value
1787 }
1788}
1789
1790impl fmt::Display for CapabilityGrammarError {
1791 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1792 write!(
1793 f,
1794 "invalid capability grammar: field {} has offending value {:?}",
1795 self.field, self.value
1796 )
1797 }
1798}
1799
1800impl std::error::Error for CapabilityGrammarError {}
1801
1802impl ModuleManifest {
1803 pub fn validate_capability_grammar(&self) -> Result<(), CapabilityGrammarError> {
1805 let Some(capabilities) = &self.capabilities else {
1806 return Ok(());
1807 };
1808
1809 validate_capability_list("capabilities.provides", &capabilities.provides)?;
1810 validate_requires(&capabilities.requires)?;
1811 validate_capability_list(
1812 "capabilities.must_never_reach",
1813 &capabilities.must_never_reach,
1814 )
1815 }
1816}
1817
1818pub fn validate_manifest_capability_grammar(
1823 manifest: &Value,
1824) -> Result<(), CapabilityGrammarError> {
1825 let Some(object) = manifest.as_object() else {
1826 return Ok(());
1827 };
1828
1829 validate_capabilities_value(object.get("capabilities"))?;
1830 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
1831}
1832
1833pub fn validate_hello_capability_grammar(hello: &Value) -> Result<(), CapabilityGrammarError> {
1839 let Some(object) = hello.as_object() else {
1840 return Ok(());
1841 };
1842 if let Some(manifest) = object.get("manifest") {
1843 validate_manifest_capability_grammar(manifest)?;
1844 }
1845 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
1846}
1847
1848pub fn is_valid_capability_identifier(identifier: &str) -> bool {
1850 if identifier.chars().any(char::is_whitespace) {
1851 return false;
1852 }
1853 let Some((name, version)) = identifier.split_once("/v") else {
1854 return false;
1855 };
1856 if name.is_empty() || name.len() > 64 || version.is_empty() {
1857 return false;
1858 }
1859
1860 let name_bytes = name.as_bytes();
1861 if !name_bytes[0].is_ascii_lowercase()
1862 || (name.len() > 1
1863 && !name_bytes[name.len() - 1].is_ascii_lowercase()
1864 && !name_bytes[name.len() - 1].is_ascii_digit())
1865 || name_bytes.windows(2).any(|pair| pair == b"--")
1866 {
1867 return false;
1868 }
1869 if !name_bytes
1870 .iter()
1871 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-')
1872 {
1873 return false;
1874 }
1875
1876 if version.len() > 1 && version.starts_with('0')
1877 || !version.bytes().all(|byte| byte.is_ascii_digit())
1878 {
1879 return false;
1880 }
1881 matches!(
1882 version.parse::<u64>(),
1883 Ok(value) if (1..=u64::from(u32::MAX)).contains(&value)
1884 )
1885}
1886
1887fn validate_capabilities_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
1888 let Some(value) = value else {
1889 return Ok(());
1890 };
1891 let Some(object) = value.as_object() else {
1892 return Err(CapabilityGrammarError::new(
1893 "capabilities",
1894 value_description(value),
1895 ));
1896 };
1897
1898 for (key, value) in object {
1899 if !matches!(key.as_str(), "provides" | "requires" | "must_never_reach") {
1900 return Err(CapabilityGrammarError::new(
1901 field_child("capabilities", key),
1902 value_description(value),
1903 ));
1904 }
1905 }
1906
1907 validate_capability_list_value("capabilities.provides", object.get("provides"))?;
1908 validate_requires_value(object.get("requires"))?;
1909 validate_capability_list_value(
1910 "capabilities.must_never_reach",
1911 object.get("must_never_reach"),
1912 )
1913}
1914
1915fn validate_capability_list_value(
1916 field: &str,
1917 value: Option<&Value>,
1918) -> Result<(), CapabilityGrammarError> {
1919 let Some(value) = value else {
1920 return Ok(());
1921 };
1922 let Some(values) = value.as_array() else {
1923 return Err(CapabilityGrammarError::new(field, value_description(value)));
1924 };
1925
1926 let mut seen = HashSet::new();
1927 for (index, value) in values.iter().enumerate() {
1928 let field = format!("{field}[{index}]");
1929 let Some(identifier) = value.as_str() else {
1930 return Err(CapabilityGrammarError::new(field, value_description(value)));
1931 };
1932 validate_capability_identifier(&field, identifier)?;
1933 if !seen.insert(identifier) {
1934 return Err(CapabilityGrammarError::new(field, identifier));
1935 }
1936 }
1937 Ok(())
1938}
1939
1940fn validate_requires_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
1941 let Some(value) = value else {
1942 return Ok(());
1943 };
1944 let Some(values) = value.as_array() else {
1945 return Err(CapabilityGrammarError::new(
1946 "capabilities.requires",
1947 value_description(value),
1948 ));
1949 };
1950
1951 let mut seen = HashSet::new();
1952 for (index, value) in values.iter().enumerate() {
1953 let entry_field = format!("capabilities.requires[{index}]");
1954 let Some(object) = value.as_object() else {
1955 return Err(CapabilityGrammarError::new(
1956 entry_field,
1957 value_description(value),
1958 ));
1959 };
1960 for (key, value) in object {
1961 if !matches!(key.as_str(), "capability" | "need") {
1962 return Err(CapabilityGrammarError::new(
1963 field_child(&entry_field, key),
1964 value_description(value),
1965 ));
1966 }
1967 }
1968 let capability_field = format!("{entry_field}.capability");
1969 let Some(capability) = object.get("capability").and_then(Value::as_str) else {
1970 return Err(CapabilityGrammarError::new(
1971 capability_field,
1972 object
1973 .get("capability")
1974 .map_or("<missing>".to_string(), value_description),
1975 ));
1976 };
1977 validate_capability_identifier(&capability_field, capability)?;
1978
1979 let need_field = format!("{entry_field}.need");
1980 let Some(need) = object.get("need").and_then(Value::as_str) else {
1981 return Err(CapabilityGrammarError::new(
1982 need_field,
1983 object
1984 .get("need")
1985 .map_or("<missing>".to_string(), value_description),
1986 ));
1987 };
1988 if !matches!(need, "required" | "optional") {
1989 return Err(CapabilityGrammarError::new(need_field, need));
1990 }
1991 if !seen.insert(capability) {
1992 return Err(CapabilityGrammarError::new(entry_field, capability));
1993 }
1994 }
1995 Ok(())
1996}
1997
1998fn validate_capability_list(field: &str, values: &[String]) -> Result<(), CapabilityGrammarError> {
1999 let mut seen = HashSet::new();
2000 for (index, identifier) in values.iter().enumerate() {
2001 let field = format!("{field}[{index}]");
2002 validate_capability_identifier(&field, identifier)?;
2003 if !seen.insert(identifier) {
2004 return Err(CapabilityGrammarError::new(field, identifier));
2005 }
2006 }
2007 Ok(())
2008}
2009
2010fn validate_requires(values: &[CapabilityRequirement]) -> Result<(), CapabilityGrammarError> {
2011 let mut seen = HashSet::new();
2012 for (index, requirement) in values.iter().enumerate() {
2013 let field = format!("capabilities.requires[{index}].capability");
2014 validate_capability_identifier(&field, &requirement.capability)?;
2015 if !seen.insert(&requirement.capability) {
2016 return Err(CapabilityGrammarError::new(
2017 format!("capabilities.requires[{index}]"),
2018 &requirement.capability,
2019 ));
2020 }
2021 }
2022 Ok(())
2023}
2024
2025fn validate_capability_identifier(
2026 field: &str,
2027 identifier: &str,
2028) -> Result<(), CapabilityGrammarError> {
2029 if is_valid_capability_identifier(identifier) {
2030 Ok(())
2031 } else {
2032 Err(CapabilityGrammarError::new(field, identifier))
2033 }
2034}
2035
2036fn validate_runtime_computed(
2037 value: Option<&Value>,
2038 field: &str,
2039) -> Result<(), CapabilityGrammarError> {
2040 let Some(value) = value else {
2041 return Ok(());
2042 };
2043 let Some(pointers) = value.as_array() else {
2044 return Err(CapabilityGrammarError::new(field, value_description(value)));
2045 };
2046
2047 for (index, pointer) in pointers.iter().enumerate() {
2048 let field = format!("{field}[{index}]");
2049 let Some(pointer) = pointer.as_str() else {
2050 return Err(CapabilityGrammarError::new(
2051 field,
2052 value_description(pointer),
2053 ));
2054 };
2055 let Some(tokens) = parse_json_pointer(pointer) else {
2056 return Err(CapabilityGrammarError::new(field, pointer));
2057 };
2058 if tokens.first().is_some_and(|token| token == "capabilities") {
2059 return Err(CapabilityGrammarError::new(field, pointer));
2060 }
2061 }
2062 Ok(())
2063}
2064
2065fn parse_json_pointer(pointer: &str) -> Option<Vec<String>> {
2066 if pointer.is_empty() {
2067 return Some(Vec::new());
2068 }
2069 let raw_tokens = pointer.strip_prefix('/')?;
2070 raw_tokens
2071 .split('/')
2072 .map(unescape_json_pointer_token)
2073 .collect()
2074}
2075
2076fn unescape_json_pointer_token(token: &str) -> Option<String> {
2077 let mut output = String::with_capacity(token.len());
2078 let mut characters = token.chars();
2079 while let Some(character) = characters.next() {
2080 if character != '~' {
2081 output.push(character);
2082 continue;
2083 }
2084 match characters.next()? {
2085 '0' => output.push('~'),
2086 '1' => output.push('/'),
2087 _ => return None,
2088 }
2089 }
2090 Some(output)
2091}
2092
2093fn field_child(parent: &str, child: &str) -> String {
2094 let child = safe_error_value(child);
2095 format!("{parent}.{child}")
2096}
2097
2098fn value_description(value: &Value) -> String {
2099 match value {
2100 Value::String(value) => safe_error_value(value),
2101 Value::Null => "null".to_string(),
2102 Value::Bool(value) => value.to_string(),
2103 Value::Number(value) => value.to_string(),
2104 Value::Array(_) => "<array>".to_string(),
2105 Value::Object(_) => "<object>".to_string(),
2106 }
2107}
2108
2109fn safe_error_value(value: &str) -> String {
2110 let lower = value.to_ascii_lowercase();
2111 if ["secret", "password", "api_key"]
2112 .iter()
2113 .any(|marker| lower.contains(marker))
2114 || lower.starts_with("sk-")
2115 || lower.starts_with("akia")
2116 || lower.starts_with("bearer ")
2117 || lower.starts_with("token=")
2118 || lower.starts_with("credential=")
2119 {
2120 "<redacted>".to_string()
2121 } else {
2122 value.to_string()
2123 }
2124}
2125
2126#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2132#[serde(rename_all = "snake_case")]
2133pub enum TrustTier {
2134 FirstParty,
2135 Reviewed,
2136 Untrusted,
2137}
2138
2139#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2143#[serde(tag = "role", rename_all = "snake_case")]
2144pub enum ProviderRole {
2145 ToolProvider {
2146 tools: Vec<Tool>,
2147 identity_scope: Vec<IdentityScope>,
2155 concurrency: Concurrency,
2156 emits_push: bool,
2157 sub_supervises: bool,
2158 },
2159 PipelineStage {
2160 stage: PipelineStageKind,
2161 applies_to: PipelineAppliesTo,
2162 interface: String,
2163 declares_frozen_floor: bool,
2164 needs_signals: Vec<String>,
2165 conformance_class: String,
2166 },
2167 ManagementSurface {
2168 operations: Vec<ManagementOperation>,
2169 config_schema: Value,
2170 observability: Vec<ObservabilitySurface>,
2171 identity_scope: Vec<IdentityScope>,
2175 #[serde(default)]
2176 concurrency: Concurrency,
2177 },
2178 InternalService {
2179 service_id: String,
2180 transport: InternalTransport,
2181 agent_facing: bool,
2182 operations: Vec<String>,
2183 },
2184}
2185
2186#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2199#[serde(rename_all = "snake_case")]
2200pub enum ExecutionMode {
2201 Pure,
2202 Mutating,
2203 Unfenceable,
2204}
2205
2206#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2208pub struct Tool {
2209 pub name: String,
2210 #[serde(default, skip_serializing_if = "Option::is_none")]
2211 pub description: Option<String>,
2212 pub execution_mode: ExecutionMode,
2217 pub schema: Value,
2218}
2219
2220#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2226#[serde(rename_all = "snake_case")]
2227pub enum Concurrency {
2228 Serial,
2230 ModuleManaged,
2233 StatelessParallel,
2236}
2237
2238#[allow(clippy::derivable_impls)]
2239impl Default for Concurrency {
2250 fn default() -> Self {
2251 Self::ModuleManaged
2252 }
2253}
2254
2255#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2262#[serde(rename_all = "snake_case")]
2263pub enum IdentityScope {
2264 Session,
2265 Project,
2266}
2267
2268#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2270#[serde(rename_all = "snake_case")]
2271pub enum PipelineStageKind {
2272 Transform,
2273 Codec,
2274 Auth,
2275}
2276
2277#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2279pub struct PipelineAppliesTo {
2280 pub provider: String,
2281 pub model: String,
2282}
2283
2284#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2287#[non_exhaustive]
2288pub struct OperationPayload {
2289 max_bytes: usize,
2290}
2291
2292impl OperationPayload {
2293 pub fn new(max_bytes: usize) -> Self {
2294 Self { max_bytes }
2295 }
2296
2297 pub fn max_bytes(&self) -> usize {
2298 self.max_bytes
2299 }
2300}
2301
2302#[derive(Debug, Clone, PartialEq, Eq)]
2304#[non_exhaustive]
2305pub enum OperationPayloadError {
2306 UnknownOperation { operation: String },
2307 WatchOperation { operation: String },
2308 InvalidMaxBytes { operation: String },
2309}
2310
2311impl fmt::Display for OperationPayloadError {
2312 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2313 write!(f, "{self:?}")
2314 }
2315}
2316
2317impl std::error::Error for OperationPayloadError {}
2318
2319impl ModuleManifest {
2320 pub fn validate_operation_payload(&self) -> Result<(), OperationPayloadError> {
2323 for (name, payload) in &self.operation_payload {
2324 if !self.provides.iter().any(|role| match role {
2325 ProviderRole::ManagementSurface { operations, .. } => {
2326 operations.iter().any(|op| op.name == *name)
2327 }
2328 _ => false,
2329 }) {
2330 return Err(OperationPayloadError::UnknownOperation {
2331 operation: name.clone(),
2332 });
2333 }
2334 if self
2335 .operation_delivery
2336 .get(name)
2337 .is_some_and(OperationDelivery::is_watch)
2338 {
2339 return Err(OperationPayloadError::WatchOperation {
2340 operation: name.clone(),
2341 });
2342 }
2343 if !(1..=crate::framed_body::MAX_DECLARED_PAYLOAD_BYTES).contains(&payload.max_bytes) {
2344 return Err(OperationPayloadError::InvalidMaxBytes {
2345 operation: name.clone(),
2346 });
2347 }
2348 }
2349 Ok(())
2350 }
2351}
2352
2353#[derive(Debug, Clone, PartialEq, Eq)]
2358#[non_exhaustive]
2359pub enum FlowOperationsError {
2360 FlowScopesNotDeclared,
2363 NotAList,
2365 TooMany { count: usize },
2367 DuplicateOperation { operation: String },
2369 UnknownOperation { operation: String },
2371}
2372
2373impl fmt::Display for FlowOperationsError {
2374 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2375 match self {
2376 Self::FlowScopesNotDeclared => write!(
2377 f,
2378 "flow_operations requires '{}' or '{}' in capabilities.provides",
2379 crate::scope::FLOW_SCOPES_CAPABILITY,
2380 crate::call_mode::CALL_MODES_CAPABILITY
2381 ),
2382 Self::NotAList => f.write_str("flow_operations must be an array of operation names"),
2383 Self::TooMany { count } => write!(
2384 f,
2385 "flow_operations lists {count} names, more than {MAX_FLOW_OPERATIONS}"
2386 ),
2387 Self::DuplicateOperation { operation } => {
2388 write!(f, "flow_operations names '{operation}' more than once")
2389 }
2390 Self::UnknownOperation { operation } => write!(
2391 f,
2392 "flow_operations names '{operation}', which is not a declared management operation"
2393 ),
2394 }
2395 }
2396}
2397
2398impl std::error::Error for FlowOperationsError {}
2399
2400impl ModuleManifest {
2401 pub fn validate_flow_operations(&self) -> Result<(), FlowOperationsError> {
2406 match &self.flow_operations {
2407 Some(operations) => check_flow_operations(self, operations),
2408 None => Ok(()),
2409 }
2410 }
2411}
2412
2413fn check_flow_operations(
2414 manifest: &ModuleManifest,
2415 operations: &[String],
2416) -> Result<(), FlowOperationsError> {
2417 let admits_flows = manifest.capabilities.as_ref().is_some_and(|capabilities| {
2418 capabilities.provides.iter().any(|capability| {
2419 capability == crate::scope::FLOW_SCOPES_CAPABILITY
2420 || capability == crate::call_mode::CALL_MODES_CAPABILITY
2421 })
2422 });
2423 if !admits_flows {
2424 return Err(FlowOperationsError::FlowScopesNotDeclared);
2425 }
2426 if operations.len() > MAX_FLOW_OPERATIONS {
2427 return Err(FlowOperationsError::TooMany {
2428 count: operations.len(),
2429 });
2430 }
2431 let mut seen = HashSet::new();
2432 for operation in operations {
2433 if !seen.insert(operation.as_str()) {
2434 return Err(FlowOperationsError::DuplicateOperation {
2435 operation: operation.clone(),
2436 });
2437 }
2438 let declared = manifest.provides.iter().any(|role| match role {
2439 ProviderRole::ManagementSurface { operations, .. } => {
2440 operations.iter().any(|op| op.name == *operation)
2441 }
2442 _ => false,
2443 });
2444 if !declared {
2445 return Err(FlowOperationsError::UnknownOperation {
2446 operation: operation.clone(),
2447 });
2448 }
2449 }
2450 Ok(())
2451}
2452
2453fn decode_flow_operations(
2456 manifest: &ModuleManifest,
2457 value: &Value,
2458) -> Result<Vec<String>, FlowOperationsError> {
2459 let operations: Vec<String> =
2460 serde_json::from_value(value.clone()).map_err(|_| FlowOperationsError::NotAList)?;
2461 check_flow_operations(manifest, &operations)?;
2462 Ok(operations)
2463}
2464
2465pub fn validate_hello_flow_operations(hello: &Value) -> Result<(), FlowOperationsError> {
2471 let Some(manifest_value) = hello.get("manifest") else {
2472 return Ok(());
2473 };
2474 let Some(value) = manifest_value
2475 .get("flow_operations")
2476 .filter(|value| !value.is_null())
2477 else {
2478 return Ok(());
2479 };
2480 let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
2481 return Ok(());
2482 };
2483 decode_flow_operations(&manifest, value).map(|_| ())
2484}
2485
2486#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2491pub struct ManagementOperation {
2492 pub name: String,
2493 pub kind: ManagementOperationKind,
2494 #[serde(default, skip_serializing_if = "Option::is_none")]
2495 pub description: Option<String>,
2496}
2497
2498#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2499#[serde(rename_all = "snake_case")]
2500pub enum ManagementOperationKind {
2501 Query,
2502 Mutate,
2503}
2504
2505#[derive(Debug, Clone, PartialEq, Eq)]
2508#[non_exhaustive]
2509pub enum OperationDelivery {
2510 Watch,
2511 Other(String),
2512}
2513
2514impl OperationDelivery {
2515 pub const WATCH: Self = Self::Watch;
2517
2518 pub fn wire_name(&self) -> &str {
2520 match self {
2521 Self::Watch => "watch",
2522 Self::Other(value) => value,
2523 }
2524 }
2525
2526 pub fn is_watch(&self) -> bool {
2528 self.wire_name() == "watch"
2529 }
2530}
2531
2532impl Serialize for OperationDelivery {
2533 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2534 where
2535 S: serde::Serializer,
2536 {
2537 serializer.serialize_str(self.wire_name())
2538 }
2539}
2540
2541impl<'de> Deserialize<'de> for OperationDelivery {
2542 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2543 where
2544 D: Deserializer<'de>,
2545 {
2546 let value = String::deserialize(deserializer)?;
2547 Ok(if value == "watch" {
2548 Self::WATCH
2549 } else {
2550 Self::Other(value)
2551 })
2552 }
2553}
2554
2555#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2557pub struct ObservabilitySurface {
2558 pub name: String,
2559 pub kind: ObservabilityKind,
2560}
2561
2562#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2563#[serde(rename_all = "snake_case")]
2564pub enum ObservabilityKind {
2565 Snapshot,
2566 Stream,
2567}
2568
2569#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2570#[serde(rename_all = "snake_case")]
2571pub enum InternalTransport {
2572 Bulk,
2573}
2574
2575#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2577#[serde(tag = "role", rename_all = "snake_case")]
2578pub enum ConsumerRole {
2579 ToolClient { of: Vec<String> },
2580 LlmClient { via: String, auth: String },
2581 ServiceClient { of: Vec<String> },
2582}
2583
2584#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2586pub struct Bindings {
2587 pub storage: StorageBinding,
2588 pub vault_grants: Vec<VaultGrant>,
2589 pub identity: IdentityBinding,
2590}
2591
2592#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2594pub struct StorageBinding {
2595 pub kind: StorageKind,
2596 pub scope: StorageScope,
2597 pub owns_schema: bool,
2598}
2599
2600#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2601#[serde(rename_all = "snake_case")]
2602pub enum StorageKind {
2603 Sqlite,
2604}
2605
2606#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2607#[serde(rename_all = "snake_case")]
2608pub enum StorageScope {
2609 Project,
2610}
2611
2612#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2613pub struct VaultGrant {
2614 pub secret: String,
2615 pub reason: String,
2616}
2617
2618#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2619pub struct IdentityBinding {
2620 pub requires: Vec<IdentityScope>,
2621 pub optional: Vec<IdentityScope>,
2622}
2623
2624#[cfg(test)]
2625mod tests {
2626 use super::*;
2627 use serde_json::json;
2628
2629 fn aft_manifest_fixture() -> ModuleManifest {
2630 ModuleManifest::builder("aft", "0.39.2")
2631 .trust_tier(Some(TrustTier::FirstParty))
2632 .bindings(Some(Bindings {
2633 storage: StorageBinding {
2634 kind: StorageKind::Sqlite,
2635 scope: StorageScope::Project,
2636 owns_schema: true,
2637 },
2638 vault_grants: vec![VaultGrant {
2639 secret: "provider_api_key".to_string(),
2640 reason: "cortexkit_native auth".to_string(),
2641 }],
2642 identity: IdentityBinding {
2643 requires: vec![IdentityScope::Project],
2644 optional: vec![IdentityScope::Session],
2645 },
2646 }))
2647 .protocol_ver(1)
2648 .provides(vec![ProviderRole::ToolProvider {
2649 tools: vec![
2650 Tool {
2651 name: "read".to_string(),
2652 description: None,
2653 execution_mode: ExecutionMode::Pure,
2654 schema: json!({"type": "object"}),
2655 },
2656 Tool {
2657 name: "grep".to_string(),
2658 description: None,
2659 execution_mode: ExecutionMode::Pure,
2660 schema: json!({"type": "object"}),
2661 },
2662 Tool {
2663 name: "outline".to_string(),
2664 description: None,
2665 execution_mode: ExecutionMode::Pure,
2666 schema: json!({"type": "object"}),
2667 },
2668 Tool {
2669 name: "semantic_search".to_string(),
2670 description: None,
2671 execution_mode: ExecutionMode::Pure,
2672 schema: json!({"type": "object"}),
2673 },
2674 Tool {
2675 name: "edit".to_string(),
2676 description: None,
2677 execution_mode: ExecutionMode::Mutating,
2678 schema: json!({"type": "object"}),
2679 },
2680 Tool {
2681 name: "write".to_string(),
2682 description: None,
2683 execution_mode: ExecutionMode::Mutating,
2684 schema: json!({"type": "object"}),
2685 },
2686 Tool {
2687 name: "bash".to_string(),
2688 description: None,
2689 execution_mode: ExecutionMode::Unfenceable,
2690 schema: json!({"type": "object"}),
2691 },
2692 ],
2693 identity_scope: vec![IdentityScope::Session, IdentityScope::Project],
2694 concurrency: Concurrency::ModuleManaged,
2695 emits_push: true,
2696 sub_supervises: true,
2697 }])
2698 .consumes(vec![ConsumerRole::ServiceClient {
2699 of: vec!["embedding.v2".to_string()],
2700 }])
2701 .build()
2702 }
2703
2704 #[test]
2705 fn serde_round_trips_representative_manifest() {
2706 let manifest = aft_manifest_fixture();
2707 let serialized = serde_json::to_string_pretty(&manifest).unwrap();
2708 let decoded: ModuleManifest = serde_json::from_str(&serialized).unwrap();
2709
2710 assert_eq!(manifest, decoded);
2711 }
2712
2713 #[test]
2714 fn builder_defaults_additions_to_honest_absence_and_round_trips() {
2715 let manifest = ModuleManifest::builder("builder-defaults", "2.0.0").build();
2716
2717 assert_eq!(manifest.module_id, "builder-defaults");
2718 assert_eq!(manifest.module_version, "2.0.0");
2719 assert_eq!(manifest.protocol_ver, PROTOCOL_VERSION);
2720 assert_eq!(manifest.trust_tier, None);
2721 assert!(manifest.provides.is_empty());
2722 assert!(manifest.consumes.is_empty());
2723 assert_eq!(manifest.bindings, None);
2724 assert_eq!(manifest.capabilities, None);
2725 assert_eq!(manifest.self_signals, None);
2726 assert_eq!(manifest.provenance, None);
2727
2728 let encoded = serde_json::to_value(&manifest).expect("builder manifest serializes");
2729 for optional in [
2730 "trust_tier",
2731 "consumes",
2732 "bindings",
2733 "capabilities",
2734 "self_signals",
2735 "provenance",
2736 ] {
2737 assert!(
2738 encoded.get(optional).is_none(),
2739 "an absent {optional} declaration must stay absent on the wire"
2740 );
2741 }
2742 let decoded: ModuleManifest =
2743 serde_json::from_value(encoded).expect("builder manifest round-trips");
2744 assert_eq!(decoded, manifest);
2745 }
2746
2747 #[test]
2748 fn fully_populated_builder_manifest_matches_the_literal_wire_golden() {
2749 let manifest = ModuleManifest::builder("full-builder", "2.0.0")
2750 .trust_tier(Some(TrustTier::Reviewed))
2751 .bindings(Some(Bindings {
2752 storage: StorageBinding {
2753 kind: StorageKind::Sqlite,
2754 scope: StorageScope::Project,
2755 owns_schema: false,
2756 },
2757 vault_grants: Vec::new(),
2758 identity: IdentityBinding {
2759 requires: vec![IdentityScope::Project],
2760 optional: Vec::new(),
2761 },
2762 }))
2763 .provides(vec![ProviderRole::ToolProvider {
2764 tools: vec![Tool {
2765 name: "read".to_string(),
2766 description: None,
2767 execution_mode: ExecutionMode::Pure,
2768 schema: json!({"type": "object"}),
2769 }],
2770 identity_scope: vec![IdentityScope::Project],
2771 concurrency: Concurrency::Serial,
2772 emits_push: false,
2773 sub_supervises: false,
2774 }])
2775 .consumes(vec![ConsumerRole::ServiceClient {
2776 of: vec!["embedding.v2".to_string()],
2777 }])
2778 .capabilities(Some(CapabilityDeclarations {
2779 provides: vec!["embedding/v2".to_string()],
2780 requires: Vec::new(),
2781 must_never_reach: Vec::new(),
2782 }))
2783 .self_signals(Some(vec![SelfSignalDeclaration {
2784 name: "usage_poller".to_string(),
2785 kind: SelfSignalKind::Poller,
2786 effect: SelfSignalEffect::Observe,
2787 anchored_to: SignalAnchor::FixedInterval,
2788 cadence: Some(SignalCadence::Literal {
2789 interval_ms: 60_000,
2790 }),
2791 domain: Some("provider-usage".to_string()),
2792 note: None,
2793 }]))
2794 .provenance(Some(ManifestProvenance {
2795 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
2796 build_git_sha_absence_reason: None,
2797 build_lock_digest: Some(
2798 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
2799 ),
2800 wire_crate_version: Some("0.16.0".to_string()),
2801 store_schema_version: Some("42".to_string()),
2802 launch_nonce_source: None,
2803 }))
2804 .build();
2805
2806 assert_eq!(
2807 serde_json::to_vec(&manifest).expect("builder manifest serializes"),
2808 include_bytes!("../tests/golden/module_manifest_builder_full.json"),
2809 "the builder must preserve the prior fully populated literal wire bytes"
2810 );
2811 }
2812
2813 #[test]
2814 fn old_manifest_with_unread_fields_decodes_and_round_trips_verbatim() {
2815 let raw = include_bytes!("../tests/golden/module_manifest_builder_full.json");
2816 let decoded: ModuleManifest =
2817 serde_json::from_slice(raw).expect("old manifest with all unread fields decodes");
2818
2819 assert_eq!(decoded.trust_tier, Some(TrustTier::Reviewed));
2820 assert!(!decoded.consumes.is_empty());
2821 assert!(decoded.bindings.is_some());
2822
2823 let reencoded = serde_json::to_vec(&decoded).expect("re-encode succeeds");
2824 assert_eq!(
2825 reencoded, raw,
2826 "old manifest relay stays byte-for-byte verbatim"
2827 );
2828 }
2829
2830 #[test]
2831 fn new_manifest_omits_unread_fields_on_wire_and_decodes_cleanly() {
2832 let raw = include_bytes!("../tests/golden/module_manifest_diet.json");
2833 let decoded: ModuleManifest =
2834 serde_json::from_slice(raw).expect("new manifest omitting unread fields decodes");
2835
2836 assert_eq!(decoded.trust_tier, None);
2837 assert!(decoded.consumes.is_empty());
2838 assert_eq!(decoded.bindings, None);
2839
2840 let pretty = format!("{}\n", serde_json::to_string_pretty(&decoded).unwrap());
2841 assert_eq!(
2842 pretty.as_bytes(),
2843 raw,
2844 "new manifest matches golden byte-for-byte without unread keys"
2845 );
2846
2847 let as_val: serde_json::Value = serde_json::to_value(&decoded).unwrap();
2848 assert!(
2849 as_val.get("trust_tier").is_none(),
2850 "no trust_tier on wire for new manifest"
2851 );
2852 assert!(
2853 as_val.get("consumes").is_none(),
2854 "no consumes on wire for empty consumes"
2855 );
2856 assert!(
2857 as_val.get("bindings").is_none(),
2858 "no bindings on wire for new manifest"
2859 );
2860 }
2861
2862 #[test]
2863 fn aft_manifest_fixture_matches_v1_contract() {
2864 let manifest = aft_manifest_fixture();
2865
2866 assert_eq!(manifest.module_id, "aft");
2867 let ProviderRole::ToolProvider {
2868 tools,
2869 identity_scope,
2870 concurrency,
2871 emits_push,
2872 sub_supervises,
2873 } = &manifest.provides[0]
2874 else {
2875 panic!("AFT fixture must expose one tool_provider role");
2876 };
2877
2878 assert_eq!(*concurrency, Concurrency::ModuleManaged);
2879 assert!(*emits_push);
2880 assert!(*sub_supervises);
2881 assert_eq!(
2882 identity_scope,
2883 &vec![IdentityScope::Session, IdentityScope::Project]
2884 );
2885 assert_eq!(
2886 tools
2887 .iter()
2888 .map(|tool| (tool.name.as_str(), tool.execution_mode))
2889 .collect::<Vec<_>>(),
2890 vec![
2891 ("read", ExecutionMode::Pure),
2892 ("grep", ExecutionMode::Pure),
2893 ("outline", ExecutionMode::Pure),
2894 ("semantic_search", ExecutionMode::Pure),
2895 ("edit", ExecutionMode::Mutating),
2896 ("write", ExecutionMode::Mutating),
2897 ("bash", ExecutionMode::Unfenceable),
2898 ]
2899 );
2900 }
2901
2902 #[test]
2903 fn tool_provider_role_tag_serializes_as_snake_case() {
2904 let manifest = aft_manifest_fixture();
2905 let value = serde_json::to_value(&manifest).unwrap();
2906
2907 assert_eq!(value["provides"][0]["role"], "tool_provider");
2908 }
2909
2910 #[test]
2911 fn manifest_without_capabilities_preserves_the_existing_wire_shape() {
2912 let manifest = aft_manifest_fixture();
2913 let encoded = serde_json::to_value(&manifest).expect("manifest serializes");
2914 assert!(encoded.get("capabilities").is_none());
2915
2916 let decoded: ModuleManifest =
2917 serde_json::from_value(encoded).expect("legacy manifest parses");
2918 assert_eq!(decoded.capabilities, None);
2919 }
2920
2921 #[test]
2922 fn capability_identifier_lexical_grammar_accepts_only_pinned_forms() {
2923 for identifier in [
2924 "a/v1",
2925 "credentials-provider/v1",
2926 "a1-b2/v4294967295",
2927 "a123456789012345678901234567890123456789012345678901234567890123/v1",
2928 ] {
2929 assert!(
2930 is_valid_capability_identifier(identifier),
2931 "identifier must be accepted: {identifier}"
2932 );
2933 }
2934
2935 for identifier in [
2936 "credentials-Provider/v1",
2937 "credentials-provider/v01",
2938 "credentials-provider-/v1",
2939 "credentials--provider/v1",
2940 "Credentials-provider/v1",
2941 "credentials-provider/1",
2942 "credentials provider/v1",
2943 "credentials-provider/v0",
2944 "credentials-provider/v4294967296",
2945 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/v1",
2946 ] {
2947 assert!(
2948 !is_valid_capability_identifier(identifier),
2949 "identifier must be rejected: {identifier}"
2950 );
2951 }
2952 }
2953
2954 #[test]
2955 fn capability_grammar_errors_redact_secret_shaped_values() {
2956 let error = validate_manifest_capability_grammar(&json!({
2957 "capabilities": { "provides": ["sk-secret-value/v0"] }
2958 }))
2959 .expect_err("secret-shaped capability identifier is malformed");
2960 assert_eq!(error.field(), "capabilities.provides[0]");
2961 assert_eq!(error.value(), "<redacted>");
2962 assert!(!error.to_string().contains("sk-secret-value"));
2963 }
2964
2965 #[test]
2972 fn provenance_builder_sentinels_become_field_omission() {
2973 for sentinel in [
2974 "unknown",
2975 "UNKNOWN",
2976 "Unknown",
2977 "unavailable",
2978 "none",
2979 "None",
2980 " unknown ",
2981 "",
2982 ] {
2983 let p = build_provenance_from_source(
2984 BuildGitShaSource::Git {
2985 revision: sentinel,
2986 tree_state: GitTreeState::Clean,
2987 },
2988 Some(sentinel),
2989 Some(sentinel),
2990 )
2991 .expect("sentinels are omitted before form validation");
2992 assert_eq!(
2993 (
2994 p.build_git_sha,
2995 p.build_git_sha_absence_reason,
2996 p.build_lock_digest,
2997 p.store_schema_version,
2998 ),
2999 (
3000 None,
3001 Some(BuildGitShaAbsenceReason::NeverDerived),
3002 None,
3003 None,
3004 ),
3005 "sentinel {sentinel:?} must be omitted, not published"
3006 );
3007 }
3008 let real = build_provenance_from_source(
3009 BuildGitShaSource::Git {
3010 revision: "0123456789abcdef0123456789abcdef01234567",
3011 tree_state: GitTreeState::Clean,
3012 },
3013 None,
3014 Some("9"),
3015 )
3016 .expect("canonical build revision is accepted");
3017 assert_eq!(
3018 real.build_git_sha.as_deref(),
3019 Some("0123456789abcdef0123456789abcdef01234567")
3020 );
3021 assert_eq!(real.store_schema_version.as_deref(), Some("9"));
3022 assert_eq!(
3026 real.wire_crate_version.as_deref(),
3027 Some(crate::SUBC_PROTOCOL_CRATE_VERSION)
3028 );
3029 }
3030
3031 #[test]
3032 fn build_provenance_accepts_canonical_sha_and_lock_digest() {
3033 let provenance = build_provenance_from_source(
3034 BuildGitShaSource::Git {
3035 revision: " 0123456789abcdef0123456789abcdef01234567 ",
3036 tree_state: GitTreeState::Clean,
3037 },
3038 Some(" abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789 "),
3039 Some(" schema-v3 "),
3040 )
3041 .expect("canonical build facts are accepted");
3042
3043 assert_eq!(
3044 provenance,
3045 ManifestProvenance {
3046 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
3047 build_git_sha_absence_reason: None,
3048 build_lock_digest: Some(
3049 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
3050 ),
3051 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
3052 store_schema_version: Some("schema-v3".to_string()),
3053 launch_nonce_source: None,
3054 }
3055 );
3056 }
3057
3058 #[test]
3059 fn build_provenance_refuses_an_abbreviated_git_sha() {
3060 let error = build_provenance_from_source(
3061 BuildGitShaSource::Git {
3062 revision: "0123456789ab",
3063 tree_state: GitTreeState::Clean,
3064 },
3065 None,
3066 None,
3067 )
3068 .expect_err("a 12-character abbreviation is not canonical");
3069
3070 assert_eq!(error.field(), "build_git_sha");
3071 assert_eq!(error.length(), 12);
3072 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3073 assert_eq!(
3074 error.to_string(),
3075 "invalid manifest provenance form: field build_git_sha has length 12; canonical form is exactly 40 lowercase hexadecimal characters"
3076 );
3077 }
3078
3079 #[test]
3080 fn build_provenance_refuses_an_abbreviated_lock_digest() {
3081 let error = build_provenance_from_source(
3082 BuildGitShaSource::NeverDerived,
3083 Some("0123456789abcdef"),
3084 None,
3085 )
3086 .expect_err("a 16-character digest is not canonical");
3087
3088 assert_eq!(error.field(), "build_lock_digest");
3089 assert_eq!(error.length(), 16);
3090 assert_eq!(error.canonical_form(), BUILD_LOCK_DIGEST_CANONICAL_FORM);
3091 }
3092
3093 #[test]
3094 fn build_provenance_refuses_uppercase_hex() {
3095 let uppercase_sha = "A".repeat(40);
3096 let error = build_provenance_from_source(
3097 BuildGitShaSource::Git {
3098 revision: &uppercase_sha,
3099 tree_state: GitTreeState::Clean,
3100 },
3101 None,
3102 None,
3103 )
3104 .expect_err("uppercase hexadecimal is not canonical");
3105
3106 assert_eq!(error.field(), "build_git_sha");
3107 assert_eq!(error.length(), 40);
3108 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3109 }
3110
3111 #[test]
3112 fn build_provenance_refuses_dirty_revision_stamp_claimed_clean() {
3113 let error = build_provenance_from_source(
3114 BuildGitShaSource::Git {
3115 revision: "0123456789abcdef0123456789abcdef01234567-dirty",
3116 tree_state: GitTreeState::Clean,
3117 },
3118 None,
3119 None,
3120 )
3121 .expect_err("a dirty stamp is not a canonical build revision");
3122
3123 assert_eq!(error.field(), "build_git_sha");
3124 assert_eq!(error.length(), 46);
3125 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3126 }
3127
3128 #[test]
3129 fn build_provenance_keeps_a_lock_digest_when_identity_is_unavailable() {
3130 let provenance = build_provenance_from_source(
3131 BuildGitShaSource::Git {
3132 revision: "unavailable",
3133 tree_state: GitTreeState::Clean,
3134 },
3135 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"),
3136 None,
3137 )
3138 .expect("sentinel SHA is omitted before the valid lock digest is checked");
3139
3140 assert_eq!(provenance.build_git_sha, None);
3141 assert_eq!(
3142 provenance.build_lock_digest,
3143 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string())
3144 );
3145 assert_eq!(
3146 provenance.wire_crate_version,
3147 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
3148 );
3149 }
3150
3151 #[test]
3152 fn build_provenance_omits_fully_unavailable_inputs() {
3153 let provenance = build_provenance_from_source(
3154 BuildGitShaSource::NeverDerived,
3155 Some(" unavailable "),
3156 Some(" "),
3157 )
3158 .expect("omitted and sentinel inputs are not form errors");
3159
3160 assert_eq!(provenance.build_git_sha, None);
3161 assert_eq!(provenance.build_lock_digest, None);
3162 assert_eq!(provenance.store_schema_version, None);
3163 assert_eq!(
3164 provenance.wire_crate_version,
3165 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
3166 );
3167 }
3168
3169 #[test]
3170 fn legacy_build_provenance_keeps_master_wire_bytes_without_an_absence_reason() {
3171 let revision = "0123456789abcdef0123456789abcdef01234567";
3172 for (input, expected) in [
3173 (
3174 Some(revision),
3175 format!(
3176 r#"{{"build_git_sha":"{revision}","wire_crate_version":"{}"}}"#,
3177 crate::SUBC_PROTOCOL_CRATE_VERSION
3178 ),
3179 ),
3180 (
3181 None,
3182 format!(
3183 r#"{{"wire_crate_version":"{}"}}"#,
3184 crate::SUBC_PROTOCOL_CRATE_VERSION
3185 ),
3186 ),
3187 (
3188 Some("unknown"),
3189 format!(
3190 r#"{{"wire_crate_version":"{}"}}"#,
3191 crate::SUBC_PROTOCOL_CRATE_VERSION
3192 ),
3193 ),
3194 ] {
3195 let provenance = build_provenance(input, None, None)
3196 .expect("the legacy build facts remain constructible");
3197 assert_eq!(provenance.build_git_sha_absence_reason, None);
3198 assert_eq!(
3199 serde_json::to_string(&provenance).expect("legacy provenance serializes"),
3200 expected
3201 );
3202 }
3203 }
3204
3205 #[test]
3206 fn build_provenance_derives_git_sha_absence_from_the_stamping_inputs() {
3207 let revision = "0123456789abcdef0123456789abcdef01234567";
3208 let cases = [
3209 (
3210 BuildGitShaSource::Git {
3211 revision,
3212 tree_state: GitTreeState::Clean,
3213 },
3214 Some(revision),
3215 None,
3216 ),
3217 (
3218 BuildGitShaSource::Git {
3219 revision,
3220 tree_state: GitTreeState::Dirty,
3221 },
3222 None,
3223 Some(BuildGitShaAbsenceReason::DeclinedDirty),
3224 ),
3225 (
3226 BuildGitShaSource::NeverDerived,
3227 None,
3228 Some(BuildGitShaAbsenceReason::NeverDerived),
3229 ),
3230 (
3231 BuildGitShaSource::NoGitDir,
3232 None,
3233 Some(BuildGitShaAbsenceReason::NoGitDir),
3234 ),
3235 ];
3236
3237 for (source, expected_sha, expected_reason) in cases {
3238 let provenance = build_provenance_from_source(source, None, None)
3239 .expect("every stamping state constructs honest provenance");
3240 assert_eq!(provenance.build_git_sha.as_deref(), expected_sha);
3241 assert_eq!(provenance.build_git_sha_absence_reason, expected_reason);
3242 }
3243 }
3244
3245 #[test]
3246 fn unknown_git_sha_absence_reason_round_trips_byte_faithfully() {
3247 let wire = format!(
3248 r#"{{"build_git_sha_absence_reason":"future_stamper_state","wire_crate_version":"{}"}}"#,
3249 crate::SUBC_PROTOCOL_CRATE_VERSION
3250 );
3251 let provenance: ManifestProvenance =
3252 serde_json::from_str(&wire).expect("future absence reasons remain readable");
3253
3254 assert_eq!(
3255 provenance.build_git_sha_absence_reason,
3256 Some(BuildGitShaAbsenceReason::ForwardCompatibleUnknown(
3257 "future_stamper_state".to_string()
3258 ))
3259 );
3260 assert_eq!(
3261 serde_json::to_string(&provenance).expect("future absence reason reserializes"),
3262 wire
3263 );
3264 }
3265
3266 #[test]
3267 fn provenance_rejects_an_absence_reason_beside_a_declared_commit() {
3268 let error = serde_json::from_value::<ManifestProvenance>(json!({
3269 "build_git_sha": "0123456789abcdef0123456789abcdef01234567",
3270 "build_git_sha_absence_reason": "declined_dirty"
3271 }))
3272 .expect_err("a declared commit cannot also claim an absence reason");
3273
3274 assert!(error.to_string().contains(
3275 "build_git_sha_absence_reason has must be omitted when build_git_sha is present"
3276 ));
3277 }
3278
3279 #[test]
3280 fn rich_ui_descriptor_is_optional_and_round_trips_when_present() {
3281 let manifest = ModuleManifest::builder("provider", "1.0.0").build();
3282 assert_eq!(
3283 serde_json::to_string(&manifest).unwrap(),
3284 r#"{"module_id":"provider","module_version":"1.0.0","protocol_ver":2,"provides":[]}"#
3285 );
3286
3287 let descriptor = RichUiDescriptor::new(
3288 "ckios.richui.manifest/1",
3289 format!("sha256:{}", "a".repeat(64)),
3290 128,
3291 2,
3292 );
3293 let manifest = ModuleManifest::builder("provider", "1.0.0")
3294 .rich_ui(Some(descriptor.clone()))
3295 .build();
3296 let wire = serde_json::to_string(&manifest).unwrap();
3297 assert!(wire.contains("\"rich_ui\":{\"schema\":\"ckios.richui.manifest/1\""));
3298 assert_eq!(
3299 serde_json::from_str::<ModuleManifest>(&wire)
3300 .unwrap()
3301 .rich_ui,
3302 Some(descriptor)
3303 );
3304 }
3305
3306 #[test]
3307 fn rich_ui_descriptor_validation_names_each_invalid_field() {
3308 let good = json!({
3309 "schema": "ckios.richui.manifest/1",
3310 "manifest_digest": format!("sha256:{}", "a".repeat(64)),
3311 "bytes": 1,
3312 "chunks": 1
3313 });
3314 let hello = json!({"manifest": {"rich_ui": good.clone()}});
3315 assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
3316
3317 for (field, value) in [
3318 ("schema", json!("bad schema")),
3319 (
3320 "manifest_digest",
3321 json!(format!("sha256:{}", "A".repeat(64))),
3322 ),
3323 ("bytes", json!(0)),
3324 ("chunks", json!(1025)),
3325 ] {
3326 let mut invalid = hello.clone();
3327 invalid["manifest"]["rich_ui"][field] = value;
3328 let error = validate_hello_rich_ui_descriptor(&invalid)
3329 .expect_err("an invalid descriptor field must be refused");
3330 assert_eq!(error.field(), format!("rich_ui.{field}"));
3331 }
3332
3333 let mut hello = hello;
3334 hello["manifest"]["rich_ui"] = Value::Null;
3335 let error = validate_hello_rich_ui_descriptor(&hello)
3336 .expect_err("null is not an absent descriptor");
3337 assert_eq!(error.field(), "rich_ui");
3338 }
3339
3340 #[test]
3341 fn rich_ui_descriptor_validation_accepts_inclusive_bounds() {
3342 let hello = json!({"manifest": {"rich_ui": {
3343 "schema": "a".repeat(64),
3344 "manifest_digest": format!("sha256:{}", "f".repeat(64)),
3345 "bytes": 16_777_216,
3346 "chunks": 1024
3347 }}});
3348 assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
3349 }
3350}