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
22#[derive(Serialize, Debug, Clone, PartialEq)]
29#[non_exhaustive]
30pub struct ModuleManifest {
31 pub module_id: String,
32 pub module_version: String,
33 pub protocol_ver: u8,
34 #[serde(default, skip_serializing_if = "Option::is_none")]
35 pub trust_tier: Option<TrustTier>,
36 #[serde(default, skip_serializing_if = "Option::is_none")]
43 pub ready: Option<bool>,
44 pub provides: Vec<ProviderRole>,
47 #[serde(default, skip_serializing_if = "Vec::is_empty")]
48 pub consumes: Vec<ConsumerRole>,
49 #[serde(default, skip_serializing_if = "Option::is_none")]
50 pub bindings: Option<Bindings>,
51 #[serde(default, skip_serializing_if = "Option::is_none")]
57 pub capabilities: Option<CapabilityDeclarations>,
58 #[serde(default, skip_serializing_if = "Option::is_none")]
72 pub events: Option<Vec<EventDeclaration>>,
73 #[serde(default, skip_serializing_if = "Option::is_none")]
108 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
109 #[serde(default, skip_serializing_if = "Option::is_none")]
110 pub provenance: Option<ManifestProvenance>,
111 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
116 pub operation_delivery: BTreeMap<String, OperationDelivery>,
117 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
120 pub operation_payload: BTreeMap<String, OperationPayload>,
121 #[serde(default, skip_serializing_if = "Option::is_none")]
126 pub rich_ui: Option<RichUiDescriptor>,
127 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
136 pub role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
137}
138
139#[derive(Debug, Clone)]
141pub struct ModuleManifestBuilder {
142 module_id: String,
143 module_version: String,
144 protocol_ver: u8,
145 trust_tier: Option<TrustTier>,
146 ready: Option<bool>,
147 provides: Vec<ProviderRole>,
148 consumes: Vec<ConsumerRole>,
149 bindings: Option<Bindings>,
150 capabilities: Option<CapabilityDeclarations>,
151 events: Option<Vec<EventDeclaration>>,
152 self_signals: Option<Vec<SelfSignalDeclaration>>,
153 provenance: Option<ManifestProvenance>,
154 operation_delivery: BTreeMap<String, OperationDelivery>,
155 operation_payload: BTreeMap<String, OperationPayload>,
156 rich_ui: Option<RichUiDescriptor>,
157 role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
158}
159
160impl ModuleManifest {
161 pub fn builder(
169 module_id: impl Into<String>,
170 module_version: impl Into<String>,
171 ) -> ModuleManifestBuilder {
172 ModuleManifestBuilder {
173 module_id: module_id.into(),
174 module_version: module_version.into(),
175 protocol_ver: PROTOCOL_VERSION,
176 trust_tier: None,
177 ready: None,
178 provides: Vec::new(),
179 consumes: Vec::new(),
180 bindings: None,
181 capabilities: None,
182 events: None,
183 self_signals: None,
184 provenance: None,
185 operation_delivery: BTreeMap::new(),
186 operation_payload: BTreeMap::new(),
187 rich_ui: None,
188 role_declarations: BTreeMap::new(),
189 }
190 }
191
192 pub fn is_watch_operation(&self, name: &str) -> bool {
197 self.operation_delivery
198 .get(name)
199 .is_some_and(OperationDelivery::is_watch)
200 && self.provides.iter().any(|role| match role {
201 ProviderRole::ManagementSurface { operations, .. } => operations
202 .iter()
203 .any(|op| op.name == name && op.kind == ManagementOperationKind::Query),
204 _ => false,
205 })
206 }
207}
208
209impl ModuleManifestBuilder {
210 pub fn protocol_ver(mut self, protocol_ver: u8) -> Self {
212 self.protocol_ver = protocol_ver;
213 self
214 }
215
216 pub fn trust_tier(mut self, trust_tier: Option<TrustTier>) -> Self {
220 self.trust_tier = trust_tier;
221 self
222 }
223
224 pub fn ready(mut self, ready: bool) -> Self {
226 self.ready = Some(ready);
227 self
228 }
229
230 pub fn provides(mut self, provides: Vec<ProviderRole>) -> Self {
232 self.provides = provides;
233 self
234 }
235
236 pub fn consumes(mut self, consumes: Vec<ConsumerRole>) -> Self {
238 self.consumes = consumes;
239 self
240 }
241
242 pub fn bindings(mut self, bindings: Option<Bindings>) -> Self {
246 self.bindings = bindings;
247 self
248 }
249
250 pub fn capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
252 self.capabilities = capabilities;
253 self
254 }
255
256 pub fn events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
258 self.events = events;
259 self
260 }
261
262 pub fn self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
264 self.self_signals = self_signals;
265 self
266 }
267
268 pub fn provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
270 self.provenance = provenance;
271 self
272 }
273
274 pub fn operation_delivery(
276 mut self,
277 operation_delivery: BTreeMap<String, OperationDelivery>,
278 ) -> Self {
279 self.operation_delivery = operation_delivery;
280 self
281 }
282
283 pub fn operation_payload(
285 mut self,
286 operation_payload: BTreeMap<String, OperationPayload>,
287 ) -> Self {
288 self.operation_payload = operation_payload;
289 self
290 }
291
292 pub fn rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
294 self.rich_ui = rich_ui;
295 self
296 }
297
298 pub fn role_declarations(
300 mut self,
301 role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
302 ) -> Self {
303 self.role_declarations = role_declarations;
304 self
305 }
306
307 pub fn build(self) -> ModuleManifest {
309 ModuleManifest {
310 module_id: self.module_id,
311 module_version: self.module_version,
312 protocol_ver: self.protocol_ver,
313 trust_tier: self.trust_tier,
314 ready: self.ready,
315 provides: self.provides,
316 consumes: self.consumes,
317 bindings: self.bindings,
318 capabilities: self.capabilities,
319 events: self.events,
320 self_signals: self.self_signals,
321 provenance: self.provenance,
322 operation_delivery: self.operation_delivery,
323 operation_payload: self.operation_payload,
324 rich_ui: self.rich_ui,
325 role_declarations: self.role_declarations,
326 }
327 }
328}
329
330#[derive(Deserialize)]
350struct ModuleManifestWire {
351 module_id: String,
352 module_version: String,
353 protocol_ver: u8,
354 #[serde(default)]
355 trust_tier: Option<TrustTier>,
356 #[serde(default)]
357 ready: Option<bool>,
358 provides: Vec<ProviderRole>,
359 #[serde(default)]
360 consumes: Vec<ConsumerRole>,
361 #[serde(default)]
362 bindings: Option<Bindings>,
363 #[serde(default)]
364 capabilities: Option<CapabilityDeclarations>,
365 #[serde(default)]
366 events: Option<Value>,
367 #[serde(default)]
368 self_signals: Option<Vec<SelfSignalDeclaration>>,
369 #[serde(default)]
370 provenance: Option<ManifestProvenance>,
371 #[serde(default)]
372 operation_delivery: Option<Value>,
373 #[serde(default)]
374 operation_payload: BTreeMap<String, OperationPayload>,
375 #[serde(default)]
376 rich_ui: Option<RichUiDescriptor>,
377 #[serde(default)]
381 runtime_computed: Option<Value>,
382 #[serde(default)]
383 role_declarations: Option<Value>,
384}
385
386impl<'de> Deserialize<'de> for ModuleManifest {
387 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
388 where
389 D: Deserializer<'de>,
390 {
391 let wire = ModuleManifestWire::deserialize(deserializer)?;
392 validate_runtime_computed(wire.runtime_computed.as_ref(), "runtime_computed")
393 .map_err(D::Error::custom)?;
394 validate_events_value(wire.events.as_ref()).map_err(D::Error::custom)?;
395 let events = wire
396 .events
397 .map(serde_json::from_value)
398 .transpose()
399 .map_err(D::Error::custom)?;
400 let mut builder = Self::builder(wire.module_id, wire.module_version)
401 .protocol_ver(wire.protocol_ver)
402 .trust_tier(wire.trust_tier);
403 if let Some(ready) = wire.ready {
404 builder = builder.ready(ready);
405 }
406 let manifest = builder
407 .provides(wire.provides)
408 .consumes(wire.consumes)
409 .bindings(wire.bindings)
410 .capabilities(wire.capabilities)
411 .events(events)
412 .self_signals(wire.self_signals)
413 .provenance(wire.provenance)
414 .operation_delivery(
415 wire.operation_delivery
416 .and_then(|value| serde_json::from_value(value).ok())
417 .unwrap_or_default(),
418 )
419 .rich_ui(wire.rich_ui)
420 .role_declarations(
421 wire.role_declarations
422 .filter(|value| validate_role_declarations_value(Some(value)).is_ok())
423 .and_then(|value| serde_json::from_value(value).ok())
424 .unwrap_or_default(),
425 )
426 .operation_payload(wire.operation_payload)
427 .build();
428 manifest
429 .validate_operation_payload()
430 .map_err(D::Error::custom)?;
431 manifest
432 .validate_capability_grammar()
433 .map_err(D::Error::custom)?;
434 if let Some(rich_ui) = &manifest.rich_ui {
435 rich_ui.validate().map_err(D::Error::custom)?;
436 }
437 Ok(manifest)
438 }
439}
440
441#[derive(Debug, Clone, PartialEq, Eq)]
443pub struct RoleDeclarationsError(&'static str);
444
445impl fmt::Display for RoleDeclarationsError {
446 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
447 f.write_str(self.0)
448 }
449}
450
451impl std::error::Error for RoleDeclarationsError {}
452
453pub fn validate_hello_role_declarations(hello: &Value) -> Result<(), RoleDeclarationsError> {
455 validate_role_declarations_value(
456 hello
457 .get("manifest")
458 .and_then(|manifest| manifest.get("role_declarations")),
459 )
460}
461
462fn validate_role_declarations_value(value: Option<&Value>) -> Result<(), RoleDeclarationsError> {
463 let Some(value) = value else {
464 return Ok(());
465 };
466 let map = value
467 .as_object()
468 .ok_or(RoleDeclarationsError("role_declarations must be an object"))?;
469 for (role, declaration) in map {
470 if !is_valid_capability_identifier(role) {
471 return Err(RoleDeclarationsError(
472 "role_declarations key must use capability-name grammar",
473 ));
474 }
475 if !declaration.is_object() {
476 return Err(RoleDeclarationsError(
477 "role_declarations values must be objects",
478 ));
479 }
480 }
481 let bytes = serde_json::to_vec(value)
482 .map_err(|_| RoleDeclarationsError("role_declarations could not be serialized"))?;
483 if bytes.len() > MAX_ROLE_DECLARATIONS_BYTES {
484 return Err(RoleDeclarationsError(
485 "role_declarations exceeds 16384 compact JSON bytes",
486 ));
487 }
488 Ok(())
489}
490
491#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
497#[non_exhaustive]
498pub struct RichUiDescriptor {
499 pub schema: String,
501 pub manifest_digest: String,
503 pub bytes: u64,
505 pub chunks: u32,
507}
508
509impl RichUiDescriptor {
510 pub fn new(
512 schema: impl Into<String>,
513 manifest_digest: impl Into<String>,
514 bytes: u64,
515 chunks: u32,
516 ) -> Self {
517 Self {
518 schema: schema.into(),
519 manifest_digest: manifest_digest.into(),
520 bytes,
521 chunks,
522 }
523 }
524
525 pub fn validate(&self) -> Result<(), RichUiDescriptorError> {
527 validate_rich_ui_fields(
528 &self.schema,
529 &self.manifest_digest,
530 self.bytes,
531 u64::from(self.chunks),
532 )
533 }
534}
535
536#[derive(Debug, Clone, PartialEq, Eq)]
538#[non_exhaustive]
539pub struct RichUiDescriptorError {
540 field: String,
541 reason: &'static str,
542}
543
544impl RichUiDescriptorError {
545 fn new(field: impl Into<String>, reason: &'static str) -> Self {
546 Self {
547 field: field.into(),
548 reason,
549 }
550 }
551
552 pub fn field(&self) -> &str {
554 &self.field
555 }
556}
557
558impl fmt::Display for RichUiDescriptorError {
559 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
560 write!(
561 f,
562 "invalid rich_ui descriptor: field {} {}",
563 self.field, self.reason
564 )
565 }
566}
567
568impl std::error::Error for RichUiDescriptorError {}
569
570pub fn validate_hello_rich_ui_descriptor(hello: &Value) -> Result<(), RichUiDescriptorError> {
572 let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
573 return Ok(());
574 };
575 let Some(value) = manifest.get("rich_ui") else {
576 return Ok(());
577 };
578 validate_rich_ui_descriptor_value(value)
579}
580
581fn validate_rich_ui_descriptor_value(value: &Value) -> Result<(), RichUiDescriptorError> {
582 let descriptor = value
583 .as_object()
584 .ok_or_else(|| RichUiDescriptorError::new("rich_ui", "must be an object"))?;
585 let schema = descriptor
586 .get("schema")
587 .and_then(Value::as_str)
588 .ok_or_else(|| RichUiDescriptorError::new("rich_ui.schema", "must be a string"))?;
589 let digest = descriptor
590 .get("manifest_digest")
591 .and_then(Value::as_str)
592 .ok_or_else(|| RichUiDescriptorError::new("rich_ui.manifest_digest", "must be a string"))?;
593 let bytes = descriptor
594 .get("bytes")
595 .and_then(Value::as_u64)
596 .ok_or_else(|| {
597 RichUiDescriptorError::new("rich_ui.bytes", "must be an integer from 1 to 16777216")
598 })?;
599 let chunks = descriptor
600 .get("chunks")
601 .and_then(Value::as_u64)
602 .ok_or_else(|| {
603 RichUiDescriptorError::new("rich_ui.chunks", "must be an integer from 1 to 1024")
604 })?;
605 validate_rich_ui_fields(schema, digest, bytes, chunks)
606}
607
608fn validate_rich_ui_fields(
609 schema: &str,
610 digest: &str,
611 bytes: u64,
612 chunks: u64,
613) -> Result<(), RichUiDescriptorError> {
614 if !(1..=64).contains(&schema.len())
615 || !schema.bytes().all(|byte| {
616 byte.is_ascii_lowercase()
617 || byte.is_ascii_digit()
618 || matches!(byte, b'.' | b'_' | b'/' | b'-')
619 })
620 {
621 return Err(RichUiDescriptorError::new(
622 "rich_ui.schema",
623 "must be 1 to 64 bytes of [a-z0-9._/-]",
624 ));
625 }
626 if !digest.strip_prefix("sha256:").is_some_and(|hex| {
627 hex.len() == 64
628 && hex
629 .bytes()
630 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
631 }) {
632 return Err(RichUiDescriptorError::new(
633 "rich_ui.manifest_digest",
634 "must be sha256: followed by 64 lowercase hexadecimal characters",
635 ));
636 }
637 if !(1..=16_777_216).contains(&bytes) {
638 return Err(RichUiDescriptorError::new(
639 "rich_ui.bytes",
640 "must be an integer from 1 to 16777216",
641 ));
642 }
643 if !(1..=1_024).contains(&chunks) {
644 return Err(RichUiDescriptorError::new(
645 "rich_ui.chunks",
646 "must be an integer from 1 to 1024",
647 ));
648 }
649 Ok(())
650}
651
652pub const CAP_CATALOG_EVENTS_V1: &str = "catalog-events/v1";
658
659pub const CAP_SCOPE_BIND_PROOF_V1: &str = "scope-bind-proof/v1";
663
664pub const CAP_SCOPE_BIND_PROOF_V2: &str = "scope-bind-proof/v2";
668
669pub const CAP_SCOPE_REPLACE_IF_IDLE_V1: &str = "scope-replace-if-idle/v1";
671
672#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
674#[non_exhaustive]
675pub struct EventDeclaration {
676 pub name: String,
683 pub version: u32,
685 pub headers: Vec<String>,
688 #[serde(default, skip_serializing_if = "Option::is_none")]
690 pub summary: Option<String>,
691}
692
693impl EventDeclaration {
694 pub fn new(name: impl Into<String>, version: u32) -> Self {
697 Self {
698 name: name.into(),
699 version,
700 headers: Vec::new(),
701 summary: None,
702 }
703 }
704
705 pub fn with_headers(mut self, headers: Vec<String>) -> Self {
707 self.headers = headers;
708 self
709 }
710
711 pub fn with_summary(mut self, summary: Option<String>) -> Self {
713 self.summary = summary;
714 self
715 }
716}
717
718#[derive(Debug, Clone, PartialEq, Eq)]
720#[non_exhaustive]
721pub struct EventDeclarationError {
722 field: String,
723 reason: &'static str,
724}
725
726impl EventDeclarationError {
727 fn new(field: impl Into<String>, reason: &'static str) -> Self {
728 Self {
729 field: field.into(),
730 reason,
731 }
732 }
733
734 pub fn field(&self) -> &str {
736 &self.field
737 }
738}
739
740impl fmt::Display for EventDeclarationError {
741 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
742 write!(
743 f,
744 "invalid event declaration: field {} {}",
745 self.field, self.reason
746 )
747 }
748}
749
750impl std::error::Error for EventDeclarationError {}
751
752pub fn validate_hello_event_declarations(hello: &Value) -> Result<(), EventDeclarationError> {
754 validate_events_value(
755 hello
756 .get("manifest")
757 .and_then(|manifest| manifest.get("events")),
758 )
759}
760
761fn is_valid_event_name(name: &str) -> bool {
764 let level_count = name.split('.').count();
765 (1..=4).contains(&level_count)
766 && name.split('.').all(|level| {
767 if level.is_empty() {
768 return false;
769 }
770 let first = level.as_bytes()[0];
771 (1..=63).contains(&level.len())
772 && (first.is_ascii_lowercase() || first.is_ascii_digit())
773 && level
774 .bytes()
775 .skip(1)
776 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
777 && !level.strip_prefix('v').is_some_and(|digits| {
778 !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit())
779 })
780 })
781}
782
783fn validate_events_value(value: Option<&Value>) -> Result<(), EventDeclarationError> {
784 let Some(value) = value.filter(|value| !value.is_null()) else {
785 return Ok(());
786 };
787 let entries = value
788 .as_array()
789 .ok_or_else(|| EventDeclarationError::new("events", "must be a list"))?;
790 if entries.len() > 64 {
791 return Err(EventDeclarationError::new(
792 "events",
793 "must contain at most 64 declarations",
794 ));
795 }
796 let mut pairs = HashSet::new();
797 for (index, entry) in entries.iter().enumerate() {
798 let field = format!("events[{index}]");
799 let entry = entry
800 .as_object()
801 .ok_or_else(|| EventDeclarationError::new(&field, "must be an object"))?;
802 let name_field = format!("{field}.name");
803 let name = entry
804 .get("name")
805 .and_then(Value::as_str)
806 .ok_or_else(|| EventDeclarationError::new(&name_field, "must be a string"))?;
807 if !is_valid_event_name(name) {
808 return Err(EventDeclarationError::new(
809 name_field,
810 "must contain one to four valid dot-separated event-name levels",
811 ));
812 }
813 let version = entry
814 .get("version")
815 .and_then(Value::as_u64)
816 .filter(|version| (1..=u32::MAX as u64).contains(version))
817 .ok_or_else(|| {
818 EventDeclarationError::new(
819 format!("{field}.version"),
820 "must be an integer between 1 and u32::MAX",
821 )
822 })?;
823 if !pairs.insert((name, version)) {
824 return Err(EventDeclarationError::new(
825 &field,
826 "duplicates an event (name, version) pair",
827 ));
828 }
829 let headers_field = format!("{field}.headers");
830 let headers = entry
831 .get("headers")
832 .and_then(Value::as_array)
833 .ok_or_else(|| EventDeclarationError::new(&headers_field, "must be a list"))?;
834 if headers.len() > 16 {
835 return Err(EventDeclarationError::new(
836 headers_field,
837 "must contain at most 16 headers",
838 ));
839 }
840 let mut names = HashSet::new();
841 for (header_index, header) in headers.iter().enumerate() {
842 let header_field = format!("{headers_field}[{header_index}]");
843 let header = header
844 .as_str()
845 .ok_or_else(|| EventDeclarationError::new(&header_field, "must be a string"))?;
846 if !(1..=32).contains(&header.len())
847 || !header.as_bytes()[0].is_ascii_lowercase()
848 || !header
849 .bytes()
850 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
851 {
852 return Err(EventDeclarationError::new(
853 header_field,
854 "must match [a-z][a-z0-9_]{0,31}",
855 ));
856 }
857 if !names.insert(header) {
858 return Err(EventDeclarationError::new(
859 header_field,
860 "duplicates a header name",
861 ));
862 }
863 }
864 if let Some(summary) = entry.get("summary").filter(|value| !value.is_null()) {
865 let summary_field = format!("{field}.summary");
866 let summary = summary
867 .as_str()
868 .ok_or_else(|| EventDeclarationError::new(&summary_field, "must be a string"))?;
869 if summary.chars().count() > 200 || summary.chars().any(char::is_control) {
870 return Err(EventDeclarationError::new(
871 summary_field,
872 "must contain at most 200 characters and no control characters",
873 ));
874 }
875 }
876 }
877 Ok(())
878}
879
880#[derive(Debug, Clone, PartialEq, Eq)]
882pub struct SelfSignalDeclarationError {
883 module_id: String,
884 entry_index: usize,
885 field: &'static str,
886}
887
888impl fmt::Display for SelfSignalDeclarationError {
889 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
890 write!(
891 f,
892 "module_id '{}' self_signals[{}] is missing required field '{}'",
893 self.module_id.escape_debug(),
894 self.entry_index,
895 self.field
896 )
897 }
898}
899
900pub fn validate_hello_self_signal_declarations(
907 hello: &Value,
908) -> Result<(), SelfSignalDeclarationError> {
909 let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
910 return Ok(());
911 };
912 let module_id = manifest
913 .get("module_id")
914 .and_then(Value::as_str)
915 .unwrap_or("<unknown>");
916 let Some(entries) = manifest.get("self_signals").and_then(Value::as_array) else {
917 return Ok(());
918 };
919
920 for (entry_index, entry) in entries.iter().enumerate() {
921 let Some(entry) = entry.as_object() else {
922 continue;
923 };
924 for field in ["effect", "anchored_to"] {
925 if !entry.contains_key(field) {
926 return Err(SelfSignalDeclarationError {
927 module_id: module_id.to_string(),
928 entry_index,
929 field,
930 });
931 }
932 }
933 }
934 Ok(())
935}
936
937#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
939#[serde(deny_unknown_fields)]
940pub struct CapabilityDeclarations {
941 #[serde(default)]
942 pub provides: Vec<String>,
943 #[serde(default)]
944 pub requires: Vec<CapabilityRequirement>,
945 #[serde(default)]
946 pub must_never_reach: Vec<String>,
947}
948
949#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
951pub struct SelfSignalDeclaration {
952 pub name: String,
954 pub kind: SelfSignalKind,
982 pub effect: SelfSignalEffect,
984 pub anchored_to: SignalAnchor,
986 #[serde(default, skip_serializing_if = "Option::is_none")]
993 pub cadence: Option<SignalCadence>,
994 #[serde(default, skip_serializing_if = "Option::is_none")]
996 pub domain: Option<String>,
997 #[serde(default, skip_serializing_if = "Option::is_none")]
998 pub note: Option<String>,
999}
1000
1001#[derive(Debug, Clone, PartialEq, Eq)]
1003pub enum SelfSignalKind {
1004 Keepalive,
1005 Busy,
1007 Poller,
1008 Cron,
1009 Sweep,
1010 Watchdog,
1011 Heartbeat,
1012 Other(String),
1013}
1014
1015impl SelfSignalKind {
1016 fn wire_name(&self) -> &str {
1017 match self {
1018 Self::Keepalive => "keepalive",
1019 Self::Busy => "busy",
1020 Self::Poller => "poller",
1021 Self::Cron => "cron",
1022 Self::Sweep => "sweep",
1023 Self::Watchdog => "watchdog",
1024 Self::Heartbeat => "heartbeat",
1025 Self::Other(value) => value,
1026 }
1027 }
1028}
1029
1030impl Serialize for SelfSignalKind {
1031 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1032 where
1033 S: serde::Serializer,
1034 {
1035 serializer.serialize_str(self.wire_name())
1036 }
1037}
1038
1039impl<'de> Deserialize<'de> for SelfSignalKind {
1040 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1041 where
1042 D: Deserializer<'de>,
1043 {
1044 let value = String::deserialize(deserializer)?;
1045 Ok(match value.as_str() {
1046 "keepalive" => Self::Keepalive,
1047 "busy" => Self::Busy,
1048 "poller" => Self::Poller,
1049 "cron" => Self::Cron,
1050 "sweep" => Self::Sweep,
1051 "watchdog" => Self::Watchdog,
1052 "heartbeat" => Self::Heartbeat,
1053 _ => Self::Other(value),
1054 })
1055 }
1056}
1057
1058#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1060#[serde(rename_all = "lowercase")]
1061pub enum SelfSignalEffect {
1062 Observe,
1063 Mutate,
1064}
1065
1066#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1068#[serde(rename_all = "snake_case")]
1069pub enum SignalAnchor {
1070 FixedInterval,
1073 Event { event: String },
1076 HealthGauges { gauges: Vec<String> },
1078}
1079
1080#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1082#[serde(rename_all = "snake_case")]
1083pub enum SignalCadence {
1084 Literal { interval_ms: u64 },
1085 Derived { source: String },
1086}
1087
1088#[derive(Serialize, Debug, Clone, Default, PartialEq, Eq)]
1165#[non_exhaustive]
1166pub struct ManifestProvenance {
1167 #[serde(default, skip_serializing_if = "Option::is_none")]
1168 pub build_git_sha: Option<String>,
1169 #[serde(default, skip_serializing_if = "Option::is_none")]
1173 pub build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1174 #[serde(default, skip_serializing_if = "Option::is_none")]
1175 pub build_lock_digest: Option<String>,
1176 #[serde(default, skip_serializing_if = "Option::is_none")]
1185 pub wire_crate_version: Option<String>,
1186 #[serde(default, skip_serializing_if = "Option::is_none")]
1187 pub store_schema_version: Option<String>,
1188 #[serde(default, skip_serializing_if = "Option::is_none")]
1194 pub launch_nonce_source: Option<LaunchNonceSource>,
1195}
1196
1197#[derive(Debug, Clone, PartialEq, Eq)]
1204#[non_exhaustive]
1205pub enum LaunchNonceSource {
1206 Fd,
1208 Pipe,
1210 Env,
1212 ForwardCompatibleUnknown(String),
1213}
1214
1215impl LaunchNonceSource {
1216 pub fn wire_name(&self) -> &str {
1218 match self {
1219 Self::Fd => "fd",
1220 Self::Pipe => "pipe",
1221 Self::Env => "env",
1222 Self::ForwardCompatibleUnknown(value) => value,
1223 }
1224 }
1225
1226 pub fn from_wire_name(value: &str) -> Self {
1228 match value {
1229 "fd" => Self::Fd,
1230 "pipe" => Self::Pipe,
1231 "env" => Self::Env,
1232 _ => Self::ForwardCompatibleUnknown(value.to_string()),
1233 }
1234 }
1235}
1236
1237impl Serialize for LaunchNonceSource {
1238 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1239 where
1240 S: serde::Serializer,
1241 {
1242 serializer.serialize_str(self.wire_name())
1243 }
1244}
1245
1246impl<'de> Deserialize<'de> for LaunchNonceSource {
1247 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1248 where
1249 D: serde::Deserializer<'de>,
1250 {
1251 let value = String::deserialize(deserializer)?;
1252 Ok(Self::from_wire_name(&value))
1253 }
1254}
1255
1256#[derive(Debug, Clone, PartialEq, Eq)]
1261pub enum BuildGitShaAbsenceReason {
1262 DeclinedDirty,
1263 NeverDerived,
1264 NoGitDir,
1265 ForwardCompatibleUnknown(String),
1266}
1267
1268impl BuildGitShaAbsenceReason {
1269 fn wire_name(&self) -> &str {
1270 match self {
1271 Self::DeclinedDirty => "declined_dirty",
1272 Self::NeverDerived => "never_derived",
1273 Self::NoGitDir => "no_git_dir",
1274 Self::ForwardCompatibleUnknown(value) => value,
1275 }
1276 }
1277}
1278
1279impl Serialize for BuildGitShaAbsenceReason {
1280 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1281 where
1282 S: serde::Serializer,
1283 {
1284 serializer.serialize_str(self.wire_name())
1285 }
1286}
1287
1288impl<'de> Deserialize<'de> for BuildGitShaAbsenceReason {
1289 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1290 where
1291 D: serde::Deserializer<'de>,
1292 {
1293 let value = String::deserialize(deserializer)?;
1294 Ok(match value.as_str() {
1295 "declined_dirty" => Self::DeclinedDirty,
1296 "never_derived" => Self::NeverDerived,
1297 "no_git_dir" => Self::NoGitDir,
1298 _ => Self::ForwardCompatibleUnknown(value),
1299 })
1300 }
1301}
1302
1303#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1305pub enum GitTreeState {
1306 Clean,
1307 Dirty,
1308}
1309
1310#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1315pub enum BuildGitShaSource<'a> {
1316 Git {
1317 revision: &'a str,
1318 tree_state: GitTreeState,
1319 },
1320 NeverDerived,
1321 NoGitDir,
1322}
1323
1324pub fn attestable_commit(revision: &str, tree_state: GitTreeState) -> Option<&str> {
1328 match tree_state {
1329 GitTreeState::Clean => Some(revision),
1330 GitTreeState::Dirty => None,
1331 }
1332}
1333
1334const MAX_PROVENANCE_VALUE_BYTES: usize = 128;
1335const BUILD_GIT_SHA_CANONICAL_FORM: &str = "exactly 40 lowercase hexadecimal characters";
1336const BUILD_LOCK_DIGEST_CANONICAL_FORM: &str = "exactly 64 lowercase hexadecimal characters";
1337
1338#[derive(Deserialize)]
1339struct ManifestProvenanceWire {
1340 #[serde(default)]
1341 build_git_sha: Option<String>,
1342 #[serde(default)]
1343 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1344 #[serde(default)]
1345 build_lock_digest: Option<String>,
1346 #[serde(default)]
1347 wire_crate_version: Option<String>,
1348 #[serde(default)]
1349 store_schema_version: Option<String>,
1350 #[serde(default)]
1351 launch_nonce_source: Option<LaunchNonceSource>,
1352}
1353
1354impl<'de> Deserialize<'de> for ManifestProvenance {
1355 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1356 where
1357 D: Deserializer<'de>,
1358 {
1359 let wire = ManifestProvenanceWire::deserialize(deserializer)?;
1360 let provenance = Self {
1361 build_git_sha: wire.build_git_sha,
1362 build_git_sha_absence_reason: wire.build_git_sha_absence_reason,
1363 build_lock_digest: wire.build_lock_digest,
1364 wire_crate_version: wire.wire_crate_version,
1365 store_schema_version: wire.store_schema_version,
1366 launch_nonce_source: wire.launch_nonce_source,
1367 };
1368 provenance.validate().map_err(D::Error::custom)?;
1369 Ok(provenance)
1370 }
1371}
1372
1373#[derive(Debug, Clone, PartialEq, Eq)]
1375pub struct ProvenanceFormError {
1376 field: &'static str,
1377 length: usize,
1378 canonical_form: &'static str,
1379}
1380
1381impl ProvenanceFormError {
1382 fn new(field: &'static str, length: usize, canonical_form: &'static str) -> Self {
1383 Self {
1384 field,
1385 length,
1386 canonical_form,
1387 }
1388 }
1389
1390 pub fn field(&self) -> &str {
1392 self.field
1393 }
1394
1395 pub fn length(&self) -> usize {
1397 self.length
1398 }
1399
1400 pub fn canonical_form(&self) -> &str {
1402 self.canonical_form
1403 }
1404}
1405
1406impl fmt::Display for ProvenanceFormError {
1407 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1408 write!(
1409 f,
1410 "invalid manifest provenance form: field {} has length {}; canonical form is {}",
1411 self.field, self.length, self.canonical_form
1412 )
1413 }
1414}
1415
1416impl std::error::Error for ProvenanceFormError {}
1417
1418#[derive(Debug, Clone, PartialEq, Eq)]
1419pub struct ManifestProvenanceError {
1420 field: String,
1421 value: String,
1422 reason: &'static str,
1423}
1424
1425impl ManifestProvenanceError {
1426 fn new(field: &str, value: &str, reason: &'static str) -> Self {
1427 Self {
1428 field: field.to_string(),
1429 value: safe_error_value(value),
1430 reason,
1431 }
1432 }
1433
1434 pub fn field(&self) -> &str {
1435 &self.field
1436 }
1437}
1438
1439impl fmt::Display for ManifestProvenanceError {
1440 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1441 write!(
1442 f,
1443 "invalid manifest provenance: field {} has {} (value {:?})",
1444 self.field, self.reason, self.value
1445 )
1446 }
1447}
1448
1449impl std::error::Error for ManifestProvenanceError {}
1450
1451impl ManifestProvenance {
1452 pub fn new() -> Self {
1454 Self::default()
1455 }
1456
1457 pub fn with_build_git_sha(mut self, value: Option<String>) -> Self {
1458 self.build_git_sha = value;
1459 self
1460 }
1461
1462 pub fn with_build_git_sha_absence_reason(
1463 mut self,
1464 value: Option<BuildGitShaAbsenceReason>,
1465 ) -> Self {
1466 self.build_git_sha_absence_reason = value;
1467 self
1468 }
1469
1470 pub fn with_build_lock_digest(mut self, value: Option<String>) -> Self {
1471 self.build_lock_digest = value;
1472 self
1473 }
1474
1475 pub fn with_wire_crate_version(mut self, value: Option<String>) -> Self {
1476 self.wire_crate_version = value;
1477 self
1478 }
1479
1480 pub fn with_store_schema_version(mut self, value: Option<String>) -> Self {
1481 self.store_schema_version = value;
1482 self
1483 }
1484
1485 pub fn with_launch_nonce_source(mut self, value: Option<LaunchNonceSource>) -> Self {
1490 self.launch_nonce_source = value;
1491 self
1492 }
1493
1494 pub fn validate(&self) -> Result<(), ManifestProvenanceError> {
1495 if let (Some(_), Some(reason)) = (
1496 self.build_git_sha.as_ref(),
1497 self.build_git_sha_absence_reason.as_ref(),
1498 ) {
1499 return Err(ManifestProvenanceError::new(
1500 "build_git_sha_absence_reason",
1501 reason.wire_name(),
1502 "must be omitted when build_git_sha is present",
1503 ));
1504 }
1505 for (field, value) in [
1506 ("build_git_sha", self.build_git_sha.as_deref()),
1507 (
1508 "build_git_sha_absence_reason",
1509 self.build_git_sha_absence_reason
1510 .as_ref()
1511 .map(|reason| reason.wire_name()),
1512 ),
1513 ("build_lock_digest", self.build_lock_digest.as_deref()),
1514 ("wire_crate_version", self.wire_crate_version.as_deref()),
1515 ("store_schema_version", self.store_schema_version.as_deref()),
1516 (
1517 "launch_nonce_source",
1518 self.launch_nonce_source
1519 .as_ref()
1520 .map(|source| source.wire_name()),
1521 ),
1522 ] {
1523 let Some(value) = value else { continue };
1524 if value.is_empty() {
1525 return Err(ManifestProvenanceError::new(
1526 field,
1527 value,
1528 "must not be empty",
1529 ));
1530 }
1531 if value.len() > MAX_PROVENANCE_VALUE_BYTES {
1536 return Err(ManifestProvenanceError::new(
1537 field,
1538 value,
1539 "exceeds the 128-byte maximum",
1540 ));
1541 }
1542 if value.bytes().any(|byte| !(0x20..=0x7e).contains(&byte)) {
1543 return Err(ManifestProvenanceError::new(
1544 field,
1545 value,
1546 "contains non-printable ASCII",
1547 ));
1548 }
1549 }
1550 Ok(())
1551 }
1552}
1553
1554pub fn build_provenance(
1572 build_git_sha: Option<&str>,
1573 build_lock_digest: Option<&str>,
1574 store_schema_version: Option<&str>,
1575) -> Result<ManifestProvenance, ProvenanceFormError> {
1576 let build_git_sha = normalize_and_validate_build_git_sha(build_git_sha)?;
1577 build_provenance_with_build_git_sha(
1578 build_git_sha,
1579 None,
1580 build_lock_digest,
1581 store_schema_version,
1582 )
1583}
1584
1585pub fn build_provenance_from_source(
1601 build_git_sha_source: BuildGitShaSource<'_>,
1602 build_lock_digest: Option<&str>,
1603 store_schema_version: Option<&str>,
1604) -> Result<ManifestProvenance, ProvenanceFormError> {
1605 let (raw_build_git_sha, mut build_git_sha_absence_reason) = match build_git_sha_source {
1606 BuildGitShaSource::Git {
1607 revision,
1608 tree_state,
1609 } => match attestable_commit(revision, tree_state) {
1610 Some(revision) => (Some(revision), None),
1611 None => (None, Some(BuildGitShaAbsenceReason::DeclinedDirty)),
1612 },
1613 BuildGitShaSource::NeverDerived => (None, Some(BuildGitShaAbsenceReason::NeverDerived)),
1614 BuildGitShaSource::NoGitDir => (None, Some(BuildGitShaAbsenceReason::NoGitDir)),
1615 };
1616 let build_git_sha = normalize_and_validate_build_git_sha(raw_build_git_sha)?;
1617 if build_git_sha.is_none() {
1618 build_git_sha_absence_reason.get_or_insert(BuildGitShaAbsenceReason::NeverDerived);
1619 }
1620 build_provenance_with_build_git_sha(
1621 build_git_sha,
1622 build_git_sha_absence_reason,
1623 build_lock_digest,
1624 store_schema_version,
1625 )
1626}
1627
1628fn normalize_and_validate_build_git_sha(
1629 build_git_sha: Option<&str>,
1630) -> Result<Option<String>, ProvenanceFormError> {
1631 let build_git_sha = normalize_provenance_fact(build_git_sha);
1632 validate_provenance_form(
1633 "build_git_sha",
1634 build_git_sha.as_deref(),
1635 BUILD_GIT_SHA_CANONICAL_FORM,
1636 40,
1637 )?;
1638 Ok(build_git_sha)
1639}
1640
1641fn build_provenance_with_build_git_sha(
1642 build_git_sha: Option<String>,
1643 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1644 build_lock_digest: Option<&str>,
1645 store_schema_version: Option<&str>,
1646) -> Result<ManifestProvenance, ProvenanceFormError> {
1647 let build_lock_digest = normalize_provenance_fact(build_lock_digest);
1648 validate_provenance_form(
1649 "build_lock_digest",
1650 build_lock_digest.as_deref(),
1651 BUILD_LOCK_DIGEST_CANONICAL_FORM,
1652 64,
1653 )?;
1654
1655 Ok(ManifestProvenance {
1656 build_git_sha,
1657 build_git_sha_absence_reason,
1658 build_lock_digest,
1659 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
1660 store_schema_version: normalize_provenance_fact(store_schema_version),
1661 launch_nonce_source: None,
1662 })
1663}
1664
1665fn validate_provenance_form(
1666 field: &'static str,
1667 value: Option<&str>,
1668 canonical_form: &'static str,
1669 expected_length: usize,
1670) -> Result<(), ProvenanceFormError> {
1671 let Some(value) = value else { return Ok(()) };
1672 if value.len() != expected_length
1673 || !value
1674 .bytes()
1675 .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
1676 {
1677 return Err(ProvenanceFormError::new(field, value.len(), canonical_form));
1678 }
1679 Ok(())
1680}
1681
1682pub const PROVENANCE_SENTINELS: [&str; 3] = ["unknown", "unavailable", "none"];
1690
1691fn normalize_provenance_fact(value: Option<&str>) -> Option<String> {
1692 let value = value?.trim();
1693 if value.is_empty() {
1694 return None;
1695 }
1696 let lowered = value.to_ascii_lowercase();
1697 if PROVENANCE_SENTINELS.contains(&lowered.as_str()) {
1698 return None;
1699 }
1700 Some(value.to_string())
1701}
1702
1703#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1705#[serde(deny_unknown_fields)]
1706pub struct CapabilityRequirement {
1707 pub capability: String,
1708 pub need: CapabilityNeed,
1709}
1710
1711#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1713#[serde(rename_all = "snake_case")]
1714pub enum CapabilityNeed {
1715 Required,
1716 Optional,
1717}
1718
1719#[derive(Debug, Clone, PartialEq, Eq)]
1721pub struct CapabilityGrammarError {
1722 field: String,
1723 value: String,
1724}
1725
1726impl CapabilityGrammarError {
1727 fn new(field: impl Into<String>, value: impl AsRef<str>) -> Self {
1728 Self {
1729 field: field.into(),
1730 value: safe_error_value(value.as_ref()),
1731 }
1732 }
1733
1734 pub fn field(&self) -> &str {
1736 &self.field
1737 }
1738
1739 pub fn value(&self) -> &str {
1741 &self.value
1742 }
1743}
1744
1745impl fmt::Display for CapabilityGrammarError {
1746 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1747 write!(
1748 f,
1749 "invalid capability grammar: field {} has offending value {:?}",
1750 self.field, self.value
1751 )
1752 }
1753}
1754
1755impl std::error::Error for CapabilityGrammarError {}
1756
1757impl ModuleManifest {
1758 pub fn validate_capability_grammar(&self) -> Result<(), CapabilityGrammarError> {
1760 let Some(capabilities) = &self.capabilities else {
1761 return Ok(());
1762 };
1763
1764 validate_capability_list("capabilities.provides", &capabilities.provides)?;
1765 validate_requires(&capabilities.requires)?;
1766 validate_capability_list(
1767 "capabilities.must_never_reach",
1768 &capabilities.must_never_reach,
1769 )
1770 }
1771}
1772
1773pub fn validate_manifest_capability_grammar(
1778 manifest: &Value,
1779) -> Result<(), CapabilityGrammarError> {
1780 let Some(object) = manifest.as_object() else {
1781 return Ok(());
1782 };
1783
1784 validate_capabilities_value(object.get("capabilities"))?;
1785 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
1786}
1787
1788pub fn validate_hello_capability_grammar(hello: &Value) -> Result<(), CapabilityGrammarError> {
1794 let Some(object) = hello.as_object() else {
1795 return Ok(());
1796 };
1797 if let Some(manifest) = object.get("manifest") {
1798 validate_manifest_capability_grammar(manifest)?;
1799 }
1800 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
1801}
1802
1803pub fn is_valid_capability_identifier(identifier: &str) -> bool {
1805 if identifier.chars().any(char::is_whitespace) {
1806 return false;
1807 }
1808 let Some((name, version)) = identifier.split_once("/v") else {
1809 return false;
1810 };
1811 if name.is_empty() || name.len() > 64 || version.is_empty() {
1812 return false;
1813 }
1814
1815 let name_bytes = name.as_bytes();
1816 if !name_bytes[0].is_ascii_lowercase()
1817 || (name.len() > 1
1818 && !name_bytes[name.len() - 1].is_ascii_lowercase()
1819 && !name_bytes[name.len() - 1].is_ascii_digit())
1820 || name_bytes.windows(2).any(|pair| pair == b"--")
1821 {
1822 return false;
1823 }
1824 if !name_bytes
1825 .iter()
1826 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-')
1827 {
1828 return false;
1829 }
1830
1831 if version.len() > 1 && version.starts_with('0')
1832 || !version.bytes().all(|byte| byte.is_ascii_digit())
1833 {
1834 return false;
1835 }
1836 matches!(
1837 version.parse::<u64>(),
1838 Ok(value) if (1..=u64::from(u32::MAX)).contains(&value)
1839 )
1840}
1841
1842fn validate_capabilities_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
1843 let Some(value) = value else {
1844 return Ok(());
1845 };
1846 let Some(object) = value.as_object() else {
1847 return Err(CapabilityGrammarError::new(
1848 "capabilities",
1849 value_description(value),
1850 ));
1851 };
1852
1853 for (key, value) in object {
1854 if !matches!(key.as_str(), "provides" | "requires" | "must_never_reach") {
1855 return Err(CapabilityGrammarError::new(
1856 field_child("capabilities", key),
1857 value_description(value),
1858 ));
1859 }
1860 }
1861
1862 validate_capability_list_value("capabilities.provides", object.get("provides"))?;
1863 validate_requires_value(object.get("requires"))?;
1864 validate_capability_list_value(
1865 "capabilities.must_never_reach",
1866 object.get("must_never_reach"),
1867 )
1868}
1869
1870fn validate_capability_list_value(
1871 field: &str,
1872 value: Option<&Value>,
1873) -> Result<(), CapabilityGrammarError> {
1874 let Some(value) = value else {
1875 return Ok(());
1876 };
1877 let Some(values) = value.as_array() else {
1878 return Err(CapabilityGrammarError::new(field, value_description(value)));
1879 };
1880
1881 let mut seen = HashSet::new();
1882 for (index, value) in values.iter().enumerate() {
1883 let field = format!("{field}[{index}]");
1884 let Some(identifier) = value.as_str() else {
1885 return Err(CapabilityGrammarError::new(field, value_description(value)));
1886 };
1887 validate_capability_identifier(&field, identifier)?;
1888 if !seen.insert(identifier) {
1889 return Err(CapabilityGrammarError::new(field, identifier));
1890 }
1891 }
1892 Ok(())
1893}
1894
1895fn validate_requires_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
1896 let Some(value) = value else {
1897 return Ok(());
1898 };
1899 let Some(values) = value.as_array() else {
1900 return Err(CapabilityGrammarError::new(
1901 "capabilities.requires",
1902 value_description(value),
1903 ));
1904 };
1905
1906 let mut seen = HashSet::new();
1907 for (index, value) in values.iter().enumerate() {
1908 let entry_field = format!("capabilities.requires[{index}]");
1909 let Some(object) = value.as_object() else {
1910 return Err(CapabilityGrammarError::new(
1911 entry_field,
1912 value_description(value),
1913 ));
1914 };
1915 for (key, value) in object {
1916 if !matches!(key.as_str(), "capability" | "need") {
1917 return Err(CapabilityGrammarError::new(
1918 field_child(&entry_field, key),
1919 value_description(value),
1920 ));
1921 }
1922 }
1923 let capability_field = format!("{entry_field}.capability");
1924 let Some(capability) = object.get("capability").and_then(Value::as_str) else {
1925 return Err(CapabilityGrammarError::new(
1926 capability_field,
1927 object
1928 .get("capability")
1929 .map_or("<missing>".to_string(), value_description),
1930 ));
1931 };
1932 validate_capability_identifier(&capability_field, capability)?;
1933
1934 let need_field = format!("{entry_field}.need");
1935 let Some(need) = object.get("need").and_then(Value::as_str) else {
1936 return Err(CapabilityGrammarError::new(
1937 need_field,
1938 object
1939 .get("need")
1940 .map_or("<missing>".to_string(), value_description),
1941 ));
1942 };
1943 if !matches!(need, "required" | "optional") {
1944 return Err(CapabilityGrammarError::new(need_field, need));
1945 }
1946 if !seen.insert(capability) {
1947 return Err(CapabilityGrammarError::new(entry_field, capability));
1948 }
1949 }
1950 Ok(())
1951}
1952
1953fn validate_capability_list(field: &str, values: &[String]) -> Result<(), CapabilityGrammarError> {
1954 let mut seen = HashSet::new();
1955 for (index, identifier) in values.iter().enumerate() {
1956 let field = format!("{field}[{index}]");
1957 validate_capability_identifier(&field, identifier)?;
1958 if !seen.insert(identifier) {
1959 return Err(CapabilityGrammarError::new(field, identifier));
1960 }
1961 }
1962 Ok(())
1963}
1964
1965fn validate_requires(values: &[CapabilityRequirement]) -> Result<(), CapabilityGrammarError> {
1966 let mut seen = HashSet::new();
1967 for (index, requirement) in values.iter().enumerate() {
1968 let field = format!("capabilities.requires[{index}].capability");
1969 validate_capability_identifier(&field, &requirement.capability)?;
1970 if !seen.insert(&requirement.capability) {
1971 return Err(CapabilityGrammarError::new(
1972 format!("capabilities.requires[{index}]"),
1973 &requirement.capability,
1974 ));
1975 }
1976 }
1977 Ok(())
1978}
1979
1980fn validate_capability_identifier(
1981 field: &str,
1982 identifier: &str,
1983) -> Result<(), CapabilityGrammarError> {
1984 if is_valid_capability_identifier(identifier) {
1985 Ok(())
1986 } else {
1987 Err(CapabilityGrammarError::new(field, identifier))
1988 }
1989}
1990
1991fn validate_runtime_computed(
1992 value: Option<&Value>,
1993 field: &str,
1994) -> Result<(), CapabilityGrammarError> {
1995 let Some(value) = value else {
1996 return Ok(());
1997 };
1998 let Some(pointers) = value.as_array() else {
1999 return Err(CapabilityGrammarError::new(field, value_description(value)));
2000 };
2001
2002 for (index, pointer) in pointers.iter().enumerate() {
2003 let field = format!("{field}[{index}]");
2004 let Some(pointer) = pointer.as_str() else {
2005 return Err(CapabilityGrammarError::new(
2006 field,
2007 value_description(pointer),
2008 ));
2009 };
2010 let Some(tokens) = parse_json_pointer(pointer) else {
2011 return Err(CapabilityGrammarError::new(field, pointer));
2012 };
2013 if tokens.first().is_some_and(|token| token == "capabilities") {
2014 return Err(CapabilityGrammarError::new(field, pointer));
2015 }
2016 }
2017 Ok(())
2018}
2019
2020fn parse_json_pointer(pointer: &str) -> Option<Vec<String>> {
2021 if pointer.is_empty() {
2022 return Some(Vec::new());
2023 }
2024 let raw_tokens = pointer.strip_prefix('/')?;
2025 raw_tokens
2026 .split('/')
2027 .map(unescape_json_pointer_token)
2028 .collect()
2029}
2030
2031fn unescape_json_pointer_token(token: &str) -> Option<String> {
2032 let mut output = String::with_capacity(token.len());
2033 let mut characters = token.chars();
2034 while let Some(character) = characters.next() {
2035 if character != '~' {
2036 output.push(character);
2037 continue;
2038 }
2039 match characters.next()? {
2040 '0' => output.push('~'),
2041 '1' => output.push('/'),
2042 _ => return None,
2043 }
2044 }
2045 Some(output)
2046}
2047
2048fn field_child(parent: &str, child: &str) -> String {
2049 let child = safe_error_value(child);
2050 format!("{parent}.{child}")
2051}
2052
2053fn value_description(value: &Value) -> String {
2054 match value {
2055 Value::String(value) => safe_error_value(value),
2056 Value::Null => "null".to_string(),
2057 Value::Bool(value) => value.to_string(),
2058 Value::Number(value) => value.to_string(),
2059 Value::Array(_) => "<array>".to_string(),
2060 Value::Object(_) => "<object>".to_string(),
2061 }
2062}
2063
2064fn safe_error_value(value: &str) -> String {
2065 let lower = value.to_ascii_lowercase();
2066 if ["secret", "password", "api_key"]
2067 .iter()
2068 .any(|marker| lower.contains(marker))
2069 || lower.starts_with("sk-")
2070 || lower.starts_with("akia")
2071 || lower.starts_with("bearer ")
2072 || lower.starts_with("token=")
2073 || lower.starts_with("credential=")
2074 {
2075 "<redacted>".to_string()
2076 } else {
2077 value.to_string()
2078 }
2079}
2080
2081#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2087#[serde(rename_all = "snake_case")]
2088pub enum TrustTier {
2089 FirstParty,
2090 Reviewed,
2091 Untrusted,
2092}
2093
2094#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2098#[serde(tag = "role", rename_all = "snake_case")]
2099pub enum ProviderRole {
2100 ToolProvider {
2101 tools: Vec<Tool>,
2102 identity_scope: Vec<IdentityScope>,
2110 concurrency: Concurrency,
2111 emits_push: bool,
2112 sub_supervises: bool,
2113 },
2114 PipelineStage {
2115 stage: PipelineStageKind,
2116 applies_to: PipelineAppliesTo,
2117 interface: String,
2118 declares_frozen_floor: bool,
2119 needs_signals: Vec<String>,
2120 conformance_class: String,
2121 },
2122 ManagementSurface {
2123 operations: Vec<ManagementOperation>,
2124 config_schema: Value,
2125 observability: Vec<ObservabilitySurface>,
2126 identity_scope: Vec<IdentityScope>,
2130 #[serde(default)]
2131 concurrency: Concurrency,
2132 },
2133 InternalService {
2134 service_id: String,
2135 transport: InternalTransport,
2136 agent_facing: bool,
2137 operations: Vec<String>,
2138 },
2139}
2140
2141#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2154#[serde(rename_all = "snake_case")]
2155pub enum ExecutionMode {
2156 Pure,
2157 Mutating,
2158 Unfenceable,
2159}
2160
2161#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2163pub struct Tool {
2164 pub name: String,
2165 #[serde(default, skip_serializing_if = "Option::is_none")]
2166 pub description: Option<String>,
2167 pub execution_mode: ExecutionMode,
2172 pub schema: Value,
2173}
2174
2175#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2181#[serde(rename_all = "snake_case")]
2182pub enum Concurrency {
2183 Serial,
2185 ModuleManaged,
2188 StatelessParallel,
2191}
2192
2193#[allow(clippy::derivable_impls)]
2194impl Default for Concurrency {
2205 fn default() -> Self {
2206 Self::ModuleManaged
2207 }
2208}
2209
2210#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2217#[serde(rename_all = "snake_case")]
2218pub enum IdentityScope {
2219 Session,
2220 Project,
2221}
2222
2223#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2225#[serde(rename_all = "snake_case")]
2226pub enum PipelineStageKind {
2227 Transform,
2228 Codec,
2229 Auth,
2230}
2231
2232#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2234pub struct PipelineAppliesTo {
2235 pub provider: String,
2236 pub model: String,
2237}
2238
2239#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2242#[non_exhaustive]
2243pub struct OperationPayload {
2244 max_bytes: usize,
2245}
2246
2247impl OperationPayload {
2248 pub fn new(max_bytes: usize) -> Self {
2249 Self { max_bytes }
2250 }
2251
2252 pub fn max_bytes(&self) -> usize {
2253 self.max_bytes
2254 }
2255}
2256
2257#[derive(Debug, Clone, PartialEq, Eq)]
2259#[non_exhaustive]
2260pub enum OperationPayloadError {
2261 UnknownOperation { operation: String },
2262 WatchOperation { operation: String },
2263 InvalidMaxBytes { operation: String },
2264}
2265
2266impl fmt::Display for OperationPayloadError {
2267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2268 write!(f, "{self:?}")
2269 }
2270}
2271
2272impl std::error::Error for OperationPayloadError {}
2273
2274impl ModuleManifest {
2275 pub fn validate_operation_payload(&self) -> Result<(), OperationPayloadError> {
2278 for (name, payload) in &self.operation_payload {
2279 if !self.provides.iter().any(|role| match role {
2280 ProviderRole::ManagementSurface { operations, .. } => {
2281 operations.iter().any(|op| op.name == *name)
2282 }
2283 _ => false,
2284 }) {
2285 return Err(OperationPayloadError::UnknownOperation {
2286 operation: name.clone(),
2287 });
2288 }
2289 if self
2290 .operation_delivery
2291 .get(name)
2292 .is_some_and(OperationDelivery::is_watch)
2293 {
2294 return Err(OperationPayloadError::WatchOperation {
2295 operation: name.clone(),
2296 });
2297 }
2298 if !(1..=crate::framed_body::MAX_DECLARED_PAYLOAD_BYTES).contains(&payload.max_bytes) {
2299 return Err(OperationPayloadError::InvalidMaxBytes {
2300 operation: name.clone(),
2301 });
2302 }
2303 }
2304 Ok(())
2305 }
2306}
2307
2308#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2313pub struct ManagementOperation {
2314 pub name: String,
2315 pub kind: ManagementOperationKind,
2316 #[serde(default, skip_serializing_if = "Option::is_none")]
2317 pub description: Option<String>,
2318}
2319
2320#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2321#[serde(rename_all = "snake_case")]
2322pub enum ManagementOperationKind {
2323 Query,
2324 Mutate,
2325}
2326
2327#[derive(Debug, Clone, PartialEq, Eq)]
2330#[non_exhaustive]
2331pub enum OperationDelivery {
2332 Watch,
2333 Other(String),
2334}
2335
2336impl OperationDelivery {
2337 pub const WATCH: Self = Self::Watch;
2339
2340 pub fn wire_name(&self) -> &str {
2342 match self {
2343 Self::Watch => "watch",
2344 Self::Other(value) => value,
2345 }
2346 }
2347
2348 pub fn is_watch(&self) -> bool {
2350 self.wire_name() == "watch"
2351 }
2352}
2353
2354impl Serialize for OperationDelivery {
2355 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2356 where
2357 S: serde::Serializer,
2358 {
2359 serializer.serialize_str(self.wire_name())
2360 }
2361}
2362
2363impl<'de> Deserialize<'de> for OperationDelivery {
2364 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2365 where
2366 D: Deserializer<'de>,
2367 {
2368 let value = String::deserialize(deserializer)?;
2369 Ok(if value == "watch" {
2370 Self::WATCH
2371 } else {
2372 Self::Other(value)
2373 })
2374 }
2375}
2376
2377#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2379pub struct ObservabilitySurface {
2380 pub name: String,
2381 pub kind: ObservabilityKind,
2382}
2383
2384#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2385#[serde(rename_all = "snake_case")]
2386pub enum ObservabilityKind {
2387 Snapshot,
2388 Stream,
2389}
2390
2391#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2392#[serde(rename_all = "snake_case")]
2393pub enum InternalTransport {
2394 Bulk,
2395}
2396
2397#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2399#[serde(tag = "role", rename_all = "snake_case")]
2400pub enum ConsumerRole {
2401 ToolClient { of: Vec<String> },
2402 LlmClient { via: String, auth: String },
2403 ServiceClient { of: Vec<String> },
2404}
2405
2406#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2408pub struct Bindings {
2409 pub storage: StorageBinding,
2410 pub vault_grants: Vec<VaultGrant>,
2411 pub identity: IdentityBinding,
2412}
2413
2414#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2416pub struct StorageBinding {
2417 pub kind: StorageKind,
2418 pub scope: StorageScope,
2419 pub owns_schema: bool,
2420}
2421
2422#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2423#[serde(rename_all = "snake_case")]
2424pub enum StorageKind {
2425 Sqlite,
2426}
2427
2428#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2429#[serde(rename_all = "snake_case")]
2430pub enum StorageScope {
2431 Project,
2432}
2433
2434#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2435pub struct VaultGrant {
2436 pub secret: String,
2437 pub reason: String,
2438}
2439
2440#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2441pub struct IdentityBinding {
2442 pub requires: Vec<IdentityScope>,
2443 pub optional: Vec<IdentityScope>,
2444}
2445
2446#[cfg(test)]
2447mod tests {
2448 use super::*;
2449 use serde_json::json;
2450
2451 fn aft_manifest_fixture() -> ModuleManifest {
2452 ModuleManifest::builder("aft", "0.39.2")
2453 .trust_tier(Some(TrustTier::FirstParty))
2454 .bindings(Some(Bindings {
2455 storage: StorageBinding {
2456 kind: StorageKind::Sqlite,
2457 scope: StorageScope::Project,
2458 owns_schema: true,
2459 },
2460 vault_grants: vec![VaultGrant {
2461 secret: "provider_api_key".to_string(),
2462 reason: "cortexkit_native auth".to_string(),
2463 }],
2464 identity: IdentityBinding {
2465 requires: vec![IdentityScope::Project],
2466 optional: vec![IdentityScope::Session],
2467 },
2468 }))
2469 .protocol_ver(1)
2470 .provides(vec![ProviderRole::ToolProvider {
2471 tools: vec![
2472 Tool {
2473 name: "read".to_string(),
2474 description: None,
2475 execution_mode: ExecutionMode::Pure,
2476 schema: json!({"type": "object"}),
2477 },
2478 Tool {
2479 name: "grep".to_string(),
2480 description: None,
2481 execution_mode: ExecutionMode::Pure,
2482 schema: json!({"type": "object"}),
2483 },
2484 Tool {
2485 name: "outline".to_string(),
2486 description: None,
2487 execution_mode: ExecutionMode::Pure,
2488 schema: json!({"type": "object"}),
2489 },
2490 Tool {
2491 name: "semantic_search".to_string(),
2492 description: None,
2493 execution_mode: ExecutionMode::Pure,
2494 schema: json!({"type": "object"}),
2495 },
2496 Tool {
2497 name: "edit".to_string(),
2498 description: None,
2499 execution_mode: ExecutionMode::Mutating,
2500 schema: json!({"type": "object"}),
2501 },
2502 Tool {
2503 name: "write".to_string(),
2504 description: None,
2505 execution_mode: ExecutionMode::Mutating,
2506 schema: json!({"type": "object"}),
2507 },
2508 Tool {
2509 name: "bash".to_string(),
2510 description: None,
2511 execution_mode: ExecutionMode::Unfenceable,
2512 schema: json!({"type": "object"}),
2513 },
2514 ],
2515 identity_scope: vec![IdentityScope::Session, IdentityScope::Project],
2516 concurrency: Concurrency::ModuleManaged,
2517 emits_push: true,
2518 sub_supervises: true,
2519 }])
2520 .consumes(vec![ConsumerRole::ServiceClient {
2521 of: vec!["embedding.v2".to_string()],
2522 }])
2523 .build()
2524 }
2525
2526 #[test]
2527 fn serde_round_trips_representative_manifest() {
2528 let manifest = aft_manifest_fixture();
2529 let serialized = serde_json::to_string_pretty(&manifest).unwrap();
2530 let decoded: ModuleManifest = serde_json::from_str(&serialized).unwrap();
2531
2532 assert_eq!(manifest, decoded);
2533 }
2534
2535 #[test]
2536 fn builder_defaults_additions_to_honest_absence_and_round_trips() {
2537 let manifest = ModuleManifest::builder("builder-defaults", "2.0.0").build();
2538
2539 assert_eq!(manifest.module_id, "builder-defaults");
2540 assert_eq!(manifest.module_version, "2.0.0");
2541 assert_eq!(manifest.protocol_ver, PROTOCOL_VERSION);
2542 assert_eq!(manifest.trust_tier, None);
2543 assert!(manifest.provides.is_empty());
2544 assert!(manifest.consumes.is_empty());
2545 assert_eq!(manifest.bindings, None);
2546 assert_eq!(manifest.capabilities, None);
2547 assert_eq!(manifest.self_signals, None);
2548 assert_eq!(manifest.provenance, None);
2549
2550 let encoded = serde_json::to_value(&manifest).expect("builder manifest serializes");
2551 for optional in [
2552 "trust_tier",
2553 "consumes",
2554 "bindings",
2555 "capabilities",
2556 "self_signals",
2557 "provenance",
2558 ] {
2559 assert!(
2560 encoded.get(optional).is_none(),
2561 "an absent {optional} declaration must stay absent on the wire"
2562 );
2563 }
2564 let decoded: ModuleManifest =
2565 serde_json::from_value(encoded).expect("builder manifest round-trips");
2566 assert_eq!(decoded, manifest);
2567 }
2568
2569 #[test]
2570 fn fully_populated_builder_manifest_matches_the_literal_wire_golden() {
2571 let manifest = ModuleManifest::builder("full-builder", "2.0.0")
2572 .trust_tier(Some(TrustTier::Reviewed))
2573 .bindings(Some(Bindings {
2574 storage: StorageBinding {
2575 kind: StorageKind::Sqlite,
2576 scope: StorageScope::Project,
2577 owns_schema: false,
2578 },
2579 vault_grants: Vec::new(),
2580 identity: IdentityBinding {
2581 requires: vec![IdentityScope::Project],
2582 optional: Vec::new(),
2583 },
2584 }))
2585 .provides(vec![ProviderRole::ToolProvider {
2586 tools: vec![Tool {
2587 name: "read".to_string(),
2588 description: None,
2589 execution_mode: ExecutionMode::Pure,
2590 schema: json!({"type": "object"}),
2591 }],
2592 identity_scope: vec![IdentityScope::Project],
2593 concurrency: Concurrency::Serial,
2594 emits_push: false,
2595 sub_supervises: false,
2596 }])
2597 .consumes(vec![ConsumerRole::ServiceClient {
2598 of: vec!["embedding.v2".to_string()],
2599 }])
2600 .capabilities(Some(CapabilityDeclarations {
2601 provides: vec!["embedding/v2".to_string()],
2602 requires: Vec::new(),
2603 must_never_reach: Vec::new(),
2604 }))
2605 .self_signals(Some(vec![SelfSignalDeclaration {
2606 name: "usage_poller".to_string(),
2607 kind: SelfSignalKind::Poller,
2608 effect: SelfSignalEffect::Observe,
2609 anchored_to: SignalAnchor::FixedInterval,
2610 cadence: Some(SignalCadence::Literal {
2611 interval_ms: 60_000,
2612 }),
2613 domain: Some("provider-usage".to_string()),
2614 note: None,
2615 }]))
2616 .provenance(Some(ManifestProvenance {
2617 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
2618 build_git_sha_absence_reason: None,
2619 build_lock_digest: Some(
2620 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
2621 ),
2622 wire_crate_version: Some("0.16.0".to_string()),
2623 store_schema_version: Some("42".to_string()),
2624 launch_nonce_source: None,
2625 }))
2626 .build();
2627
2628 assert_eq!(
2629 serde_json::to_vec(&manifest).expect("builder manifest serializes"),
2630 include_bytes!("../tests/golden/module_manifest_builder_full.json"),
2631 "the builder must preserve the prior fully populated literal wire bytes"
2632 );
2633 }
2634
2635 #[test]
2636 fn old_manifest_with_unread_fields_decodes_and_round_trips_verbatim() {
2637 let raw = include_bytes!("../tests/golden/module_manifest_builder_full.json");
2638 let decoded: ModuleManifest =
2639 serde_json::from_slice(raw).expect("old manifest with all unread fields decodes");
2640
2641 assert_eq!(decoded.trust_tier, Some(TrustTier::Reviewed));
2642 assert!(!decoded.consumes.is_empty());
2643 assert!(decoded.bindings.is_some());
2644
2645 let reencoded = serde_json::to_vec(&decoded).expect("re-encode succeeds");
2646 assert_eq!(
2647 reencoded, raw,
2648 "old manifest relay stays byte-for-byte verbatim"
2649 );
2650 }
2651
2652 #[test]
2653 fn new_manifest_omits_unread_fields_on_wire_and_decodes_cleanly() {
2654 let raw = include_bytes!("../tests/golden/module_manifest_diet.json");
2655 let decoded: ModuleManifest =
2656 serde_json::from_slice(raw).expect("new manifest omitting unread fields decodes");
2657
2658 assert_eq!(decoded.trust_tier, None);
2659 assert!(decoded.consumes.is_empty());
2660 assert_eq!(decoded.bindings, None);
2661
2662 let pretty = format!("{}\n", serde_json::to_string_pretty(&decoded).unwrap());
2663 assert_eq!(
2664 pretty.as_bytes(),
2665 raw,
2666 "new manifest matches golden byte-for-byte without unread keys"
2667 );
2668
2669 let as_val: serde_json::Value = serde_json::to_value(&decoded).unwrap();
2670 assert!(
2671 as_val.get("trust_tier").is_none(),
2672 "no trust_tier on wire for new manifest"
2673 );
2674 assert!(
2675 as_val.get("consumes").is_none(),
2676 "no consumes on wire for empty consumes"
2677 );
2678 assert!(
2679 as_val.get("bindings").is_none(),
2680 "no bindings on wire for new manifest"
2681 );
2682 }
2683
2684 #[test]
2685 fn aft_manifest_fixture_matches_v1_contract() {
2686 let manifest = aft_manifest_fixture();
2687
2688 assert_eq!(manifest.module_id, "aft");
2689 let ProviderRole::ToolProvider {
2690 tools,
2691 identity_scope,
2692 concurrency,
2693 emits_push,
2694 sub_supervises,
2695 } = &manifest.provides[0]
2696 else {
2697 panic!("AFT fixture must expose one tool_provider role");
2698 };
2699
2700 assert_eq!(*concurrency, Concurrency::ModuleManaged);
2701 assert!(*emits_push);
2702 assert!(*sub_supervises);
2703 assert_eq!(
2704 identity_scope,
2705 &vec![IdentityScope::Session, IdentityScope::Project]
2706 );
2707 assert_eq!(
2708 tools
2709 .iter()
2710 .map(|tool| (tool.name.as_str(), tool.execution_mode))
2711 .collect::<Vec<_>>(),
2712 vec![
2713 ("read", ExecutionMode::Pure),
2714 ("grep", ExecutionMode::Pure),
2715 ("outline", ExecutionMode::Pure),
2716 ("semantic_search", ExecutionMode::Pure),
2717 ("edit", ExecutionMode::Mutating),
2718 ("write", ExecutionMode::Mutating),
2719 ("bash", ExecutionMode::Unfenceable),
2720 ]
2721 );
2722 }
2723
2724 #[test]
2725 fn tool_provider_role_tag_serializes_as_snake_case() {
2726 let manifest = aft_manifest_fixture();
2727 let value = serde_json::to_value(&manifest).unwrap();
2728
2729 assert_eq!(value["provides"][0]["role"], "tool_provider");
2730 }
2731
2732 #[test]
2733 fn manifest_without_capabilities_preserves_the_existing_wire_shape() {
2734 let manifest = aft_manifest_fixture();
2735 let encoded = serde_json::to_value(&manifest).expect("manifest serializes");
2736 assert!(encoded.get("capabilities").is_none());
2737
2738 let decoded: ModuleManifest =
2739 serde_json::from_value(encoded).expect("legacy manifest parses");
2740 assert_eq!(decoded.capabilities, None);
2741 }
2742
2743 #[test]
2744 fn capability_identifier_lexical_grammar_accepts_only_pinned_forms() {
2745 for identifier in [
2746 "a/v1",
2747 "credentials-provider/v1",
2748 "a1-b2/v4294967295",
2749 "a123456789012345678901234567890123456789012345678901234567890123/v1",
2750 ] {
2751 assert!(
2752 is_valid_capability_identifier(identifier),
2753 "identifier must be accepted: {identifier}"
2754 );
2755 }
2756
2757 for identifier in [
2758 "credentials-Provider/v1",
2759 "credentials-provider/v01",
2760 "credentials-provider-/v1",
2761 "credentials--provider/v1",
2762 "Credentials-provider/v1",
2763 "credentials-provider/1",
2764 "credentials provider/v1",
2765 "credentials-provider/v0",
2766 "credentials-provider/v4294967296",
2767 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/v1",
2768 ] {
2769 assert!(
2770 !is_valid_capability_identifier(identifier),
2771 "identifier must be rejected: {identifier}"
2772 );
2773 }
2774 }
2775
2776 #[test]
2777 fn capability_grammar_errors_redact_secret_shaped_values() {
2778 let error = validate_manifest_capability_grammar(&json!({
2779 "capabilities": { "provides": ["sk-secret-value/v0"] }
2780 }))
2781 .expect_err("secret-shaped capability identifier is malformed");
2782 assert_eq!(error.field(), "capabilities.provides[0]");
2783 assert_eq!(error.value(), "<redacted>");
2784 assert!(!error.to_string().contains("sk-secret-value"));
2785 }
2786
2787 #[test]
2794 fn provenance_builder_sentinels_become_field_omission() {
2795 for sentinel in [
2796 "unknown",
2797 "UNKNOWN",
2798 "Unknown",
2799 "unavailable",
2800 "none",
2801 "None",
2802 " unknown ",
2803 "",
2804 ] {
2805 let p = build_provenance_from_source(
2806 BuildGitShaSource::Git {
2807 revision: sentinel,
2808 tree_state: GitTreeState::Clean,
2809 },
2810 Some(sentinel),
2811 Some(sentinel),
2812 )
2813 .expect("sentinels are omitted before form validation");
2814 assert_eq!(
2815 (
2816 p.build_git_sha,
2817 p.build_git_sha_absence_reason,
2818 p.build_lock_digest,
2819 p.store_schema_version,
2820 ),
2821 (
2822 None,
2823 Some(BuildGitShaAbsenceReason::NeverDerived),
2824 None,
2825 None,
2826 ),
2827 "sentinel {sentinel:?} must be omitted, not published"
2828 );
2829 }
2830 let real = build_provenance_from_source(
2831 BuildGitShaSource::Git {
2832 revision: "0123456789abcdef0123456789abcdef01234567",
2833 tree_state: GitTreeState::Clean,
2834 },
2835 None,
2836 Some("9"),
2837 )
2838 .expect("canonical build revision is accepted");
2839 assert_eq!(
2840 real.build_git_sha.as_deref(),
2841 Some("0123456789abcdef0123456789abcdef01234567")
2842 );
2843 assert_eq!(real.store_schema_version.as_deref(), Some("9"));
2844 assert_eq!(
2848 real.wire_crate_version.as_deref(),
2849 Some(crate::SUBC_PROTOCOL_CRATE_VERSION)
2850 );
2851 }
2852
2853 #[test]
2854 fn build_provenance_accepts_canonical_sha_and_lock_digest() {
2855 let provenance = build_provenance_from_source(
2856 BuildGitShaSource::Git {
2857 revision: " 0123456789abcdef0123456789abcdef01234567 ",
2858 tree_state: GitTreeState::Clean,
2859 },
2860 Some(" abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789 "),
2861 Some(" schema-v3 "),
2862 )
2863 .expect("canonical build facts are accepted");
2864
2865 assert_eq!(
2866 provenance,
2867 ManifestProvenance {
2868 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
2869 build_git_sha_absence_reason: None,
2870 build_lock_digest: Some(
2871 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
2872 ),
2873 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
2874 store_schema_version: Some("schema-v3".to_string()),
2875 launch_nonce_source: None,
2876 }
2877 );
2878 }
2879
2880 #[test]
2881 fn build_provenance_refuses_an_abbreviated_git_sha() {
2882 let error = build_provenance_from_source(
2883 BuildGitShaSource::Git {
2884 revision: "0123456789ab",
2885 tree_state: GitTreeState::Clean,
2886 },
2887 None,
2888 None,
2889 )
2890 .expect_err("a 12-character abbreviation is not canonical");
2891
2892 assert_eq!(error.field(), "build_git_sha");
2893 assert_eq!(error.length(), 12);
2894 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
2895 assert_eq!(
2896 error.to_string(),
2897 "invalid manifest provenance form: field build_git_sha has length 12; canonical form is exactly 40 lowercase hexadecimal characters"
2898 );
2899 }
2900
2901 #[test]
2902 fn build_provenance_refuses_an_abbreviated_lock_digest() {
2903 let error = build_provenance_from_source(
2904 BuildGitShaSource::NeverDerived,
2905 Some("0123456789abcdef"),
2906 None,
2907 )
2908 .expect_err("a 16-character digest is not canonical");
2909
2910 assert_eq!(error.field(), "build_lock_digest");
2911 assert_eq!(error.length(), 16);
2912 assert_eq!(error.canonical_form(), BUILD_LOCK_DIGEST_CANONICAL_FORM);
2913 }
2914
2915 #[test]
2916 fn build_provenance_refuses_uppercase_hex() {
2917 let uppercase_sha = "A".repeat(40);
2918 let error = build_provenance_from_source(
2919 BuildGitShaSource::Git {
2920 revision: &uppercase_sha,
2921 tree_state: GitTreeState::Clean,
2922 },
2923 None,
2924 None,
2925 )
2926 .expect_err("uppercase hexadecimal is not canonical");
2927
2928 assert_eq!(error.field(), "build_git_sha");
2929 assert_eq!(error.length(), 40);
2930 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
2931 }
2932
2933 #[test]
2934 fn build_provenance_refuses_dirty_revision_stamp_claimed_clean() {
2935 let error = build_provenance_from_source(
2936 BuildGitShaSource::Git {
2937 revision: "0123456789abcdef0123456789abcdef01234567-dirty",
2938 tree_state: GitTreeState::Clean,
2939 },
2940 None,
2941 None,
2942 )
2943 .expect_err("a dirty stamp is not a canonical build revision");
2944
2945 assert_eq!(error.field(), "build_git_sha");
2946 assert_eq!(error.length(), 46);
2947 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
2948 }
2949
2950 #[test]
2951 fn build_provenance_keeps_a_lock_digest_when_identity_is_unavailable() {
2952 let provenance = build_provenance_from_source(
2953 BuildGitShaSource::Git {
2954 revision: "unavailable",
2955 tree_state: GitTreeState::Clean,
2956 },
2957 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"),
2958 None,
2959 )
2960 .expect("sentinel SHA is omitted before the valid lock digest is checked");
2961
2962 assert_eq!(provenance.build_git_sha, None);
2963 assert_eq!(
2964 provenance.build_lock_digest,
2965 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string())
2966 );
2967 assert_eq!(
2968 provenance.wire_crate_version,
2969 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
2970 );
2971 }
2972
2973 #[test]
2974 fn build_provenance_omits_fully_unavailable_inputs() {
2975 let provenance = build_provenance_from_source(
2976 BuildGitShaSource::NeverDerived,
2977 Some(" unavailable "),
2978 Some(" "),
2979 )
2980 .expect("omitted and sentinel inputs are not form errors");
2981
2982 assert_eq!(provenance.build_git_sha, None);
2983 assert_eq!(provenance.build_lock_digest, None);
2984 assert_eq!(provenance.store_schema_version, None);
2985 assert_eq!(
2986 provenance.wire_crate_version,
2987 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
2988 );
2989 }
2990
2991 #[test]
2992 fn legacy_build_provenance_keeps_master_wire_bytes_without_an_absence_reason() {
2993 let revision = "0123456789abcdef0123456789abcdef01234567";
2994 for (input, expected) in [
2995 (
2996 Some(revision),
2997 format!(
2998 r#"{{"build_git_sha":"{revision}","wire_crate_version":"{}"}}"#,
2999 crate::SUBC_PROTOCOL_CRATE_VERSION
3000 ),
3001 ),
3002 (
3003 None,
3004 format!(
3005 r#"{{"wire_crate_version":"{}"}}"#,
3006 crate::SUBC_PROTOCOL_CRATE_VERSION
3007 ),
3008 ),
3009 (
3010 Some("unknown"),
3011 format!(
3012 r#"{{"wire_crate_version":"{}"}}"#,
3013 crate::SUBC_PROTOCOL_CRATE_VERSION
3014 ),
3015 ),
3016 ] {
3017 let provenance = build_provenance(input, None, None)
3018 .expect("the legacy build facts remain constructible");
3019 assert_eq!(provenance.build_git_sha_absence_reason, None);
3020 assert_eq!(
3021 serde_json::to_string(&provenance).expect("legacy provenance serializes"),
3022 expected
3023 );
3024 }
3025 }
3026
3027 #[test]
3028 fn build_provenance_derives_git_sha_absence_from_the_stamping_inputs() {
3029 let revision = "0123456789abcdef0123456789abcdef01234567";
3030 let cases = [
3031 (
3032 BuildGitShaSource::Git {
3033 revision,
3034 tree_state: GitTreeState::Clean,
3035 },
3036 Some(revision),
3037 None,
3038 ),
3039 (
3040 BuildGitShaSource::Git {
3041 revision,
3042 tree_state: GitTreeState::Dirty,
3043 },
3044 None,
3045 Some(BuildGitShaAbsenceReason::DeclinedDirty),
3046 ),
3047 (
3048 BuildGitShaSource::NeverDerived,
3049 None,
3050 Some(BuildGitShaAbsenceReason::NeverDerived),
3051 ),
3052 (
3053 BuildGitShaSource::NoGitDir,
3054 None,
3055 Some(BuildGitShaAbsenceReason::NoGitDir),
3056 ),
3057 ];
3058
3059 for (source, expected_sha, expected_reason) in cases {
3060 let provenance = build_provenance_from_source(source, None, None)
3061 .expect("every stamping state constructs honest provenance");
3062 assert_eq!(provenance.build_git_sha.as_deref(), expected_sha);
3063 assert_eq!(provenance.build_git_sha_absence_reason, expected_reason);
3064 }
3065 }
3066
3067 #[test]
3068 fn unknown_git_sha_absence_reason_round_trips_byte_faithfully() {
3069 let wire = format!(
3070 r#"{{"build_git_sha_absence_reason":"future_stamper_state","wire_crate_version":"{}"}}"#,
3071 crate::SUBC_PROTOCOL_CRATE_VERSION
3072 );
3073 let provenance: ManifestProvenance =
3074 serde_json::from_str(&wire).expect("future absence reasons remain readable");
3075
3076 assert_eq!(
3077 provenance.build_git_sha_absence_reason,
3078 Some(BuildGitShaAbsenceReason::ForwardCompatibleUnknown(
3079 "future_stamper_state".to_string()
3080 ))
3081 );
3082 assert_eq!(
3083 serde_json::to_string(&provenance).expect("future absence reason reserializes"),
3084 wire
3085 );
3086 }
3087
3088 #[test]
3089 fn provenance_rejects_an_absence_reason_beside_a_declared_commit() {
3090 let error = serde_json::from_value::<ManifestProvenance>(json!({
3091 "build_git_sha": "0123456789abcdef0123456789abcdef01234567",
3092 "build_git_sha_absence_reason": "declined_dirty"
3093 }))
3094 .expect_err("a declared commit cannot also claim an absence reason");
3095
3096 assert!(error.to_string().contains(
3097 "build_git_sha_absence_reason has must be omitted when build_git_sha is present"
3098 ));
3099 }
3100
3101 #[test]
3102 fn rich_ui_descriptor_is_optional_and_round_trips_when_present() {
3103 let manifest = ModuleManifest::builder("provider", "1.0.0").build();
3104 assert_eq!(
3105 serde_json::to_string(&manifest).unwrap(),
3106 r#"{"module_id":"provider","module_version":"1.0.0","protocol_ver":2,"provides":[]}"#
3107 );
3108
3109 let descriptor = RichUiDescriptor::new(
3110 "ckios.richui.manifest/1",
3111 format!("sha256:{}", "a".repeat(64)),
3112 128,
3113 2,
3114 );
3115 let manifest = ModuleManifest::builder("provider", "1.0.0")
3116 .rich_ui(Some(descriptor.clone()))
3117 .build();
3118 let wire = serde_json::to_string(&manifest).unwrap();
3119 assert!(wire.contains("\"rich_ui\":{\"schema\":\"ckios.richui.manifest/1\""));
3120 assert_eq!(
3121 serde_json::from_str::<ModuleManifest>(&wire)
3122 .unwrap()
3123 .rich_ui,
3124 Some(descriptor)
3125 );
3126 }
3127
3128 #[test]
3129 fn rich_ui_descriptor_validation_names_each_invalid_field() {
3130 let good = json!({
3131 "schema": "ckios.richui.manifest/1",
3132 "manifest_digest": format!("sha256:{}", "a".repeat(64)),
3133 "bytes": 1,
3134 "chunks": 1
3135 });
3136 let hello = json!({"manifest": {"rich_ui": good.clone()}});
3137 assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
3138
3139 for (field, value) in [
3140 ("schema", json!("bad schema")),
3141 (
3142 "manifest_digest",
3143 json!(format!("sha256:{}", "A".repeat(64))),
3144 ),
3145 ("bytes", json!(0)),
3146 ("chunks", json!(1025)),
3147 ] {
3148 let mut invalid = hello.clone();
3149 invalid["manifest"]["rich_ui"][field] = value;
3150 let error = validate_hello_rich_ui_descriptor(&invalid)
3151 .expect_err("an invalid descriptor field must be refused");
3152 assert_eq!(error.field(), format!("rich_ui.{field}"));
3153 }
3154
3155 let mut hello = hello;
3156 hello["manifest"]["rich_ui"] = Value::Null;
3157 let error = validate_hello_rich_ui_descriptor(&hello)
3158 .expect_err("null is not an absent descriptor");
3159 assert_eq!(error.field(), "rich_ui");
3160 }
3161
3162 #[test]
3163 fn rich_ui_descriptor_validation_accepts_inclusive_bounds() {
3164 let hello = json!({"manifest": {"rich_ui": {
3165 "schema": "a".repeat(64),
3166 "manifest_digest": format!("sha256:{}", "f".repeat(64)),
3167 "bytes": 16_777_216,
3168 "chunks": 1024
3169 }}});
3170 assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
3171 }
3172}