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