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,
392 pub version: u32,
394 pub headers: Vec<String>,
397 #[serde(default, skip_serializing_if = "Option::is_none")]
399 pub summary: Option<String>,
400}
401
402impl EventDeclaration {
403 pub fn new(name: impl Into<String>, version: u32) -> Self {
406 Self {
407 name: name.into(),
408 version,
409 headers: Vec::new(),
410 summary: None,
411 }
412 }
413
414 pub fn with_headers(mut self, headers: Vec<String>) -> Self {
416 self.headers = headers;
417 self
418 }
419
420 pub fn with_summary(mut self, summary: Option<String>) -> Self {
422 self.summary = summary;
423 self
424 }
425}
426
427#[derive(Debug, Clone, PartialEq, Eq)]
429#[non_exhaustive]
430pub struct EventDeclarationError {
431 field: String,
432 reason: &'static str,
433}
434
435impl EventDeclarationError {
436 fn new(field: impl Into<String>, reason: &'static str) -> Self {
437 Self {
438 field: field.into(),
439 reason,
440 }
441 }
442
443 pub fn field(&self) -> &str {
445 &self.field
446 }
447}
448
449impl fmt::Display for EventDeclarationError {
450 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
451 write!(
452 f,
453 "invalid event declaration: field {} {}",
454 self.field, self.reason
455 )
456 }
457}
458
459impl std::error::Error for EventDeclarationError {}
460
461pub fn validate_hello_event_declarations(hello: &Value) -> Result<(), EventDeclarationError> {
463 validate_events_value(
464 hello
465 .get("manifest")
466 .and_then(|manifest| manifest.get("events")),
467 )
468}
469
470fn is_valid_event_name(name: &str) -> bool {
471 (1..=63).contains(&name.len())
472 && name.as_bytes()[0].is_ascii_alphanumeric()
473 && name
474 .bytes()
475 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
476}
477
478fn validate_events_value(value: Option<&Value>) -> Result<(), EventDeclarationError> {
479 let Some(value) = value.filter(|value| !value.is_null()) else {
480 return Ok(());
481 };
482 let entries = value
483 .as_array()
484 .ok_or_else(|| EventDeclarationError::new("events", "must be a list"))?;
485 if entries.len() > 64 {
486 return Err(EventDeclarationError::new(
487 "events",
488 "must contain at most 64 declarations",
489 ));
490 }
491 let mut pairs = HashSet::new();
492 for (index, entry) in entries.iter().enumerate() {
493 let field = format!("events[{index}]");
494 let entry = entry
495 .as_object()
496 .ok_or_else(|| EventDeclarationError::new(&field, "must be an object"))?;
497 let name_field = format!("{field}.name");
498 let name = entry
499 .get("name")
500 .and_then(Value::as_str)
501 .ok_or_else(|| EventDeclarationError::new(&name_field, "must be a string"))?;
502 if !is_valid_event_name(name) {
503 return Err(EventDeclarationError::new(
504 name_field,
505 "must match [a-z0-9][a-z0-9_]{0,62}",
506 ));
507 }
508 let version = entry
509 .get("version")
510 .and_then(Value::as_u64)
511 .filter(|version| (1..=u32::MAX as u64).contains(version))
512 .ok_or_else(|| {
513 EventDeclarationError::new(
514 format!("{field}.version"),
515 "must be an integer between 1 and u32::MAX",
516 )
517 })?;
518 if !pairs.insert((name, version)) {
519 return Err(EventDeclarationError::new(
520 &field,
521 "duplicates an event (name, version) pair",
522 ));
523 }
524 let headers_field = format!("{field}.headers");
525 let headers = entry
526 .get("headers")
527 .and_then(Value::as_array)
528 .ok_or_else(|| EventDeclarationError::new(&headers_field, "must be a list"))?;
529 if headers.len() > 16 {
530 return Err(EventDeclarationError::new(
531 headers_field,
532 "must contain at most 16 headers",
533 ));
534 }
535 let mut names = HashSet::new();
536 for (header_index, header) in headers.iter().enumerate() {
537 let header_field = format!("{headers_field}[{header_index}]");
538 let header = header
539 .as_str()
540 .ok_or_else(|| EventDeclarationError::new(&header_field, "must be a string"))?;
541 if !(1..=32).contains(&header.len())
542 || !header.as_bytes()[0].is_ascii_lowercase()
543 || !header
544 .bytes()
545 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
546 {
547 return Err(EventDeclarationError::new(
548 header_field,
549 "must match [a-z][a-z0-9_]{0,31}",
550 ));
551 }
552 if !names.insert(header) {
553 return Err(EventDeclarationError::new(
554 header_field,
555 "duplicates a header name",
556 ));
557 }
558 }
559 if let Some(summary) = entry.get("summary").filter(|value| !value.is_null()) {
560 let summary_field = format!("{field}.summary");
561 let summary = summary
562 .as_str()
563 .ok_or_else(|| EventDeclarationError::new(&summary_field, "must be a string"))?;
564 if summary.chars().count() > 200 || summary.chars().any(char::is_control) {
565 return Err(EventDeclarationError::new(
566 summary_field,
567 "must contain at most 200 characters and no control characters",
568 ));
569 }
570 }
571 }
572 Ok(())
573}
574
575#[derive(Debug, Clone, PartialEq, Eq)]
577pub struct SelfSignalDeclarationError {
578 module_id: String,
579 entry_index: usize,
580 field: &'static str,
581}
582
583impl fmt::Display for SelfSignalDeclarationError {
584 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
585 write!(
586 f,
587 "module_id '{}' self_signals[{}] is missing required field '{}'",
588 self.module_id.escape_debug(),
589 self.entry_index,
590 self.field
591 )
592 }
593}
594
595pub fn validate_hello_self_signal_declarations(
602 hello: &Value,
603) -> Result<(), SelfSignalDeclarationError> {
604 let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
605 return Ok(());
606 };
607 let module_id = manifest
608 .get("module_id")
609 .and_then(Value::as_str)
610 .unwrap_or("<unknown>");
611 let Some(entries) = manifest.get("self_signals").and_then(Value::as_array) else {
612 return Ok(());
613 };
614
615 for (entry_index, entry) in entries.iter().enumerate() {
616 let Some(entry) = entry.as_object() else {
617 continue;
618 };
619 for field in ["effect", "anchored_to"] {
620 if !entry.contains_key(field) {
621 return Err(SelfSignalDeclarationError {
622 module_id: module_id.to_string(),
623 entry_index,
624 field,
625 });
626 }
627 }
628 }
629 Ok(())
630}
631
632#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
634#[serde(deny_unknown_fields)]
635pub struct CapabilityDeclarations {
636 #[serde(default)]
637 pub provides: Vec<String>,
638 #[serde(default)]
639 pub requires: Vec<CapabilityRequirement>,
640 #[serde(default)]
641 pub must_never_reach: Vec<String>,
642}
643
644#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
646pub struct SelfSignalDeclaration {
647 pub name: String,
649 pub kind: SelfSignalKind,
677 pub effect: SelfSignalEffect,
679 pub anchored_to: SignalAnchor,
681 #[serde(default, skip_serializing_if = "Option::is_none")]
688 pub cadence: Option<SignalCadence>,
689 #[serde(default, skip_serializing_if = "Option::is_none")]
691 pub domain: Option<String>,
692 #[serde(default, skip_serializing_if = "Option::is_none")]
693 pub note: Option<String>,
694}
695
696#[derive(Debug, Clone, PartialEq, Eq)]
698pub enum SelfSignalKind {
699 Keepalive,
700 Busy,
702 Poller,
703 Cron,
704 Sweep,
705 Watchdog,
706 Heartbeat,
707 Other(String),
708}
709
710impl SelfSignalKind {
711 fn wire_name(&self) -> &str {
712 match self {
713 Self::Keepalive => "keepalive",
714 Self::Busy => "busy",
715 Self::Poller => "poller",
716 Self::Cron => "cron",
717 Self::Sweep => "sweep",
718 Self::Watchdog => "watchdog",
719 Self::Heartbeat => "heartbeat",
720 Self::Other(value) => value,
721 }
722 }
723}
724
725impl Serialize for SelfSignalKind {
726 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
727 where
728 S: serde::Serializer,
729 {
730 serializer.serialize_str(self.wire_name())
731 }
732}
733
734impl<'de> Deserialize<'de> for SelfSignalKind {
735 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
736 where
737 D: Deserializer<'de>,
738 {
739 let value = String::deserialize(deserializer)?;
740 Ok(match value.as_str() {
741 "keepalive" => Self::Keepalive,
742 "busy" => Self::Busy,
743 "poller" => Self::Poller,
744 "cron" => Self::Cron,
745 "sweep" => Self::Sweep,
746 "watchdog" => Self::Watchdog,
747 "heartbeat" => Self::Heartbeat,
748 _ => Self::Other(value),
749 })
750 }
751}
752
753#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
755#[serde(rename_all = "lowercase")]
756pub enum SelfSignalEffect {
757 Observe,
758 Mutate,
759}
760
761#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
763#[serde(rename_all = "snake_case")]
764pub enum SignalAnchor {
765 FixedInterval,
768 Event { event: String },
771 HealthGauges { gauges: Vec<String> },
773}
774
775#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
777#[serde(rename_all = "snake_case")]
778pub enum SignalCadence {
779 Literal { interval_ms: u64 },
780 Derived { source: String },
781}
782
783#[derive(Serialize, Debug, Clone, Default, PartialEq, Eq)]
860#[non_exhaustive]
861pub struct ManifestProvenance {
862 #[serde(default, skip_serializing_if = "Option::is_none")]
863 pub build_git_sha: Option<String>,
864 #[serde(default, skip_serializing_if = "Option::is_none")]
868 pub build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
869 #[serde(default, skip_serializing_if = "Option::is_none")]
870 pub build_lock_digest: Option<String>,
871 #[serde(default, skip_serializing_if = "Option::is_none")]
880 pub wire_crate_version: Option<String>,
881 #[serde(default, skip_serializing_if = "Option::is_none")]
882 pub store_schema_version: Option<String>,
883 #[serde(default, skip_serializing_if = "Option::is_none")]
889 pub launch_nonce_source: Option<LaunchNonceSource>,
890}
891
892#[derive(Debug, Clone, PartialEq, Eq)]
899#[non_exhaustive]
900pub enum LaunchNonceSource {
901 Fd,
903 Pipe,
905 Env,
907 ForwardCompatibleUnknown(String),
908}
909
910impl LaunchNonceSource {
911 pub fn wire_name(&self) -> &str {
913 match self {
914 Self::Fd => "fd",
915 Self::Pipe => "pipe",
916 Self::Env => "env",
917 Self::ForwardCompatibleUnknown(value) => value,
918 }
919 }
920
921 pub fn from_wire_name(value: &str) -> Self {
923 match value {
924 "fd" => Self::Fd,
925 "pipe" => Self::Pipe,
926 "env" => Self::Env,
927 _ => Self::ForwardCompatibleUnknown(value.to_string()),
928 }
929 }
930}
931
932impl Serialize for LaunchNonceSource {
933 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
934 where
935 S: serde::Serializer,
936 {
937 serializer.serialize_str(self.wire_name())
938 }
939}
940
941impl<'de> Deserialize<'de> for LaunchNonceSource {
942 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
943 where
944 D: serde::Deserializer<'de>,
945 {
946 let value = String::deserialize(deserializer)?;
947 Ok(Self::from_wire_name(&value))
948 }
949}
950
951#[derive(Debug, Clone, PartialEq, Eq)]
956pub enum BuildGitShaAbsenceReason {
957 DeclinedDirty,
958 NeverDerived,
959 NoGitDir,
960 ForwardCompatibleUnknown(String),
961}
962
963impl BuildGitShaAbsenceReason {
964 fn wire_name(&self) -> &str {
965 match self {
966 Self::DeclinedDirty => "declined_dirty",
967 Self::NeverDerived => "never_derived",
968 Self::NoGitDir => "no_git_dir",
969 Self::ForwardCompatibleUnknown(value) => value,
970 }
971 }
972}
973
974impl Serialize for BuildGitShaAbsenceReason {
975 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
976 where
977 S: serde::Serializer,
978 {
979 serializer.serialize_str(self.wire_name())
980 }
981}
982
983impl<'de> Deserialize<'de> for BuildGitShaAbsenceReason {
984 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
985 where
986 D: serde::Deserializer<'de>,
987 {
988 let value = String::deserialize(deserializer)?;
989 Ok(match value.as_str() {
990 "declined_dirty" => Self::DeclinedDirty,
991 "never_derived" => Self::NeverDerived,
992 "no_git_dir" => Self::NoGitDir,
993 _ => Self::ForwardCompatibleUnknown(value),
994 })
995 }
996}
997
998#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1000pub enum GitTreeState {
1001 Clean,
1002 Dirty,
1003}
1004
1005#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1010pub enum BuildGitShaSource<'a> {
1011 Git {
1012 revision: &'a str,
1013 tree_state: GitTreeState,
1014 },
1015 NeverDerived,
1016 NoGitDir,
1017}
1018
1019pub fn attestable_commit(revision: &str, tree_state: GitTreeState) -> Option<&str> {
1023 match tree_state {
1024 GitTreeState::Clean => Some(revision),
1025 GitTreeState::Dirty => None,
1026 }
1027}
1028
1029const MAX_PROVENANCE_VALUE_BYTES: usize = 128;
1030const BUILD_GIT_SHA_CANONICAL_FORM: &str = "exactly 40 lowercase hexadecimal characters";
1031const BUILD_LOCK_DIGEST_CANONICAL_FORM: &str = "exactly 64 lowercase hexadecimal characters";
1032
1033#[derive(Deserialize)]
1034struct ManifestProvenanceWire {
1035 #[serde(default)]
1036 build_git_sha: Option<String>,
1037 #[serde(default)]
1038 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1039 #[serde(default)]
1040 build_lock_digest: Option<String>,
1041 #[serde(default)]
1042 wire_crate_version: Option<String>,
1043 #[serde(default)]
1044 store_schema_version: Option<String>,
1045 #[serde(default)]
1046 launch_nonce_source: Option<LaunchNonceSource>,
1047}
1048
1049impl<'de> Deserialize<'de> for ManifestProvenance {
1050 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1051 where
1052 D: Deserializer<'de>,
1053 {
1054 let wire = ManifestProvenanceWire::deserialize(deserializer)?;
1055 let provenance = Self {
1056 build_git_sha: wire.build_git_sha,
1057 build_git_sha_absence_reason: wire.build_git_sha_absence_reason,
1058 build_lock_digest: wire.build_lock_digest,
1059 wire_crate_version: wire.wire_crate_version,
1060 store_schema_version: wire.store_schema_version,
1061 launch_nonce_source: wire.launch_nonce_source,
1062 };
1063 provenance.validate().map_err(D::Error::custom)?;
1064 Ok(provenance)
1065 }
1066}
1067
1068#[derive(Debug, Clone, PartialEq, Eq)]
1070pub struct ProvenanceFormError {
1071 field: &'static str,
1072 length: usize,
1073 canonical_form: &'static str,
1074}
1075
1076impl ProvenanceFormError {
1077 fn new(field: &'static str, length: usize, canonical_form: &'static str) -> Self {
1078 Self {
1079 field,
1080 length,
1081 canonical_form,
1082 }
1083 }
1084
1085 pub fn field(&self) -> &str {
1087 self.field
1088 }
1089
1090 pub fn length(&self) -> usize {
1092 self.length
1093 }
1094
1095 pub fn canonical_form(&self) -> &str {
1097 self.canonical_form
1098 }
1099}
1100
1101impl fmt::Display for ProvenanceFormError {
1102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1103 write!(
1104 f,
1105 "invalid manifest provenance form: field {} has length {}; canonical form is {}",
1106 self.field, self.length, self.canonical_form
1107 )
1108 }
1109}
1110
1111impl std::error::Error for ProvenanceFormError {}
1112
1113#[derive(Debug, Clone, PartialEq, Eq)]
1114pub struct ManifestProvenanceError {
1115 field: String,
1116 value: String,
1117 reason: &'static str,
1118}
1119
1120impl ManifestProvenanceError {
1121 fn new(field: &str, value: &str, reason: &'static str) -> Self {
1122 Self {
1123 field: field.to_string(),
1124 value: safe_error_value(value),
1125 reason,
1126 }
1127 }
1128
1129 pub fn field(&self) -> &str {
1130 &self.field
1131 }
1132}
1133
1134impl fmt::Display for ManifestProvenanceError {
1135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1136 write!(
1137 f,
1138 "invalid manifest provenance: field {} has {} (value {:?})",
1139 self.field, self.reason, self.value
1140 )
1141 }
1142}
1143
1144impl std::error::Error for ManifestProvenanceError {}
1145
1146impl ManifestProvenance {
1147 pub fn new() -> Self {
1149 Self::default()
1150 }
1151
1152 pub fn with_build_git_sha(mut self, value: Option<String>) -> Self {
1153 self.build_git_sha = value;
1154 self
1155 }
1156
1157 pub fn with_build_git_sha_absence_reason(
1158 mut self,
1159 value: Option<BuildGitShaAbsenceReason>,
1160 ) -> Self {
1161 self.build_git_sha_absence_reason = value;
1162 self
1163 }
1164
1165 pub fn with_build_lock_digest(mut self, value: Option<String>) -> Self {
1166 self.build_lock_digest = value;
1167 self
1168 }
1169
1170 pub fn with_wire_crate_version(mut self, value: Option<String>) -> Self {
1171 self.wire_crate_version = value;
1172 self
1173 }
1174
1175 pub fn with_store_schema_version(mut self, value: Option<String>) -> Self {
1176 self.store_schema_version = value;
1177 self
1178 }
1179
1180 pub fn with_launch_nonce_source(mut self, value: Option<LaunchNonceSource>) -> Self {
1185 self.launch_nonce_source = value;
1186 self
1187 }
1188
1189 pub fn validate(&self) -> Result<(), ManifestProvenanceError> {
1190 if let (Some(_), Some(reason)) = (
1191 self.build_git_sha.as_ref(),
1192 self.build_git_sha_absence_reason.as_ref(),
1193 ) {
1194 return Err(ManifestProvenanceError::new(
1195 "build_git_sha_absence_reason",
1196 reason.wire_name(),
1197 "must be omitted when build_git_sha is present",
1198 ));
1199 }
1200 for (field, value) in [
1201 ("build_git_sha", self.build_git_sha.as_deref()),
1202 (
1203 "build_git_sha_absence_reason",
1204 self.build_git_sha_absence_reason
1205 .as_ref()
1206 .map(|reason| reason.wire_name()),
1207 ),
1208 ("build_lock_digest", self.build_lock_digest.as_deref()),
1209 ("wire_crate_version", self.wire_crate_version.as_deref()),
1210 ("store_schema_version", self.store_schema_version.as_deref()),
1211 (
1212 "launch_nonce_source",
1213 self.launch_nonce_source
1214 .as_ref()
1215 .map(|source| source.wire_name()),
1216 ),
1217 ] {
1218 let Some(value) = value else { continue };
1219 if value.is_empty() {
1220 return Err(ManifestProvenanceError::new(
1221 field,
1222 value,
1223 "must not be empty",
1224 ));
1225 }
1226 if value.len() > MAX_PROVENANCE_VALUE_BYTES {
1231 return Err(ManifestProvenanceError::new(
1232 field,
1233 value,
1234 "exceeds the 128-byte maximum",
1235 ));
1236 }
1237 if value.bytes().any(|byte| !(0x20..=0x7e).contains(&byte)) {
1238 return Err(ManifestProvenanceError::new(
1239 field,
1240 value,
1241 "contains non-printable ASCII",
1242 ));
1243 }
1244 }
1245 Ok(())
1246 }
1247}
1248
1249pub fn build_provenance(
1267 build_git_sha: Option<&str>,
1268 build_lock_digest: Option<&str>,
1269 store_schema_version: Option<&str>,
1270) -> Result<ManifestProvenance, ProvenanceFormError> {
1271 let build_git_sha = normalize_and_validate_build_git_sha(build_git_sha)?;
1272 build_provenance_with_build_git_sha(
1273 build_git_sha,
1274 None,
1275 build_lock_digest,
1276 store_schema_version,
1277 )
1278}
1279
1280pub fn build_provenance_from_source(
1296 build_git_sha_source: BuildGitShaSource<'_>,
1297 build_lock_digest: Option<&str>,
1298 store_schema_version: Option<&str>,
1299) -> Result<ManifestProvenance, ProvenanceFormError> {
1300 let (raw_build_git_sha, mut build_git_sha_absence_reason) = match build_git_sha_source {
1301 BuildGitShaSource::Git {
1302 revision,
1303 tree_state,
1304 } => match attestable_commit(revision, tree_state) {
1305 Some(revision) => (Some(revision), None),
1306 None => (None, Some(BuildGitShaAbsenceReason::DeclinedDirty)),
1307 },
1308 BuildGitShaSource::NeverDerived => (None, Some(BuildGitShaAbsenceReason::NeverDerived)),
1309 BuildGitShaSource::NoGitDir => (None, Some(BuildGitShaAbsenceReason::NoGitDir)),
1310 };
1311 let build_git_sha = normalize_and_validate_build_git_sha(raw_build_git_sha)?;
1312 if build_git_sha.is_none() {
1313 build_git_sha_absence_reason.get_or_insert(BuildGitShaAbsenceReason::NeverDerived);
1314 }
1315 build_provenance_with_build_git_sha(
1316 build_git_sha,
1317 build_git_sha_absence_reason,
1318 build_lock_digest,
1319 store_schema_version,
1320 )
1321}
1322
1323fn normalize_and_validate_build_git_sha(
1324 build_git_sha: Option<&str>,
1325) -> Result<Option<String>, ProvenanceFormError> {
1326 let build_git_sha = normalize_provenance_fact(build_git_sha);
1327 validate_provenance_form(
1328 "build_git_sha",
1329 build_git_sha.as_deref(),
1330 BUILD_GIT_SHA_CANONICAL_FORM,
1331 40,
1332 )?;
1333 Ok(build_git_sha)
1334}
1335
1336fn build_provenance_with_build_git_sha(
1337 build_git_sha: Option<String>,
1338 build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1339 build_lock_digest: Option<&str>,
1340 store_schema_version: Option<&str>,
1341) -> Result<ManifestProvenance, ProvenanceFormError> {
1342 let build_lock_digest = normalize_provenance_fact(build_lock_digest);
1343 validate_provenance_form(
1344 "build_lock_digest",
1345 build_lock_digest.as_deref(),
1346 BUILD_LOCK_DIGEST_CANONICAL_FORM,
1347 64,
1348 )?;
1349
1350 Ok(ManifestProvenance {
1351 build_git_sha,
1352 build_git_sha_absence_reason,
1353 build_lock_digest,
1354 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
1355 store_schema_version: normalize_provenance_fact(store_schema_version),
1356 launch_nonce_source: None,
1357 })
1358}
1359
1360fn validate_provenance_form(
1361 field: &'static str,
1362 value: Option<&str>,
1363 canonical_form: &'static str,
1364 expected_length: usize,
1365) -> Result<(), ProvenanceFormError> {
1366 let Some(value) = value else { return Ok(()) };
1367 if value.len() != expected_length
1368 || !value
1369 .bytes()
1370 .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
1371 {
1372 return Err(ProvenanceFormError::new(field, value.len(), canonical_form));
1373 }
1374 Ok(())
1375}
1376
1377pub const PROVENANCE_SENTINELS: [&str; 3] = ["unknown", "unavailable", "none"];
1385
1386fn normalize_provenance_fact(value: Option<&str>) -> Option<String> {
1387 let value = value?.trim();
1388 if value.is_empty() {
1389 return None;
1390 }
1391 let lowered = value.to_ascii_lowercase();
1392 if PROVENANCE_SENTINELS.contains(&lowered.as_str()) {
1393 return None;
1394 }
1395 Some(value.to_string())
1396}
1397
1398#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1400#[serde(deny_unknown_fields)]
1401pub struct CapabilityRequirement {
1402 pub capability: String,
1403 pub need: CapabilityNeed,
1404}
1405
1406#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1408#[serde(rename_all = "snake_case")]
1409pub enum CapabilityNeed {
1410 Required,
1411 Optional,
1412}
1413
1414#[derive(Debug, Clone, PartialEq, Eq)]
1416pub struct CapabilityGrammarError {
1417 field: String,
1418 value: String,
1419}
1420
1421impl CapabilityGrammarError {
1422 fn new(field: impl Into<String>, value: impl AsRef<str>) -> Self {
1423 Self {
1424 field: field.into(),
1425 value: safe_error_value(value.as_ref()),
1426 }
1427 }
1428
1429 pub fn field(&self) -> &str {
1431 &self.field
1432 }
1433
1434 pub fn value(&self) -> &str {
1436 &self.value
1437 }
1438}
1439
1440impl fmt::Display for CapabilityGrammarError {
1441 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1442 write!(
1443 f,
1444 "invalid capability grammar: field {} has offending value {:?}",
1445 self.field, self.value
1446 )
1447 }
1448}
1449
1450impl std::error::Error for CapabilityGrammarError {}
1451
1452impl ModuleManifest {
1453 pub fn validate_capability_grammar(&self) -> Result<(), CapabilityGrammarError> {
1455 let Some(capabilities) = &self.capabilities else {
1456 return Ok(());
1457 };
1458
1459 validate_capability_list("capabilities.provides", &capabilities.provides)?;
1460 validate_requires(&capabilities.requires)?;
1461 validate_capability_list(
1462 "capabilities.must_never_reach",
1463 &capabilities.must_never_reach,
1464 )
1465 }
1466}
1467
1468pub fn validate_manifest_capability_grammar(
1473 manifest: &Value,
1474) -> Result<(), CapabilityGrammarError> {
1475 let Some(object) = manifest.as_object() else {
1476 return Ok(());
1477 };
1478
1479 validate_capabilities_value(object.get("capabilities"))?;
1480 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
1481}
1482
1483pub fn validate_hello_capability_grammar(hello: &Value) -> Result<(), CapabilityGrammarError> {
1489 let Some(object) = hello.as_object() else {
1490 return Ok(());
1491 };
1492 if let Some(manifest) = object.get("manifest") {
1493 validate_manifest_capability_grammar(manifest)?;
1494 }
1495 validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
1496}
1497
1498pub fn is_valid_capability_identifier(identifier: &str) -> bool {
1500 if identifier.chars().any(char::is_whitespace) {
1501 return false;
1502 }
1503 let Some((name, version)) = identifier.split_once("/v") else {
1504 return false;
1505 };
1506 if name.is_empty() || name.len() > 64 || version.is_empty() {
1507 return false;
1508 }
1509
1510 let name_bytes = name.as_bytes();
1511 if !name_bytes[0].is_ascii_lowercase()
1512 || (name.len() > 1
1513 && !name_bytes[name.len() - 1].is_ascii_lowercase()
1514 && !name_bytes[name.len() - 1].is_ascii_digit())
1515 || name_bytes.windows(2).any(|pair| pair == b"--")
1516 {
1517 return false;
1518 }
1519 if !name_bytes
1520 .iter()
1521 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-')
1522 {
1523 return false;
1524 }
1525
1526 if version.len() > 1 && version.starts_with('0')
1527 || !version.bytes().all(|byte| byte.is_ascii_digit())
1528 {
1529 return false;
1530 }
1531 matches!(
1532 version.parse::<u64>(),
1533 Ok(value) if (1..=u64::from(u32::MAX)).contains(&value)
1534 )
1535}
1536
1537fn validate_capabilities_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
1538 let Some(value) = value else {
1539 return Ok(());
1540 };
1541 let Some(object) = value.as_object() else {
1542 return Err(CapabilityGrammarError::new(
1543 "capabilities",
1544 value_description(value),
1545 ));
1546 };
1547
1548 for (key, value) in object {
1549 if !matches!(key.as_str(), "provides" | "requires" | "must_never_reach") {
1550 return Err(CapabilityGrammarError::new(
1551 field_child("capabilities", key),
1552 value_description(value),
1553 ));
1554 }
1555 }
1556
1557 validate_capability_list_value("capabilities.provides", object.get("provides"))?;
1558 validate_requires_value(object.get("requires"))?;
1559 validate_capability_list_value(
1560 "capabilities.must_never_reach",
1561 object.get("must_never_reach"),
1562 )
1563}
1564
1565fn validate_capability_list_value(
1566 field: &str,
1567 value: Option<&Value>,
1568) -> Result<(), CapabilityGrammarError> {
1569 let Some(value) = value else {
1570 return Ok(());
1571 };
1572 let Some(values) = value.as_array() else {
1573 return Err(CapabilityGrammarError::new(field, value_description(value)));
1574 };
1575
1576 let mut seen = HashSet::new();
1577 for (index, value) in values.iter().enumerate() {
1578 let field = format!("{field}[{index}]");
1579 let Some(identifier) = value.as_str() else {
1580 return Err(CapabilityGrammarError::new(field, value_description(value)));
1581 };
1582 validate_capability_identifier(&field, identifier)?;
1583 if !seen.insert(identifier) {
1584 return Err(CapabilityGrammarError::new(field, identifier));
1585 }
1586 }
1587 Ok(())
1588}
1589
1590fn validate_requires_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
1591 let Some(value) = value else {
1592 return Ok(());
1593 };
1594 let Some(values) = value.as_array() else {
1595 return Err(CapabilityGrammarError::new(
1596 "capabilities.requires",
1597 value_description(value),
1598 ));
1599 };
1600
1601 let mut seen = HashSet::new();
1602 for (index, value) in values.iter().enumerate() {
1603 let entry_field = format!("capabilities.requires[{index}]");
1604 let Some(object) = value.as_object() else {
1605 return Err(CapabilityGrammarError::new(
1606 entry_field,
1607 value_description(value),
1608 ));
1609 };
1610 for (key, value) in object {
1611 if !matches!(key.as_str(), "capability" | "need") {
1612 return Err(CapabilityGrammarError::new(
1613 field_child(&entry_field, key),
1614 value_description(value),
1615 ));
1616 }
1617 }
1618 let capability_field = format!("{entry_field}.capability");
1619 let Some(capability) = object.get("capability").and_then(Value::as_str) else {
1620 return Err(CapabilityGrammarError::new(
1621 capability_field,
1622 object
1623 .get("capability")
1624 .map_or("<missing>".to_string(), value_description),
1625 ));
1626 };
1627 validate_capability_identifier(&capability_field, capability)?;
1628
1629 let need_field = format!("{entry_field}.need");
1630 let Some(need) = object.get("need").and_then(Value::as_str) else {
1631 return Err(CapabilityGrammarError::new(
1632 need_field,
1633 object
1634 .get("need")
1635 .map_or("<missing>".to_string(), value_description),
1636 ));
1637 };
1638 if !matches!(need, "required" | "optional") {
1639 return Err(CapabilityGrammarError::new(need_field, need));
1640 }
1641 if !seen.insert(capability) {
1642 return Err(CapabilityGrammarError::new(entry_field, capability));
1643 }
1644 }
1645 Ok(())
1646}
1647
1648fn validate_capability_list(field: &str, values: &[String]) -> Result<(), CapabilityGrammarError> {
1649 let mut seen = HashSet::new();
1650 for (index, identifier) in values.iter().enumerate() {
1651 let field = format!("{field}[{index}]");
1652 validate_capability_identifier(&field, identifier)?;
1653 if !seen.insert(identifier) {
1654 return Err(CapabilityGrammarError::new(field, identifier));
1655 }
1656 }
1657 Ok(())
1658}
1659
1660fn validate_requires(values: &[CapabilityRequirement]) -> Result<(), CapabilityGrammarError> {
1661 let mut seen = HashSet::new();
1662 for (index, requirement) in values.iter().enumerate() {
1663 let field = format!("capabilities.requires[{index}].capability");
1664 validate_capability_identifier(&field, &requirement.capability)?;
1665 if !seen.insert(&requirement.capability) {
1666 return Err(CapabilityGrammarError::new(
1667 format!("capabilities.requires[{index}]"),
1668 &requirement.capability,
1669 ));
1670 }
1671 }
1672 Ok(())
1673}
1674
1675fn validate_capability_identifier(
1676 field: &str,
1677 identifier: &str,
1678) -> Result<(), CapabilityGrammarError> {
1679 if is_valid_capability_identifier(identifier) {
1680 Ok(())
1681 } else {
1682 Err(CapabilityGrammarError::new(field, identifier))
1683 }
1684}
1685
1686fn validate_runtime_computed(
1687 value: Option<&Value>,
1688 field: &str,
1689) -> Result<(), CapabilityGrammarError> {
1690 let Some(value) = value else {
1691 return Ok(());
1692 };
1693 let Some(pointers) = value.as_array() else {
1694 return Err(CapabilityGrammarError::new(field, value_description(value)));
1695 };
1696
1697 for (index, pointer) in pointers.iter().enumerate() {
1698 let field = format!("{field}[{index}]");
1699 let Some(pointer) = pointer.as_str() else {
1700 return Err(CapabilityGrammarError::new(
1701 field,
1702 value_description(pointer),
1703 ));
1704 };
1705 let Some(tokens) = parse_json_pointer(pointer) else {
1706 return Err(CapabilityGrammarError::new(field, pointer));
1707 };
1708 if tokens.first().is_some_and(|token| token == "capabilities") {
1709 return Err(CapabilityGrammarError::new(field, pointer));
1710 }
1711 }
1712 Ok(())
1713}
1714
1715fn parse_json_pointer(pointer: &str) -> Option<Vec<String>> {
1716 if pointer.is_empty() {
1717 return Some(Vec::new());
1718 }
1719 let raw_tokens = pointer.strip_prefix('/')?;
1720 raw_tokens
1721 .split('/')
1722 .map(unescape_json_pointer_token)
1723 .collect()
1724}
1725
1726fn unescape_json_pointer_token(token: &str) -> Option<String> {
1727 let mut output = String::with_capacity(token.len());
1728 let mut characters = token.chars();
1729 while let Some(character) = characters.next() {
1730 if character != '~' {
1731 output.push(character);
1732 continue;
1733 }
1734 match characters.next()? {
1735 '0' => output.push('~'),
1736 '1' => output.push('/'),
1737 _ => return None,
1738 }
1739 }
1740 Some(output)
1741}
1742
1743fn field_child(parent: &str, child: &str) -> String {
1744 let child = safe_error_value(child);
1745 format!("{parent}.{child}")
1746}
1747
1748fn value_description(value: &Value) -> String {
1749 match value {
1750 Value::String(value) => safe_error_value(value),
1751 Value::Null => "null".to_string(),
1752 Value::Bool(value) => value.to_string(),
1753 Value::Number(value) => value.to_string(),
1754 Value::Array(_) => "<array>".to_string(),
1755 Value::Object(_) => "<object>".to_string(),
1756 }
1757}
1758
1759fn safe_error_value(value: &str) -> String {
1760 let lower = value.to_ascii_lowercase();
1761 if ["secret", "password", "api_key"]
1762 .iter()
1763 .any(|marker| lower.contains(marker))
1764 || lower.starts_with("sk-")
1765 || lower.starts_with("akia")
1766 || lower.starts_with("bearer ")
1767 || lower.starts_with("token=")
1768 || lower.starts_with("credential=")
1769 {
1770 "<redacted>".to_string()
1771 } else {
1772 value.to_string()
1773 }
1774}
1775
1776#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
1782#[serde(rename_all = "snake_case")]
1783pub enum TrustTier {
1784 FirstParty,
1785 Reviewed,
1786 Untrusted,
1787}
1788
1789#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
1793#[serde(tag = "role", rename_all = "snake_case")]
1794pub enum ProviderRole {
1795 ToolProvider {
1796 tools: Vec<Tool>,
1797 identity_scope: Vec<IdentityScope>,
1805 concurrency: Concurrency,
1806 emits_push: bool,
1807 sub_supervises: bool,
1808 },
1809 PipelineStage {
1810 stage: PipelineStageKind,
1811 applies_to: PipelineAppliesTo,
1812 interface: String,
1813 declares_frozen_floor: bool,
1814 needs_signals: Vec<String>,
1815 conformance_class: String,
1816 },
1817 ManagementSurface {
1818 operations: Vec<ManagementOperation>,
1819 config_schema: Value,
1820 observability: Vec<ObservabilitySurface>,
1821 identity_scope: Vec<IdentityScope>,
1825 #[serde(default)]
1826 concurrency: Concurrency,
1827 },
1828 InternalService {
1829 service_id: String,
1830 transport: InternalTransport,
1831 agent_facing: bool,
1832 operations: Vec<String>,
1833 },
1834}
1835
1836#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1849#[serde(rename_all = "snake_case")]
1850pub enum ExecutionMode {
1851 Pure,
1852 Mutating,
1853 Unfenceable,
1854}
1855
1856#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
1858pub struct Tool {
1859 pub name: String,
1860 #[serde(default, skip_serializing_if = "Option::is_none")]
1861 pub description: Option<String>,
1862 pub execution_mode: ExecutionMode,
1867 pub schema: Value,
1868}
1869
1870#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
1876#[serde(rename_all = "snake_case")]
1877pub enum Concurrency {
1878 Serial,
1880 ModuleManaged,
1883 StatelessParallel,
1886}
1887
1888#[allow(clippy::derivable_impls)]
1889impl Default for Concurrency {
1900 fn default() -> Self {
1901 Self::ModuleManaged
1902 }
1903}
1904
1905#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
1912#[serde(rename_all = "snake_case")]
1913pub enum IdentityScope {
1914 Session,
1915 Project,
1916}
1917
1918#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
1920#[serde(rename_all = "snake_case")]
1921pub enum PipelineStageKind {
1922 Transform,
1923 Codec,
1924 Auth,
1925}
1926
1927#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
1929pub struct PipelineAppliesTo {
1930 pub provider: String,
1931 pub model: String,
1932}
1933
1934#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
1939pub struct ManagementOperation {
1940 pub name: String,
1941 pub kind: ManagementOperationKind,
1942 #[serde(default, skip_serializing_if = "Option::is_none")]
1943 pub description: Option<String>,
1944}
1945
1946#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
1947#[serde(rename_all = "snake_case")]
1948pub enum ManagementOperationKind {
1949 Query,
1950 Mutate,
1951}
1952
1953#[derive(Debug, Clone, PartialEq, Eq)]
1956#[non_exhaustive]
1957pub enum OperationDelivery {
1958 Watch,
1959 Other(String),
1960}
1961
1962impl OperationDelivery {
1963 pub const WATCH: Self = Self::Watch;
1965
1966 pub fn wire_name(&self) -> &str {
1968 match self {
1969 Self::Watch => "watch",
1970 Self::Other(value) => value,
1971 }
1972 }
1973
1974 pub fn is_watch(&self) -> bool {
1976 self.wire_name() == "watch"
1977 }
1978}
1979
1980impl Serialize for OperationDelivery {
1981 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1982 where
1983 S: serde::Serializer,
1984 {
1985 serializer.serialize_str(self.wire_name())
1986 }
1987}
1988
1989impl<'de> Deserialize<'de> for OperationDelivery {
1990 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1991 where
1992 D: Deserializer<'de>,
1993 {
1994 let value = String::deserialize(deserializer)?;
1995 Ok(if value == "watch" {
1996 Self::WATCH
1997 } else {
1998 Self::Other(value)
1999 })
2000 }
2001}
2002
2003#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2005pub struct ObservabilitySurface {
2006 pub name: String,
2007 pub kind: ObservabilityKind,
2008}
2009
2010#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2011#[serde(rename_all = "snake_case")]
2012pub enum ObservabilityKind {
2013 Snapshot,
2014 Stream,
2015}
2016
2017#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2018#[serde(rename_all = "snake_case")]
2019pub enum InternalTransport {
2020 Bulk,
2021}
2022
2023#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2025#[serde(tag = "role", rename_all = "snake_case")]
2026pub enum ConsumerRole {
2027 ToolClient { of: Vec<String> },
2028 LlmClient { via: String, auth: String },
2029 ServiceClient { of: Vec<String> },
2030}
2031
2032#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2034pub struct Bindings {
2035 pub storage: StorageBinding,
2036 pub vault_grants: Vec<VaultGrant>,
2037 pub identity: IdentityBinding,
2038}
2039
2040#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2042pub struct StorageBinding {
2043 pub kind: StorageKind,
2044 pub scope: StorageScope,
2045 pub owns_schema: bool,
2046}
2047
2048#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2049#[serde(rename_all = "snake_case")]
2050pub enum StorageKind {
2051 Sqlite,
2052}
2053
2054#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2055#[serde(rename_all = "snake_case")]
2056pub enum StorageScope {
2057 Project,
2058}
2059
2060#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2061pub struct VaultGrant {
2062 pub secret: String,
2063 pub reason: String,
2064}
2065
2066#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2067pub struct IdentityBinding {
2068 pub requires: Vec<IdentityScope>,
2069 pub optional: Vec<IdentityScope>,
2070}
2071
2072#[cfg(test)]
2073mod tests {
2074 use super::*;
2075 use serde_json::json;
2076
2077 fn aft_manifest_fixture() -> ModuleManifest {
2078 ModuleManifest::builder("aft", "0.39.2")
2079 .trust_tier(Some(TrustTier::FirstParty))
2080 .bindings(Some(Bindings {
2081 storage: StorageBinding {
2082 kind: StorageKind::Sqlite,
2083 scope: StorageScope::Project,
2084 owns_schema: true,
2085 },
2086 vault_grants: vec![VaultGrant {
2087 secret: "provider_api_key".to_string(),
2088 reason: "cortexkit_native auth".to_string(),
2089 }],
2090 identity: IdentityBinding {
2091 requires: vec![IdentityScope::Project],
2092 optional: vec![IdentityScope::Session],
2093 },
2094 }))
2095 .protocol_ver(1)
2096 .provides(vec![ProviderRole::ToolProvider {
2097 tools: vec![
2098 Tool {
2099 name: "read".to_string(),
2100 description: None,
2101 execution_mode: ExecutionMode::Pure,
2102 schema: json!({"type": "object"}),
2103 },
2104 Tool {
2105 name: "grep".to_string(),
2106 description: None,
2107 execution_mode: ExecutionMode::Pure,
2108 schema: json!({"type": "object"}),
2109 },
2110 Tool {
2111 name: "outline".to_string(),
2112 description: None,
2113 execution_mode: ExecutionMode::Pure,
2114 schema: json!({"type": "object"}),
2115 },
2116 Tool {
2117 name: "semantic_search".to_string(),
2118 description: None,
2119 execution_mode: ExecutionMode::Pure,
2120 schema: json!({"type": "object"}),
2121 },
2122 Tool {
2123 name: "edit".to_string(),
2124 description: None,
2125 execution_mode: ExecutionMode::Mutating,
2126 schema: json!({"type": "object"}),
2127 },
2128 Tool {
2129 name: "write".to_string(),
2130 description: None,
2131 execution_mode: ExecutionMode::Mutating,
2132 schema: json!({"type": "object"}),
2133 },
2134 Tool {
2135 name: "bash".to_string(),
2136 description: None,
2137 execution_mode: ExecutionMode::Unfenceable,
2138 schema: json!({"type": "object"}),
2139 },
2140 ],
2141 identity_scope: vec![IdentityScope::Session, IdentityScope::Project],
2142 concurrency: Concurrency::ModuleManaged,
2143 emits_push: true,
2144 sub_supervises: true,
2145 }])
2146 .consumes(vec![ConsumerRole::ServiceClient {
2147 of: vec!["embedding.v2".to_string()],
2148 }])
2149 .build()
2150 }
2151
2152 #[test]
2153 fn serde_round_trips_representative_manifest() {
2154 let manifest = aft_manifest_fixture();
2155 let serialized = serde_json::to_string_pretty(&manifest).unwrap();
2156 let decoded: ModuleManifest = serde_json::from_str(&serialized).unwrap();
2157
2158 assert_eq!(manifest, decoded);
2159 }
2160
2161 #[test]
2162 fn builder_defaults_additions_to_honest_absence_and_round_trips() {
2163 let manifest = ModuleManifest::builder("builder-defaults", "2.0.0").build();
2164
2165 assert_eq!(manifest.module_id, "builder-defaults");
2166 assert_eq!(manifest.module_version, "2.0.0");
2167 assert_eq!(manifest.protocol_ver, PROTOCOL_VERSION);
2168 assert_eq!(manifest.trust_tier, None);
2169 assert!(manifest.provides.is_empty());
2170 assert!(manifest.consumes.is_empty());
2171 assert_eq!(manifest.bindings, None);
2172 assert_eq!(manifest.capabilities, None);
2173 assert_eq!(manifest.self_signals, None);
2174 assert_eq!(manifest.provenance, None);
2175
2176 let encoded = serde_json::to_value(&manifest).expect("builder manifest serializes");
2177 for optional in [
2178 "trust_tier",
2179 "consumes",
2180 "bindings",
2181 "capabilities",
2182 "self_signals",
2183 "provenance",
2184 ] {
2185 assert!(
2186 encoded.get(optional).is_none(),
2187 "an absent {optional} declaration must stay absent on the wire"
2188 );
2189 }
2190 let decoded: ModuleManifest =
2191 serde_json::from_value(encoded).expect("builder manifest round-trips");
2192 assert_eq!(decoded, manifest);
2193 }
2194
2195 #[test]
2196 fn fully_populated_builder_manifest_matches_the_literal_wire_golden() {
2197 let manifest = ModuleManifest::builder("full-builder", "2.0.0")
2198 .trust_tier(Some(TrustTier::Reviewed))
2199 .bindings(Some(Bindings {
2200 storage: StorageBinding {
2201 kind: StorageKind::Sqlite,
2202 scope: StorageScope::Project,
2203 owns_schema: false,
2204 },
2205 vault_grants: Vec::new(),
2206 identity: IdentityBinding {
2207 requires: vec![IdentityScope::Project],
2208 optional: Vec::new(),
2209 },
2210 }))
2211 .provides(vec![ProviderRole::ToolProvider {
2212 tools: vec![Tool {
2213 name: "read".to_string(),
2214 description: None,
2215 execution_mode: ExecutionMode::Pure,
2216 schema: json!({"type": "object"}),
2217 }],
2218 identity_scope: vec![IdentityScope::Project],
2219 concurrency: Concurrency::Serial,
2220 emits_push: false,
2221 sub_supervises: false,
2222 }])
2223 .consumes(vec![ConsumerRole::ServiceClient {
2224 of: vec!["embedding.v2".to_string()],
2225 }])
2226 .capabilities(Some(CapabilityDeclarations {
2227 provides: vec!["embedding/v2".to_string()],
2228 requires: Vec::new(),
2229 must_never_reach: Vec::new(),
2230 }))
2231 .self_signals(Some(vec![SelfSignalDeclaration {
2232 name: "usage_poller".to_string(),
2233 kind: SelfSignalKind::Poller,
2234 effect: SelfSignalEffect::Observe,
2235 anchored_to: SignalAnchor::FixedInterval,
2236 cadence: Some(SignalCadence::Literal {
2237 interval_ms: 60_000,
2238 }),
2239 domain: Some("provider-usage".to_string()),
2240 note: None,
2241 }]))
2242 .provenance(Some(ManifestProvenance {
2243 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
2244 build_git_sha_absence_reason: None,
2245 build_lock_digest: Some(
2246 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
2247 ),
2248 wire_crate_version: Some("0.16.0".to_string()),
2249 store_schema_version: Some("42".to_string()),
2250 launch_nonce_source: None,
2251 }))
2252 .build();
2253
2254 assert_eq!(
2255 serde_json::to_vec(&manifest).expect("builder manifest serializes"),
2256 include_bytes!("../tests/golden/module_manifest_builder_full.json"),
2257 "the builder must preserve the prior fully populated literal wire bytes"
2258 );
2259 }
2260
2261 #[test]
2262 fn old_manifest_with_unread_fields_decodes_and_round_trips_verbatim() {
2263 let raw = include_bytes!("../tests/golden/module_manifest_builder_full.json");
2264 let decoded: ModuleManifest =
2265 serde_json::from_slice(raw).expect("old manifest with all unread fields decodes");
2266
2267 assert_eq!(decoded.trust_tier, Some(TrustTier::Reviewed));
2268 assert!(!decoded.consumes.is_empty());
2269 assert!(decoded.bindings.is_some());
2270
2271 let reencoded = serde_json::to_vec(&decoded).expect("re-encode succeeds");
2272 assert_eq!(
2273 reencoded, raw,
2274 "old manifest relay stays byte-for-byte verbatim"
2275 );
2276 }
2277
2278 #[test]
2279 fn new_manifest_omits_unread_fields_on_wire_and_decodes_cleanly() {
2280 let raw = include_bytes!("../tests/golden/module_manifest_diet.json");
2281 let decoded: ModuleManifest =
2282 serde_json::from_slice(raw).expect("new manifest omitting unread fields decodes");
2283
2284 assert_eq!(decoded.trust_tier, None);
2285 assert!(decoded.consumes.is_empty());
2286 assert_eq!(decoded.bindings, None);
2287
2288 let pretty = format!("{}\n", serde_json::to_string_pretty(&decoded).unwrap());
2289 assert_eq!(
2290 pretty.as_bytes(),
2291 raw,
2292 "new manifest matches golden byte-for-byte without unread keys"
2293 );
2294
2295 let as_val: serde_json::Value = serde_json::to_value(&decoded).unwrap();
2296 assert!(
2297 as_val.get("trust_tier").is_none(),
2298 "no trust_tier on wire for new manifest"
2299 );
2300 assert!(
2301 as_val.get("consumes").is_none(),
2302 "no consumes on wire for empty consumes"
2303 );
2304 assert!(
2305 as_val.get("bindings").is_none(),
2306 "no bindings on wire for new manifest"
2307 );
2308 }
2309
2310 #[test]
2311 fn aft_manifest_fixture_matches_v1_contract() {
2312 let manifest = aft_manifest_fixture();
2313
2314 assert_eq!(manifest.module_id, "aft");
2315 let ProviderRole::ToolProvider {
2316 tools,
2317 identity_scope,
2318 concurrency,
2319 emits_push,
2320 sub_supervises,
2321 } = &manifest.provides[0]
2322 else {
2323 panic!("AFT fixture must expose one tool_provider role");
2324 };
2325
2326 assert_eq!(*concurrency, Concurrency::ModuleManaged);
2327 assert!(*emits_push);
2328 assert!(*sub_supervises);
2329 assert_eq!(
2330 identity_scope,
2331 &vec![IdentityScope::Session, IdentityScope::Project]
2332 );
2333 assert_eq!(
2334 tools
2335 .iter()
2336 .map(|tool| (tool.name.as_str(), tool.execution_mode))
2337 .collect::<Vec<_>>(),
2338 vec![
2339 ("read", ExecutionMode::Pure),
2340 ("grep", ExecutionMode::Pure),
2341 ("outline", ExecutionMode::Pure),
2342 ("semantic_search", ExecutionMode::Pure),
2343 ("edit", ExecutionMode::Mutating),
2344 ("write", ExecutionMode::Mutating),
2345 ("bash", ExecutionMode::Unfenceable),
2346 ]
2347 );
2348 }
2349
2350 #[test]
2351 fn tool_provider_role_tag_serializes_as_snake_case() {
2352 let manifest = aft_manifest_fixture();
2353 let value = serde_json::to_value(&manifest).unwrap();
2354
2355 assert_eq!(value["provides"][0]["role"], "tool_provider");
2356 }
2357
2358 #[test]
2359 fn manifest_without_capabilities_preserves_the_existing_wire_shape() {
2360 let manifest = aft_manifest_fixture();
2361 let encoded = serde_json::to_value(&manifest).expect("manifest serializes");
2362 assert!(encoded.get("capabilities").is_none());
2363
2364 let decoded: ModuleManifest =
2365 serde_json::from_value(encoded).expect("legacy manifest parses");
2366 assert_eq!(decoded.capabilities, None);
2367 }
2368
2369 #[test]
2370 fn capability_identifier_lexical_grammar_accepts_only_pinned_forms() {
2371 for identifier in [
2372 "a/v1",
2373 "credentials-provider/v1",
2374 "a1-b2/v4294967295",
2375 "a123456789012345678901234567890123456789012345678901234567890123/v1",
2376 ] {
2377 assert!(
2378 is_valid_capability_identifier(identifier),
2379 "identifier must be accepted: {identifier}"
2380 );
2381 }
2382
2383 for identifier in [
2384 "credentials-Provider/v1",
2385 "credentials-provider/v01",
2386 "credentials-provider-/v1",
2387 "credentials--provider/v1",
2388 "Credentials-provider/v1",
2389 "credentials-provider/1",
2390 "credentials provider/v1",
2391 "credentials-provider/v0",
2392 "credentials-provider/v4294967296",
2393 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/v1",
2394 ] {
2395 assert!(
2396 !is_valid_capability_identifier(identifier),
2397 "identifier must be rejected: {identifier}"
2398 );
2399 }
2400 }
2401
2402 #[test]
2403 fn capability_grammar_errors_redact_secret_shaped_values() {
2404 let error = validate_manifest_capability_grammar(&json!({
2405 "capabilities": { "provides": ["sk-secret-value/v0"] }
2406 }))
2407 .expect_err("secret-shaped capability identifier is malformed");
2408 assert_eq!(error.field(), "capabilities.provides[0]");
2409 assert_eq!(error.value(), "<redacted>");
2410 assert!(!error.to_string().contains("sk-secret-value"));
2411 }
2412
2413 #[test]
2420 fn provenance_builder_sentinels_become_field_omission() {
2421 for sentinel in [
2422 "unknown",
2423 "UNKNOWN",
2424 "Unknown",
2425 "unavailable",
2426 "none",
2427 "None",
2428 " unknown ",
2429 "",
2430 ] {
2431 let p = build_provenance_from_source(
2432 BuildGitShaSource::Git {
2433 revision: sentinel,
2434 tree_state: GitTreeState::Clean,
2435 },
2436 Some(sentinel),
2437 Some(sentinel),
2438 )
2439 .expect("sentinels are omitted before form validation");
2440 assert_eq!(
2441 (
2442 p.build_git_sha,
2443 p.build_git_sha_absence_reason,
2444 p.build_lock_digest,
2445 p.store_schema_version,
2446 ),
2447 (
2448 None,
2449 Some(BuildGitShaAbsenceReason::NeverDerived),
2450 None,
2451 None,
2452 ),
2453 "sentinel {sentinel:?} must be omitted, not published"
2454 );
2455 }
2456 let real = build_provenance_from_source(
2457 BuildGitShaSource::Git {
2458 revision: "0123456789abcdef0123456789abcdef01234567",
2459 tree_state: GitTreeState::Clean,
2460 },
2461 None,
2462 Some("9"),
2463 )
2464 .expect("canonical build revision is accepted");
2465 assert_eq!(
2466 real.build_git_sha.as_deref(),
2467 Some("0123456789abcdef0123456789abcdef01234567")
2468 );
2469 assert_eq!(real.store_schema_version.as_deref(), Some("9"));
2470 assert_eq!(
2474 real.wire_crate_version.as_deref(),
2475 Some(crate::SUBC_PROTOCOL_CRATE_VERSION)
2476 );
2477 }
2478
2479 #[test]
2480 fn build_provenance_accepts_canonical_sha_and_lock_digest() {
2481 let provenance = build_provenance_from_source(
2482 BuildGitShaSource::Git {
2483 revision: " 0123456789abcdef0123456789abcdef01234567 ",
2484 tree_state: GitTreeState::Clean,
2485 },
2486 Some(" abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789 "),
2487 Some(" schema-v3 "),
2488 )
2489 .expect("canonical build facts are accepted");
2490
2491 assert_eq!(
2492 provenance,
2493 ManifestProvenance {
2494 build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
2495 build_git_sha_absence_reason: None,
2496 build_lock_digest: Some(
2497 "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
2498 ),
2499 wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
2500 store_schema_version: Some("schema-v3".to_string()),
2501 launch_nonce_source: None,
2502 }
2503 );
2504 }
2505
2506 #[test]
2507 fn build_provenance_refuses_an_abbreviated_git_sha() {
2508 let error = build_provenance_from_source(
2509 BuildGitShaSource::Git {
2510 revision: "0123456789ab",
2511 tree_state: GitTreeState::Clean,
2512 },
2513 None,
2514 None,
2515 )
2516 .expect_err("a 12-character abbreviation is not canonical");
2517
2518 assert_eq!(error.field(), "build_git_sha");
2519 assert_eq!(error.length(), 12);
2520 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
2521 assert_eq!(
2522 error.to_string(),
2523 "invalid manifest provenance form: field build_git_sha has length 12; canonical form is exactly 40 lowercase hexadecimal characters"
2524 );
2525 }
2526
2527 #[test]
2528 fn build_provenance_refuses_an_abbreviated_lock_digest() {
2529 let error = build_provenance_from_source(
2530 BuildGitShaSource::NeverDerived,
2531 Some("0123456789abcdef"),
2532 None,
2533 )
2534 .expect_err("a 16-character digest is not canonical");
2535
2536 assert_eq!(error.field(), "build_lock_digest");
2537 assert_eq!(error.length(), 16);
2538 assert_eq!(error.canonical_form(), BUILD_LOCK_DIGEST_CANONICAL_FORM);
2539 }
2540
2541 #[test]
2542 fn build_provenance_refuses_uppercase_hex() {
2543 let uppercase_sha = "A".repeat(40);
2544 let error = build_provenance_from_source(
2545 BuildGitShaSource::Git {
2546 revision: &uppercase_sha,
2547 tree_state: GitTreeState::Clean,
2548 },
2549 None,
2550 None,
2551 )
2552 .expect_err("uppercase hexadecimal is not canonical");
2553
2554 assert_eq!(error.field(), "build_git_sha");
2555 assert_eq!(error.length(), 40);
2556 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
2557 }
2558
2559 #[test]
2560 fn build_provenance_refuses_dirty_revision_stamp_claimed_clean() {
2561 let error = build_provenance_from_source(
2562 BuildGitShaSource::Git {
2563 revision: "0123456789abcdef0123456789abcdef01234567-dirty",
2564 tree_state: GitTreeState::Clean,
2565 },
2566 None,
2567 None,
2568 )
2569 .expect_err("a dirty stamp is not a canonical build revision");
2570
2571 assert_eq!(error.field(), "build_git_sha");
2572 assert_eq!(error.length(), 46);
2573 assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
2574 }
2575
2576 #[test]
2577 fn build_provenance_keeps_a_lock_digest_when_identity_is_unavailable() {
2578 let provenance = build_provenance_from_source(
2579 BuildGitShaSource::Git {
2580 revision: "unavailable",
2581 tree_state: GitTreeState::Clean,
2582 },
2583 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"),
2584 None,
2585 )
2586 .expect("sentinel SHA is omitted before the valid lock digest is checked");
2587
2588 assert_eq!(provenance.build_git_sha, None);
2589 assert_eq!(
2590 provenance.build_lock_digest,
2591 Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string())
2592 );
2593 assert_eq!(
2594 provenance.wire_crate_version,
2595 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
2596 );
2597 }
2598
2599 #[test]
2600 fn build_provenance_omits_fully_unavailable_inputs() {
2601 let provenance = build_provenance_from_source(
2602 BuildGitShaSource::NeverDerived,
2603 Some(" unavailable "),
2604 Some(" "),
2605 )
2606 .expect("omitted and sentinel inputs are not form errors");
2607
2608 assert_eq!(provenance.build_git_sha, None);
2609 assert_eq!(provenance.build_lock_digest, None);
2610 assert_eq!(provenance.store_schema_version, None);
2611 assert_eq!(
2612 provenance.wire_crate_version,
2613 Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
2614 );
2615 }
2616
2617 #[test]
2618 fn legacy_build_provenance_keeps_master_wire_bytes_without_an_absence_reason() {
2619 let revision = "0123456789abcdef0123456789abcdef01234567";
2620 for (input, expected) in [
2621 (
2622 Some(revision),
2623 format!(
2624 r#"{{"build_git_sha":"{revision}","wire_crate_version":"{}"}}"#,
2625 crate::SUBC_PROTOCOL_CRATE_VERSION
2626 ),
2627 ),
2628 (
2629 None,
2630 format!(
2631 r#"{{"wire_crate_version":"{}"}}"#,
2632 crate::SUBC_PROTOCOL_CRATE_VERSION
2633 ),
2634 ),
2635 (
2636 Some("unknown"),
2637 format!(
2638 r#"{{"wire_crate_version":"{}"}}"#,
2639 crate::SUBC_PROTOCOL_CRATE_VERSION
2640 ),
2641 ),
2642 ] {
2643 let provenance = build_provenance(input, None, None)
2644 .expect("the legacy build facts remain constructible");
2645 assert_eq!(provenance.build_git_sha_absence_reason, None);
2646 assert_eq!(
2647 serde_json::to_string(&provenance).expect("legacy provenance serializes"),
2648 expected
2649 );
2650 }
2651 }
2652
2653 #[test]
2654 fn build_provenance_derives_git_sha_absence_from_the_stamping_inputs() {
2655 let revision = "0123456789abcdef0123456789abcdef01234567";
2656 let cases = [
2657 (
2658 BuildGitShaSource::Git {
2659 revision,
2660 tree_state: GitTreeState::Clean,
2661 },
2662 Some(revision),
2663 None,
2664 ),
2665 (
2666 BuildGitShaSource::Git {
2667 revision,
2668 tree_state: GitTreeState::Dirty,
2669 },
2670 None,
2671 Some(BuildGitShaAbsenceReason::DeclinedDirty),
2672 ),
2673 (
2674 BuildGitShaSource::NeverDerived,
2675 None,
2676 Some(BuildGitShaAbsenceReason::NeverDerived),
2677 ),
2678 (
2679 BuildGitShaSource::NoGitDir,
2680 None,
2681 Some(BuildGitShaAbsenceReason::NoGitDir),
2682 ),
2683 ];
2684
2685 for (source, expected_sha, expected_reason) in cases {
2686 let provenance = build_provenance_from_source(source, None, None)
2687 .expect("every stamping state constructs honest provenance");
2688 assert_eq!(provenance.build_git_sha.as_deref(), expected_sha);
2689 assert_eq!(provenance.build_git_sha_absence_reason, expected_reason);
2690 }
2691 }
2692
2693 #[test]
2694 fn unknown_git_sha_absence_reason_round_trips_byte_faithfully() {
2695 let wire = format!(
2696 r#"{{"build_git_sha_absence_reason":"future_stamper_state","wire_crate_version":"{}"}}"#,
2697 crate::SUBC_PROTOCOL_CRATE_VERSION
2698 );
2699 let provenance: ManifestProvenance =
2700 serde_json::from_str(&wire).expect("future absence reasons remain readable");
2701
2702 assert_eq!(
2703 provenance.build_git_sha_absence_reason,
2704 Some(BuildGitShaAbsenceReason::ForwardCompatibleUnknown(
2705 "future_stamper_state".to_string()
2706 ))
2707 );
2708 assert_eq!(
2709 serde_json::to_string(&provenance).expect("future absence reason reserializes"),
2710 wire
2711 );
2712 }
2713
2714 #[test]
2715 fn provenance_rejects_an_absence_reason_beside_a_declared_commit() {
2716 let error = serde_json::from_value::<ManifestProvenance>(json!({
2717 "build_git_sha": "0123456789abcdef0123456789abcdef01234567",
2718 "build_git_sha_absence_reason": "declined_dirty"
2719 }))
2720 .expect_err("a declared commit cannot also claim an absence reason");
2721
2722 assert!(error.to_string().contains(
2723 "build_git_sha_absence_reason has must be omitted when build_git_sha is present"
2724 ));
2725 }
2726}