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
19#[derive(Serialize, Debug, Clone, PartialEq)]
26#[non_exhaustive]
27pub struct ModuleManifest {
28 pub module_id: String,
29 pub module_version: String,
30 pub protocol_ver: u8,
31 #[serde(default, skip_serializing_if = "Option::is_none")]
32 pub trust_tier: Option<TrustTier>,
33 #[serde(default, skip_serializing_if = "Option::is_none")]
40 pub ready: Option<bool>,
41 pub provides: Vec<ProviderRole>,
44 #[serde(default, skip_serializing_if = "Vec::is_empty")]
45 pub consumes: Vec<ConsumerRole>,
46 #[serde(default, skip_serializing_if = "Option::is_none")]
47 pub bindings: Option<Bindings>,
48 #[serde(default, skip_serializing_if = "Option::is_none")]
54 pub capabilities: Option<CapabilityDeclarations>,
55 #[serde(default, skip_serializing_if = "Option::is_none")]
69 pub events: Option<Vec<EventDeclaration>>,
70 #[serde(default, skip_serializing_if = "Option::is_none")]
105 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
106 #[serde(default, skip_serializing_if = "Option::is_none")]
107 pub provenance: Option<ManifestProvenance>,
108 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
113 pub operation_delivery: BTreeMap<String, OperationDelivery>,
114 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
117 pub operation_payload: BTreeMap<String, OperationPayload>,
118 #[serde(default, skip_serializing_if = "Option::is_none")]
123 pub rich_ui: Option<RichUiDescriptor>,
124}
125
126#[derive(Debug, Clone)]
128pub struct ModuleManifestBuilder {
129 module_id: String,
130 module_version: String,
131 protocol_ver: u8,
132 trust_tier: Option<TrustTier>,
133 ready: Option<bool>,
134 provides: Vec<ProviderRole>,
135 consumes: Vec<ConsumerRole>,
136 bindings: Option<Bindings>,
137 capabilities: Option<CapabilityDeclarations>,
138 events: Option<Vec<EventDeclaration>>,
139 self_signals: Option<Vec<SelfSignalDeclaration>>,
140 provenance: Option<ManifestProvenance>,
141 operation_delivery: BTreeMap<String, OperationDelivery>,
142 operation_payload: BTreeMap<String, OperationPayload>,
143 rich_ui: Option<RichUiDescriptor>,
144}
145
146impl ModuleManifest {
147 pub fn builder(
155 module_id: impl Into<String>,
156 module_version: impl Into<String>,
157 ) -> ModuleManifestBuilder {
158 ModuleManifestBuilder {
159 module_id: module_id.into(),
160 module_version: module_version.into(),
161 protocol_ver: PROTOCOL_VERSION,
162 trust_tier: None,
163 ready: None,
164 provides: Vec::new(),
165 consumes: Vec::new(),
166 bindings: None,
167 capabilities: None,
168 events: None,
169 self_signals: None,
170 provenance: None,
171 operation_delivery: BTreeMap::new(),
172 operation_payload: BTreeMap::new(),
173 rich_ui: None,
174 }
175 }
176
177 pub fn is_watch_operation(&self, name: &str) -> bool {
182 self.operation_delivery
183 .get(name)
184 .is_some_and(OperationDelivery::is_watch)
185 && self.provides.iter().any(|role| match role {
186 ProviderRole::ManagementSurface { operations, .. } => operations
187 .iter()
188 .any(|op| op.name == name && op.kind == ManagementOperationKind::Query),
189 _ => false,
190 })
191 }
192}
193
194impl ModuleManifestBuilder {
195 pub fn protocol_ver(mut self, protocol_ver: u8) -> Self {
197 self.protocol_ver = protocol_ver;
198 self
199 }
200
201 pub fn trust_tier(mut self, trust_tier: Option<TrustTier>) -> Self {
205 self.trust_tier = trust_tier;
206 self
207 }
208
209 pub fn ready(mut self, ready: bool) -> Self {
211 self.ready = Some(ready);
212 self
213 }
214
215 pub fn provides(mut self, provides: Vec<ProviderRole>) -> Self {
217 self.provides = provides;
218 self
219 }
220
221 pub fn consumes(mut self, consumes: Vec<ConsumerRole>) -> Self {
223 self.consumes = consumes;
224 self
225 }
226
227 pub fn bindings(mut self, bindings: Option<Bindings>) -> Self {
231 self.bindings = bindings;
232 self
233 }
234
235 pub fn capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
237 self.capabilities = capabilities;
238 self
239 }
240
241 pub fn events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
243 self.events = events;
244 self
245 }
246
247 pub fn self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
249 self.self_signals = self_signals;
250 self
251 }
252
253 pub fn provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
255 self.provenance = provenance;
256 self
257 }
258
259 pub fn operation_delivery(
261 mut self,
262 operation_delivery: BTreeMap<String, OperationDelivery>,
263 ) -> Self {
264 self.operation_delivery = operation_delivery;
265 self
266 }
267
268 pub fn operation_payload(
270 mut self,
271 operation_payload: BTreeMap<String, OperationPayload>,
272 ) -> Self {
273 self.operation_payload = operation_payload;
274 self
275 }
276
277 pub fn rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
279 self.rich_ui = rich_ui;
280 self
281 }
282
283 pub fn build(self) -> ModuleManifest {
285 ModuleManifest {
286 module_id: self.module_id,
287 module_version: self.module_version,
288 protocol_ver: self.protocol_ver,
289 trust_tier: self.trust_tier,
290 ready: self.ready,
291 provides: self.provides,
292 consumes: self.consumes,
293 bindings: self.bindings,
294 capabilities: self.capabilities,
295 events: self.events,
296 self_signals: self.self_signals,
297 provenance: self.provenance,
298 operation_delivery: self.operation_delivery,
299 operation_payload: self.operation_payload,
300 rich_ui: self.rich_ui,
301 }
302 }
303}
304
305#[derive(Deserialize)]
323struct ModuleManifestWire {
324 module_id: String,
325 module_version: String,
326 protocol_ver: u8,
327 #[serde(default)]
328 trust_tier: Option<TrustTier>,
329 #[serde(default)]
330 ready: Option<bool>,
331 provides: Vec<ProviderRole>,
332 #[serde(default)]
333 consumes: Vec<ConsumerRole>,
334 #[serde(default)]
335 bindings: Option<Bindings>,
336 #[serde(default)]
337 capabilities: Option<CapabilityDeclarations>,
338 #[serde(default)]
339 events: Option<Value>,
340 #[serde(default)]
341 self_signals: Option<Vec<SelfSignalDeclaration>>,
342 #[serde(default)]
343 provenance: Option<ManifestProvenance>,
344 #[serde(default)]
345 operation_delivery: Option<Value>,
346 #[serde(default)]
347 operation_payload: BTreeMap<String, OperationPayload>,
348 #[serde(default)]
349 rich_ui: Option<RichUiDescriptor>,
350 #[serde(default)]
354 runtime_computed: Option<Value>,
355}
356
357impl<'de> Deserialize<'de> for ModuleManifest {
358 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
359 where
360 D: Deserializer<'de>,
361 {
362 let wire = ModuleManifestWire::deserialize(deserializer)?;
363 validate_runtime_computed(wire.runtime_computed.as_ref(), "runtime_computed")
364 .map_err(D::Error::custom)?;
365 validate_events_value(wire.events.as_ref()).map_err(D::Error::custom)?;
366 let events = wire
367 .events
368 .map(serde_json::from_value)
369 .transpose()
370 .map_err(D::Error::custom)?;
371 let mut builder = Self::builder(wire.module_id, wire.module_version)
372 .protocol_ver(wire.protocol_ver)
373 .trust_tier(wire.trust_tier);
374 if let Some(ready) = wire.ready {
375 builder = builder.ready(ready);
376 }
377 let manifest = builder
378 .provides(wire.provides)
379 .consumes(wire.consumes)
380 .bindings(wire.bindings)
381 .capabilities(wire.capabilities)
382 .events(events)
383 .self_signals(wire.self_signals)
384 .provenance(wire.provenance)
385 .operation_delivery(
386 wire.operation_delivery
387 .and_then(|value| serde_json::from_value(value).ok())
388 .unwrap_or_default(),
389 )
390 .rich_ui(wire.rich_ui)
391 .operation_payload(wire.operation_payload)
392 .build();
393 manifest
394 .validate_operation_payload()
395 .map_err(D::Error::custom)?;
396 manifest
397 .validate_capability_grammar()
398 .map_err(D::Error::custom)?;
399 if let Some(rich_ui) = &manifest.rich_ui {
400 rich_ui.validate().map_err(D::Error::custom)?;
401 }
402 Ok(manifest)
403 }
404}
405
406#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
412#[non_exhaustive]
413pub struct RichUiDescriptor {
414 pub schema: String,
416 pub manifest_digest: String,
418 pub bytes: u64,
420 pub chunks: u32,
422}
423
424impl RichUiDescriptor {
425 pub fn new(
427 schema: impl Into<String>,
428 manifest_digest: impl Into<String>,
429 bytes: u64,
430 chunks: u32,
431 ) -> Self {
432 Self {
433 schema: schema.into(),
434 manifest_digest: manifest_digest.into(),
435 bytes,
436 chunks,
437 }
438 }
439
440 pub fn validate(&self) -> Result<(), RichUiDescriptorError> {
442 validate_rich_ui_fields(
443 &self.schema,
444 &self.manifest_digest,
445 self.bytes,
446 u64::from(self.chunks),
447 )
448 }
449}
450
451#[derive(Debug, Clone, PartialEq, Eq)]
453#[non_exhaustive]
454pub struct RichUiDescriptorError {
455 field: String,
456 reason: &'static str,
457}
458
459impl RichUiDescriptorError {
460 fn new(field: impl Into<String>, reason: &'static str) -> Self {
461 Self {
462 field: field.into(),
463 reason,
464 }
465 }
466
467 pub fn field(&self) -> &str {
469 &self.field
470 }
471}
472
473impl fmt::Display for RichUiDescriptorError {
474 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
475 write!(
476 f,
477 "invalid rich_ui descriptor: field {} {}",
478 self.field, self.reason
479 )
480 }
481}
482
483impl std::error::Error for RichUiDescriptorError {}
484
485pub fn validate_hello_rich_ui_descriptor(hello: &Value) -> Result<(), RichUiDescriptorError> {
487 let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
488 return Ok(());
489 };
490 let Some(value) = manifest.get("rich_ui") else {
491 return Ok(());
492 };
493 validate_rich_ui_descriptor_value(value)
494}
495
496fn validate_rich_ui_descriptor_value(value: &Value) -> Result<(), RichUiDescriptorError> {
497 let descriptor = value
498 .as_object()
499 .ok_or_else(|| RichUiDescriptorError::new("rich_ui", "must be an object"))?;
500 let schema = descriptor
501 .get("schema")
502 .and_then(Value::as_str)
503 .ok_or_else(|| RichUiDescriptorError::new("rich_ui.schema", "must be a string"))?;
504 let digest = descriptor
505 .get("manifest_digest")
506 .and_then(Value::as_str)
507 .ok_or_else(|| RichUiDescriptorError::new("rich_ui.manifest_digest", "must be a string"))?;
508 let bytes = descriptor
509 .get("bytes")
510 .and_then(Value::as_u64)
511 .ok_or_else(|| {
512 RichUiDescriptorError::new("rich_ui.bytes", "must be an integer from 1 to 16777216")
513 })?;
514 let chunks = descriptor
515 .get("chunks")
516 .and_then(Value::as_u64)
517 .ok_or_else(|| {
518 RichUiDescriptorError::new("rich_ui.chunks", "must be an integer from 1 to 1024")
519 })?;
520 validate_rich_ui_fields(schema, digest, bytes, chunks)
521}
522
523fn validate_rich_ui_fields(
524 schema: &str,
525 digest: &str,
526 bytes: u64,
527 chunks: u64,
528) -> Result<(), RichUiDescriptorError> {
529 if !(1..=64).contains(&schema.len())
530 || !schema.bytes().all(|byte| {
531 byte.is_ascii_lowercase()
532 || byte.is_ascii_digit()
533 || matches!(byte, b'.' | b'_' | b'/' | b'-')
534 })
535 {
536 return Err(RichUiDescriptorError::new(
537 "rich_ui.schema",
538 "must be 1 to 64 bytes of [a-z0-9._/-]",
539 ));
540 }
541 if !digest.strip_prefix("sha256:").is_some_and(|hex| {
542 hex.len() == 64
543 && hex
544 .bytes()
545 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
546 }) {
547 return Err(RichUiDescriptorError::new(
548 "rich_ui.manifest_digest",
549 "must be sha256: followed by 64 lowercase hexadecimal characters",
550 ));
551 }
552 if !(1..=16_777_216).contains(&bytes) {
553 return Err(RichUiDescriptorError::new(
554 "rich_ui.bytes",
555 "must be an integer from 1 to 16777216",
556 ));
557 }
558 if !(1..=1_024).contains(&chunks) {
559 return Err(RichUiDescriptorError::new(
560 "rich_ui.chunks",
561 "must be an integer from 1 to 1024",
562 ));
563 }
564 Ok(())
565}
566
567pub const CAP_CATALOG_EVENTS_V1: &str = "catalog-events/v1";
573
574pub const CAP_SCOPE_BIND_PROOF_V1: &str = "scope-bind-proof/v1";
578
579pub const CAP_SCOPE_BIND_PROOF_V2: &str = "scope-bind-proof/v2";
583
584pub const CAP_SCOPE_REPLACE_IF_IDLE_V1: &str = "scope-replace-if-idle/v1";
586
587#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
589#[non_exhaustive]
590pub struct EventDeclaration {
591 pub name: String,
598 pub version: u32,
600 pub headers: Vec<String>,
603 #[serde(default, skip_serializing_if = "Option::is_none")]
605 pub summary: Option<String>,
606}
607
608impl EventDeclaration {
609 pub fn new(name: impl Into<String>, version: u32) -> Self {
612 Self {
613 name: name.into(),
614 version,
615 headers: Vec::new(),
616 summary: None,
617 }
618 }
619
620 pub fn with_headers(mut self, headers: Vec<String>) -> Self {
622 self.headers = headers;
623 self
624 }
625
626 pub fn with_summary(mut self, summary: Option<String>) -> Self {
628 self.summary = summary;
629 self
630 }
631}
632
633#[derive(Debug, Clone, PartialEq, Eq)]
635#[non_exhaustive]
636pub struct EventDeclarationError {
637 field: String,
638 reason: &'static str,
639}
640
641impl EventDeclarationError {
642 fn new(field: impl Into<String>, reason: &'static str) -> Self {
643 Self {
644 field: field.into(),
645 reason,
646 }
647 }
648
649 pub fn field(&self) -> &str {
651 &self.field
652 }
653}
654
655impl fmt::Display for EventDeclarationError {
656 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
657 write!(
658 f,
659 "invalid event declaration: field {} {}",
660 self.field, self.reason
661 )
662 }
663}
664
665impl std::error::Error for EventDeclarationError {}
666
667pub fn validate_hello_event_declarations(hello: &Value) -> Result<(), EventDeclarationError> {
669 validate_events_value(
670 hello
671 .get("manifest")
672 .and_then(|manifest| manifest.get("events")),
673 )
674}
675
676fn is_valid_event_name(name: &str) -> bool {
679 let level_count = name.split('.').count();
680 (1..=4).contains(&level_count)
681 && name.split('.').all(|level| {
682 if level.is_empty() {
683 return false;
684 }
685 let first = level.as_bytes()[0];
686 (1..=63).contains(&level.len())
687 && (first.is_ascii_lowercase() || first.is_ascii_digit())
688 && level
689 .bytes()
690 .skip(1)
691 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
692 && !level.strip_prefix('v').is_some_and(|digits| {
693 !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit())
694 })
695 })
696}
697
698fn validate_events_value(value: Option<&Value>) -> Result<(), EventDeclarationError> {
699 let Some(value) = value.filter(|value| !value.is_null()) else {
700 return Ok(());
701 };
702 let entries = value
703 .as_array()
704 .ok_or_else(|| EventDeclarationError::new("events", "must be a list"))?;
705 if entries.len() > 64 {
706 return Err(EventDeclarationError::new(
707 "events",
708 "must contain at most 64 declarations",
709 ));
710 }
711 let mut pairs = HashSet::new();
712 for (index, entry) in entries.iter().enumerate() {
713 let field = format!("events[{index}]");
714 let entry = entry
715 .as_object()
716 .ok_or_else(|| EventDeclarationError::new(&field, "must be an object"))?;
717 let name_field = format!("{field}.name");
718 let name = entry
719 .get("name")
720 .and_then(Value::as_str)
721 .ok_or_else(|| EventDeclarationError::new(&name_field, "must be a string"))?;
722 if !is_valid_event_name(name) {
723 return Err(EventDeclarationError::new(
724 name_field,
725 "must contain one to four valid dot-separated event-name levels",
726 ));
727 }
728 let version = entry
729 .get("version")
730 .and_then(Value::as_u64)
731 .filter(|version| (1..=u32::MAX as u64).contains(version))
732 .ok_or_else(|| {
733 EventDeclarationError::new(
734 format!("{field}.version"),
735 "must be an integer between 1 and u32::MAX",
736 )
737 })?;
738 if !pairs.insert((name, version)) {
739 return Err(EventDeclarationError::new(
740 &field,
741 "duplicates an event (name, version) pair",
742 ));
743 }
744 let headers_field = format!("{field}.headers");
745 let headers = entry
746 .get("headers")
747 .and_then(Value::as_array)
748 .ok_or_else(|| EventDeclarationError::new(&headers_field, "must be a list"))?;
749 if headers.len() > 16 {
750 return Err(EventDeclarationError::new(
751 headers_field,
752 "must contain at most 16 headers",
753 ));
754 }
755 let mut names = HashSet::new();
756 for (header_index, header) in headers.iter().enumerate() {
757 let header_field = format!("{headers_field}[{header_index}]");
758 let header = header
759 .as_str()
760 .ok_or_else(|| EventDeclarationError::new(&header_field, "must be a string"))?;
761 if !(1..=32).contains(&header.len())
762 || !header.as_bytes()[0].is_ascii_lowercase()
763 || !header
764 .bytes()
765 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
766 {
767 return Err(EventDeclarationError::new(
768 header_field,
769 "must match [a-z][a-z0-9_]{0,31}",
770 ));
771 }
772 if !names.insert(header) {
773 return Err(EventDeclarationError::new(
774 header_field,
775 "duplicates a header name",
776 ));
777 }
778 }
779 if let Some(summary) = entry.get("summary").filter(|value| !value.is_null()) {
780 let summary_field = format!("{field}.summary");
781 let summary = summary
782 .as_str()
783 .ok_or_else(|| EventDeclarationError::new(&summary_field, "must be a string"))?;
784 if summary.chars().count() > 200 || summary.chars().any(char::is_control) {
785 return Err(EventDeclarationError::new(
786 summary_field,
787 "must contain at most 200 characters and no control characters",
788 ));
789 }
790 }
791 }
792 Ok(())
793}
794
795#[derive(Debug, Clone, PartialEq, Eq)]
797pub struct SelfSignalDeclarationError {
798 module_id: String,
799 entry_index: usize,
800 field: &'static str,
801}
802
803impl fmt::Display for SelfSignalDeclarationError {
804 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
805 write!(
806 f,
807 "module_id '{}' self_signals[{}] is missing required field '{}'",
808 self.module_id.escape_debug(),
809 self.entry_index,
810 self.field
811 )
812 }
813}
814
815pub fn validate_hello_self_signal_declarations(
822 hello: &Value,
823) -> Result<(), SelfSignalDeclarationError> {
824 let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
825 return Ok(());
826 };
827 let module_id = manifest
828 .get("module_id")
829 .and_then(Value::as_str)
830 .unwrap_or("<unknown>");
831 let Some(entries) = manifest.get("self_signals").and_then(Value::as_array) else {
832 return Ok(());
833 };
834
835 for (entry_index, entry) in entries.iter().enumerate() {
836 let Some(entry) = entry.as_object() else {
837 continue;
838 };
839 for field in ["effect", "anchored_to"] {
840 if !entry.contains_key(field) {
841 return Err(SelfSignalDeclarationError {
842 module_id: module_id.to_string(),
843 entry_index,
844 field,
845 });
846 }
847 }
848 }
849 Ok(())
850}
851
852#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
854#[serde(deny_unknown_fields)]
855pub struct CapabilityDeclarations {
856 #[serde(default)]
857 pub provides: Vec<String>,
858 #[serde(default)]
859 pub requires: Vec<CapabilityRequirement>,
860 #[serde(default)]
861 pub must_never_reach: Vec<String>,
862}
863
864#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
866pub struct SelfSignalDeclaration {
867 pub name: String,
869 pub kind: SelfSignalKind,
897 pub effect: SelfSignalEffect,
899 pub anchored_to: SignalAnchor,
901 #[serde(default, skip_serializing_if = "Option::is_none")]
908 pub cadence: Option<SignalCadence>,
909 #[serde(default, skip_serializing_if = "Option::is_none")]
911 pub domain: Option<String>,
912 #[serde(default, skip_serializing_if = "Option::is_none")]
913 pub note: Option<String>,
914}
915
916#[derive(Debug, Clone, PartialEq, Eq)]
918pub enum SelfSignalKind {
919 Keepalive,
920 Busy,
922 Poller,
923 Cron,
924 Sweep,
925 Watchdog,
926 Heartbeat,
927 Other(String),
928}
929
930impl SelfSignalKind {
931 fn wire_name(&self) -> &str {
932 match self {
933 Self::Keepalive => "keepalive",
934 Self::Busy => "busy",
935 Self::Poller => "poller",
936 Self::Cron => "cron",
937 Self::Sweep => "sweep",
938 Self::Watchdog => "watchdog",
939 Self::Heartbeat => "heartbeat",
940 Self::Other(value) => value,
941 }
942 }
943}
944
945impl Serialize for SelfSignalKind {
946 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
947 where
948 S: serde::Serializer,
949 {
950 serializer.serialize_str(self.wire_name())
951 }
952}
953
954impl<'de> Deserialize<'de> for SelfSignalKind {
955 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
956 where
957 D: Deserializer<'de>,
958 {
959 let value = String::deserialize(deserializer)?;
960 Ok(match value.as_str() {
961 "keepalive" => Self::Keepalive,
962 "busy" => Self::Busy,
963 "poller" => Self::Poller,
964 "cron" => Self::Cron,
965 "sweep" => Self::Sweep,
966 "watchdog" => Self::Watchdog,
967 "heartbeat" => Self::Heartbeat,
968 _ => Self::Other(value),
969 })
970 }
971}
972
973#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
975#[serde(rename_all = "lowercase")]
976pub enum SelfSignalEffect {
977 Observe,
978 Mutate,
979}
980
981#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
983#[serde(rename_all = "snake_case")]
984pub enum SignalAnchor {
985 FixedInterval,
988 Event { event: String },
991 HealthGauges { gauges: Vec<String> },
993}
994
995#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
997#[serde(rename_all = "snake_case")]
998pub enum SignalCadence {
999 Literal { interval_ms: u64 },
1000 Derived { source: String },
1001}
1002
1003#[derive(Serialize, Debug, Clone, Default, PartialEq, Eq)]
1080#[non_exhaustive]
1081pub struct ManifestProvenance {
1082 #[serde(default, skip_serializing_if = "Option::is_none")]
1083 pub build_git_sha: Option<String>,
1084 #[serde(default, skip_serializing_if = "Option::is_none")]
1088 pub build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1089 #[serde(default, skip_serializing_if = "Option::is_none")]
1090 pub build_lock_digest: Option<String>,
1091 #[serde(default, skip_serializing_if = "Option::is_none")]
1100 pub wire_crate_version: Option<String>,
1101 #[serde(default, skip_serializing_if = "Option::is_none")]
1102 pub store_schema_version: Option<String>,
1103 #[serde(default, skip_serializing_if = "Option::is_none")]
1109 pub launch_nonce_source: Option<LaunchNonceSource>,
1110}
1111
1112#[derive(Debug, Clone, PartialEq, Eq)]
1119#[non_exhaustive]
1120pub enum LaunchNonceSource {
1121 Fd,
1123 Pipe,
1125 Env,
1127 ForwardCompatibleUnknown(String),
1128}
1129
1130impl LaunchNonceSource {
1131 pub fn wire_name(&self) -> &str {
1133 match self {
1134 Self::Fd => "fd",
1135 Self::Pipe => "pipe",
1136 Self::Env => "env",
1137 Self::ForwardCompatibleUnknown(value) => value,
1138 }
1139 }
1140
1141 pub fn from_wire_name(value: &str) -> Self {
1143 match value {
1144 "fd" => Self::Fd,
1145 "pipe" => Self::Pipe,
1146 "env" => Self::Env,
1147 _ => Self::ForwardCompatibleUnknown(value.to_string()),
1148 }
1149 }
1150}
1151
1152impl Serialize for LaunchNonceSource {
1153 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1154 where
1155 S: serde::Serializer,
1156 {
1157 serializer.serialize_str(self.wire_name())
1158 }
1159}
1160
1161impl<'de> Deserialize<'de> for LaunchNonceSource {
1162 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1163 where
1164 D: serde::Deserializer<'de>,
1165 {
1166 let value = String::deserialize(deserializer)?;
1167 Ok(Self::from_wire_name(&value))
1168 }
1169}
1170
1171#[derive(Debug, Clone, PartialEq, Eq)]
1176pub enum BuildGitShaAbsenceReason {
1177 DeclinedDirty,
1178 NeverDerived,
1179 NoGitDir,
1180 ForwardCompatibleUnknown(String),
1181}
1182
1183impl BuildGitShaAbsenceReason {
1184 fn wire_name(&self) -> &str {
1185 match self {
1186 Self::DeclinedDirty => "declined_dirty",
1187 Self::NeverDerived => "never_derived",
1188 Self::NoGitDir => "no_git_dir",
1189 Self::ForwardCompatibleUnknown(value) => value,
1190 }
1191 }
1192}
1193
1194impl Serialize for BuildGitShaAbsenceReason {
1195 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1196 where
1197 S: serde::Serializer,
1198 {
1199 serializer.serialize_str(self.wire_name())
1200 }
1201}
1202
1203impl<'de> Deserialize<'de> for BuildGitShaAbsenceReason {
1204 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1205 where
1206 D: serde::Deserializer<'de>,
1207 {
1208 let value = String::deserialize(deserializer)?;
1209 Ok(match value.as_str() {
1210 "declined_dirty" => Self::DeclinedDirty,
1211 "never_derived" => Self::NeverDerived,
1212 "no_git_dir" => Self::NoGitDir,
1213 _ => Self::ForwardCompatibleUnknown(value),
1214 })
1215 }
1216}
1217
1218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1220pub enum GitTreeState {
1221 Clean,
1222 Dirty,
1223}
1224
1225#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1230pub enum BuildGitShaSource<'a> {
1231 Git {
1232 revision: &'a str,
1233 tree_state: GitTreeState,
1234 },
1235 NeverDerived,
1236 NoGitDir,
1237}
1238
1239pub fn attestable_commit(revision: &str, tree_state: GitTreeState) -> Option<&str> {
1243 match tree_state {
1244 GitTreeState::Clean => Some(revision),
1245 GitTreeState::Dirty => None,
1246 }
1247}
1248
1249const MAX_PROVENANCE_VALUE_BYTES: usize = 128;
1250const BUILD_GIT_SHA_CANONICAL_FORM: &str = "exactly 40 lowercase hexadecimal characters";
1251const BUILD_LOCK_DIGEST_CANONICAL_FORM: &str = "exactly 64 lowercase hexadecimal characters";
1252
1253#[derive(Deserialize)]
1254struct ManifestProvenanceWire {
1255 #[serde(default)]
1256 build_git_sha: Option<String>,
1257 #[serde(default)]
1258 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1259 #[serde(default)]
1260 build_lock_digest: Option<String>,
1261 #[serde(default)]
1262 wire_crate_version: Option<String>,
1263 #[serde(default)]
1264 store_schema_version: Option<String>,
1265 #[serde(default)]
1266 launch_nonce_source: Option<LaunchNonceSource>,
1267}
1268
1269impl<'de> Deserialize<'de> for ManifestProvenance {
1270 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1271 where
1272 D: Deserializer<'de>,
1273 {
1274 let wire = ManifestProvenanceWire::deserialize(deserializer)?;
1275 let provenance = Self {
1276 build_git_sha: wire.build_git_sha,
1277 build_git_sha_absence_reason: wire.build_git_sha_absence_reason,
1278 build_lock_digest: wire.build_lock_digest,
1279 wire_crate_version: wire.wire_crate_version,
1280 store_schema_version: wire.store_schema_version,
1281 launch_nonce_source: wire.launch_nonce_source,
1282 };
1283 provenance.validate().map_err(D::Error::custom)?;
1284 Ok(provenance)
1285 }
1286}
1287
1288#[derive(Debug, Clone, PartialEq, Eq)]
1290pub struct ProvenanceFormError {
1291 field: &'static str,
1292 length: usize,
1293 canonical_form: &'static str,
1294}
1295
1296impl ProvenanceFormError {
1297 fn new(field: &'static str, length: usize, canonical_form: &'static str) -> Self {
1298 Self {
1299 field,
1300 length,
1301 canonical_form,
1302 }
1303 }
1304
1305 pub fn field(&self) -> &str {
1307 self.field
1308 }
1309
1310 pub fn length(&self) -> usize {
1312 self.length
1313 }
1314
1315 pub fn canonical_form(&self) -> &str {
1317 self.canonical_form
1318 }
1319}
1320
1321impl fmt::Display for ProvenanceFormError {
1322 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1323 write!(
1324 f,
1325 "invalid manifest provenance form: field {} has length {}; canonical form is {}",
1326 self.field, self.length, self.canonical_form
1327 )
1328 }
1329}
1330
1331impl std::error::Error for ProvenanceFormError {}
1332
1333#[derive(Debug, Clone, PartialEq, Eq)]
1334pub struct ManifestProvenanceError {
1335 field: String,
1336 value: String,
1337 reason: &'static str,
1338}
1339
1340impl ManifestProvenanceError {
1341 fn new(field: &str, value: &str, reason: &'static str) -> Self {
1342 Self {
1343 field: field.to_string(),
1344 value: safe_error_value(value),
1345 reason,
1346 }
1347 }
1348
1349 pub fn field(&self) -> &str {
1350 &self.field
1351 }
1352}
1353
1354impl fmt::Display for ManifestProvenanceError {
1355 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1356 write!(
1357 f,
1358 "invalid manifest provenance: field {} has {} (value {:?})",
1359 self.field, self.reason, self.value
1360 )
1361 }
1362}
1363
1364impl std::error::Error for ManifestProvenanceError {}
1365
1366impl ManifestProvenance {
1367 pub fn new() -> Self {
1369 Self::default()
1370 }
1371
1372 pub fn with_build_git_sha(mut self, value: Option<String>) -> Self {
1373 self.build_git_sha = value;
1374 self
1375 }
1376
1377 pub fn with_build_git_sha_absence_reason(
1378 mut self,
1379 value: Option<BuildGitShaAbsenceReason>,
1380 ) -> Self {
1381 self.build_git_sha_absence_reason = value;
1382 self
1383 }
1384
1385 pub fn with_build_lock_digest(mut self, value: Option<String>) -> Self {
1386 self.build_lock_digest = value;
1387 self
1388 }
1389
1390 pub fn with_wire_crate_version(mut self, value: Option<String>) -> Self {
1391 self.wire_crate_version = value;
1392 self
1393 }
1394
1395 pub fn with_store_schema_version(mut self, value: Option<String>) -> Self {
1396 self.store_schema_version = value;
1397 self
1398 }
1399
1400 pub fn with_launch_nonce_source(mut self, value: Option<LaunchNonceSource>) -> Self {
1405 self.launch_nonce_source = value;
1406 self
1407 }
1408
1409 pub fn validate(&self) -> Result<(), ManifestProvenanceError> {
1410 if let (Some(_), Some(reason)) = (
1411 self.build_git_sha.as_ref(),
1412 self.build_git_sha_absence_reason.as_ref(),
1413 ) {
1414 return Err(ManifestProvenanceError::new(
1415 "build_git_sha_absence_reason",
1416 reason.wire_name(),
1417 "must be omitted when build_git_sha is present",
1418 ));
1419 }
1420 for (field, value) in [
1421 ("build_git_sha", self.build_git_sha.as_deref()),
1422 (
1423 "build_git_sha_absence_reason",
1424 self.build_git_sha_absence_reason
1425 .as_ref()
1426 .map(|reason| reason.wire_name()),
1427 ),
1428 ("build_lock_digest", self.build_lock_digest.as_deref()),
1429 ("wire_crate_version", self.wire_crate_version.as_deref()),
1430 ("store_schema_version", self.store_schema_version.as_deref()),
1431 (
1432 "launch_nonce_source",
1433 self.launch_nonce_source
1434 .as_ref()
1435 .map(|source| source.wire_name()),
1436 ),
1437 ] {
1438 let Some(value) = value else { continue };
1439 if value.is_empty() {
1440 return Err(ManifestProvenanceError::new(
1441 field,
1442 value,
1443 "must not be empty",
1444 ));
1445 }
1446 if value.len() > MAX_PROVENANCE_VALUE_BYTES {
1451 return Err(ManifestProvenanceError::new(
1452 field,
1453 value,
1454 "exceeds the 128-byte maximum",
1455 ));
1456 }
1457 if value.bytes().any(|byte| !(0x20..=0x7e).contains(&byte)) {
1458 return Err(ManifestProvenanceError::new(
1459 field,
1460 value,
1461 "contains non-printable ASCII",
1462 ));
1463 }
1464 }
1465 Ok(())
1466 }
1467}
1468
1469pub fn build_provenance(
1487 build_git_sha: Option<&str>,
1488 build_lock_digest: Option<&str>,
1489 store_schema_version: Option<&str>,
1490) -> Result<ManifestProvenance, ProvenanceFormError> {
1491 let build_git_sha = normalize_and_validate_build_git_sha(build_git_sha)?;
1492 build_provenance_with_build_git_sha(
1493 build_git_sha,
1494 None,
1495 build_lock_digest,
1496 store_schema_version,
1497 )
1498}
1499
1500pub fn build_provenance_from_source(
1516 build_git_sha_source: BuildGitShaSource<'_>,
1517 build_lock_digest: Option<&str>,
1518 store_schema_version: Option<&str>,
1519) -> Result<ManifestProvenance, ProvenanceFormError> {
1520 let (raw_build_git_sha, mut build_git_sha_absence_reason) = match build_git_sha_source {
1521 BuildGitShaSource::Git {
1522 revision,
1523 tree_state,
1524 } => match attestable_commit(revision, tree_state) {
1525 Some(revision) => (Some(revision), None),
1526 None => (None, Some(BuildGitShaAbsenceReason::DeclinedDirty)),
1527 },
1528 BuildGitShaSource::NeverDerived => (None, Some(BuildGitShaAbsenceReason::NeverDerived)),
1529 BuildGitShaSource::NoGitDir => (None, Some(BuildGitShaAbsenceReason::NoGitDir)),
1530 };
1531 let build_git_sha = normalize_and_validate_build_git_sha(raw_build_git_sha)?;
1532 if build_git_sha.is_none() {
1533 build_git_sha_absence_reason.get_or_insert(BuildGitShaAbsenceReason::NeverDerived);
1534 }
1535 build_provenance_with_build_git_sha(
1536 build_git_sha,
1537 build_git_sha_absence_reason,
1538 build_lock_digest,
1539 store_schema_version,
1540 )
1541}
1542
1543fn normalize_and_validate_build_git_sha(
1544 build_git_sha: Option<&str>,
1545) -> Result<Option<String>, ProvenanceFormError> {
1546 let build_git_sha = normalize_provenance_fact(build_git_sha);
1547 validate_provenance_form(
1548 "build_git_sha",
1549 build_git_sha.as_deref(),
1550 BUILD_GIT_SHA_CANONICAL_FORM,
1551 40,
1552 )?;
1553 Ok(build_git_sha)
1554}
1555
1556fn build_provenance_with_build_git_sha(
1557 build_git_sha: Option<String>,
1558 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1559 build_lock_digest: Option<&str>,
1560 store_schema_version: Option<&str>,
1561) -> Result<ManifestProvenance, ProvenanceFormError> {
1562 let build_lock_digest = normalize_provenance_fact(build_lock_digest);
1563 validate_provenance_form(
1564 "build_lock_digest",
1565 build_lock_digest.as_deref(),
1566 BUILD_LOCK_DIGEST_CANONICAL_FORM,
1567 64,
1568 )?;
1569
1570 Ok(ManifestProvenance {
1571 build_git_sha,
1572 build_git_sha_absence_reason,
1573 build_lock_digest,
1574 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
1575 store_schema_version: normalize_provenance_fact(store_schema_version),
1576 launch_nonce_source: None,
1577 })
1578}
1579
1580fn validate_provenance_form(
1581 field: &'static str,
1582 value: Option<&str>,
1583 canonical_form: &'static str,
1584 expected_length: usize,
1585) -> Result<(), ProvenanceFormError> {
1586 let Some(value) = value else { return Ok(()) };
1587 if value.len() != expected_length
1588 || !value
1589 .bytes()
1590 .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
1591 {
1592 return Err(ProvenanceFormError::new(field, value.len(), canonical_form));
1593 }
1594 Ok(())
1595}
1596
1597pub const PROVENANCE_SENTINELS: [&str; 3] = ["unknown", "unavailable", "none"];
1605
1606fn normalize_provenance_fact(value: Option<&str>) -> Option<String> {
1607 let value = value?.trim();
1608 if value.is_empty() {
1609 return None;
1610 }
1611 let lowered = value.to_ascii_lowercase();
1612 if PROVENANCE_SENTINELS.contains(&lowered.as_str()) {
1613 return None;
1614 }
1615 Some(value.to_string())
1616}
1617
1618#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1620#[serde(deny_unknown_fields)]
1621pub struct CapabilityRequirement {
1622 pub capability: String,
1623 pub need: CapabilityNeed,
1624}
1625
1626#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1628#[serde(rename_all = "snake_case")]
1629pub enum CapabilityNeed {
1630 Required,
1631 Optional,
1632}
1633
1634#[derive(Debug, Clone, PartialEq, Eq)]
1636pub struct CapabilityGrammarError {
1637 field: String,
1638 value: String,
1639}
1640
1641impl CapabilityGrammarError {
1642 fn new(field: impl Into<String>, value: impl AsRef<str>) -> Self {
1643 Self {
1644 field: field.into(),
1645 value: safe_error_value(value.as_ref()),
1646 }
1647 }
1648
1649 pub fn field(&self) -> &str {
1651 &self.field
1652 }
1653
1654 pub fn value(&self) -> &str {
1656 &self.value
1657 }
1658}
1659
1660impl fmt::Display for CapabilityGrammarError {
1661 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1662 write!(
1663 f,
1664 "invalid capability grammar: field {} has offending value {:?}",
1665 self.field, self.value
1666 )
1667 }
1668}
1669
1670impl std::error::Error for CapabilityGrammarError {}
1671
1672impl ModuleManifest {
1673 pub fn validate_capability_grammar(&self) -> Result<(), CapabilityGrammarError> {
1675 let Some(capabilities) = &self.capabilities else {
1676 return Ok(());
1677 };
1678
1679 validate_capability_list("capabilities.provides", &capabilities.provides)?;
1680 validate_requires(&capabilities.requires)?;
1681 validate_capability_list(
1682 "capabilities.must_never_reach",
1683 &capabilities.must_never_reach,
1684 )
1685 }
1686}
1687
1688pub fn validate_manifest_capability_grammar(
1693 manifest: &Value,
1694) -> Result<(), CapabilityGrammarError> {
1695 let Some(object) = manifest.as_object() else {
1696 return Ok(());
1697 };
1698
1699 validate_capabilities_value(object.get("capabilities"))?;
1700 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
1701}
1702
1703pub fn validate_hello_capability_grammar(hello: &Value) -> Result<(), CapabilityGrammarError> {
1709 let Some(object) = hello.as_object() else {
1710 return Ok(());
1711 };
1712 if let Some(manifest) = object.get("manifest") {
1713 validate_manifest_capability_grammar(manifest)?;
1714 }
1715 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
1716}
1717
1718pub fn is_valid_capability_identifier(identifier: &str) -> bool {
1720 if identifier.chars().any(char::is_whitespace) {
1721 return false;
1722 }
1723 let Some((name, version)) = identifier.split_once("/v") else {
1724 return false;
1725 };
1726 if name.is_empty() || name.len() > 64 || version.is_empty() {
1727 return false;
1728 }
1729
1730 let name_bytes = name.as_bytes();
1731 if !name_bytes[0].is_ascii_lowercase()
1732 || (name.len() > 1
1733 && !name_bytes[name.len() - 1].is_ascii_lowercase()
1734 && !name_bytes[name.len() - 1].is_ascii_digit())
1735 || name_bytes.windows(2).any(|pair| pair == b"--")
1736 {
1737 return false;
1738 }
1739 if !name_bytes
1740 .iter()
1741 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-')
1742 {
1743 return false;
1744 }
1745
1746 if version.len() > 1 && version.starts_with('0')
1747 || !version.bytes().all(|byte| byte.is_ascii_digit())
1748 {
1749 return false;
1750 }
1751 matches!(
1752 version.parse::<u64>(),
1753 Ok(value) if (1..=u64::from(u32::MAX)).contains(&value)
1754 )
1755}
1756
1757fn validate_capabilities_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
1758 let Some(value) = value else {
1759 return Ok(());
1760 };
1761 let Some(object) = value.as_object() else {
1762 return Err(CapabilityGrammarError::new(
1763 "capabilities",
1764 value_description(value),
1765 ));
1766 };
1767
1768 for (key, value) in object {
1769 if !matches!(key.as_str(), "provides" | "requires" | "must_never_reach") {
1770 return Err(CapabilityGrammarError::new(
1771 field_child("capabilities", key),
1772 value_description(value),
1773 ));
1774 }
1775 }
1776
1777 validate_capability_list_value("capabilities.provides", object.get("provides"))?;
1778 validate_requires_value(object.get("requires"))?;
1779 validate_capability_list_value(
1780 "capabilities.must_never_reach",
1781 object.get("must_never_reach"),
1782 )
1783}
1784
1785fn validate_capability_list_value(
1786 field: &str,
1787 value: Option<&Value>,
1788) -> Result<(), CapabilityGrammarError> {
1789 let Some(value) = value else {
1790 return Ok(());
1791 };
1792 let Some(values) = value.as_array() else {
1793 return Err(CapabilityGrammarError::new(field, value_description(value)));
1794 };
1795
1796 let mut seen = HashSet::new();
1797 for (index, value) in values.iter().enumerate() {
1798 let field = format!("{field}[{index}]");
1799 let Some(identifier) = value.as_str() else {
1800 return Err(CapabilityGrammarError::new(field, value_description(value)));
1801 };
1802 validate_capability_identifier(&field, identifier)?;
1803 if !seen.insert(identifier) {
1804 return Err(CapabilityGrammarError::new(field, identifier));
1805 }
1806 }
1807 Ok(())
1808}
1809
1810fn validate_requires_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
1811 let Some(value) = value else {
1812 return Ok(());
1813 };
1814 let Some(values) = value.as_array() else {
1815 return Err(CapabilityGrammarError::new(
1816 "capabilities.requires",
1817 value_description(value),
1818 ));
1819 };
1820
1821 let mut seen = HashSet::new();
1822 for (index, value) in values.iter().enumerate() {
1823 let entry_field = format!("capabilities.requires[{index}]");
1824 let Some(object) = value.as_object() else {
1825 return Err(CapabilityGrammarError::new(
1826 entry_field,
1827 value_description(value),
1828 ));
1829 };
1830 for (key, value) in object {
1831 if !matches!(key.as_str(), "capability" | "need") {
1832 return Err(CapabilityGrammarError::new(
1833 field_child(&entry_field, key),
1834 value_description(value),
1835 ));
1836 }
1837 }
1838 let capability_field = format!("{entry_field}.capability");
1839 let Some(capability) = object.get("capability").and_then(Value::as_str) else {
1840 return Err(CapabilityGrammarError::new(
1841 capability_field,
1842 object
1843 .get("capability")
1844 .map_or("<missing>".to_string(), value_description),
1845 ));
1846 };
1847 validate_capability_identifier(&capability_field, capability)?;
1848
1849 let need_field = format!("{entry_field}.need");
1850 let Some(need) = object.get("need").and_then(Value::as_str) else {
1851 return Err(CapabilityGrammarError::new(
1852 need_field,
1853 object
1854 .get("need")
1855 .map_or("<missing>".to_string(), value_description),
1856 ));
1857 };
1858 if !matches!(need, "required" | "optional") {
1859 return Err(CapabilityGrammarError::new(need_field, need));
1860 }
1861 if !seen.insert(capability) {
1862 return Err(CapabilityGrammarError::new(entry_field, capability));
1863 }
1864 }
1865 Ok(())
1866}
1867
1868fn validate_capability_list(field: &str, values: &[String]) -> Result<(), CapabilityGrammarError> {
1869 let mut seen = HashSet::new();
1870 for (index, identifier) in values.iter().enumerate() {
1871 let field = format!("{field}[{index}]");
1872 validate_capability_identifier(&field, identifier)?;
1873 if !seen.insert(identifier) {
1874 return Err(CapabilityGrammarError::new(field, identifier));
1875 }
1876 }
1877 Ok(())
1878}
1879
1880fn validate_requires(values: &[CapabilityRequirement]) -> Result<(), CapabilityGrammarError> {
1881 let mut seen = HashSet::new();
1882 for (index, requirement) in values.iter().enumerate() {
1883 let field = format!("capabilities.requires[{index}].capability");
1884 validate_capability_identifier(&field, &requirement.capability)?;
1885 if !seen.insert(&requirement.capability) {
1886 return Err(CapabilityGrammarError::new(
1887 format!("capabilities.requires[{index}]"),
1888 &requirement.capability,
1889 ));
1890 }
1891 }
1892 Ok(())
1893}
1894
1895fn validate_capability_identifier(
1896 field: &str,
1897 identifier: &str,
1898) -> Result<(), CapabilityGrammarError> {
1899 if is_valid_capability_identifier(identifier) {
1900 Ok(())
1901 } else {
1902 Err(CapabilityGrammarError::new(field, identifier))
1903 }
1904}
1905
1906fn validate_runtime_computed(
1907 value: Option<&Value>,
1908 field: &str,
1909) -> Result<(), CapabilityGrammarError> {
1910 let Some(value) = value else {
1911 return Ok(());
1912 };
1913 let Some(pointers) = value.as_array() else {
1914 return Err(CapabilityGrammarError::new(field, value_description(value)));
1915 };
1916
1917 for (index, pointer) in pointers.iter().enumerate() {
1918 let field = format!("{field}[{index}]");
1919 let Some(pointer) = pointer.as_str() else {
1920 return Err(CapabilityGrammarError::new(
1921 field,
1922 value_description(pointer),
1923 ));
1924 };
1925 let Some(tokens) = parse_json_pointer(pointer) else {
1926 return Err(CapabilityGrammarError::new(field, pointer));
1927 };
1928 if tokens.first().is_some_and(|token| token == "capabilities") {
1929 return Err(CapabilityGrammarError::new(field, pointer));
1930 }
1931 }
1932 Ok(())
1933}
1934
1935fn parse_json_pointer(pointer: &str) -> Option<Vec<String>> {
1936 if pointer.is_empty() {
1937 return Some(Vec::new());
1938 }
1939 let raw_tokens = pointer.strip_prefix('/')?;
1940 raw_tokens
1941 .split('/')
1942 .map(unescape_json_pointer_token)
1943 .collect()
1944}
1945
1946fn unescape_json_pointer_token(token: &str) -> Option<String> {
1947 let mut output = String::with_capacity(token.len());
1948 let mut characters = token.chars();
1949 while let Some(character) = characters.next() {
1950 if character != '~' {
1951 output.push(character);
1952 continue;
1953 }
1954 match characters.next()? {
1955 '0' => output.push('~'),
1956 '1' => output.push('/'),
1957 _ => return None,
1958 }
1959 }
1960 Some(output)
1961}
1962
1963fn field_child(parent: &str, child: &str) -> String {
1964 let child = safe_error_value(child);
1965 format!("{parent}.{child}")
1966}
1967
1968fn value_description(value: &Value) -> String {
1969 match value {
1970 Value::String(value) => safe_error_value(value),
1971 Value::Null => "null".to_string(),
1972 Value::Bool(value) => value.to_string(),
1973 Value::Number(value) => value.to_string(),
1974 Value::Array(_) => "<array>".to_string(),
1975 Value::Object(_) => "<object>".to_string(),
1976 }
1977}
1978
1979fn safe_error_value(value: &str) -> String {
1980 let lower = value.to_ascii_lowercase();
1981 if ["secret", "password", "api_key"]
1982 .iter()
1983 .any(|marker| lower.contains(marker))
1984 || lower.starts_with("sk-")
1985 || lower.starts_with("akia")
1986 || lower.starts_with("bearer ")
1987 || lower.starts_with("token=")
1988 || lower.starts_with("credential=")
1989 {
1990 "<redacted>".to_string()
1991 } else {
1992 value.to_string()
1993 }
1994}
1995
1996#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2002#[serde(rename_all = "snake_case")]
2003pub enum TrustTier {
2004 FirstParty,
2005 Reviewed,
2006 Untrusted,
2007}
2008
2009#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2013#[serde(tag = "role", rename_all = "snake_case")]
2014pub enum ProviderRole {
2015 ToolProvider {
2016 tools: Vec<Tool>,
2017 identity_scope: Vec<IdentityScope>,
2025 concurrency: Concurrency,
2026 emits_push: bool,
2027 sub_supervises: bool,
2028 },
2029 PipelineStage {
2030 stage: PipelineStageKind,
2031 applies_to: PipelineAppliesTo,
2032 interface: String,
2033 declares_frozen_floor: bool,
2034 needs_signals: Vec<String>,
2035 conformance_class: String,
2036 },
2037 ManagementSurface {
2038 operations: Vec<ManagementOperation>,
2039 config_schema: Value,
2040 observability: Vec<ObservabilitySurface>,
2041 identity_scope: Vec<IdentityScope>,
2045 #[serde(default)]
2046 concurrency: Concurrency,
2047 },
2048 InternalService {
2049 service_id: String,
2050 transport: InternalTransport,
2051 agent_facing: bool,
2052 operations: Vec<String>,
2053 },
2054}
2055
2056#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2069#[serde(rename_all = "snake_case")]
2070pub enum ExecutionMode {
2071 Pure,
2072 Mutating,
2073 Unfenceable,
2074}
2075
2076#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2078pub struct Tool {
2079 pub name: String,
2080 #[serde(default, skip_serializing_if = "Option::is_none")]
2081 pub description: Option<String>,
2082 pub execution_mode: ExecutionMode,
2087 pub schema: Value,
2088}
2089
2090#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2096#[serde(rename_all = "snake_case")]
2097pub enum Concurrency {
2098 Serial,
2100 ModuleManaged,
2103 StatelessParallel,
2106}
2107
2108#[allow(clippy::derivable_impls)]
2109impl Default for Concurrency {
2120 fn default() -> Self {
2121 Self::ModuleManaged
2122 }
2123}
2124
2125#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2132#[serde(rename_all = "snake_case")]
2133pub enum IdentityScope {
2134 Session,
2135 Project,
2136}
2137
2138#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2140#[serde(rename_all = "snake_case")]
2141pub enum PipelineStageKind {
2142 Transform,
2143 Codec,
2144 Auth,
2145}
2146
2147#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2149pub struct PipelineAppliesTo {
2150 pub provider: String,
2151 pub model: String,
2152}
2153
2154#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2157#[non_exhaustive]
2158pub struct OperationPayload {
2159 max_bytes: usize,
2160}
2161
2162impl OperationPayload {
2163 pub fn new(max_bytes: usize) -> Self {
2164 Self { max_bytes }
2165 }
2166
2167 pub fn max_bytes(&self) -> usize {
2168 self.max_bytes
2169 }
2170}
2171
2172#[derive(Debug, Clone, PartialEq, Eq)]
2174#[non_exhaustive]
2175pub enum OperationPayloadError {
2176 UnknownOperation { operation: String },
2177 WatchOperation { operation: String },
2178 InvalidMaxBytes { operation: String },
2179}
2180
2181impl fmt::Display for OperationPayloadError {
2182 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2183 write!(f, "{self:?}")
2184 }
2185}
2186
2187impl std::error::Error for OperationPayloadError {}
2188
2189impl ModuleManifest {
2190 pub fn validate_operation_payload(&self) -> Result<(), OperationPayloadError> {
2193 for (name, payload) in &self.operation_payload {
2194 if !self.provides.iter().any(|role| match role {
2195 ProviderRole::ManagementSurface { operations, .. } => {
2196 operations.iter().any(|op| op.name == *name)
2197 }
2198 _ => false,
2199 }) {
2200 return Err(OperationPayloadError::UnknownOperation {
2201 operation: name.clone(),
2202 });
2203 }
2204 if self
2205 .operation_delivery
2206 .get(name)
2207 .is_some_and(OperationDelivery::is_watch)
2208 {
2209 return Err(OperationPayloadError::WatchOperation {
2210 operation: name.clone(),
2211 });
2212 }
2213 if !(1..=crate::framed_body::MAX_DECLARED_PAYLOAD_BYTES).contains(&payload.max_bytes) {
2214 return Err(OperationPayloadError::InvalidMaxBytes {
2215 operation: name.clone(),
2216 });
2217 }
2218 }
2219 Ok(())
2220 }
2221}
2222
2223#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2228pub struct ManagementOperation {
2229 pub name: String,
2230 pub kind: ManagementOperationKind,
2231 #[serde(default, skip_serializing_if = "Option::is_none")]
2232 pub description: Option<String>,
2233}
2234
2235#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2236#[serde(rename_all = "snake_case")]
2237pub enum ManagementOperationKind {
2238 Query,
2239 Mutate,
2240}
2241
2242#[derive(Debug, Clone, PartialEq, Eq)]
2245#[non_exhaustive]
2246pub enum OperationDelivery {
2247 Watch,
2248 Other(String),
2249}
2250
2251impl OperationDelivery {
2252 pub const WATCH: Self = Self::Watch;
2254
2255 pub fn wire_name(&self) -> &str {
2257 match self {
2258 Self::Watch => "watch",
2259 Self::Other(value) => value,
2260 }
2261 }
2262
2263 pub fn is_watch(&self) -> bool {
2265 self.wire_name() == "watch"
2266 }
2267}
2268
2269impl Serialize for OperationDelivery {
2270 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2271 where
2272 S: serde::Serializer,
2273 {
2274 serializer.serialize_str(self.wire_name())
2275 }
2276}
2277
2278impl<'de> Deserialize<'de> for OperationDelivery {
2279 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2280 where
2281 D: Deserializer<'de>,
2282 {
2283 let value = String::deserialize(deserializer)?;
2284 Ok(if value == "watch" {
2285 Self::WATCH
2286 } else {
2287 Self::Other(value)
2288 })
2289 }
2290}
2291
2292#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2294pub struct ObservabilitySurface {
2295 pub name: String,
2296 pub kind: ObservabilityKind,
2297}
2298
2299#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2300#[serde(rename_all = "snake_case")]
2301pub enum ObservabilityKind {
2302 Snapshot,
2303 Stream,
2304}
2305
2306#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2307#[serde(rename_all = "snake_case")]
2308pub enum InternalTransport {
2309 Bulk,
2310}
2311
2312#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2314#[serde(tag = "role", rename_all = "snake_case")]
2315pub enum ConsumerRole {
2316 ToolClient { of: Vec<String> },
2317 LlmClient { via: String, auth: String },
2318 ServiceClient { of: Vec<String> },
2319}
2320
2321#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2323pub struct Bindings {
2324 pub storage: StorageBinding,
2325 pub vault_grants: Vec<VaultGrant>,
2326 pub identity: IdentityBinding,
2327}
2328
2329#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2331pub struct StorageBinding {
2332 pub kind: StorageKind,
2333 pub scope: StorageScope,
2334 pub owns_schema: bool,
2335}
2336
2337#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2338#[serde(rename_all = "snake_case")]
2339pub enum StorageKind {
2340 Sqlite,
2341}
2342
2343#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2344#[serde(rename_all = "snake_case")]
2345pub enum StorageScope {
2346 Project,
2347}
2348
2349#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2350pub struct VaultGrant {
2351 pub secret: String,
2352 pub reason: String,
2353}
2354
2355#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2356pub struct IdentityBinding {
2357 pub requires: Vec<IdentityScope>,
2358 pub optional: Vec<IdentityScope>,
2359}
2360
2361#[cfg(test)]
2362mod tests {
2363 use super::*;
2364 use serde_json::json;
2365
2366 fn aft_manifest_fixture() -> ModuleManifest {
2367 ModuleManifest::builder("aft", "0.39.2")
2368 .trust_tier(Some(TrustTier::FirstParty))
2369 .bindings(Some(Bindings {
2370 storage: StorageBinding {
2371 kind: StorageKind::Sqlite,
2372 scope: StorageScope::Project,
2373 owns_schema: true,
2374 },
2375 vault_grants: vec![VaultGrant {
2376 secret: "provider_api_key".to_string(),
2377 reason: "cortexkit_native auth".to_string(),
2378 }],
2379 identity: IdentityBinding {
2380 requires: vec![IdentityScope::Project],
2381 optional: vec![IdentityScope::Session],
2382 },
2383 }))
2384 .protocol_ver(1)
2385 .provides(vec![ProviderRole::ToolProvider {
2386 tools: vec![
2387 Tool {
2388 name: "read".to_string(),
2389 description: None,
2390 execution_mode: ExecutionMode::Pure,
2391 schema: json!({"type": "object"}),
2392 },
2393 Tool {
2394 name: "grep".to_string(),
2395 description: None,
2396 execution_mode: ExecutionMode::Pure,
2397 schema: json!({"type": "object"}),
2398 },
2399 Tool {
2400 name: "outline".to_string(),
2401 description: None,
2402 execution_mode: ExecutionMode::Pure,
2403 schema: json!({"type": "object"}),
2404 },
2405 Tool {
2406 name: "semantic_search".to_string(),
2407 description: None,
2408 execution_mode: ExecutionMode::Pure,
2409 schema: json!({"type": "object"}),
2410 },
2411 Tool {
2412 name: "edit".to_string(),
2413 description: None,
2414 execution_mode: ExecutionMode::Mutating,
2415 schema: json!({"type": "object"}),
2416 },
2417 Tool {
2418 name: "write".to_string(),
2419 description: None,
2420 execution_mode: ExecutionMode::Mutating,
2421 schema: json!({"type": "object"}),
2422 },
2423 Tool {
2424 name: "bash".to_string(),
2425 description: None,
2426 execution_mode: ExecutionMode::Unfenceable,
2427 schema: json!({"type": "object"}),
2428 },
2429 ],
2430 identity_scope: vec![IdentityScope::Session, IdentityScope::Project],
2431 concurrency: Concurrency::ModuleManaged,
2432 emits_push: true,
2433 sub_supervises: true,
2434 }])
2435 .consumes(vec![ConsumerRole::ServiceClient {
2436 of: vec!["embedding.v2".to_string()],
2437 }])
2438 .build()
2439 }
2440
2441 #[test]
2442 fn serde_round_trips_representative_manifest() {
2443 let manifest = aft_manifest_fixture();
2444 let serialized = serde_json::to_string_pretty(&manifest).unwrap();
2445 let decoded: ModuleManifest = serde_json::from_str(&serialized).unwrap();
2446
2447 assert_eq!(manifest, decoded);
2448 }
2449
2450 #[test]
2451 fn builder_defaults_additions_to_honest_absence_and_round_trips() {
2452 let manifest = ModuleManifest::builder("builder-defaults", "2.0.0").build();
2453
2454 assert_eq!(manifest.module_id, "builder-defaults");
2455 assert_eq!(manifest.module_version, "2.0.0");
2456 assert_eq!(manifest.protocol_ver, PROTOCOL_VERSION);
2457 assert_eq!(manifest.trust_tier, None);
2458 assert!(manifest.provides.is_empty());
2459 assert!(manifest.consumes.is_empty());
2460 assert_eq!(manifest.bindings, None);
2461 assert_eq!(manifest.capabilities, None);
2462 assert_eq!(manifest.self_signals, None);
2463 assert_eq!(manifest.provenance, None);
2464
2465 let encoded = serde_json::to_value(&manifest).expect("builder manifest serializes");
2466 for optional in [
2467 "trust_tier",
2468 "consumes",
2469 "bindings",
2470 "capabilities",
2471 "self_signals",
2472 "provenance",
2473 ] {
2474 assert!(
2475 encoded.get(optional).is_none(),
2476 "an absent {optional} declaration must stay absent on the wire"
2477 );
2478 }
2479 let decoded: ModuleManifest =
2480 serde_json::from_value(encoded).expect("builder manifest round-trips");
2481 assert_eq!(decoded, manifest);
2482 }
2483
2484 #[test]
2485 fn fully_populated_builder_manifest_matches_the_literal_wire_golden() {
2486 let manifest = ModuleManifest::builder("full-builder", "2.0.0")
2487 .trust_tier(Some(TrustTier::Reviewed))
2488 .bindings(Some(Bindings {
2489 storage: StorageBinding {
2490 kind: StorageKind::Sqlite,
2491 scope: StorageScope::Project,
2492 owns_schema: false,
2493 },
2494 vault_grants: Vec::new(),
2495 identity: IdentityBinding {
2496 requires: vec![IdentityScope::Project],
2497 optional: Vec::new(),
2498 },
2499 }))
2500 .provides(vec![ProviderRole::ToolProvider {
2501 tools: vec![Tool {
2502 name: "read".to_string(),
2503 description: None,
2504 execution_mode: ExecutionMode::Pure,
2505 schema: json!({"type": "object"}),
2506 }],
2507 identity_scope: vec![IdentityScope::Project],
2508 concurrency: Concurrency::Serial,
2509 emits_push: false,
2510 sub_supervises: false,
2511 }])
2512 .consumes(vec![ConsumerRole::ServiceClient {
2513 of: vec!["embedding.v2".to_string()],
2514 }])
2515 .capabilities(Some(CapabilityDeclarations {
2516 provides: vec!["embedding/v2".to_string()],
2517 requires: Vec::new(),
2518 must_never_reach: Vec::new(),
2519 }))
2520 .self_signals(Some(vec![SelfSignalDeclaration {
2521 name: "usage_poller".to_string(),
2522 kind: SelfSignalKind::Poller,
2523 effect: SelfSignalEffect::Observe,
2524 anchored_to: SignalAnchor::FixedInterval,
2525 cadence: Some(SignalCadence::Literal {
2526 interval_ms: 60_000,
2527 }),
2528 domain: Some("provider-usage".to_string()),
2529 note: None,
2530 }]))
2531 .provenance(Some(ManifestProvenance {
2532 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
2533 build_git_sha_absence_reason: None,
2534 build_lock_digest: Some(
2535 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
2536 ),
2537 wire_crate_version: Some("0.16.0".to_string()),
2538 store_schema_version: Some("42".to_string()),
2539 launch_nonce_source: None,
2540 }))
2541 .build();
2542
2543 assert_eq!(
2544 serde_json::to_vec(&manifest).expect("builder manifest serializes"),
2545 include_bytes!("../tests/golden/module_manifest_builder_full.json"),
2546 "the builder must preserve the prior fully populated literal wire bytes"
2547 );
2548 }
2549
2550 #[test]
2551 fn old_manifest_with_unread_fields_decodes_and_round_trips_verbatim() {
2552 let raw = include_bytes!("../tests/golden/module_manifest_builder_full.json");
2553 let decoded: ModuleManifest =
2554 serde_json::from_slice(raw).expect("old manifest with all unread fields decodes");
2555
2556 assert_eq!(decoded.trust_tier, Some(TrustTier::Reviewed));
2557 assert!(!decoded.consumes.is_empty());
2558 assert!(decoded.bindings.is_some());
2559
2560 let reencoded = serde_json::to_vec(&decoded).expect("re-encode succeeds");
2561 assert_eq!(
2562 reencoded, raw,
2563 "old manifest relay stays byte-for-byte verbatim"
2564 );
2565 }
2566
2567 #[test]
2568 fn new_manifest_omits_unread_fields_on_wire_and_decodes_cleanly() {
2569 let raw = include_bytes!("../tests/golden/module_manifest_diet.json");
2570 let decoded: ModuleManifest =
2571 serde_json::from_slice(raw).expect("new manifest omitting unread fields decodes");
2572
2573 assert_eq!(decoded.trust_tier, None);
2574 assert!(decoded.consumes.is_empty());
2575 assert_eq!(decoded.bindings, None);
2576
2577 let pretty = format!("{}\n", serde_json::to_string_pretty(&decoded).unwrap());
2578 assert_eq!(
2579 pretty.as_bytes(),
2580 raw,
2581 "new manifest matches golden byte-for-byte without unread keys"
2582 );
2583
2584 let as_val: serde_json::Value = serde_json::to_value(&decoded).unwrap();
2585 assert!(
2586 as_val.get("trust_tier").is_none(),
2587 "no trust_tier on wire for new manifest"
2588 );
2589 assert!(
2590 as_val.get("consumes").is_none(),
2591 "no consumes on wire for empty consumes"
2592 );
2593 assert!(
2594 as_val.get("bindings").is_none(),
2595 "no bindings on wire for new manifest"
2596 );
2597 }
2598
2599 #[test]
2600 fn aft_manifest_fixture_matches_v1_contract() {
2601 let manifest = aft_manifest_fixture();
2602
2603 assert_eq!(manifest.module_id, "aft");
2604 let ProviderRole::ToolProvider {
2605 tools,
2606 identity_scope,
2607 concurrency,
2608 emits_push,
2609 sub_supervises,
2610 } = &manifest.provides[0]
2611 else {
2612 panic!("AFT fixture must expose one tool_provider role");
2613 };
2614
2615 assert_eq!(*concurrency, Concurrency::ModuleManaged);
2616 assert!(*emits_push);
2617 assert!(*sub_supervises);
2618 assert_eq!(
2619 identity_scope,
2620 &vec![IdentityScope::Session, IdentityScope::Project]
2621 );
2622 assert_eq!(
2623 tools
2624 .iter()
2625 .map(|tool| (tool.name.as_str(), tool.execution_mode))
2626 .collect::<Vec<_>>(),
2627 vec![
2628 ("read", ExecutionMode::Pure),
2629 ("grep", ExecutionMode::Pure),
2630 ("outline", ExecutionMode::Pure),
2631 ("semantic_search", ExecutionMode::Pure),
2632 ("edit", ExecutionMode::Mutating),
2633 ("write", ExecutionMode::Mutating),
2634 ("bash", ExecutionMode::Unfenceable),
2635 ]
2636 );
2637 }
2638
2639 #[test]
2640 fn tool_provider_role_tag_serializes_as_snake_case() {
2641 let manifest = aft_manifest_fixture();
2642 let value = serde_json::to_value(&manifest).unwrap();
2643
2644 assert_eq!(value["provides"][0]["role"], "tool_provider");
2645 }
2646
2647 #[test]
2648 fn manifest_without_capabilities_preserves_the_existing_wire_shape() {
2649 let manifest = aft_manifest_fixture();
2650 let encoded = serde_json::to_value(&manifest).expect("manifest serializes");
2651 assert!(encoded.get("capabilities").is_none());
2652
2653 let decoded: ModuleManifest =
2654 serde_json::from_value(encoded).expect("legacy manifest parses");
2655 assert_eq!(decoded.capabilities, None);
2656 }
2657
2658 #[test]
2659 fn capability_identifier_lexical_grammar_accepts_only_pinned_forms() {
2660 for identifier in [
2661 "a/v1",
2662 "credentials-provider/v1",
2663 "a1-b2/v4294967295",
2664 "a123456789012345678901234567890123456789012345678901234567890123/v1",
2665 ] {
2666 assert!(
2667 is_valid_capability_identifier(identifier),
2668 "identifier must be accepted: {identifier}"
2669 );
2670 }
2671
2672 for identifier in [
2673 "credentials-Provider/v1",
2674 "credentials-provider/v01",
2675 "credentials-provider-/v1",
2676 "credentials--provider/v1",
2677 "Credentials-provider/v1",
2678 "credentials-provider/1",
2679 "credentials provider/v1",
2680 "credentials-provider/v0",
2681 "credentials-provider/v4294967296",
2682 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/v1",
2683 ] {
2684 assert!(
2685 !is_valid_capability_identifier(identifier),
2686 "identifier must be rejected: {identifier}"
2687 );
2688 }
2689 }
2690
2691 #[test]
2692 fn capability_grammar_errors_redact_secret_shaped_values() {
2693 let error = validate_manifest_capability_grammar(&json!({
2694 "capabilities": { "provides": ["sk-secret-value/v0"] }
2695 }))
2696 .expect_err("secret-shaped capability identifier is malformed");
2697 assert_eq!(error.field(), "capabilities.provides[0]");
2698 assert_eq!(error.value(), "<redacted>");
2699 assert!(!error.to_string().contains("sk-secret-value"));
2700 }
2701
2702 #[test]
2709 fn provenance_builder_sentinels_become_field_omission() {
2710 for sentinel in [
2711 "unknown",
2712 "UNKNOWN",
2713 "Unknown",
2714 "unavailable",
2715 "none",
2716 "None",
2717 " unknown ",
2718 "",
2719 ] {
2720 let p = build_provenance_from_source(
2721 BuildGitShaSource::Git {
2722 revision: sentinel,
2723 tree_state: GitTreeState::Clean,
2724 },
2725 Some(sentinel),
2726 Some(sentinel),
2727 )
2728 .expect("sentinels are omitted before form validation");
2729 assert_eq!(
2730 (
2731 p.build_git_sha,
2732 p.build_git_sha_absence_reason,
2733 p.build_lock_digest,
2734 p.store_schema_version,
2735 ),
2736 (
2737 None,
2738 Some(BuildGitShaAbsenceReason::NeverDerived),
2739 None,
2740 None,
2741 ),
2742 "sentinel {sentinel:?} must be omitted, not published"
2743 );
2744 }
2745 let real = build_provenance_from_source(
2746 BuildGitShaSource::Git {
2747 revision: "0123456789abcdef0123456789abcdef01234567",
2748 tree_state: GitTreeState::Clean,
2749 },
2750 None,
2751 Some("9"),
2752 )
2753 .expect("canonical build revision is accepted");
2754 assert_eq!(
2755 real.build_git_sha.as_deref(),
2756 Some("0123456789abcdef0123456789abcdef01234567")
2757 );
2758 assert_eq!(real.store_schema_version.as_deref(), Some("9"));
2759 assert_eq!(
2763 real.wire_crate_version.as_deref(),
2764 Some(crate::SUBC_PROTOCOL_CRATE_VERSION)
2765 );
2766 }
2767
2768 #[test]
2769 fn build_provenance_accepts_canonical_sha_and_lock_digest() {
2770 let provenance = build_provenance_from_source(
2771 BuildGitShaSource::Git {
2772 revision: " 0123456789abcdef0123456789abcdef01234567 ",
2773 tree_state: GitTreeState::Clean,
2774 },
2775 Some(" abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789 "),
2776 Some(" schema-v3 "),
2777 )
2778 .expect("canonical build facts are accepted");
2779
2780 assert_eq!(
2781 provenance,
2782 ManifestProvenance {
2783 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
2784 build_git_sha_absence_reason: None,
2785 build_lock_digest: Some(
2786 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
2787 ),
2788 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
2789 store_schema_version: Some("schema-v3".to_string()),
2790 launch_nonce_source: None,
2791 }
2792 );
2793 }
2794
2795 #[test]
2796 fn build_provenance_refuses_an_abbreviated_git_sha() {
2797 let error = build_provenance_from_source(
2798 BuildGitShaSource::Git {
2799 revision: "0123456789ab",
2800 tree_state: GitTreeState::Clean,
2801 },
2802 None,
2803 None,
2804 )
2805 .expect_err("a 12-character abbreviation is not canonical");
2806
2807 assert_eq!(error.field(), "build_git_sha");
2808 assert_eq!(error.length(), 12);
2809 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
2810 assert_eq!(
2811 error.to_string(),
2812 "invalid manifest provenance form: field build_git_sha has length 12; canonical form is exactly 40 lowercase hexadecimal characters"
2813 );
2814 }
2815
2816 #[test]
2817 fn build_provenance_refuses_an_abbreviated_lock_digest() {
2818 let error = build_provenance_from_source(
2819 BuildGitShaSource::NeverDerived,
2820 Some("0123456789abcdef"),
2821 None,
2822 )
2823 .expect_err("a 16-character digest is not canonical");
2824
2825 assert_eq!(error.field(), "build_lock_digest");
2826 assert_eq!(error.length(), 16);
2827 assert_eq!(error.canonical_form(), BUILD_LOCK_DIGEST_CANONICAL_FORM);
2828 }
2829
2830 #[test]
2831 fn build_provenance_refuses_uppercase_hex() {
2832 let uppercase_sha = "A".repeat(40);
2833 let error = build_provenance_from_source(
2834 BuildGitShaSource::Git {
2835 revision: &uppercase_sha,
2836 tree_state: GitTreeState::Clean,
2837 },
2838 None,
2839 None,
2840 )
2841 .expect_err("uppercase hexadecimal is not canonical");
2842
2843 assert_eq!(error.field(), "build_git_sha");
2844 assert_eq!(error.length(), 40);
2845 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
2846 }
2847
2848 #[test]
2849 fn build_provenance_refuses_dirty_revision_stamp_claimed_clean() {
2850 let error = build_provenance_from_source(
2851 BuildGitShaSource::Git {
2852 revision: "0123456789abcdef0123456789abcdef01234567-dirty",
2853 tree_state: GitTreeState::Clean,
2854 },
2855 None,
2856 None,
2857 )
2858 .expect_err("a dirty stamp is not a canonical build revision");
2859
2860 assert_eq!(error.field(), "build_git_sha");
2861 assert_eq!(error.length(), 46);
2862 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
2863 }
2864
2865 #[test]
2866 fn build_provenance_keeps_a_lock_digest_when_identity_is_unavailable() {
2867 let provenance = build_provenance_from_source(
2868 BuildGitShaSource::Git {
2869 revision: "unavailable",
2870 tree_state: GitTreeState::Clean,
2871 },
2872 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"),
2873 None,
2874 )
2875 .expect("sentinel SHA is omitted before the valid lock digest is checked");
2876
2877 assert_eq!(provenance.build_git_sha, None);
2878 assert_eq!(
2879 provenance.build_lock_digest,
2880 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string())
2881 );
2882 assert_eq!(
2883 provenance.wire_crate_version,
2884 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
2885 );
2886 }
2887
2888 #[test]
2889 fn build_provenance_omits_fully_unavailable_inputs() {
2890 let provenance = build_provenance_from_source(
2891 BuildGitShaSource::NeverDerived,
2892 Some(" unavailable "),
2893 Some(" "),
2894 )
2895 .expect("omitted and sentinel inputs are not form errors");
2896
2897 assert_eq!(provenance.build_git_sha, None);
2898 assert_eq!(provenance.build_lock_digest, None);
2899 assert_eq!(provenance.store_schema_version, None);
2900 assert_eq!(
2901 provenance.wire_crate_version,
2902 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
2903 );
2904 }
2905
2906 #[test]
2907 fn legacy_build_provenance_keeps_master_wire_bytes_without_an_absence_reason() {
2908 let revision = "0123456789abcdef0123456789abcdef01234567";
2909 for (input, expected) in [
2910 (
2911 Some(revision),
2912 format!(
2913 r#"{{"build_git_sha":"{revision}","wire_crate_version":"{}"}}"#,
2914 crate::SUBC_PROTOCOL_CRATE_VERSION
2915 ),
2916 ),
2917 (
2918 None,
2919 format!(
2920 r#"{{"wire_crate_version":"{}"}}"#,
2921 crate::SUBC_PROTOCOL_CRATE_VERSION
2922 ),
2923 ),
2924 (
2925 Some("unknown"),
2926 format!(
2927 r#"{{"wire_crate_version":"{}"}}"#,
2928 crate::SUBC_PROTOCOL_CRATE_VERSION
2929 ),
2930 ),
2931 ] {
2932 let provenance = build_provenance(input, None, None)
2933 .expect("the legacy build facts remain constructible");
2934 assert_eq!(provenance.build_git_sha_absence_reason, None);
2935 assert_eq!(
2936 serde_json::to_string(&provenance).expect("legacy provenance serializes"),
2937 expected
2938 );
2939 }
2940 }
2941
2942 #[test]
2943 fn build_provenance_derives_git_sha_absence_from_the_stamping_inputs() {
2944 let revision = "0123456789abcdef0123456789abcdef01234567";
2945 let cases = [
2946 (
2947 BuildGitShaSource::Git {
2948 revision,
2949 tree_state: GitTreeState::Clean,
2950 },
2951 Some(revision),
2952 None,
2953 ),
2954 (
2955 BuildGitShaSource::Git {
2956 revision,
2957 tree_state: GitTreeState::Dirty,
2958 },
2959 None,
2960 Some(BuildGitShaAbsenceReason::DeclinedDirty),
2961 ),
2962 (
2963 BuildGitShaSource::NeverDerived,
2964 None,
2965 Some(BuildGitShaAbsenceReason::NeverDerived),
2966 ),
2967 (
2968 BuildGitShaSource::NoGitDir,
2969 None,
2970 Some(BuildGitShaAbsenceReason::NoGitDir),
2971 ),
2972 ];
2973
2974 for (source, expected_sha, expected_reason) in cases {
2975 let provenance = build_provenance_from_source(source, None, None)
2976 .expect("every stamping state constructs honest provenance");
2977 assert_eq!(provenance.build_git_sha.as_deref(), expected_sha);
2978 assert_eq!(provenance.build_git_sha_absence_reason, expected_reason);
2979 }
2980 }
2981
2982 #[test]
2983 fn unknown_git_sha_absence_reason_round_trips_byte_faithfully() {
2984 let wire = format!(
2985 r#"{{"build_git_sha_absence_reason":"future_stamper_state","wire_crate_version":"{}"}}"#,
2986 crate::SUBC_PROTOCOL_CRATE_VERSION
2987 );
2988 let provenance: ManifestProvenance =
2989 serde_json::from_str(&wire).expect("future absence reasons remain readable");
2990
2991 assert_eq!(
2992 provenance.build_git_sha_absence_reason,
2993 Some(BuildGitShaAbsenceReason::ForwardCompatibleUnknown(
2994 "future_stamper_state".to_string()
2995 ))
2996 );
2997 assert_eq!(
2998 serde_json::to_string(&provenance).expect("future absence reason reserializes"),
2999 wire
3000 );
3001 }
3002
3003 #[test]
3004 fn provenance_rejects_an_absence_reason_beside_a_declared_commit() {
3005 let error = serde_json::from_value::<ManifestProvenance>(json!({
3006 "build_git_sha": "0123456789abcdef0123456789abcdef01234567",
3007 "build_git_sha_absence_reason": "declined_dirty"
3008 }))
3009 .expect_err("a declared commit cannot also claim an absence reason");
3010
3011 assert!(error.to_string().contains(
3012 "build_git_sha_absence_reason has must be omitted when build_git_sha is present"
3013 ));
3014 }
3015
3016 #[test]
3017 fn rich_ui_descriptor_is_optional_and_round_trips_when_present() {
3018 let manifest = ModuleManifest::builder("provider", "1.0.0").build();
3019 assert_eq!(
3020 serde_json::to_string(&manifest).unwrap(),
3021 r#"{"module_id":"provider","module_version":"1.0.0","protocol_ver":2,"provides":[]}"#
3022 );
3023
3024 let descriptor = RichUiDescriptor::new(
3025 "ckios.richui.manifest/1",
3026 format!("sha256:{}", "a".repeat(64)),
3027 128,
3028 2,
3029 );
3030 let manifest = ModuleManifest::builder("provider", "1.0.0")
3031 .rich_ui(Some(descriptor.clone()))
3032 .build();
3033 let wire = serde_json::to_string(&manifest).unwrap();
3034 assert!(wire.contains("\"rich_ui\":{\"schema\":\"ckios.richui.manifest/1\""));
3035 assert_eq!(
3036 serde_json::from_str::<ModuleManifest>(&wire)
3037 .unwrap()
3038 .rich_ui,
3039 Some(descriptor)
3040 );
3041 }
3042
3043 #[test]
3044 fn rich_ui_descriptor_validation_names_each_invalid_field() {
3045 let good = json!({
3046 "schema": "ckios.richui.manifest/1",
3047 "manifest_digest": format!("sha256:{}", "a".repeat(64)),
3048 "bytes": 1,
3049 "chunks": 1
3050 });
3051 let hello = json!({"manifest": {"rich_ui": good.clone()}});
3052 assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
3053
3054 for (field, value) in [
3055 ("schema", json!("bad schema")),
3056 (
3057 "manifest_digest",
3058 json!(format!("sha256:{}", "A".repeat(64))),
3059 ),
3060 ("bytes", json!(0)),
3061 ("chunks", json!(1025)),
3062 ] {
3063 let mut invalid = hello.clone();
3064 invalid["manifest"]["rich_ui"][field] = value;
3065 let error = validate_hello_rich_ui_descriptor(&invalid)
3066 .expect_err("an invalid descriptor field must be refused");
3067 assert_eq!(error.field(), format!("rich_ui.{field}"));
3068 }
3069
3070 let mut hello = hello;
3071 hello["manifest"]["rich_ui"] = Value::Null;
3072 let error = validate_hello_rich_ui_descriptor(&hello)
3073 .expect_err("null is not an absent descriptor");
3074 assert_eq!(error.field(), "rich_ui");
3075 }
3076
3077 #[test]
3078 fn rich_ui_descriptor_validation_accepts_inclusive_bounds() {
3079 let hello = json!({"manifest": {"rich_ui": {
3080 "schema": "a".repeat(64),
3081 "manifest_digest": format!("sha256:{}", "f".repeat(64)),
3082 "bytes": 16_777_216,
3083 "chunks": 1024
3084 }}});
3085 assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
3086 }
3087}