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}
115
116#[derive(Debug, Clone)]
118pub struct ModuleManifestBuilder {
119 module_id: String,
120 module_version: String,
121 protocol_ver: u8,
122 trust_tier: Option<TrustTier>,
123 ready: Option<bool>,
124 provides: Vec<ProviderRole>,
125 consumes: Vec<ConsumerRole>,
126 bindings: Option<Bindings>,
127 capabilities: Option<CapabilityDeclarations>,
128 events: Option<Vec<EventDeclaration>>,
129 self_signals: Option<Vec<SelfSignalDeclaration>>,
130 provenance: Option<ManifestProvenance>,
131 operation_delivery: BTreeMap<String, OperationDelivery>,
132}
133
134impl ModuleManifest {
135 pub fn builder(
143 module_id: impl Into<String>,
144 module_version: impl Into<String>,
145 ) -> ModuleManifestBuilder {
146 ModuleManifestBuilder {
147 module_id: module_id.into(),
148 module_version: module_version.into(),
149 protocol_ver: PROTOCOL_VERSION,
150 trust_tier: None,
151 ready: None,
152 provides: Vec::new(),
153 consumes: Vec::new(),
154 bindings: None,
155 capabilities: None,
156 events: None,
157 self_signals: None,
158 provenance: None,
159 operation_delivery: BTreeMap::new(),
160 }
161 }
162
163 pub fn is_watch_operation(&self, name: &str) -> bool {
168 self.operation_delivery
169 .get(name)
170 .is_some_and(OperationDelivery::is_watch)
171 && self.provides.iter().any(|role| match role {
172 ProviderRole::ManagementSurface { operations, .. } => operations
173 .iter()
174 .any(|op| op.name == name && op.kind == ManagementOperationKind::Query),
175 _ => false,
176 })
177 }
178}
179
180impl ModuleManifestBuilder {
181 pub fn protocol_ver(mut self, protocol_ver: u8) -> Self {
183 self.protocol_ver = protocol_ver;
184 self
185 }
186
187 pub fn trust_tier(mut self, trust_tier: Option<TrustTier>) -> Self {
191 self.trust_tier = trust_tier;
192 self
193 }
194
195 pub fn ready(mut self, ready: bool) -> Self {
197 self.ready = Some(ready);
198 self
199 }
200
201 pub fn provides(mut self, provides: Vec<ProviderRole>) -> Self {
203 self.provides = provides;
204 self
205 }
206
207 pub fn consumes(mut self, consumes: Vec<ConsumerRole>) -> Self {
209 self.consumes = consumes;
210 self
211 }
212
213 pub fn bindings(mut self, bindings: Option<Bindings>) -> Self {
217 self.bindings = bindings;
218 self
219 }
220
221 pub fn capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
223 self.capabilities = capabilities;
224 self
225 }
226
227 pub fn events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
229 self.events = events;
230 self
231 }
232
233 pub fn self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
235 self.self_signals = self_signals;
236 self
237 }
238
239 pub fn provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
241 self.provenance = provenance;
242 self
243 }
244
245 pub fn operation_delivery(
247 mut self,
248 operation_delivery: BTreeMap<String, OperationDelivery>,
249 ) -> Self {
250 self.operation_delivery = operation_delivery;
251 self
252 }
253
254 pub fn build(self) -> ModuleManifest {
256 ModuleManifest {
257 module_id: self.module_id,
258 module_version: self.module_version,
259 protocol_ver: self.protocol_ver,
260 trust_tier: self.trust_tier,
261 ready: self.ready,
262 provides: self.provides,
263 consumes: self.consumes,
264 bindings: self.bindings,
265 capabilities: self.capabilities,
266 events: self.events,
267 self_signals: self.self_signals,
268 provenance: self.provenance,
269 operation_delivery: self.operation_delivery,
270 }
271 }
272}
273
274#[derive(Deserialize)]
292struct ModuleManifestWire {
293 module_id: String,
294 module_version: String,
295 protocol_ver: u8,
296 #[serde(default)]
297 trust_tier: Option<TrustTier>,
298 #[serde(default)]
299 ready: Option<bool>,
300 provides: Vec<ProviderRole>,
301 #[serde(default)]
302 consumes: Vec<ConsumerRole>,
303 #[serde(default)]
304 bindings: Option<Bindings>,
305 #[serde(default)]
306 capabilities: Option<CapabilityDeclarations>,
307 #[serde(default)]
308 events: Option<Value>,
309 #[serde(default)]
310 self_signals: Option<Vec<SelfSignalDeclaration>>,
311 #[serde(default)]
312 provenance: Option<ManifestProvenance>,
313 #[serde(default)]
314 operation_delivery: Option<Value>,
315 #[serde(default)]
319 runtime_computed: Option<Value>,
320}
321
322impl<'de> Deserialize<'de> for ModuleManifest {
323 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
324 where
325 D: Deserializer<'de>,
326 {
327 let wire = ModuleManifestWire::deserialize(deserializer)?;
328 validate_runtime_computed(wire.runtime_computed.as_ref(), "runtime_computed")
329 .map_err(D::Error::custom)?;
330 validate_events_value(wire.events.as_ref()).map_err(D::Error::custom)?;
331 let events = wire
332 .events
333 .map(serde_json::from_value)
334 .transpose()
335 .map_err(D::Error::custom)?;
336 let mut builder = Self::builder(wire.module_id, wire.module_version)
337 .protocol_ver(wire.protocol_ver)
338 .trust_tier(wire.trust_tier);
339 if let Some(ready) = wire.ready {
340 builder = builder.ready(ready);
341 }
342 let manifest = builder
343 .provides(wire.provides)
344 .consumes(wire.consumes)
345 .bindings(wire.bindings)
346 .capabilities(wire.capabilities)
347 .events(events)
348 .self_signals(wire.self_signals)
349 .provenance(wire.provenance)
350 .operation_delivery(
351 wire.operation_delivery
352 .and_then(|value| serde_json::from_value(value).ok())
353 .unwrap_or_default(),
354 )
355 .build();
356 manifest
357 .validate_capability_grammar()
358 .map_err(D::Error::custom)?;
359 Ok(manifest)
360 }
361}
362
363pub const CAP_CATALOG_EVENTS_V1: &str = "catalog-events/v1";
369
370pub const CAP_SCOPE_BIND_PROOF_V1: &str = "scope-bind-proof/v1";
374
375pub const CAP_SCOPE_BIND_PROOF_V2: &str = "scope-bind-proof/v2";
379
380pub const CAP_SCOPE_REPLACE_IF_IDLE_V1: &str = "scope-replace-if-idle/v1";
382
383#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
385#[non_exhaustive]
386pub struct EventDeclaration {
387 pub name: String,
394 pub version: u32,
396 pub headers: Vec<String>,
399 #[serde(default, skip_serializing_if = "Option::is_none")]
401 pub summary: Option<String>,
402}
403
404impl EventDeclaration {
405 pub fn new(name: impl Into<String>, version: u32) -> Self {
408 Self {
409 name: name.into(),
410 version,
411 headers: Vec::new(),
412 summary: None,
413 }
414 }
415
416 pub fn with_headers(mut self, headers: Vec<String>) -> Self {
418 self.headers = headers;
419 self
420 }
421
422 pub fn with_summary(mut self, summary: Option<String>) -> Self {
424 self.summary = summary;
425 self
426 }
427}
428
429#[derive(Debug, Clone, PartialEq, Eq)]
431#[non_exhaustive]
432pub struct EventDeclarationError {
433 field: String,
434 reason: &'static str,
435}
436
437impl EventDeclarationError {
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 EventDeclarationError {
452 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
453 write!(
454 f,
455 "invalid event declaration: field {} {}",
456 self.field, self.reason
457 )
458 }
459}
460
461impl std::error::Error for EventDeclarationError {}
462
463pub fn validate_hello_event_declarations(hello: &Value) -> Result<(), EventDeclarationError> {
465 validate_events_value(
466 hello
467 .get("manifest")
468 .and_then(|manifest| manifest.get("events")),
469 )
470}
471
472fn is_valid_event_name(name: &str) -> bool {
475 let level_count = name.split('.').count();
476 (1..=4).contains(&level_count)
477 && name.split('.').all(|level| {
478 if level.is_empty() {
479 return false;
480 }
481 let first = level.as_bytes()[0];
482 (1..=63).contains(&level.len())
483 && (first.is_ascii_lowercase() || first.is_ascii_digit())
484 && level
485 .bytes()
486 .skip(1)
487 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
488 && !level.strip_prefix('v').is_some_and(|digits| {
489 !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit())
490 })
491 })
492}
493
494fn validate_events_value(value: Option<&Value>) -> Result<(), EventDeclarationError> {
495 let Some(value) = value.filter(|value| !value.is_null()) else {
496 return Ok(());
497 };
498 let entries = value
499 .as_array()
500 .ok_or_else(|| EventDeclarationError::new("events", "must be a list"))?;
501 if entries.len() > 64 {
502 return Err(EventDeclarationError::new(
503 "events",
504 "must contain at most 64 declarations",
505 ));
506 }
507 let mut pairs = HashSet::new();
508 for (index, entry) in entries.iter().enumerate() {
509 let field = format!("events[{index}]");
510 let entry = entry
511 .as_object()
512 .ok_or_else(|| EventDeclarationError::new(&field, "must be an object"))?;
513 let name_field = format!("{field}.name");
514 let name = entry
515 .get("name")
516 .and_then(Value::as_str)
517 .ok_or_else(|| EventDeclarationError::new(&name_field, "must be a string"))?;
518 if !is_valid_event_name(name) {
519 return Err(EventDeclarationError::new(
520 name_field,
521 "must contain one to four valid dot-separated event-name levels",
522 ));
523 }
524 let version = entry
525 .get("version")
526 .and_then(Value::as_u64)
527 .filter(|version| (1..=u32::MAX as u64).contains(version))
528 .ok_or_else(|| {
529 EventDeclarationError::new(
530 format!("{field}.version"),
531 "must be an integer between 1 and u32::MAX",
532 )
533 })?;
534 if !pairs.insert((name, version)) {
535 return Err(EventDeclarationError::new(
536 &field,
537 "duplicates an event (name, version) pair",
538 ));
539 }
540 let headers_field = format!("{field}.headers");
541 let headers = entry
542 .get("headers")
543 .and_then(Value::as_array)
544 .ok_or_else(|| EventDeclarationError::new(&headers_field, "must be a list"))?;
545 if headers.len() > 16 {
546 return Err(EventDeclarationError::new(
547 headers_field,
548 "must contain at most 16 headers",
549 ));
550 }
551 let mut names = HashSet::new();
552 for (header_index, header) in headers.iter().enumerate() {
553 let header_field = format!("{headers_field}[{header_index}]");
554 let header = header
555 .as_str()
556 .ok_or_else(|| EventDeclarationError::new(&header_field, "must be a string"))?;
557 if !(1..=32).contains(&header.len())
558 || !header.as_bytes()[0].is_ascii_lowercase()
559 || !header
560 .bytes()
561 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
562 {
563 return Err(EventDeclarationError::new(
564 header_field,
565 "must match [a-z][a-z0-9_]{0,31}",
566 ));
567 }
568 if !names.insert(header) {
569 return Err(EventDeclarationError::new(
570 header_field,
571 "duplicates a header name",
572 ));
573 }
574 }
575 if let Some(summary) = entry.get("summary").filter(|value| !value.is_null()) {
576 let summary_field = format!("{field}.summary");
577 let summary = summary
578 .as_str()
579 .ok_or_else(|| EventDeclarationError::new(&summary_field, "must be a string"))?;
580 if summary.chars().count() > 200 || summary.chars().any(char::is_control) {
581 return Err(EventDeclarationError::new(
582 summary_field,
583 "must contain at most 200 characters and no control characters",
584 ));
585 }
586 }
587 }
588 Ok(())
589}
590
591#[derive(Debug, Clone, PartialEq, Eq)]
593pub struct SelfSignalDeclarationError {
594 module_id: String,
595 entry_index: usize,
596 field: &'static str,
597}
598
599impl fmt::Display for SelfSignalDeclarationError {
600 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
601 write!(
602 f,
603 "module_id '{}' self_signals[{}] is missing required field '{}'",
604 self.module_id.escape_debug(),
605 self.entry_index,
606 self.field
607 )
608 }
609}
610
611pub fn validate_hello_self_signal_declarations(
618 hello: &Value,
619) -> Result<(), SelfSignalDeclarationError> {
620 let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
621 return Ok(());
622 };
623 let module_id = manifest
624 .get("module_id")
625 .and_then(Value::as_str)
626 .unwrap_or("<unknown>");
627 let Some(entries) = manifest.get("self_signals").and_then(Value::as_array) else {
628 return Ok(());
629 };
630
631 for (entry_index, entry) in entries.iter().enumerate() {
632 let Some(entry) = entry.as_object() else {
633 continue;
634 };
635 for field in ["effect", "anchored_to"] {
636 if !entry.contains_key(field) {
637 return Err(SelfSignalDeclarationError {
638 module_id: module_id.to_string(),
639 entry_index,
640 field,
641 });
642 }
643 }
644 }
645 Ok(())
646}
647
648#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
650#[serde(deny_unknown_fields)]
651pub struct CapabilityDeclarations {
652 #[serde(default)]
653 pub provides: Vec<String>,
654 #[serde(default)]
655 pub requires: Vec<CapabilityRequirement>,
656 #[serde(default)]
657 pub must_never_reach: Vec<String>,
658}
659
660#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
662pub struct SelfSignalDeclaration {
663 pub name: String,
665 pub kind: SelfSignalKind,
693 pub effect: SelfSignalEffect,
695 pub anchored_to: SignalAnchor,
697 #[serde(default, skip_serializing_if = "Option::is_none")]
704 pub cadence: Option<SignalCadence>,
705 #[serde(default, skip_serializing_if = "Option::is_none")]
707 pub domain: Option<String>,
708 #[serde(default, skip_serializing_if = "Option::is_none")]
709 pub note: Option<String>,
710}
711
712#[derive(Debug, Clone, PartialEq, Eq)]
714pub enum SelfSignalKind {
715 Keepalive,
716 Busy,
718 Poller,
719 Cron,
720 Sweep,
721 Watchdog,
722 Heartbeat,
723 Other(String),
724}
725
726impl SelfSignalKind {
727 fn wire_name(&self) -> &str {
728 match self {
729 Self::Keepalive => "keepalive",
730 Self::Busy => "busy",
731 Self::Poller => "poller",
732 Self::Cron => "cron",
733 Self::Sweep => "sweep",
734 Self::Watchdog => "watchdog",
735 Self::Heartbeat => "heartbeat",
736 Self::Other(value) => value,
737 }
738 }
739}
740
741impl Serialize for SelfSignalKind {
742 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
743 where
744 S: serde::Serializer,
745 {
746 serializer.serialize_str(self.wire_name())
747 }
748}
749
750impl<'de> Deserialize<'de> for SelfSignalKind {
751 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
752 where
753 D: Deserializer<'de>,
754 {
755 let value = String::deserialize(deserializer)?;
756 Ok(match value.as_str() {
757 "keepalive" => Self::Keepalive,
758 "busy" => Self::Busy,
759 "poller" => Self::Poller,
760 "cron" => Self::Cron,
761 "sweep" => Self::Sweep,
762 "watchdog" => Self::Watchdog,
763 "heartbeat" => Self::Heartbeat,
764 _ => Self::Other(value),
765 })
766 }
767}
768
769#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
771#[serde(rename_all = "lowercase")]
772pub enum SelfSignalEffect {
773 Observe,
774 Mutate,
775}
776
777#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
779#[serde(rename_all = "snake_case")]
780pub enum SignalAnchor {
781 FixedInterval,
784 Event { event: String },
787 HealthGauges { gauges: Vec<String> },
789}
790
791#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
793#[serde(rename_all = "snake_case")]
794pub enum SignalCadence {
795 Literal { interval_ms: u64 },
796 Derived { source: String },
797}
798
799#[derive(Serialize, Debug, Clone, Default, PartialEq, Eq)]
876#[non_exhaustive]
877pub struct ManifestProvenance {
878 #[serde(default, skip_serializing_if = "Option::is_none")]
879 pub build_git_sha: Option<String>,
880 #[serde(default, skip_serializing_if = "Option::is_none")]
884 pub build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
885 #[serde(default, skip_serializing_if = "Option::is_none")]
886 pub build_lock_digest: Option<String>,
887 #[serde(default, skip_serializing_if = "Option::is_none")]
896 pub wire_crate_version: Option<String>,
897 #[serde(default, skip_serializing_if = "Option::is_none")]
898 pub store_schema_version: Option<String>,
899 #[serde(default, skip_serializing_if = "Option::is_none")]
905 pub launch_nonce_source: Option<LaunchNonceSource>,
906}
907
908#[derive(Debug, Clone, PartialEq, Eq)]
915#[non_exhaustive]
916pub enum LaunchNonceSource {
917 Fd,
919 Pipe,
921 Env,
923 ForwardCompatibleUnknown(String),
924}
925
926impl LaunchNonceSource {
927 pub fn wire_name(&self) -> &str {
929 match self {
930 Self::Fd => "fd",
931 Self::Pipe => "pipe",
932 Self::Env => "env",
933 Self::ForwardCompatibleUnknown(value) => value,
934 }
935 }
936
937 pub fn from_wire_name(value: &str) -> Self {
939 match value {
940 "fd" => Self::Fd,
941 "pipe" => Self::Pipe,
942 "env" => Self::Env,
943 _ => Self::ForwardCompatibleUnknown(value.to_string()),
944 }
945 }
946}
947
948impl Serialize for LaunchNonceSource {
949 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
950 where
951 S: serde::Serializer,
952 {
953 serializer.serialize_str(self.wire_name())
954 }
955}
956
957impl<'de> Deserialize<'de> for LaunchNonceSource {
958 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
959 where
960 D: serde::Deserializer<'de>,
961 {
962 let value = String::deserialize(deserializer)?;
963 Ok(Self::from_wire_name(&value))
964 }
965}
966
967#[derive(Debug, Clone, PartialEq, Eq)]
972pub enum BuildGitShaAbsenceReason {
973 DeclinedDirty,
974 NeverDerived,
975 NoGitDir,
976 ForwardCompatibleUnknown(String),
977}
978
979impl BuildGitShaAbsenceReason {
980 fn wire_name(&self) -> &str {
981 match self {
982 Self::DeclinedDirty => "declined_dirty",
983 Self::NeverDerived => "never_derived",
984 Self::NoGitDir => "no_git_dir",
985 Self::ForwardCompatibleUnknown(value) => value,
986 }
987 }
988}
989
990impl Serialize for BuildGitShaAbsenceReason {
991 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
992 where
993 S: serde::Serializer,
994 {
995 serializer.serialize_str(self.wire_name())
996 }
997}
998
999impl<'de> Deserialize<'de> for BuildGitShaAbsenceReason {
1000 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1001 where
1002 D: serde::Deserializer<'de>,
1003 {
1004 let value = String::deserialize(deserializer)?;
1005 Ok(match value.as_str() {
1006 "declined_dirty" => Self::DeclinedDirty,
1007 "never_derived" => Self::NeverDerived,
1008 "no_git_dir" => Self::NoGitDir,
1009 _ => Self::ForwardCompatibleUnknown(value),
1010 })
1011 }
1012}
1013
1014#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1016pub enum GitTreeState {
1017 Clean,
1018 Dirty,
1019}
1020
1021#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1026pub enum BuildGitShaSource<'a> {
1027 Git {
1028 revision: &'a str,
1029 tree_state: GitTreeState,
1030 },
1031 NeverDerived,
1032 NoGitDir,
1033}
1034
1035pub fn attestable_commit(revision: &str, tree_state: GitTreeState) -> Option<&str> {
1039 match tree_state {
1040 GitTreeState::Clean => Some(revision),
1041 GitTreeState::Dirty => None,
1042 }
1043}
1044
1045const MAX_PROVENANCE_VALUE_BYTES: usize = 128;
1046const BUILD_GIT_SHA_CANONICAL_FORM: &str = "exactly 40 lowercase hexadecimal characters";
1047const BUILD_LOCK_DIGEST_CANONICAL_FORM: &str = "exactly 64 lowercase hexadecimal characters";
1048
1049#[derive(Deserialize)]
1050struct ManifestProvenanceWire {
1051 #[serde(default)]
1052 build_git_sha: Option<String>,
1053 #[serde(default)]
1054 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1055 #[serde(default)]
1056 build_lock_digest: Option<String>,
1057 #[serde(default)]
1058 wire_crate_version: Option<String>,
1059 #[serde(default)]
1060 store_schema_version: Option<String>,
1061 #[serde(default)]
1062 launch_nonce_source: Option<LaunchNonceSource>,
1063}
1064
1065impl<'de> Deserialize<'de> for ManifestProvenance {
1066 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1067 where
1068 D: Deserializer<'de>,
1069 {
1070 let wire = ManifestProvenanceWire::deserialize(deserializer)?;
1071 let provenance = Self {
1072 build_git_sha: wire.build_git_sha,
1073 build_git_sha_absence_reason: wire.build_git_sha_absence_reason,
1074 build_lock_digest: wire.build_lock_digest,
1075 wire_crate_version: wire.wire_crate_version,
1076 store_schema_version: wire.store_schema_version,
1077 launch_nonce_source: wire.launch_nonce_source,
1078 };
1079 provenance.validate().map_err(D::Error::custom)?;
1080 Ok(provenance)
1081 }
1082}
1083
1084#[derive(Debug, Clone, PartialEq, Eq)]
1086pub struct ProvenanceFormError {
1087 field: &'static str,
1088 length: usize,
1089 canonical_form: &'static str,
1090}
1091
1092impl ProvenanceFormError {
1093 fn new(field: &'static str, length: usize, canonical_form: &'static str) -> Self {
1094 Self {
1095 field,
1096 length,
1097 canonical_form,
1098 }
1099 }
1100
1101 pub fn field(&self) -> &str {
1103 self.field
1104 }
1105
1106 pub fn length(&self) -> usize {
1108 self.length
1109 }
1110
1111 pub fn canonical_form(&self) -> &str {
1113 self.canonical_form
1114 }
1115}
1116
1117impl fmt::Display for ProvenanceFormError {
1118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1119 write!(
1120 f,
1121 "invalid manifest provenance form: field {} has length {}; canonical form is {}",
1122 self.field, self.length, self.canonical_form
1123 )
1124 }
1125}
1126
1127impl std::error::Error for ProvenanceFormError {}
1128
1129#[derive(Debug, Clone, PartialEq, Eq)]
1130pub struct ManifestProvenanceError {
1131 field: String,
1132 value: String,
1133 reason: &'static str,
1134}
1135
1136impl ManifestProvenanceError {
1137 fn new(field: &str, value: &str, reason: &'static str) -> Self {
1138 Self {
1139 field: field.to_string(),
1140 value: safe_error_value(value),
1141 reason,
1142 }
1143 }
1144
1145 pub fn field(&self) -> &str {
1146 &self.field
1147 }
1148}
1149
1150impl fmt::Display for ManifestProvenanceError {
1151 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1152 write!(
1153 f,
1154 "invalid manifest provenance: field {} has {} (value {:?})",
1155 self.field, self.reason, self.value
1156 )
1157 }
1158}
1159
1160impl std::error::Error for ManifestProvenanceError {}
1161
1162impl ManifestProvenance {
1163 pub fn new() -> Self {
1165 Self::default()
1166 }
1167
1168 pub fn with_build_git_sha(mut self, value: Option<String>) -> Self {
1169 self.build_git_sha = value;
1170 self
1171 }
1172
1173 pub fn with_build_git_sha_absence_reason(
1174 mut self,
1175 value: Option<BuildGitShaAbsenceReason>,
1176 ) -> Self {
1177 self.build_git_sha_absence_reason = value;
1178 self
1179 }
1180
1181 pub fn with_build_lock_digest(mut self, value: Option<String>) -> Self {
1182 self.build_lock_digest = value;
1183 self
1184 }
1185
1186 pub fn with_wire_crate_version(mut self, value: Option<String>) -> Self {
1187 self.wire_crate_version = value;
1188 self
1189 }
1190
1191 pub fn with_store_schema_version(mut self, value: Option<String>) -> Self {
1192 self.store_schema_version = value;
1193 self
1194 }
1195
1196 pub fn with_launch_nonce_source(mut self, value: Option<LaunchNonceSource>) -> Self {
1201 self.launch_nonce_source = value;
1202 self
1203 }
1204
1205 pub fn validate(&self) -> Result<(), ManifestProvenanceError> {
1206 if let (Some(_), Some(reason)) = (
1207 self.build_git_sha.as_ref(),
1208 self.build_git_sha_absence_reason.as_ref(),
1209 ) {
1210 return Err(ManifestProvenanceError::new(
1211 "build_git_sha_absence_reason",
1212 reason.wire_name(),
1213 "must be omitted when build_git_sha is present",
1214 ));
1215 }
1216 for (field, value) in [
1217 ("build_git_sha", self.build_git_sha.as_deref()),
1218 (
1219 "build_git_sha_absence_reason",
1220 self.build_git_sha_absence_reason
1221 .as_ref()
1222 .map(|reason| reason.wire_name()),
1223 ),
1224 ("build_lock_digest", self.build_lock_digest.as_deref()),
1225 ("wire_crate_version", self.wire_crate_version.as_deref()),
1226 ("store_schema_version", self.store_schema_version.as_deref()),
1227 (
1228 "launch_nonce_source",
1229 self.launch_nonce_source
1230 .as_ref()
1231 .map(|source| source.wire_name()),
1232 ),
1233 ] {
1234 let Some(value) = value else { continue };
1235 if value.is_empty() {
1236 return Err(ManifestProvenanceError::new(
1237 field,
1238 value,
1239 "must not be empty",
1240 ));
1241 }
1242 if value.len() > MAX_PROVENANCE_VALUE_BYTES {
1247 return Err(ManifestProvenanceError::new(
1248 field,
1249 value,
1250 "exceeds the 128-byte maximum",
1251 ));
1252 }
1253 if value.bytes().any(|byte| !(0x20..=0x7e).contains(&byte)) {
1254 return Err(ManifestProvenanceError::new(
1255 field,
1256 value,
1257 "contains non-printable ASCII",
1258 ));
1259 }
1260 }
1261 Ok(())
1262 }
1263}
1264
1265pub fn build_provenance(
1283 build_git_sha: Option<&str>,
1284 build_lock_digest: Option<&str>,
1285 store_schema_version: Option<&str>,
1286) -> Result<ManifestProvenance, ProvenanceFormError> {
1287 let build_git_sha = normalize_and_validate_build_git_sha(build_git_sha)?;
1288 build_provenance_with_build_git_sha(
1289 build_git_sha,
1290 None,
1291 build_lock_digest,
1292 store_schema_version,
1293 )
1294}
1295
1296pub fn build_provenance_from_source(
1312 build_git_sha_source: BuildGitShaSource<'_>,
1313 build_lock_digest: Option<&str>,
1314 store_schema_version: Option<&str>,
1315) -> Result<ManifestProvenance, ProvenanceFormError> {
1316 let (raw_build_git_sha, mut build_git_sha_absence_reason) = match build_git_sha_source {
1317 BuildGitShaSource::Git {
1318 revision,
1319 tree_state,
1320 } => match attestable_commit(revision, tree_state) {
1321 Some(revision) => (Some(revision), None),
1322 None => (None, Some(BuildGitShaAbsenceReason::DeclinedDirty)),
1323 },
1324 BuildGitShaSource::NeverDerived => (None, Some(BuildGitShaAbsenceReason::NeverDerived)),
1325 BuildGitShaSource::NoGitDir => (None, Some(BuildGitShaAbsenceReason::NoGitDir)),
1326 };
1327 let build_git_sha = normalize_and_validate_build_git_sha(raw_build_git_sha)?;
1328 if build_git_sha.is_none() {
1329 build_git_sha_absence_reason.get_or_insert(BuildGitShaAbsenceReason::NeverDerived);
1330 }
1331 build_provenance_with_build_git_sha(
1332 build_git_sha,
1333 build_git_sha_absence_reason,
1334 build_lock_digest,
1335 store_schema_version,
1336 )
1337}
1338
1339fn normalize_and_validate_build_git_sha(
1340 build_git_sha: Option<&str>,
1341) -> Result<Option<String>, ProvenanceFormError> {
1342 let build_git_sha = normalize_provenance_fact(build_git_sha);
1343 validate_provenance_form(
1344 "build_git_sha",
1345 build_git_sha.as_deref(),
1346 BUILD_GIT_SHA_CANONICAL_FORM,
1347 40,
1348 )?;
1349 Ok(build_git_sha)
1350}
1351
1352fn build_provenance_with_build_git_sha(
1353 build_git_sha: Option<String>,
1354 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1355 build_lock_digest: Option<&str>,
1356 store_schema_version: Option<&str>,
1357) -> Result<ManifestProvenance, ProvenanceFormError> {
1358 let build_lock_digest = normalize_provenance_fact(build_lock_digest);
1359 validate_provenance_form(
1360 "build_lock_digest",
1361 build_lock_digest.as_deref(),
1362 BUILD_LOCK_DIGEST_CANONICAL_FORM,
1363 64,
1364 )?;
1365
1366 Ok(ManifestProvenance {
1367 build_git_sha,
1368 build_git_sha_absence_reason,
1369 build_lock_digest,
1370 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
1371 store_schema_version: normalize_provenance_fact(store_schema_version),
1372 launch_nonce_source: None,
1373 })
1374}
1375
1376fn validate_provenance_form(
1377 field: &'static str,
1378 value: Option<&str>,
1379 canonical_form: &'static str,
1380 expected_length: usize,
1381) -> Result<(), ProvenanceFormError> {
1382 let Some(value) = value else { return Ok(()) };
1383 if value.len() != expected_length
1384 || !value
1385 .bytes()
1386 .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
1387 {
1388 return Err(ProvenanceFormError::new(field, value.len(), canonical_form));
1389 }
1390 Ok(())
1391}
1392
1393pub const PROVENANCE_SENTINELS: [&str; 3] = ["unknown", "unavailable", "none"];
1401
1402fn normalize_provenance_fact(value: Option<&str>) -> Option<String> {
1403 let value = value?.trim();
1404 if value.is_empty() {
1405 return None;
1406 }
1407 let lowered = value.to_ascii_lowercase();
1408 if PROVENANCE_SENTINELS.contains(&lowered.as_str()) {
1409 return None;
1410 }
1411 Some(value.to_string())
1412}
1413
1414#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1416#[serde(deny_unknown_fields)]
1417pub struct CapabilityRequirement {
1418 pub capability: String,
1419 pub need: CapabilityNeed,
1420}
1421
1422#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1424#[serde(rename_all = "snake_case")]
1425pub enum CapabilityNeed {
1426 Required,
1427 Optional,
1428}
1429
1430#[derive(Debug, Clone, PartialEq, Eq)]
1432pub struct CapabilityGrammarError {
1433 field: String,
1434 value: String,
1435}
1436
1437impl CapabilityGrammarError {
1438 fn new(field: impl Into<String>, value: impl AsRef<str>) -> Self {
1439 Self {
1440 field: field.into(),
1441 value: safe_error_value(value.as_ref()),
1442 }
1443 }
1444
1445 pub fn field(&self) -> &str {
1447 &self.field
1448 }
1449
1450 pub fn value(&self) -> &str {
1452 &self.value
1453 }
1454}
1455
1456impl fmt::Display for CapabilityGrammarError {
1457 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1458 write!(
1459 f,
1460 "invalid capability grammar: field {} has offending value {:?}",
1461 self.field, self.value
1462 )
1463 }
1464}
1465
1466impl std::error::Error for CapabilityGrammarError {}
1467
1468impl ModuleManifest {
1469 pub fn validate_capability_grammar(&self) -> Result<(), CapabilityGrammarError> {
1471 let Some(capabilities) = &self.capabilities else {
1472 return Ok(());
1473 };
1474
1475 validate_capability_list("capabilities.provides", &capabilities.provides)?;
1476 validate_requires(&capabilities.requires)?;
1477 validate_capability_list(
1478 "capabilities.must_never_reach",
1479 &capabilities.must_never_reach,
1480 )
1481 }
1482}
1483
1484pub fn validate_manifest_capability_grammar(
1489 manifest: &Value,
1490) -> Result<(), CapabilityGrammarError> {
1491 let Some(object) = manifest.as_object() else {
1492 return Ok(());
1493 };
1494
1495 validate_capabilities_value(object.get("capabilities"))?;
1496 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
1497}
1498
1499pub fn validate_hello_capability_grammar(hello: &Value) -> Result<(), CapabilityGrammarError> {
1505 let Some(object) = hello.as_object() else {
1506 return Ok(());
1507 };
1508 if let Some(manifest) = object.get("manifest") {
1509 validate_manifest_capability_grammar(manifest)?;
1510 }
1511 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
1512}
1513
1514pub fn is_valid_capability_identifier(identifier: &str) -> bool {
1516 if identifier.chars().any(char::is_whitespace) {
1517 return false;
1518 }
1519 let Some((name, version)) = identifier.split_once("/v") else {
1520 return false;
1521 };
1522 if name.is_empty() || name.len() > 64 || version.is_empty() {
1523 return false;
1524 }
1525
1526 let name_bytes = name.as_bytes();
1527 if !name_bytes[0].is_ascii_lowercase()
1528 || (name.len() > 1
1529 && !name_bytes[name.len() - 1].is_ascii_lowercase()
1530 && !name_bytes[name.len() - 1].is_ascii_digit())
1531 || name_bytes.windows(2).any(|pair| pair == b"--")
1532 {
1533 return false;
1534 }
1535 if !name_bytes
1536 .iter()
1537 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-')
1538 {
1539 return false;
1540 }
1541
1542 if version.len() > 1 && version.starts_with('0')
1543 || !version.bytes().all(|byte| byte.is_ascii_digit())
1544 {
1545 return false;
1546 }
1547 matches!(
1548 version.parse::<u64>(),
1549 Ok(value) if (1..=u64::from(u32::MAX)).contains(&value)
1550 )
1551}
1552
1553fn validate_capabilities_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
1554 let Some(value) = value else {
1555 return Ok(());
1556 };
1557 let Some(object) = value.as_object() else {
1558 return Err(CapabilityGrammarError::new(
1559 "capabilities",
1560 value_description(value),
1561 ));
1562 };
1563
1564 for (key, value) in object {
1565 if !matches!(key.as_str(), "provides" | "requires" | "must_never_reach") {
1566 return Err(CapabilityGrammarError::new(
1567 field_child("capabilities", key),
1568 value_description(value),
1569 ));
1570 }
1571 }
1572
1573 validate_capability_list_value("capabilities.provides", object.get("provides"))?;
1574 validate_requires_value(object.get("requires"))?;
1575 validate_capability_list_value(
1576 "capabilities.must_never_reach",
1577 object.get("must_never_reach"),
1578 )
1579}
1580
1581fn validate_capability_list_value(
1582 field: &str,
1583 value: Option<&Value>,
1584) -> Result<(), CapabilityGrammarError> {
1585 let Some(value) = value else {
1586 return Ok(());
1587 };
1588 let Some(values) = value.as_array() else {
1589 return Err(CapabilityGrammarError::new(field, value_description(value)));
1590 };
1591
1592 let mut seen = HashSet::new();
1593 for (index, value) in values.iter().enumerate() {
1594 let field = format!("{field}[{index}]");
1595 let Some(identifier) = value.as_str() else {
1596 return Err(CapabilityGrammarError::new(field, value_description(value)));
1597 };
1598 validate_capability_identifier(&field, identifier)?;
1599 if !seen.insert(identifier) {
1600 return Err(CapabilityGrammarError::new(field, identifier));
1601 }
1602 }
1603 Ok(())
1604}
1605
1606fn validate_requires_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
1607 let Some(value) = value else {
1608 return Ok(());
1609 };
1610 let Some(values) = value.as_array() else {
1611 return Err(CapabilityGrammarError::new(
1612 "capabilities.requires",
1613 value_description(value),
1614 ));
1615 };
1616
1617 let mut seen = HashSet::new();
1618 for (index, value) in values.iter().enumerate() {
1619 let entry_field = format!("capabilities.requires[{index}]");
1620 let Some(object) = value.as_object() else {
1621 return Err(CapabilityGrammarError::new(
1622 entry_field,
1623 value_description(value),
1624 ));
1625 };
1626 for (key, value) in object {
1627 if !matches!(key.as_str(), "capability" | "need") {
1628 return Err(CapabilityGrammarError::new(
1629 field_child(&entry_field, key),
1630 value_description(value),
1631 ));
1632 }
1633 }
1634 let capability_field = format!("{entry_field}.capability");
1635 let Some(capability) = object.get("capability").and_then(Value::as_str) else {
1636 return Err(CapabilityGrammarError::new(
1637 capability_field,
1638 object
1639 .get("capability")
1640 .map_or("<missing>".to_string(), value_description),
1641 ));
1642 };
1643 validate_capability_identifier(&capability_field, capability)?;
1644
1645 let need_field = format!("{entry_field}.need");
1646 let Some(need) = object.get("need").and_then(Value::as_str) else {
1647 return Err(CapabilityGrammarError::new(
1648 need_field,
1649 object
1650 .get("need")
1651 .map_or("<missing>".to_string(), value_description),
1652 ));
1653 };
1654 if !matches!(need, "required" | "optional") {
1655 return Err(CapabilityGrammarError::new(need_field, need));
1656 }
1657 if !seen.insert(capability) {
1658 return Err(CapabilityGrammarError::new(entry_field, capability));
1659 }
1660 }
1661 Ok(())
1662}
1663
1664fn validate_capability_list(field: &str, values: &[String]) -> Result<(), CapabilityGrammarError> {
1665 let mut seen = HashSet::new();
1666 for (index, identifier) in values.iter().enumerate() {
1667 let field = format!("{field}[{index}]");
1668 validate_capability_identifier(&field, identifier)?;
1669 if !seen.insert(identifier) {
1670 return Err(CapabilityGrammarError::new(field, identifier));
1671 }
1672 }
1673 Ok(())
1674}
1675
1676fn validate_requires(values: &[CapabilityRequirement]) -> Result<(), CapabilityGrammarError> {
1677 let mut seen = HashSet::new();
1678 for (index, requirement) in values.iter().enumerate() {
1679 let field = format!("capabilities.requires[{index}].capability");
1680 validate_capability_identifier(&field, &requirement.capability)?;
1681 if !seen.insert(&requirement.capability) {
1682 return Err(CapabilityGrammarError::new(
1683 format!("capabilities.requires[{index}]"),
1684 &requirement.capability,
1685 ));
1686 }
1687 }
1688 Ok(())
1689}
1690
1691fn validate_capability_identifier(
1692 field: &str,
1693 identifier: &str,
1694) -> Result<(), CapabilityGrammarError> {
1695 if is_valid_capability_identifier(identifier) {
1696 Ok(())
1697 } else {
1698 Err(CapabilityGrammarError::new(field, identifier))
1699 }
1700}
1701
1702fn validate_runtime_computed(
1703 value: Option<&Value>,
1704 field: &str,
1705) -> Result<(), CapabilityGrammarError> {
1706 let Some(value) = value else {
1707 return Ok(());
1708 };
1709 let Some(pointers) = value.as_array() else {
1710 return Err(CapabilityGrammarError::new(field, value_description(value)));
1711 };
1712
1713 for (index, pointer) in pointers.iter().enumerate() {
1714 let field = format!("{field}[{index}]");
1715 let Some(pointer) = pointer.as_str() else {
1716 return Err(CapabilityGrammarError::new(
1717 field,
1718 value_description(pointer),
1719 ));
1720 };
1721 let Some(tokens) = parse_json_pointer(pointer) else {
1722 return Err(CapabilityGrammarError::new(field, pointer));
1723 };
1724 if tokens.first().is_some_and(|token| token == "capabilities") {
1725 return Err(CapabilityGrammarError::new(field, pointer));
1726 }
1727 }
1728 Ok(())
1729}
1730
1731fn parse_json_pointer(pointer: &str) -> Option<Vec<String>> {
1732 if pointer.is_empty() {
1733 return Some(Vec::new());
1734 }
1735 let raw_tokens = pointer.strip_prefix('/')?;
1736 raw_tokens
1737 .split('/')
1738 .map(unescape_json_pointer_token)
1739 .collect()
1740}
1741
1742fn unescape_json_pointer_token(token: &str) -> Option<String> {
1743 let mut output = String::with_capacity(token.len());
1744 let mut characters = token.chars();
1745 while let Some(character) = characters.next() {
1746 if character != '~' {
1747 output.push(character);
1748 continue;
1749 }
1750 match characters.next()? {
1751 '0' => output.push('~'),
1752 '1' => output.push('/'),
1753 _ => return None,
1754 }
1755 }
1756 Some(output)
1757}
1758
1759fn field_child(parent: &str, child: &str) -> String {
1760 let child = safe_error_value(child);
1761 format!("{parent}.{child}")
1762}
1763
1764fn value_description(value: &Value) -> String {
1765 match value {
1766 Value::String(value) => safe_error_value(value),
1767 Value::Null => "null".to_string(),
1768 Value::Bool(value) => value.to_string(),
1769 Value::Number(value) => value.to_string(),
1770 Value::Array(_) => "<array>".to_string(),
1771 Value::Object(_) => "<object>".to_string(),
1772 }
1773}
1774
1775fn safe_error_value(value: &str) -> String {
1776 let lower = value.to_ascii_lowercase();
1777 if ["secret", "password", "api_key"]
1778 .iter()
1779 .any(|marker| lower.contains(marker))
1780 || lower.starts_with("sk-")
1781 || lower.starts_with("akia")
1782 || lower.starts_with("bearer ")
1783 || lower.starts_with("token=")
1784 || lower.starts_with("credential=")
1785 {
1786 "<redacted>".to_string()
1787 } else {
1788 value.to_string()
1789 }
1790}
1791
1792#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
1798#[serde(rename_all = "snake_case")]
1799pub enum TrustTier {
1800 FirstParty,
1801 Reviewed,
1802 Untrusted,
1803}
1804
1805#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
1809#[serde(tag = "role", rename_all = "snake_case")]
1810pub enum ProviderRole {
1811 ToolProvider {
1812 tools: Vec<Tool>,
1813 identity_scope: Vec<IdentityScope>,
1821 concurrency: Concurrency,
1822 emits_push: bool,
1823 sub_supervises: bool,
1824 },
1825 PipelineStage {
1826 stage: PipelineStageKind,
1827 applies_to: PipelineAppliesTo,
1828 interface: String,
1829 declares_frozen_floor: bool,
1830 needs_signals: Vec<String>,
1831 conformance_class: String,
1832 },
1833 ManagementSurface {
1834 operations: Vec<ManagementOperation>,
1835 config_schema: Value,
1836 observability: Vec<ObservabilitySurface>,
1837 identity_scope: Vec<IdentityScope>,
1841 #[serde(default)]
1842 concurrency: Concurrency,
1843 },
1844 InternalService {
1845 service_id: String,
1846 transport: InternalTransport,
1847 agent_facing: bool,
1848 operations: Vec<String>,
1849 },
1850}
1851
1852#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1865#[serde(rename_all = "snake_case")]
1866pub enum ExecutionMode {
1867 Pure,
1868 Mutating,
1869 Unfenceable,
1870}
1871
1872#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
1874pub struct Tool {
1875 pub name: String,
1876 #[serde(default, skip_serializing_if = "Option::is_none")]
1877 pub description: Option<String>,
1878 pub execution_mode: ExecutionMode,
1883 pub schema: Value,
1884}
1885
1886#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
1892#[serde(rename_all = "snake_case")]
1893pub enum Concurrency {
1894 Serial,
1896 ModuleManaged,
1899 StatelessParallel,
1902}
1903
1904#[allow(clippy::derivable_impls)]
1905impl Default for Concurrency {
1916 fn default() -> Self {
1917 Self::ModuleManaged
1918 }
1919}
1920
1921#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
1928#[serde(rename_all = "snake_case")]
1929pub enum IdentityScope {
1930 Session,
1931 Project,
1932}
1933
1934#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
1936#[serde(rename_all = "snake_case")]
1937pub enum PipelineStageKind {
1938 Transform,
1939 Codec,
1940 Auth,
1941}
1942
1943#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
1945pub struct PipelineAppliesTo {
1946 pub provider: String,
1947 pub model: String,
1948}
1949
1950#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
1955pub struct ManagementOperation {
1956 pub name: String,
1957 pub kind: ManagementOperationKind,
1958 #[serde(default, skip_serializing_if = "Option::is_none")]
1959 pub description: Option<String>,
1960}
1961
1962#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
1963#[serde(rename_all = "snake_case")]
1964pub enum ManagementOperationKind {
1965 Query,
1966 Mutate,
1967}
1968
1969#[derive(Debug, Clone, PartialEq, Eq)]
1972#[non_exhaustive]
1973pub enum OperationDelivery {
1974 Watch,
1975 Other(String),
1976}
1977
1978impl OperationDelivery {
1979 pub const WATCH: Self = Self::Watch;
1981
1982 pub fn wire_name(&self) -> &str {
1984 match self {
1985 Self::Watch => "watch",
1986 Self::Other(value) => value,
1987 }
1988 }
1989
1990 pub fn is_watch(&self) -> bool {
1992 self.wire_name() == "watch"
1993 }
1994}
1995
1996impl Serialize for OperationDelivery {
1997 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1998 where
1999 S: serde::Serializer,
2000 {
2001 serializer.serialize_str(self.wire_name())
2002 }
2003}
2004
2005impl<'de> Deserialize<'de> for OperationDelivery {
2006 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2007 where
2008 D: Deserializer<'de>,
2009 {
2010 let value = String::deserialize(deserializer)?;
2011 Ok(if value == "watch" {
2012 Self::WATCH
2013 } else {
2014 Self::Other(value)
2015 })
2016 }
2017}
2018
2019#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2021pub struct ObservabilitySurface {
2022 pub name: String,
2023 pub kind: ObservabilityKind,
2024}
2025
2026#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2027#[serde(rename_all = "snake_case")]
2028pub enum ObservabilityKind {
2029 Snapshot,
2030 Stream,
2031}
2032
2033#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2034#[serde(rename_all = "snake_case")]
2035pub enum InternalTransport {
2036 Bulk,
2037}
2038
2039#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2041#[serde(tag = "role", rename_all = "snake_case")]
2042pub enum ConsumerRole {
2043 ToolClient { of: Vec<String> },
2044 LlmClient { via: String, auth: String },
2045 ServiceClient { of: Vec<String> },
2046}
2047
2048#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2050pub struct Bindings {
2051 pub storage: StorageBinding,
2052 pub vault_grants: Vec<VaultGrant>,
2053 pub identity: IdentityBinding,
2054}
2055
2056#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2058pub struct StorageBinding {
2059 pub kind: StorageKind,
2060 pub scope: StorageScope,
2061 pub owns_schema: bool,
2062}
2063
2064#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2065#[serde(rename_all = "snake_case")]
2066pub enum StorageKind {
2067 Sqlite,
2068}
2069
2070#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2071#[serde(rename_all = "snake_case")]
2072pub enum StorageScope {
2073 Project,
2074}
2075
2076#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2077pub struct VaultGrant {
2078 pub secret: String,
2079 pub reason: String,
2080}
2081
2082#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2083pub struct IdentityBinding {
2084 pub requires: Vec<IdentityScope>,
2085 pub optional: Vec<IdentityScope>,
2086}
2087
2088#[cfg(test)]
2089mod tests {
2090 use super::*;
2091 use serde_json::json;
2092
2093 fn aft_manifest_fixture() -> ModuleManifest {
2094 ModuleManifest::builder("aft", "0.39.2")
2095 .trust_tier(Some(TrustTier::FirstParty))
2096 .bindings(Some(Bindings {
2097 storage: StorageBinding {
2098 kind: StorageKind::Sqlite,
2099 scope: StorageScope::Project,
2100 owns_schema: true,
2101 },
2102 vault_grants: vec![VaultGrant {
2103 secret: "provider_api_key".to_string(),
2104 reason: "cortexkit_native auth".to_string(),
2105 }],
2106 identity: IdentityBinding {
2107 requires: vec![IdentityScope::Project],
2108 optional: vec![IdentityScope::Session],
2109 },
2110 }))
2111 .protocol_ver(1)
2112 .provides(vec![ProviderRole::ToolProvider {
2113 tools: vec![
2114 Tool {
2115 name: "read".to_string(),
2116 description: None,
2117 execution_mode: ExecutionMode::Pure,
2118 schema: json!({"type": "object"}),
2119 },
2120 Tool {
2121 name: "grep".to_string(),
2122 description: None,
2123 execution_mode: ExecutionMode::Pure,
2124 schema: json!({"type": "object"}),
2125 },
2126 Tool {
2127 name: "outline".to_string(),
2128 description: None,
2129 execution_mode: ExecutionMode::Pure,
2130 schema: json!({"type": "object"}),
2131 },
2132 Tool {
2133 name: "semantic_search".to_string(),
2134 description: None,
2135 execution_mode: ExecutionMode::Pure,
2136 schema: json!({"type": "object"}),
2137 },
2138 Tool {
2139 name: "edit".to_string(),
2140 description: None,
2141 execution_mode: ExecutionMode::Mutating,
2142 schema: json!({"type": "object"}),
2143 },
2144 Tool {
2145 name: "write".to_string(),
2146 description: None,
2147 execution_mode: ExecutionMode::Mutating,
2148 schema: json!({"type": "object"}),
2149 },
2150 Tool {
2151 name: "bash".to_string(),
2152 description: None,
2153 execution_mode: ExecutionMode::Unfenceable,
2154 schema: json!({"type": "object"}),
2155 },
2156 ],
2157 identity_scope: vec![IdentityScope::Session, IdentityScope::Project],
2158 concurrency: Concurrency::ModuleManaged,
2159 emits_push: true,
2160 sub_supervises: true,
2161 }])
2162 .consumes(vec![ConsumerRole::ServiceClient {
2163 of: vec!["embedding.v2".to_string()],
2164 }])
2165 .build()
2166 }
2167
2168 #[test]
2169 fn serde_round_trips_representative_manifest() {
2170 let manifest = aft_manifest_fixture();
2171 let serialized = serde_json::to_string_pretty(&manifest).unwrap();
2172 let decoded: ModuleManifest = serde_json::from_str(&serialized).unwrap();
2173
2174 assert_eq!(manifest, decoded);
2175 }
2176
2177 #[test]
2178 fn builder_defaults_additions_to_honest_absence_and_round_trips() {
2179 let manifest = ModuleManifest::builder("builder-defaults", "2.0.0").build();
2180
2181 assert_eq!(manifest.module_id, "builder-defaults");
2182 assert_eq!(manifest.module_version, "2.0.0");
2183 assert_eq!(manifest.protocol_ver, PROTOCOL_VERSION);
2184 assert_eq!(manifest.trust_tier, None);
2185 assert!(manifest.provides.is_empty());
2186 assert!(manifest.consumes.is_empty());
2187 assert_eq!(manifest.bindings, None);
2188 assert_eq!(manifest.capabilities, None);
2189 assert_eq!(manifest.self_signals, None);
2190 assert_eq!(manifest.provenance, None);
2191
2192 let encoded = serde_json::to_value(&manifest).expect("builder manifest serializes");
2193 for optional in [
2194 "trust_tier",
2195 "consumes",
2196 "bindings",
2197 "capabilities",
2198 "self_signals",
2199 "provenance",
2200 ] {
2201 assert!(
2202 encoded.get(optional).is_none(),
2203 "an absent {optional} declaration must stay absent on the wire"
2204 );
2205 }
2206 let decoded: ModuleManifest =
2207 serde_json::from_value(encoded).expect("builder manifest round-trips");
2208 assert_eq!(decoded, manifest);
2209 }
2210
2211 #[test]
2212 fn fully_populated_builder_manifest_matches_the_literal_wire_golden() {
2213 let manifest = ModuleManifest::builder("full-builder", "2.0.0")
2214 .trust_tier(Some(TrustTier::Reviewed))
2215 .bindings(Some(Bindings {
2216 storage: StorageBinding {
2217 kind: StorageKind::Sqlite,
2218 scope: StorageScope::Project,
2219 owns_schema: false,
2220 },
2221 vault_grants: Vec::new(),
2222 identity: IdentityBinding {
2223 requires: vec![IdentityScope::Project],
2224 optional: Vec::new(),
2225 },
2226 }))
2227 .provides(vec![ProviderRole::ToolProvider {
2228 tools: vec![Tool {
2229 name: "read".to_string(),
2230 description: None,
2231 execution_mode: ExecutionMode::Pure,
2232 schema: json!({"type": "object"}),
2233 }],
2234 identity_scope: vec![IdentityScope::Project],
2235 concurrency: Concurrency::Serial,
2236 emits_push: false,
2237 sub_supervises: false,
2238 }])
2239 .consumes(vec![ConsumerRole::ServiceClient {
2240 of: vec!["embedding.v2".to_string()],
2241 }])
2242 .capabilities(Some(CapabilityDeclarations {
2243 provides: vec!["embedding/v2".to_string()],
2244 requires: Vec::new(),
2245 must_never_reach: Vec::new(),
2246 }))
2247 .self_signals(Some(vec![SelfSignalDeclaration {
2248 name: "usage_poller".to_string(),
2249 kind: SelfSignalKind::Poller,
2250 effect: SelfSignalEffect::Observe,
2251 anchored_to: SignalAnchor::FixedInterval,
2252 cadence: Some(SignalCadence::Literal {
2253 interval_ms: 60_000,
2254 }),
2255 domain: Some("provider-usage".to_string()),
2256 note: None,
2257 }]))
2258 .provenance(Some(ManifestProvenance {
2259 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
2260 build_git_sha_absence_reason: None,
2261 build_lock_digest: Some(
2262 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
2263 ),
2264 wire_crate_version: Some("0.16.0".to_string()),
2265 store_schema_version: Some("42".to_string()),
2266 launch_nonce_source: None,
2267 }))
2268 .build();
2269
2270 assert_eq!(
2271 serde_json::to_vec(&manifest).expect("builder manifest serializes"),
2272 include_bytes!("../tests/golden/module_manifest_builder_full.json"),
2273 "the builder must preserve the prior fully populated literal wire bytes"
2274 );
2275 }
2276
2277 #[test]
2278 fn old_manifest_with_unread_fields_decodes_and_round_trips_verbatim() {
2279 let raw = include_bytes!("../tests/golden/module_manifest_builder_full.json");
2280 let decoded: ModuleManifest =
2281 serde_json::from_slice(raw).expect("old manifest with all unread fields decodes");
2282
2283 assert_eq!(decoded.trust_tier, Some(TrustTier::Reviewed));
2284 assert!(!decoded.consumes.is_empty());
2285 assert!(decoded.bindings.is_some());
2286
2287 let reencoded = serde_json::to_vec(&decoded).expect("re-encode succeeds");
2288 assert_eq!(
2289 reencoded, raw,
2290 "old manifest relay stays byte-for-byte verbatim"
2291 );
2292 }
2293
2294 #[test]
2295 fn new_manifest_omits_unread_fields_on_wire_and_decodes_cleanly() {
2296 let raw = include_bytes!("../tests/golden/module_manifest_diet.json");
2297 let decoded: ModuleManifest =
2298 serde_json::from_slice(raw).expect("new manifest omitting unread fields decodes");
2299
2300 assert_eq!(decoded.trust_tier, None);
2301 assert!(decoded.consumes.is_empty());
2302 assert_eq!(decoded.bindings, None);
2303
2304 let pretty = format!("{}\n", serde_json::to_string_pretty(&decoded).unwrap());
2305 assert_eq!(
2306 pretty.as_bytes(),
2307 raw,
2308 "new manifest matches golden byte-for-byte without unread keys"
2309 );
2310
2311 let as_val: serde_json::Value = serde_json::to_value(&decoded).unwrap();
2312 assert!(
2313 as_val.get("trust_tier").is_none(),
2314 "no trust_tier on wire for new manifest"
2315 );
2316 assert!(
2317 as_val.get("consumes").is_none(),
2318 "no consumes on wire for empty consumes"
2319 );
2320 assert!(
2321 as_val.get("bindings").is_none(),
2322 "no bindings on wire for new manifest"
2323 );
2324 }
2325
2326 #[test]
2327 fn aft_manifest_fixture_matches_v1_contract() {
2328 let manifest = aft_manifest_fixture();
2329
2330 assert_eq!(manifest.module_id, "aft");
2331 let ProviderRole::ToolProvider {
2332 tools,
2333 identity_scope,
2334 concurrency,
2335 emits_push,
2336 sub_supervises,
2337 } = &manifest.provides[0]
2338 else {
2339 panic!("AFT fixture must expose one tool_provider role");
2340 };
2341
2342 assert_eq!(*concurrency, Concurrency::ModuleManaged);
2343 assert!(*emits_push);
2344 assert!(*sub_supervises);
2345 assert_eq!(
2346 identity_scope,
2347 &vec![IdentityScope::Session, IdentityScope::Project]
2348 );
2349 assert_eq!(
2350 tools
2351 .iter()
2352 .map(|tool| (tool.name.as_str(), tool.execution_mode))
2353 .collect::<Vec<_>>(),
2354 vec![
2355 ("read", ExecutionMode::Pure),
2356 ("grep", ExecutionMode::Pure),
2357 ("outline", ExecutionMode::Pure),
2358 ("semantic_search", ExecutionMode::Pure),
2359 ("edit", ExecutionMode::Mutating),
2360 ("write", ExecutionMode::Mutating),
2361 ("bash", ExecutionMode::Unfenceable),
2362 ]
2363 );
2364 }
2365
2366 #[test]
2367 fn tool_provider_role_tag_serializes_as_snake_case() {
2368 let manifest = aft_manifest_fixture();
2369 let value = serde_json::to_value(&manifest).unwrap();
2370
2371 assert_eq!(value["provides"][0]["role"], "tool_provider");
2372 }
2373
2374 #[test]
2375 fn manifest_without_capabilities_preserves_the_existing_wire_shape() {
2376 let manifest = aft_manifest_fixture();
2377 let encoded = serde_json::to_value(&manifest).expect("manifest serializes");
2378 assert!(encoded.get("capabilities").is_none());
2379
2380 let decoded: ModuleManifest =
2381 serde_json::from_value(encoded).expect("legacy manifest parses");
2382 assert_eq!(decoded.capabilities, None);
2383 }
2384
2385 #[test]
2386 fn capability_identifier_lexical_grammar_accepts_only_pinned_forms() {
2387 for identifier in [
2388 "a/v1",
2389 "credentials-provider/v1",
2390 "a1-b2/v4294967295",
2391 "a123456789012345678901234567890123456789012345678901234567890123/v1",
2392 ] {
2393 assert!(
2394 is_valid_capability_identifier(identifier),
2395 "identifier must be accepted: {identifier}"
2396 );
2397 }
2398
2399 for identifier in [
2400 "credentials-Provider/v1",
2401 "credentials-provider/v01",
2402 "credentials-provider-/v1",
2403 "credentials--provider/v1",
2404 "Credentials-provider/v1",
2405 "credentials-provider/1",
2406 "credentials provider/v1",
2407 "credentials-provider/v0",
2408 "credentials-provider/v4294967296",
2409 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/v1",
2410 ] {
2411 assert!(
2412 !is_valid_capability_identifier(identifier),
2413 "identifier must be rejected: {identifier}"
2414 );
2415 }
2416 }
2417
2418 #[test]
2419 fn capability_grammar_errors_redact_secret_shaped_values() {
2420 let error = validate_manifest_capability_grammar(&json!({
2421 "capabilities": { "provides": ["sk-secret-value/v0"] }
2422 }))
2423 .expect_err("secret-shaped capability identifier is malformed");
2424 assert_eq!(error.field(), "capabilities.provides[0]");
2425 assert_eq!(error.value(), "<redacted>");
2426 assert!(!error.to_string().contains("sk-secret-value"));
2427 }
2428
2429 #[test]
2436 fn provenance_builder_sentinels_become_field_omission() {
2437 for sentinel in [
2438 "unknown",
2439 "UNKNOWN",
2440 "Unknown",
2441 "unavailable",
2442 "none",
2443 "None",
2444 " unknown ",
2445 "",
2446 ] {
2447 let p = build_provenance_from_source(
2448 BuildGitShaSource::Git {
2449 revision: sentinel,
2450 tree_state: GitTreeState::Clean,
2451 },
2452 Some(sentinel),
2453 Some(sentinel),
2454 )
2455 .expect("sentinels are omitted before form validation");
2456 assert_eq!(
2457 (
2458 p.build_git_sha,
2459 p.build_git_sha_absence_reason,
2460 p.build_lock_digest,
2461 p.store_schema_version,
2462 ),
2463 (
2464 None,
2465 Some(BuildGitShaAbsenceReason::NeverDerived),
2466 None,
2467 None,
2468 ),
2469 "sentinel {sentinel:?} must be omitted, not published"
2470 );
2471 }
2472 let real = build_provenance_from_source(
2473 BuildGitShaSource::Git {
2474 revision: "0123456789abcdef0123456789abcdef01234567",
2475 tree_state: GitTreeState::Clean,
2476 },
2477 None,
2478 Some("9"),
2479 )
2480 .expect("canonical build revision is accepted");
2481 assert_eq!(
2482 real.build_git_sha.as_deref(),
2483 Some("0123456789abcdef0123456789abcdef01234567")
2484 );
2485 assert_eq!(real.store_schema_version.as_deref(), Some("9"));
2486 assert_eq!(
2490 real.wire_crate_version.as_deref(),
2491 Some(crate::SUBC_PROTOCOL_CRATE_VERSION)
2492 );
2493 }
2494
2495 #[test]
2496 fn build_provenance_accepts_canonical_sha_and_lock_digest() {
2497 let provenance = build_provenance_from_source(
2498 BuildGitShaSource::Git {
2499 revision: " 0123456789abcdef0123456789abcdef01234567 ",
2500 tree_state: GitTreeState::Clean,
2501 },
2502 Some(" abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789 "),
2503 Some(" schema-v3 "),
2504 )
2505 .expect("canonical build facts are accepted");
2506
2507 assert_eq!(
2508 provenance,
2509 ManifestProvenance {
2510 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
2511 build_git_sha_absence_reason: None,
2512 build_lock_digest: Some(
2513 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
2514 ),
2515 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
2516 store_schema_version: Some("schema-v3".to_string()),
2517 launch_nonce_source: None,
2518 }
2519 );
2520 }
2521
2522 #[test]
2523 fn build_provenance_refuses_an_abbreviated_git_sha() {
2524 let error = build_provenance_from_source(
2525 BuildGitShaSource::Git {
2526 revision: "0123456789ab",
2527 tree_state: GitTreeState::Clean,
2528 },
2529 None,
2530 None,
2531 )
2532 .expect_err("a 12-character abbreviation is not canonical");
2533
2534 assert_eq!(error.field(), "build_git_sha");
2535 assert_eq!(error.length(), 12);
2536 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
2537 assert_eq!(
2538 error.to_string(),
2539 "invalid manifest provenance form: field build_git_sha has length 12; canonical form is exactly 40 lowercase hexadecimal characters"
2540 );
2541 }
2542
2543 #[test]
2544 fn build_provenance_refuses_an_abbreviated_lock_digest() {
2545 let error = build_provenance_from_source(
2546 BuildGitShaSource::NeverDerived,
2547 Some("0123456789abcdef"),
2548 None,
2549 )
2550 .expect_err("a 16-character digest is not canonical");
2551
2552 assert_eq!(error.field(), "build_lock_digest");
2553 assert_eq!(error.length(), 16);
2554 assert_eq!(error.canonical_form(), BUILD_LOCK_DIGEST_CANONICAL_FORM);
2555 }
2556
2557 #[test]
2558 fn build_provenance_refuses_uppercase_hex() {
2559 let uppercase_sha = "A".repeat(40);
2560 let error = build_provenance_from_source(
2561 BuildGitShaSource::Git {
2562 revision: &uppercase_sha,
2563 tree_state: GitTreeState::Clean,
2564 },
2565 None,
2566 None,
2567 )
2568 .expect_err("uppercase hexadecimal is not canonical");
2569
2570 assert_eq!(error.field(), "build_git_sha");
2571 assert_eq!(error.length(), 40);
2572 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
2573 }
2574
2575 #[test]
2576 fn build_provenance_refuses_dirty_revision_stamp_claimed_clean() {
2577 let error = build_provenance_from_source(
2578 BuildGitShaSource::Git {
2579 revision: "0123456789abcdef0123456789abcdef01234567-dirty",
2580 tree_state: GitTreeState::Clean,
2581 },
2582 None,
2583 None,
2584 )
2585 .expect_err("a dirty stamp is not a canonical build revision");
2586
2587 assert_eq!(error.field(), "build_git_sha");
2588 assert_eq!(error.length(), 46);
2589 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
2590 }
2591
2592 #[test]
2593 fn build_provenance_keeps_a_lock_digest_when_identity_is_unavailable() {
2594 let provenance = build_provenance_from_source(
2595 BuildGitShaSource::Git {
2596 revision: "unavailable",
2597 tree_state: GitTreeState::Clean,
2598 },
2599 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"),
2600 None,
2601 )
2602 .expect("sentinel SHA is omitted before the valid lock digest is checked");
2603
2604 assert_eq!(provenance.build_git_sha, None);
2605 assert_eq!(
2606 provenance.build_lock_digest,
2607 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string())
2608 );
2609 assert_eq!(
2610 provenance.wire_crate_version,
2611 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
2612 );
2613 }
2614
2615 #[test]
2616 fn build_provenance_omits_fully_unavailable_inputs() {
2617 let provenance = build_provenance_from_source(
2618 BuildGitShaSource::NeverDerived,
2619 Some(" unavailable "),
2620 Some(" "),
2621 )
2622 .expect("omitted and sentinel inputs are not form errors");
2623
2624 assert_eq!(provenance.build_git_sha, None);
2625 assert_eq!(provenance.build_lock_digest, None);
2626 assert_eq!(provenance.store_schema_version, None);
2627 assert_eq!(
2628 provenance.wire_crate_version,
2629 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
2630 );
2631 }
2632
2633 #[test]
2634 fn legacy_build_provenance_keeps_master_wire_bytes_without_an_absence_reason() {
2635 let revision = "0123456789abcdef0123456789abcdef01234567";
2636 for (input, expected) in [
2637 (
2638 Some(revision),
2639 format!(
2640 r#"{{"build_git_sha":"{revision}","wire_crate_version":"{}"}}"#,
2641 crate::SUBC_PROTOCOL_CRATE_VERSION
2642 ),
2643 ),
2644 (
2645 None,
2646 format!(
2647 r#"{{"wire_crate_version":"{}"}}"#,
2648 crate::SUBC_PROTOCOL_CRATE_VERSION
2649 ),
2650 ),
2651 (
2652 Some("unknown"),
2653 format!(
2654 r#"{{"wire_crate_version":"{}"}}"#,
2655 crate::SUBC_PROTOCOL_CRATE_VERSION
2656 ),
2657 ),
2658 ] {
2659 let provenance = build_provenance(input, None, None)
2660 .expect("the legacy build facts remain constructible");
2661 assert_eq!(provenance.build_git_sha_absence_reason, None);
2662 assert_eq!(
2663 serde_json::to_string(&provenance).expect("legacy provenance serializes"),
2664 expected
2665 );
2666 }
2667 }
2668
2669 #[test]
2670 fn build_provenance_derives_git_sha_absence_from_the_stamping_inputs() {
2671 let revision = "0123456789abcdef0123456789abcdef01234567";
2672 let cases = [
2673 (
2674 BuildGitShaSource::Git {
2675 revision,
2676 tree_state: GitTreeState::Clean,
2677 },
2678 Some(revision),
2679 None,
2680 ),
2681 (
2682 BuildGitShaSource::Git {
2683 revision,
2684 tree_state: GitTreeState::Dirty,
2685 },
2686 None,
2687 Some(BuildGitShaAbsenceReason::DeclinedDirty),
2688 ),
2689 (
2690 BuildGitShaSource::NeverDerived,
2691 None,
2692 Some(BuildGitShaAbsenceReason::NeverDerived),
2693 ),
2694 (
2695 BuildGitShaSource::NoGitDir,
2696 None,
2697 Some(BuildGitShaAbsenceReason::NoGitDir),
2698 ),
2699 ];
2700
2701 for (source, expected_sha, expected_reason) in cases {
2702 let provenance = build_provenance_from_source(source, None, None)
2703 .expect("every stamping state constructs honest provenance");
2704 assert_eq!(provenance.build_git_sha.as_deref(), expected_sha);
2705 assert_eq!(provenance.build_git_sha_absence_reason, expected_reason);
2706 }
2707 }
2708
2709 #[test]
2710 fn unknown_git_sha_absence_reason_round_trips_byte_faithfully() {
2711 let wire = format!(
2712 r#"{{"build_git_sha_absence_reason":"future_stamper_state","wire_crate_version":"{}"}}"#,
2713 crate::SUBC_PROTOCOL_CRATE_VERSION
2714 );
2715 let provenance: ManifestProvenance =
2716 serde_json::from_str(&wire).expect("future absence reasons remain readable");
2717
2718 assert_eq!(
2719 provenance.build_git_sha_absence_reason,
2720 Some(BuildGitShaAbsenceReason::ForwardCompatibleUnknown(
2721 "future_stamper_state".to_string()
2722 ))
2723 );
2724 assert_eq!(
2725 serde_json::to_string(&provenance).expect("future absence reason reserializes"),
2726 wire
2727 );
2728 }
2729
2730 #[test]
2731 fn provenance_rejects_an_absence_reason_beside_a_declared_commit() {
2732 let error = serde_json::from_value::<ManifestProvenance>(json!({
2733 "build_git_sha": "0123456789abcdef0123456789abcdef01234567",
2734 "build_git_sha_absence_reason": "declined_dirty"
2735 }))
2736 .expect_err("a declared commit cannot also claim an absence reason");
2737
2738 assert!(error.to_string().contains(
2739 "build_git_sha_absence_reason has must be omitted when build_git_sha is present"
2740 ));
2741 }
2742}