1#![forbid(unsafe_code)]
9
10use std::{collections::BTreeMap, path::PathBuf};
11
12use serde::{
13 de::{Error as _, MapAccess, SeqAccess, Visitor},
14 ser::SerializeMap,
15 Deserialize, Deserializer, Serialize, Serializer,
16};
17use subc_protocol::{
18 manifest::{
19 CapabilityDeclarations, EventDeclaration, ManifestProvenance, OperationDelivery,
20 OperationPayload, ProviderRole, RichUiDescriptor, SelfSignalDeclaration,
21 },
22 scope::ScopeSelector,
23 session::HealthStatus,
24 BindIdentity, RouteTarget,
25};
26
27pub use subc_protocol::claim::{
28 Claim, ClaimMintReply, ClaimMintRequest, ClaimPresentReply, ClaimPresentRequest, ClaimPurpose,
29 ClaimRateLimitedDetail,
30};
31pub use subc_protocol::peer::CallerOrigin as CatalogOrigin;
32pub use subc_protocol::RouteCloseReason;
33use subc_protocol::{peer::MAX_ATTESTATION_INTEGER, provider_declarations::ProviderDeclarations};
34
35mod activity;
36pub use activity::*;
37
38mod scope_served_by;
39pub use scope_served_by::*;
40
41macro_rules! open_string_enum {
42 (
43 $(#[$meta:meta])*
44 $name:ident {
45 $( $(#[$variant_meta:meta])* $variant:ident => $wire_name:literal ),+ $(,)?
46 }
47 ) => {
48 $(#[$meta])*
49 #[derive(Debug, Clone, PartialEq, Eq)]
50 pub enum $name {
51 $( $(#[$variant_meta])* $variant, )+
52 Unknown(String),
53 }
54
55 impl $name {
56 fn wire_name(&self) -> &str {
57 match self {
58 $( Self::$variant => $wire_name, )+
59 Self::Unknown(value) => value,
60 }
61 }
62 }
63
64 impl Serialize for $name {
65 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
66 where
67 S: serde::Serializer,
68 {
69 serializer.serialize_str(self.wire_name())
70 }
71 }
72
73 impl<'de> Deserialize<'de> for $name {
74 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
75 where
76 D: serde::Deserializer<'de>,
77 {
78 let value = String::deserialize(deserializer)?;
79 Ok(match value.as_str() {
80 $( $wire_name => Self::$variant, )+
81 _ => Self::Unknown(value),
82 })
83 }
84 }
85 };
86}
87
88mod rescan_checked;
89pub use rescan_checked::*;
90
91mod app_open;
92pub use app_open::*;
93
94mod connection_describe;
95pub use connection_describe::*;
96
97mod subtree;
98pub use subtree::*;
99mod tree;
100pub use tree::*;
101
102#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
104pub struct ConsumerIdentity {
105 pub module_id: String,
106 pub launch_nonce: String,
107}
108
109impl std::fmt::Debug for ConsumerIdentity {
114 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115 f.debug_struct("ConsumerIdentity")
116 .field("module_id", &self.module_id)
117 .field(
118 "launch_nonce",
119 &format_args!("<{} bytes redacted>", self.launch_nonce.len()),
120 )
121 .finish()
122 }
123}
124
125pub mod config;
136
137pub mod ops {
138 pub const SERVER: &str = "server.";
139 pub const CATALOG: &str = "catalog.";
140 pub const ROUTE: &str = "route.";
141 pub const SUPERVISOR: &str = "supervisor.";
142 pub const CONFIG: &str = "config.";
143
144 pub const SERVER_DESCRIBE: &str = "server.describe";
145 pub const DAEMON_SHUTDOWN_INTENT: &str = "daemon.shutdown_intent";
146 pub const CATALOG_LIST: &str = "catalog.list";
147 pub const CATALOG_WATCH: &str = "catalog.watch";
148 pub const ROUTE_OPEN: &str = "route.open";
149 pub const ROUTE_POLL: &str = "route.poll";
150 pub const ROUTE_CLOSING: &str = "route.closing";
151 pub const ROUTE_CLOSED: &str = "route.closed";
152 pub const SUPERVISOR_LIST: &str = "supervisor.list";
153 pub const SUPERVISOR_RESTART: &str = "supervisor.restart";
154 pub const SUPERVISOR_SWAP: &str = "supervisor.swap";
155 pub const SUPERVISOR_RELOAD: &str = "supervisor.reload";
156 pub const SUPERVISOR_RESCAN: &str = "supervisor.rescan";
157 pub const SUPERVISOR_RESCAN_CHECKED: &str = "supervisor.rescan_checked";
158 pub const SUPERVISOR_RELEASE_RESERVED: &str = "supervisor.release_reserved";
159 pub const SUPERVISOR_SET_ENABLED: &str = "supervisor.set_enabled";
160 pub const SUPERVISOR_HEALTH_PROBE: &str = "supervisor.health_probe";
161 pub const SUPERVISOR_HEALTH: &str = "supervisor.health";
162 pub const SUPERVISOR_STDERR_TAIL: &str = "supervisor.stderr_tail";
163 pub const SUPERVISOR_TERMINALS: &str = "supervisor.terminals";
164 pub const SUPERVISOR_ROUTES: &str = "supervisor.routes";
165 pub const SUPERVISOR_PROVENANCE: &str = "supervisor.provenance";
166 pub const SUPERVISOR_SPAWN_SNAPSHOT: &str = "supervisor.spawn_snapshot";
167 pub const SUPERVISOR_SPAWN_SUBSCRIBE: &str = "supervisor.spawn_subscribe";
168 pub const ACTIVITY_RECORD: &str = "activity.record";
169 pub const ACTIVITY_QUERY: &str = "activity.query";
170 pub const ACTIVITY_SUBSCRIBE: &str = "activity.subscribe";
171 pub const APP_OPEN: &str = "app.open";
172 pub const CONNECTION_DESCRIBE: &str = "connection.describe";
173}
174
175#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
177#[serde(tag = "op")]
178#[allow(clippy::large_enum_variant)]
181pub enum ClientControlRequest {
182 #[serde(rename = "daemon.shutdown_intent")]
185 DaemonShutdownIntent {
186 #[serde(default)]
187 intent: serde_json::Value,
188 },
189 #[serde(rename = "server.describe")]
190 ServerDescribe {},
191 #[serde(rename = "catalog.list")]
192 CatalogList {
193 #[serde(default)]
198 module_id: Option<String>,
199 },
200 #[serde(rename = "route.open")]
201 RouteOpen {
202 target: RouteTarget,
203 identity: BindIdentity,
204 #[serde(default, skip_serializing_if = "Option::is_none")]
213 consumer_identity: Option<ConsumerIdentity>,
214 #[serde(default, skip_serializing_if = "Option::is_none")]
222 consumer_capabilities: Option<Vec<String>>,
223 #[serde(default, skip_serializing_if = "Option::is_none")]
234 role_versions: Option<BTreeMap<String, String>>,
235 #[serde(default, skip_serializing_if = "Option::is_none")]
239 busy_refusals: Option<bool>,
240 #[serde(default, skip_serializing_if = "Option::is_none")]
242 admission_facts: Option<serde_json::Value>,
243 #[serde(default, skip_serializing_if = "Option::is_none")]
250 scope: Option<ScopeSelector>,
251 },
252 #[serde(rename = "route.poll")]
253 RoutePoll {
254 route_channel: u16,
255 route_epoch: u32,
256 kind: PollKind,
257 },
258 #[serde(rename = "supervisor.list")]
259 SupervisorList {},
260 #[serde(rename = "supervisor.spawn_snapshot")]
262 SupervisorSpawnSnapshot {},
263 #[serde(rename = "supervisor.spawn_subscribe")]
279 SupervisorSpawnSubscribe {
280 #[serde(default, skip_serializing_if = "Option::is_none")]
281 since: Option<SpawnCursor>,
282 },
283 #[serde(rename = "supervisor.restart")]
284 SupervisorRestart {
285 module_id: String,
286 #[serde(default, skip_serializing_if = "Option::is_none")]
296 drain_timeout_ms: Option<u64>,
297 },
298 #[serde(rename = "supervisor.swap")]
313 SupervisorSwap {
314 module_id: String,
315 #[serde(default, skip_serializing_if = "Option::is_none")]
318 ready_timeout_ms: Option<u64>,
319 },
320 #[serde(rename = "supervisor.reload")]
321 SupervisorReload { module_id: String },
322 #[serde(rename = "supervisor.rescan")]
323 SupervisorRescan {
324 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
344 preview: bool,
345 },
346 #[serde(rename = "supervisor.rescan_checked")]
370 SupervisorRescanChecked {
371 preview: bool,
372 #[serde(default, skip_serializing_if = "Option::is_none")]
373 candidate: Option<String>,
374 #[serde(default, skip_serializing_if = "Option::is_none")]
375 expect: Option<RescanExpect>,
376 },
377 #[serde(rename = "supervisor.release_reserved")]
381 SupervisorReleaseReserved { module_id: String },
382 #[serde(rename = "supervisor.set_enabled")]
383 SupervisorSetEnabled { module_id: String, enabled: bool },
384 #[serde(rename = "supervisor.health_probe")]
385 SupervisorHealthProbe { module_id: String },
386 #[serde(rename = "supervisor.health")]
387 SupervisorHealth {},
388 #[serde(rename = "supervisor.routes")]
401 SupervisorRoutes {
402 #[serde(default, skip_serializing_if = "Option::is_none")]
403 module_id: Option<String>,
404 },
405 #[serde(rename = "supervisor.provenance")]
408 SupervisorProvenance {
409 #[serde(default, skip_serializing_if = "Option::is_none")]
410 module_id: Option<String>,
411 },
412 #[serde(rename = "supervisor.stderr_tail")]
420 SupervisorStderrTail {
421 module_id: String,
422 #[serde(default, skip_serializing_if = "Option::is_none")]
423 max_lines: Option<u32>,
424 #[serde(default, skip_serializing_if = "Option::is_none")]
425 max_bytes: Option<u32>,
426 },
427 #[serde(rename = "supervisor.terminals")]
440 SupervisorTerminals { module_id: String },
441}
442
443#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
445#[serde(tag = "op")]
446pub enum ClientControlResponse {
447 #[serde(rename = "daemon.shutdown_intent")]
448 DaemonShutdownIntent { intent: String, expires_at_ms: u64 },
449 #[serde(rename = "server.describe")]
450 ServerDescribe {
451 protocol_ver: u8,
452 subc_ops: Vec<String>,
453 capabilities: Vec<String>,
454 connected_clients: u64,
455 #[serde(default, skip_serializing_if = "Option::is_none")]
456 counters: Option<serde_json::Value>,
457 #[serde(default, skip_serializing_if = "Option::is_none")]
464 build_git_sha: Option<String>,
465 #[serde(default, skip_serializing_if = "Option::is_none")]
471 build_lock_digest: Option<String>,
472 #[serde(default, skip_serializing_if = "Vec::is_empty")]
476 capability_requirements: Vec<CapabilityRequirementStatus>,
477 #[serde(default, skip_serializing_if = "Option::is_none")]
482 machine_id: Option<String>,
483 #[serde(default, skip_serializing_if = "Option::is_none")]
492 config_path: Option<PathBuf>,
493 },
494 #[serde(rename = "catalog.list")]
495 CatalogList {
496 generation: u64,
497 modules: Vec<CatalogEntry>,
498 subc_ops: Vec<String>,
499 },
500 #[serde(rename = "route.open")]
501 RouteOpen {
502 route_channel: u16,
503 route_epoch: u32,
504 #[serde(default, skip_serializing_if = "Option::is_none")]
506 request_window: Option<usize>,
507 #[serde(default, skip_serializing_if = "Option::is_none")]
509 watch_window: Option<usize>,
510 },
511 #[serde(rename = "route.poll")]
512 RoutePoll {
513 route_channel: u16,
514 route_epoch: u32,
515 status: Option<String>,
516 live: Option<bool>,
517 },
518 #[serde(rename = "supervisor.list")]
519 SupervisorList {
520 generation: u64,
521 modules: Vec<SupervisorEntry>,
522 #[serde(default, skip_serializing_if = "Option::is_none")]
523 daemon: Option<DaemonResources>,
524 #[serde(default, skip_serializing_if = "Option::is_none")]
525 agent_commands: Option<Vec<AgentCommandResources>>,
526 },
527 #[serde(rename = "supervisor.spawn_snapshot")]
528 SupervisorSpawnSnapshot {
529 #[serde(flatten)]
530 snapshot: SpawnSnapshot,
531 },
532 #[serde(rename = "supervisor.ack")]
533 SupervisorAck { module_id: String, applied: bool },
534 #[serde(rename = "supervisor.rescan")]
535 SupervisorRescan {
536 #[serde(flatten)]
537 result: SupervisorRescanResult,
538 },
539 #[serde(rename = "supervisor.health_probe")]
540 SupervisorHealthProbe {
541 module_id: String,
542 status: HealthStatus,
543 #[serde(default, skip_serializing_if = "Option::is_none")]
544 detail: Option<String>,
545 #[serde(default, skip_serializing_if = "Option::is_none")]
546 metrics: Option<serde_json::Value>,
547 },
548 #[serde(rename = "supervisor.health")]
549 SupervisorHealth {
550 generation: u64,
551 modules: Vec<SupervisorHealthEntry>,
552 },
553 #[serde(rename = "supervisor.routes")]
554 SupervisorRoutes { modules: Vec<SupervisorRouteModule> },
555 #[serde(rename = "supervisor.provenance")]
556 SupervisorProvenance {
557 daemon: SupervisorDaemonProvenance,
558 modules: Vec<SupervisorModuleProvenance>,
559 },
560 #[serde(rename = "supervisor.stderr_tail")]
561 SupervisorStderrTail {
562 module_id: String,
563 #[serde(flatten)]
564 tail: StderrTail,
565 },
566 #[serde(rename = "supervisor.terminals")]
567 SupervisorTerminals {
568 module_id: String,
569 #[serde(flatten)]
570 terminals: TerminalHistory,
571 },
572}
573
574pub const ROUTE_CLOSE_REASONS_CAPABILITY: &str = "route-close-reasons/v1";
576
577#[non_exhaustive]
581#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
582pub struct RouteOpenRequestExt {
583 #[serde(default, skip_serializing_if = "Option::is_none")]
584 pub accepts_close_reasons: Option<Vec<String>>,
585}
586
587impl RouteOpenRequestExt {
588 pub fn new() -> Self {
589 Self::default()
590 }
591
592 #[must_use]
593 pub fn with_accepts_close_reasons(mut self, reasons: Option<Vec<String>>) -> Self {
594 self.accepts_close_reasons = reasons;
595 self
596 }
597
598 pub fn read_from(body: &serde_json::Value) -> serde_json::Result<Self> {
600 require_route_open_object(body)?;
601 serde_json::from_value(body.clone())
602 }
603
604 pub fn write_to(&self, body: &mut serde_json::Value) -> serde_json::Result<()> {
607 write_route_open_ext(body, self, &["accepts_close_reasons"])
608 }
609}
610
611#[non_exhaustive]
614#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
615pub struct RouteOpenReplyExt {
616 #[serde(
618 default,
619 skip_serializing_if = "Option::is_none",
620 deserialize_with = "deserialize_route_open_target"
621 )]
622 pub target: Option<RouteOpenTarget>,
623}
624
625impl RouteOpenReplyExt {
626 pub fn new() -> Self {
627 Self::default()
628 }
629
630 #[must_use]
631 pub fn with_target(mut self, target: Option<RouteOpenTarget>) -> Self {
632 self.target = target;
633 self
634 }
635
636 pub fn read_from(body: &serde_json::Value) -> serde_json::Result<Self> {
638 require_route_open_object(body)?;
639 serde_json::from_value(body.clone())
640 }
641
642 pub fn write_to(&self, body: &mut serde_json::Value) -> serde_json::Result<()> {
645 write_route_open_ext(body, self, &["target"])
646 }
647}
648
649fn require_route_open_object(body: &serde_json::Value) -> serde_json::Result<()> {
650 if body.is_object()
651 && body.get("op").and_then(serde_json::Value::as_str) == Some(ops::ROUTE_OPEN)
652 {
653 Ok(())
654 } else {
655 Err(serde_json::Error::custom(
656 "expected a route.open body object",
657 ))
658 }
659}
660
661fn write_route_open_ext(
662 body: &mut serde_json::Value,
663 ext: &impl Serialize,
664 keys: &[&str],
665) -> serde_json::Result<()> {
666 require_route_open_object(body)?;
667 let serde_json::Value::Object(fields) = serde_json::to_value(ext)? else {
668 unreachable!("route.open companions serialize as objects");
669 };
670 let object = body.as_object_mut().expect("validated route.open object");
671 for key in keys {
672 object.remove(*key);
673 }
674 object.extend(fields);
675 Ok(())
676}
677
678#[non_exhaustive]
680#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
681#[serde(rename_all = "snake_case")]
682pub enum RouteOpenTargetKind {
683 Spawn,
684 Prefix,
685 Unsupervised,
686 #[serde(other)]
687 Unknown,
688}
689
690#[non_exhaustive]
693#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
694pub struct RouteOpenTarget {
695 pub incarnation: String,
696 pub kind: RouteOpenTargetKind,
697 #[serde(skip_serializing_if = "Option::is_none")]
698 pub spawn: Option<u64>,
699 #[serde(skip_serializing_if = "Option::is_none")]
700 pub authority_epoch: Option<u64>,
701 pub first_party: bool,
702 #[serde(skip_serializing_if = "Option::is_none")]
703 pub approved_declarations_digest: Option<String>,
704}
705
706impl RouteOpenTarget {
707 pub fn new(
710 incarnation: impl Into<String>,
711 kind: RouteOpenTargetKind,
712 spawn: Option<u64>,
713 authority_epoch: Option<u64>,
714 first_party: bool,
715 approved_declarations_digest: Option<String>,
716 ) -> serde_json::Result<Self> {
717 serde_json::from_value(serde_json::json!({
718 "incarnation": incarnation.into(), "kind": kind,
719 "spawn": spawn, "authority_epoch": authority_epoch,
720 "first_party": first_party,
721 "approved_declarations_digest": approved_declarations_digest,
722 }))
723 }
724}
725
726impl<'de> Deserialize<'de> for RouteOpenTarget {
727 fn deserialize<D: Deserializer<'de>>(decoder: D) -> Result<Self, D::Error> {
728 decode_route_open_target(serde_json::Value::deserialize(decoder)?)
729 .map_err(D::Error::custom)?
730 .ok_or_else(|| D::Error::custom("incomplete route.open target"))
731 }
732}
733
734fn deserialize_route_open_target<'de, D: Deserializer<'de>>(
735 decoder: D,
736) -> Result<Option<RouteOpenTarget>, D::Error> {
737 decode_route_open_target(serde_json::Value::deserialize(decoder)?).map_err(D::Error::custom)
738}
739
740fn decode_route_open_target(
741 mut value: serde_json::Value,
742) -> serde_json::Result<Option<RouteOpenTarget>> {
743 if value.is_null() {
744 return Ok(None);
745 }
746 let object = value
747 .as_object_mut()
748 .ok_or_else(|| serde_json::Error::custom("expected target object"))?;
749 let is_spawn = object.get("kind").and_then(serde_json::Value::as_str) == Some("spawn");
750 if is_spawn {
751 for field in ["spawn", "authority_epoch"] {
753 if let Some(integer) = object.get(field) {
754 deserialize_optional_attestation_integer(integer)?;
755 }
756 }
757 } else {
758 for field in ["spawn", "authority_epoch", "approved_declarations_digest"] {
759 object.remove(field);
760 }
761 }
762 if ["incarnation", "kind", "first_party"]
763 .iter()
764 .any(|key| object.get(*key).is_none_or(serde_json::Value::is_null))
765 || (is_spawn
766 && ["spawn", "authority_epoch", "approved_declarations_digest"]
767 .iter()
768 .any(|key| object.get(*key).is_none_or(serde_json::Value::is_null)))
769 {
770 return Ok(None);
771 }
772 #[derive(Deserialize)]
773 struct Wire {
774 incarnation: String,
775 kind: RouteOpenTargetKind,
776 spawn: Option<u64>,
777 authority_epoch: Option<u64>,
778 first_party: bool,
779 approved_declarations_digest: Option<String>,
780 }
781 let wire: Wire = serde_json::from_value(value)?;
782 Ok(Some(RouteOpenTarget {
783 incarnation: wire.incarnation,
784 kind: wire.kind,
785 spawn: wire.spawn,
786 authority_epoch: wire.authority_epoch,
787 first_party: is_spawn && wire.first_party,
788 approved_declarations_digest: wire.approved_declarations_digest,
789 }))
790}
791
792fn deserialize_optional_attestation_integer<'de, D: Deserializer<'de>>(
793 decoder: D,
794) -> Result<Option<u64>, D::Error> {
795 let value = Option::<u64>::deserialize(decoder)?;
796 if value.is_some_and(|integer| integer > MAX_ATTESTATION_INTEGER) {
797 return Err(D::Error::custom("attestation integer exceeds 2^53-1"));
798 }
799 Ok(value)
800}
801
802#[non_exhaustive]
805#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
806#[serde(tag = "op", rename = "catalog.watch")]
807pub struct CatalogWatchRequest {}
808
809impl CatalogWatchRequest {
810 pub const OP: &'static str = ops::CATALOG_WATCH;
811
812 pub fn new() -> Self {
813 Self {}
814 }
815}
816
817#[non_exhaustive]
821#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
822#[serde(tag = "op", rename = "catalog.watch")]
823pub struct CatalogWatchResponse {
824 pub generation: u64,
825}
826
827impl CatalogWatchResponse {
828 pub const OP: &'static str = ops::CATALOG_WATCH;
829
830 pub fn new(generation: u64) -> Self {
831 Self { generation }
832 }
833}
834
835impl<'de> Deserialize<'de> for CatalogWatchRequest {
836 fn deserialize<D: Deserializer<'de>>(decoder: D) -> Result<Self, D::Error> {
837 #[derive(Deserialize)]
838 #[serde(tag = "op")]
839 enum Wire {
840 #[serde(rename = "catalog.watch")]
841 Body {},
842 }
843 let Wire::Body {} = Wire::deserialize(decoder)?;
844 Ok(Self::new())
845 }
846}
847
848impl<'de> Deserialize<'de> for CatalogWatchResponse {
849 fn deserialize<D: Deserializer<'de>>(decoder: D) -> Result<Self, D::Error> {
850 #[derive(Deserialize)]
851 #[serde(tag = "op")]
852 enum Wire {
853 #[serde(rename = "catalog.watch")]
854 Body { generation: u64 },
855 }
856 let Wire::Body { generation } = Wire::deserialize(decoder)?;
857 Ok(Self::new(generation))
858 }
859}
860
861#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
866#[serde(tag = "op")]
867pub enum ClientControlPush {
868 #[serde(rename = "route.closing")]
869 RouteClosing {
870 module_id: String,
871 #[serde(default)]
874 channels: Vec<u16>,
875 reason: RouteCloseReason,
876 },
877 #[serde(rename = "route.closed")]
878 RouteClosed {
879 module_id: String,
880 #[serde(default)]
883 channels: Vec<u16>,
884 reason: RouteCloseReason,
885 drained: bool,
887 abandoned: u32,
890 #[serde(default)]
892 excluded_subscriptions: u32,
893 #[serde(default, skip_serializing_if = "Option::is_none")]
899 terminal: Option<bool>,
900 },
901}
902
903#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
905pub struct SpawnCursor {
906 pub daemon_incarnation: String,
907 pub seq: u64,
908}
909
910#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
912pub struct LiveSpawn {
913 pub module_id: String,
914 pub spawn_generation: u64,
920 pub pid: u32,
921 pub spawned_at_ms: u64,
922}
923
924#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
926pub struct SpawnSnapshot {
927 pub cursor: SpawnCursor,
928 pub ring_bound: u64,
930 pub live: Vec<LiveSpawn>,
931}
932
933#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
935#[serde(rename_all = "snake_case")]
936pub enum SpawnEventKind {
937 Spawned,
938 Exited,
939}
940
941#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
947pub struct SpawnEvent {
948 pub cursor: SpawnCursor,
949 pub kind: SpawnEventKind,
950 pub module_id: String,
951 pub spawn_generation: u64,
953 pub pid: u32,
954 #[serde(default, skip_serializing_if = "Option::is_none")]
955 pub exit_code: Option<i32>,
956 #[serde(default, skip_serializing_if = "Option::is_none")]
957 pub exit_signal: Option<i32>,
958}
959
960#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
962pub struct StderrTail {
963 pub capture: StderrCaptureState,
964 pub entries: Vec<StderrTailEntry>,
965 #[serde(default, skip_serializing_if = "is_zero_u64")]
974 pub dropped_lines: u64,
975}
976
977#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
979pub struct SupervisorRouteModule {
980 pub module_id: String,
981 pub routes: Vec<SupervisorRoute>,
982}
983
984#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
986pub struct SupervisorRoute {
987 pub consumer: SupervisorRouteConsumer,
988 pub age_ms: u64,
990 pub draining: bool,
993 #[serde(default, skip_serializing_if = "Option::is_none")]
999 pub drain_reason: Option<RouteCloseReason>,
1000}
1001
1002#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1004pub struct SupervisorModuleProvenance {
1005 pub module_id: String,
1006 pub module_declared: ModuleDeclaredProvenance,
1007 pub daemon_observed: SupervisorObservedProcess,
1008}
1009
1010#[non_exhaustive]
1013#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
1014pub struct SupervisorModuleProvenanceExt {
1015 #[serde(default, skip_serializing_if = "Option::is_none")]
1017 pub registration: Option<RegistrationMethod>,
1018 #[serde(default, skip_serializing_if = "Option::is_none")]
1022 pub registration_declaration: Option<String>,
1023}
1024
1025impl SupervisorModuleProvenanceExt {
1026 pub fn new() -> Self {
1027 Self::default()
1028 }
1029
1030 #[must_use]
1031 pub fn with_registration(mut self, registration: Option<RegistrationMethod>) -> Self {
1032 self.registration = registration;
1033 self
1034 }
1035
1036 pub fn read_from(entry: &serde_json::Value) -> serde_json::Result<Self> {
1038 if !entry.is_object() {
1039 return Err(serde_json::Error::custom(
1040 "expected a module provenance entry object",
1041 ));
1042 }
1043 serde_json::from_value(entry.clone())
1044 }
1045
1046 pub fn write_to(&self, entry: &mut serde_json::Value) -> serde_json::Result<()> {
1049 let object = entry.as_object_mut().ok_or_else(|| {
1050 serde_json::Error::custom("expected a module provenance entry object")
1051 })?;
1052 object.remove("registration");
1053 if let Some(method) = &self.registration {
1054 object.insert("registration".into(), serde_json::to_value(method)?);
1055 }
1056 object.remove("registration_declaration");
1057 if let Some(declaration) = &self.registration_declaration {
1058 object.insert(
1059 "registration_declaration".into(),
1060 declaration.clone().into(),
1061 );
1062 }
1063 Ok(())
1064 }
1065}
1066
1067#[non_exhaustive]
1070#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1071#[serde(rename_all = "snake_case")]
1072pub enum RegistrationMethod {
1073 Channel,
1074 Nonce,
1075 #[serde(other)]
1076 Unknown,
1077}
1078
1079pub const REGISTRATION_CHANNEL_UNSUPPORTED: &str = "registration_channel_unsupported";
1082
1083#[derive(Debug, Clone, PartialEq)]
1085pub enum ModuleDeclaredProvenance {
1086 Reported {
1087 build: ManifestProvenance,
1088 },
1089 Unverifiable,
1090 Unknown {
1093 tag: String,
1094 body: OrderedJsonObject,
1095 },
1096}
1097
1098#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1103pub struct SupervisorObservedProcess {
1104 #[serde(default, skip_serializing_if = "Option::is_none")]
1110 pub launch_nonce_source: Option<String>,
1111 #[serde(default, skip_serializing_if = "Option::is_none")]
1112 pub pid: Option<u32>,
1113 #[serde(default, skip_serializing_if = "Option::is_none")]
1114 pub spawned_at_ms: Option<u64>,
1115 #[serde(default, skip_serializing_if = "Option::is_none")]
1116 pub spawned_from: Option<PathBuf>,
1117 pub running_image: RunningImageAgreement,
1118}
1119
1120#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1137#[non_exhaustive]
1138pub struct PendingReloadVerdict {
1139 pub path: ReloadPathAgreement,
1140 pub image: RunningImageAgreement,
1141 #[serde(default, skip_serializing_if = "Option::is_none")]
1142 pub spec: Option<LaunchSpecAgreement>,
1143}
1144
1145impl PendingReloadVerdict {
1146 #[must_use]
1148 pub fn new(path: ReloadPathAgreement, image: RunningImageAgreement) -> Self {
1149 Self {
1150 path,
1151 image,
1152 spec: None,
1153 }
1154 }
1155
1156 #[must_use]
1158 pub fn with_spec(mut self, spec: Option<LaunchSpecAgreement>) -> Self {
1159 self.spec = spec;
1160 self
1161 }
1162}
1163
1164#[cfg(test)]
1165mod launch_spec_wire_tests {
1166 use super::*;
1167
1168 #[test]
1169 fn older_daemon_omission_is_not_reported_and_unknown_status_round_trips() {
1170 let old = r#"{"path":{"status":"match"},"image":{"status":"unavailable","reason":"not_running"}}"#;
1171 let parsed: PendingReloadVerdict = serde_json::from_str(old).unwrap();
1172 assert_eq!(parsed.spec, None);
1173 assert_eq!(serde_json::to_string(&parsed).unwrap(), old);
1174 let future = r#"{"status":"future_spec","detail":{"z":1,"a":2}}"#;
1175 let parsed: LaunchSpecAgreement = serde_json::from_str(future).unwrap();
1176 assert!(
1177 matches!(parsed, LaunchSpecAgreement::Unknown { ref tag, .. } if tag == "future_spec")
1178 );
1179 assert_eq!(serde_json::to_string(&parsed).unwrap(), future);
1180 let unavailable = LaunchSpecAgreement::Unavailable {
1181 reason: LaunchSpecUnavailableReason::SpawnedSpecUnavailable,
1182 };
1183 let encoded = serde_json::to_string(&unavailable).unwrap();
1184 assert_eq!(
1185 encoded,
1186 r#"{"status":"unavailable","reason":"spawned_spec_unavailable"}"#
1187 );
1188 assert_eq!(
1189 serde_json::from_str::<LaunchSpecAgreement>(&encoded).unwrap(),
1190 unavailable
1191 );
1192 }
1193}
1194
1195#[derive(Debug, Clone, PartialEq)]
1198pub enum LaunchSpecAgreement {
1199 Match,
1200 Mismatch,
1201 Unavailable {
1202 reason: LaunchSpecUnavailableReason,
1203 },
1204 Unknown {
1205 tag: String,
1206 body: OrderedJsonObject,
1207 },
1208}
1209
1210open_string_enum! {
1211 LaunchSpecUnavailableReason {
1212 NotRunning => "not_running",
1213 SpawnedSpecUnavailable => "spawned_spec_unavailable",
1214 }
1215}
1216
1217#[derive(Debug, Clone, PartialEq)]
1219pub enum ReloadPathAgreement {
1220 Match,
1221 Mismatch {
1222 configured: PathBuf,
1223 spawned_from: PathBuf,
1224 },
1225 Unavailable {
1226 reason: ReloadPathUnavailableReason,
1227 },
1228 Unknown {
1229 tag: String,
1230 body: OrderedJsonObject,
1231 },
1232}
1233
1234open_string_enum! {
1235 ReloadPathUnavailableReason {
1237 NotRunning => "not_running",
1238 SpawnedPathUnavailable => "spawned_path_unavailable",
1239 }
1240}
1241
1242#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1244pub struct SupervisorDaemonProvenance {
1245 pub daemon_build: DaemonBuildProvenance,
1246 pub daemon_observed: DaemonObservedProcess,
1247}
1248
1249#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1251pub struct DaemonBuildProvenance {
1252 #[serde(default, skip_serializing_if = "Option::is_none")]
1253 pub build_git_sha: Option<String>,
1254 #[serde(default, skip_serializing_if = "Option::is_none")]
1255 pub build_lock_digest: Option<String>,
1256}
1257
1258#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1260pub struct DaemonObservedProcess {
1261 #[serde(default, skip_serializing_if = "Option::is_none")]
1262 pub pid: Option<u32>,
1263 #[serde(default, skip_serializing_if = "Option::is_none")]
1268 pub started_at_ms: Option<u64>,
1269 pub running_image: RunningImageAgreement,
1270}
1271
1272#[derive(Debug, Clone, PartialEq)]
1274pub enum RunningImageAgreement {
1275 Match {
1276 evidence: RunningImageEvidence,
1277 },
1278 Mismatch {
1279 running: RunningImageEvidence,
1280 disk: RunningImageEvidence,
1281 },
1282 Unavailable {
1283 reason: RunningImageUnavailableReason,
1284 },
1285 Unknown {
1288 tag: String,
1289 body: OrderedJsonObject,
1290 },
1291}
1292
1293#[derive(Debug, Clone, PartialEq)]
1295pub enum RunningImageEvidence {
1296 LinuxProcSha256 {
1297 digest: String,
1298 },
1299 MacosSpawnInode {
1300 device: u64,
1301 inode: u64,
1302 },
1303 WindowsSpawnFileId {
1305 volume_serial_number: u64,
1306 file_id: [u8; 16],
1307 },
1308 Unknown {
1311 tag: String,
1312 body: OrderedJsonObject,
1313 },
1314}
1315
1316open_string_enum! {
1317 RunningImageUnavailableReason {
1319 NotRunning => "not_running",
1320 NotYetMeasured => "not_yet_measured",
1321 UnsupportedPlatform => "unsupported_platform",
1322 RunningExecutableUnreadable => "running_executable_unreadable",
1323 RunningExecutablePermissionDenied => "running_executable_permission_denied",
1324 ProcessHidden => "process_hidden",
1325 SpawnedPathUnreadable => "spawned_path_unreadable",
1326 HashFailed => "hash_failed",
1327 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
1328 }
1329}
1330
1331#[derive(Debug, Clone, PartialEq)]
1337pub enum SupervisorRouteConsumer {
1338 Reserved {
1339 module_id: String,
1340 },
1341 Direct {
1342 connection_id: u64,
1343 },
1344 Unknown {
1347 tag: String,
1348 body: OrderedJsonObject,
1349 },
1350}
1351
1352#[derive(Debug, Clone, PartialEq)]
1359pub enum StderrCaptureState {
1360 Captured,
1363 Incomplete { reason: String },
1365 NotCaptured { reason: String },
1367 Unknown {
1370 tag: String,
1371 body: OrderedJsonObject,
1372 },
1373}
1374
1375#[derive(Debug, Clone, PartialEq)]
1376pub enum StderrTailEntry {
1377 Line {
1378 text: String,
1379 truncated: bool,
1384 at_ms: Option<u64>,
1388 },
1389 ProcessStart,
1394 Unknown {
1397 tag: String,
1398 body: OrderedJsonObject,
1399 },
1400}
1401
1402#[derive(Debug, Serialize, Deserialize)]
1403#[serde(tag = "status", rename_all = "snake_case")]
1404enum ModuleDeclaredProvenanceWire {
1405 Reported { build: ManifestProvenance },
1406 Unverifiable,
1407}
1408
1409#[derive(Debug, Serialize, Deserialize)]
1410#[serde(tag = "status", rename_all = "snake_case")]
1411enum RunningImageAgreementWire {
1412 Match {
1413 evidence: RunningImageEvidence,
1414 },
1415 Mismatch {
1416 running: RunningImageEvidence,
1417 disk: RunningImageEvidence,
1418 },
1419 Unavailable {
1420 reason: RunningImageUnavailableReason,
1421 },
1422}
1423
1424#[derive(Debug, Serialize, Deserialize)]
1425#[serde(tag = "status", rename_all = "snake_case")]
1426enum ReloadPathAgreementWire {
1427 Match,
1428 Mismatch {
1429 configured: PathBuf,
1430 spawned_from: PathBuf,
1431 },
1432 Unavailable {
1433 reason: ReloadPathUnavailableReason,
1434 },
1435}
1436
1437#[derive(Debug, Serialize, Deserialize)]
1438#[serde(tag = "status", rename_all = "snake_case")]
1439enum LaunchSpecAgreementWire {
1440 Match,
1441 Mismatch,
1442 Unavailable { reason: LaunchSpecUnavailableReason },
1443}
1444
1445#[derive(Debug, Serialize, Deserialize)]
1446#[serde(tag = "method", rename_all = "snake_case")]
1447enum RunningImageEvidenceWire {
1448 LinuxProcSha256 {
1449 digest: String,
1450 },
1451 MacosSpawnInode {
1452 device: u64,
1453 inode: u64,
1454 },
1455 WindowsSpawnFileId {
1456 volume_serial_number: u64,
1457 file_id: [u8; 16],
1458 },
1459}
1460
1461#[derive(Debug, Serialize, Deserialize)]
1462#[serde(tag = "kind", rename_all = "snake_case")]
1463enum SupervisorRouteConsumerWire {
1464 Reserved { module_id: String },
1465 Direct { connection_id: u64 },
1466}
1467
1468#[derive(Debug, Serialize, Deserialize)]
1469#[serde(tag = "state", rename_all = "snake_case")]
1470enum StderrCaptureStateWire {
1471 Captured,
1472 Incomplete { reason: String },
1473 NotCaptured { reason: String },
1474}
1475
1476#[derive(Debug, Serialize, Deserialize)]
1477#[serde(tag = "status", rename_all = "snake_case")]
1478enum ChildResourceUsageWire {
1479 Measured(ChildResourceReading),
1480 Unavailable {
1481 reason: ChildResourceUnavailableReason,
1482 },
1483}
1484
1485#[derive(Debug, Serialize, Deserialize)]
1486#[serde(tag = "kind", rename_all = "snake_case")]
1487enum StderrTailEntryWire {
1488 Line {
1489 text: String,
1490 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1491 truncated: bool,
1492 #[serde(default, skip_serializing_if = "Option::is_none")]
1495 at_ms: Option<u64>,
1496 },
1497 ProcessStart,
1498}
1499
1500#[derive(Debug, Clone, PartialEq)]
1502pub enum OrderedJsonValue {
1503 Null,
1504 Bool(bool),
1505 Number(serde_json::Number),
1506 String(String),
1507 Array(Vec<Self>),
1508 Object(OrderedJsonObject),
1509}
1510
1511#[derive(Debug, Clone, PartialEq)]
1513pub struct OrderedJsonObject(Vec<(String, OrderedJsonValue)>);
1514
1515impl OrderedJsonObject {
1516 pub fn as_entries(&self) -> &[(String, OrderedJsonValue)] {
1518 &self.0
1519 }
1520
1521 fn into_value(self) -> serde_json::Value {
1522 serde_json::Value::Object(
1523 self.0
1524 .into_iter()
1525 .map(|(key, value)| (key, value.into_value()))
1526 .collect(),
1527 )
1528 }
1529}
1530
1531impl OrderedJsonValue {
1532 fn into_value(self) -> serde_json::Value {
1533 match self {
1534 Self::Null => serde_json::Value::Null,
1535 Self::Bool(value) => serde_json::Value::Bool(value),
1536 Self::Number(value) => serde_json::Value::Number(value),
1537 Self::String(value) => serde_json::Value::String(value),
1538 Self::Array(values) => {
1539 serde_json::Value::Array(values.into_iter().map(Self::into_value).collect())
1540 }
1541 Self::Object(value) => value.into_value(),
1542 }
1543 }
1544}
1545
1546impl Serialize for OrderedJsonValue {
1547 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1548 where
1549 S: Serializer,
1550 {
1551 match self {
1552 Self::Null => serializer.serialize_unit(),
1553 Self::Bool(value) => serializer.serialize_bool(*value),
1554 Self::Number(value) => value.serialize(serializer),
1555 Self::String(value) => serializer.serialize_str(value),
1556 Self::Array(values) => values.serialize(serializer),
1557 Self::Object(value) => value.serialize(serializer),
1558 }
1559 }
1560}
1561
1562impl<'de> Deserialize<'de> for OrderedJsonValue {
1563 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1564 where
1565 D: Deserializer<'de>,
1566 {
1567 struct OrderedValueVisitor;
1568
1569 impl<'de> Visitor<'de> for OrderedValueVisitor {
1570 type Value = OrderedJsonValue;
1571
1572 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1573 formatter.write_str("a JSON value with ordered object members")
1574 }
1575
1576 fn visit_unit<E>(self) -> Result<Self::Value, E>
1577 where
1578 E: serde::de::Error,
1579 {
1580 Ok(OrderedJsonValue::Null)
1581 }
1582
1583 fn visit_none<E>(self) -> Result<Self::Value, E>
1584 where
1585 E: serde::de::Error,
1586 {
1587 Ok(OrderedJsonValue::Null)
1588 }
1589
1590 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1591 where
1592 D: Deserializer<'de>,
1593 {
1594 OrderedJsonValue::deserialize(deserializer)
1595 }
1596
1597 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
1598 where
1599 E: serde::de::Error,
1600 {
1601 Ok(OrderedJsonValue::Bool(value))
1602 }
1603
1604 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
1605 where
1606 E: serde::de::Error,
1607 {
1608 Ok(OrderedJsonValue::Number(value.into()))
1609 }
1610
1611 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
1612 where
1613 E: serde::de::Error,
1614 {
1615 Ok(OrderedJsonValue::Number(value.into()))
1616 }
1617
1618 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1619 where
1620 E: serde::de::Error,
1621 {
1622 serde_json::Number::from_f64(value)
1623 .map(OrderedJsonValue::Number)
1624 .ok_or_else(|| E::custom("non-finite JSON number"))
1625 }
1626
1627 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1628 where
1629 E: serde::de::Error,
1630 {
1631 Ok(OrderedJsonValue::String(value.to_owned()))
1632 }
1633
1634 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
1635 where
1636 E: serde::de::Error,
1637 {
1638 Ok(OrderedJsonValue::String(value))
1639 }
1640
1641 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1642 where
1643 A: SeqAccess<'de>,
1644 {
1645 let mut values = Vec::new();
1646 while let Some(value) = sequence.next_element()? {
1647 values.push(value);
1648 }
1649 Ok(OrderedJsonValue::Array(values))
1650 }
1651
1652 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1653 where
1654 A: MapAccess<'de>,
1655 {
1656 let mut entries = Vec::new();
1657 while let Some((key, value)) = map.next_entry()? {
1658 entries.push((key, value));
1659 }
1660 Ok(OrderedJsonValue::Object(OrderedJsonObject(entries)))
1661 }
1662 }
1663
1664 deserializer.deserialize_any(OrderedValueVisitor)
1665 }
1666}
1667
1668impl Serialize for OrderedJsonObject {
1669 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1670 where
1671 S: Serializer,
1672 {
1673 let mut map = serializer.serialize_map(Some(self.0.len()))?;
1674 for (key, value) in &self.0 {
1675 map.serialize_entry(key, value)?;
1676 }
1677 map.end()
1678 }
1679}
1680
1681impl<'de> Deserialize<'de> for OrderedJsonObject {
1682 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1683 where
1684 D: Deserializer<'de>,
1685 {
1686 struct OrderedObjectVisitor;
1687
1688 impl<'de> Visitor<'de> for OrderedObjectVisitor {
1689 type Value = OrderedJsonObject;
1690
1691 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1692 formatter.write_str("an object with ordered JSON members")
1693 }
1694
1695 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1696 where
1697 A: MapAccess<'de>,
1698 {
1699 let mut entries = Vec::new();
1700 while let Some((key, value)) = map.next_entry()? {
1701 entries.push((key, value));
1702 }
1703 Ok(OrderedJsonObject(entries))
1704 }
1705 }
1706
1707 deserializer.deserialize_map(OrderedObjectVisitor)
1708 }
1709}
1710
1711fn read_tagged<'de, D>(
1712 deserializer: D,
1713 field: &'static str,
1714) -> Result<(String, OrderedJsonObject), D::Error>
1715where
1716 D: Deserializer<'de>,
1717{
1718 let body = OrderedJsonObject::deserialize(deserializer)?;
1719 let mut tag = None;
1720 for (key, value) in body.as_entries() {
1721 if key != field {
1722 continue;
1723 }
1724 if tag.is_some() {
1725 return Err(D::Error::custom(format!(
1726 "tagged object has duplicate `{field}` field"
1727 )));
1728 }
1729 let OrderedJsonValue::String(value) = value else {
1730 return Err(D::Error::custom(format!(
1731 "tagged object has no string `{field}` field"
1732 )));
1733 };
1734 tag = Some(value);
1735 }
1736 let Some(tag) = tag else {
1737 return Err(D::Error::custom(format!(
1738 "tagged object has no string `{field}` field"
1739 )));
1740 };
1741 Ok((tag.to_string(), body))
1742}
1743
1744fn read_ordered_tagged(
1745 value: OrderedJsonValue,
1746 field: &'static str,
1747) -> Result<(String, OrderedJsonObject), String> {
1748 let OrderedJsonValue::Object(body) = value else {
1749 return Err(format!("expected tagged object with `{field}` field"));
1750 };
1751 let mut tag = None;
1752 for (key, value) in body.as_entries() {
1753 if key != field {
1754 continue;
1755 }
1756 if tag.is_some() {
1757 return Err(format!("tagged object has duplicate `{field}` field"));
1758 }
1759 let OrderedJsonValue::String(value) = value else {
1760 return Err(format!("tagged object has no string `{field}` field"));
1761 };
1762 tag = Some(value);
1763 }
1764 let Some(tag) = tag else {
1765 return Err(format!("tagged object has no string `{field}` field"));
1766 };
1767 Ok((tag.to_string(), body))
1768}
1769
1770fn ordered_field<'a>(body: &'a OrderedJsonObject, field: &str) -> Option<&'a OrderedJsonValue> {
1771 body.as_entries()
1772 .iter()
1773 .find_map(|(key, value)| (key == field).then_some(value))
1774}
1775
1776fn ordered_string(body: &OrderedJsonObject, field: &str) -> Result<String, String> {
1777 match ordered_field(body, field) {
1778 Some(OrderedJsonValue::String(value)) => Ok(value.clone()),
1779 Some(_) => Err(format!("tagged object field `{field}` is not a string")),
1780 None => Err(format!("tagged object has no `{field}` field")),
1781 }
1782}
1783
1784fn decode_running_image_evidence(value: OrderedJsonValue) -> Result<RunningImageEvidence, String> {
1785 let (tag, body) = read_ordered_tagged(value, "method")?;
1786 match tag.as_str() {
1787 "linux_proc_sha256" => Ok(RunningImageEvidence::LinuxProcSha256 {
1788 digest: ordered_string(&body, "digest")?,
1789 }),
1790 "macos_spawn_inode" => {
1791 let device = ordered_field(&body, "device")
1792 .and_then(|value| match value {
1793 OrderedJsonValue::Number(number) => number.as_u64(),
1794 _ => None,
1795 })
1796 .ok_or_else(|| "tagged object has no unsigned `device` field".to_string())?;
1797 let inode = ordered_field(&body, "inode")
1798 .and_then(|value| match value {
1799 OrderedJsonValue::Number(number) => number.as_u64(),
1800 _ => None,
1801 })
1802 .ok_or_else(|| "tagged object has no unsigned `inode` field".to_string())?;
1803 Ok(RunningImageEvidence::MacosSpawnInode { device, inode })
1804 }
1805 "windows_spawn_file_id" => {
1806 let wire: RunningImageEvidenceWire = serde_json::from_value(
1807 serde_json::to_value(&body).map_err(|error| error.to_string())?,
1808 )
1809 .map_err(|error| error.to_string())?;
1810 match wire {
1811 RunningImageEvidenceWire::WindowsSpawnFileId {
1812 volume_serial_number,
1813 file_id,
1814 } => Ok(RunningImageEvidence::WindowsSpawnFileId {
1815 volume_serial_number,
1816 file_id,
1817 }),
1818 _ => unreachable!(),
1819 }
1820 }
1821 _ => Ok(RunningImageEvidence::Unknown { tag, body }),
1822 }
1823}
1824
1825impl Serialize for ModuleDeclaredProvenance {
1826 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1827 where
1828 S: Serializer,
1829 {
1830 match self {
1831 Self::Reported { build } => ModuleDeclaredProvenanceWire::Reported {
1832 build: build.clone(),
1833 }
1834 .serialize(serializer),
1835 Self::Unverifiable => ModuleDeclaredProvenanceWire::Unverifiable.serialize(serializer),
1836 Self::Unknown { body, .. } => body.serialize(serializer),
1837 }
1838 }
1839}
1840
1841impl<'de> Deserialize<'de> for ModuleDeclaredProvenance {
1842 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1843 where
1844 D: serde::Deserializer<'de>,
1845 {
1846 let (tag, value) = read_tagged(deserializer, "status")?;
1847 match tag.as_str() {
1848 "reported" => match serde_json::from_value(value.into_value())
1849 .map_err(D::Error::custom)?
1850 {
1851 ModuleDeclaredProvenanceWire::Reported { build } => Ok(Self::Reported { build }),
1852 ModuleDeclaredProvenanceWire::Unverifiable => unreachable!(),
1853 },
1854 "unverifiable" => {
1855 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1856 ModuleDeclaredProvenanceWire::Unverifiable => Ok(Self::Unverifiable),
1857 ModuleDeclaredProvenanceWire::Reported { .. } => unreachable!(),
1858 }
1859 }
1860 _ => Ok(Self::Unknown { tag, body: value }),
1861 }
1862 }
1863}
1864
1865impl Serialize for RunningImageAgreement {
1866 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1867 where
1868 S: Serializer,
1869 {
1870 match self {
1871 Self::Match { evidence } => RunningImageAgreementWire::Match {
1872 evidence: evidence.clone(),
1873 }
1874 .serialize(serializer),
1875 Self::Mismatch { running, disk } => RunningImageAgreementWire::Mismatch {
1876 running: running.clone(),
1877 disk: disk.clone(),
1878 }
1879 .serialize(serializer),
1880 Self::Unavailable { reason } => RunningImageAgreementWire::Unavailable {
1881 reason: reason.clone(),
1882 }
1883 .serialize(serializer),
1884 Self::Unknown { body, .. } => body.serialize(serializer),
1885 }
1886 }
1887}
1888
1889impl Serialize for ReloadPathAgreement {
1890 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1891 where
1892 S: Serializer,
1893 {
1894 match self {
1895 Self::Match => ReloadPathAgreementWire::Match.serialize(serializer),
1896 Self::Mismatch {
1897 configured,
1898 spawned_from,
1899 } => ReloadPathAgreementWire::Mismatch {
1900 configured: configured.clone(),
1901 spawned_from: spawned_from.clone(),
1902 }
1903 .serialize(serializer),
1904 Self::Unavailable { reason } => ReloadPathAgreementWire::Unavailable {
1905 reason: reason.clone(),
1906 }
1907 .serialize(serializer),
1908 Self::Unknown { body, .. } => body.serialize(serializer),
1909 }
1910 }
1911}
1912
1913impl Serialize for LaunchSpecAgreement {
1914 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1915 where
1916 S: Serializer,
1917 {
1918 match self {
1919 Self::Match => LaunchSpecAgreementWire::Match.serialize(serializer),
1920 Self::Mismatch => LaunchSpecAgreementWire::Mismatch.serialize(serializer),
1921 Self::Unavailable { reason } => LaunchSpecAgreementWire::Unavailable {
1922 reason: reason.clone(),
1923 }
1924 .serialize(serializer),
1925 Self::Unknown { body, .. } => body.serialize(serializer),
1926 }
1927 }
1928}
1929
1930impl<'de> Deserialize<'de> for LaunchSpecAgreement {
1931 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1932 where
1933 D: Deserializer<'de>,
1934 {
1935 let (tag, body) = read_tagged(deserializer, "status")?;
1936 match tag.as_str() {
1937 "match" => Ok(Self::Match),
1938 "mismatch" => Ok(Self::Mismatch),
1939 "unavailable" => match serde_json::from_value(body.into_value())
1940 .map_err(D::Error::custom)?
1941 {
1942 LaunchSpecAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1943 _ => unreachable!(),
1944 },
1945 _ => Ok(Self::Unknown { tag, body }),
1946 }
1947 }
1948}
1949
1950impl<'de> Deserialize<'de> for ReloadPathAgreement {
1951 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1952 where
1953 D: Deserializer<'de>,
1954 {
1955 let (tag, body) = read_tagged(deserializer, "status")?;
1956 match tag.as_str() {
1957 "match" => Ok(Self::Match),
1958 "mismatch" => {
1959 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1960 ReloadPathAgreementWire::Mismatch {
1961 configured,
1962 spawned_from,
1963 } => Ok(Self::Mismatch {
1964 configured,
1965 spawned_from,
1966 }),
1967 _ => unreachable!(),
1968 }
1969 }
1970 "unavailable" => match serde_json::from_value(body.into_value())
1971 .map_err(D::Error::custom)?
1972 {
1973 ReloadPathAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1974 _ => unreachable!(),
1975 },
1976 _ => Ok(Self::Unknown { tag, body }),
1977 }
1978 }
1979}
1980
1981impl<'de> Deserialize<'de> for RunningImageAgreement {
1982 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1983 where
1984 D: serde::Deserializer<'de>,
1985 {
1986 let (tag, value) = read_tagged(deserializer, "status")?;
1987 match tag.as_str() {
1988 "match" => Ok(Self::Match {
1989 evidence: decode_running_image_evidence(
1990 ordered_field(&value, "evidence")
1991 .cloned()
1992 .ok_or_else(|| D::Error::custom("tagged object has no `evidence` field"))?,
1993 )
1994 .map_err(D::Error::custom)?,
1995 }),
1996 "mismatch" => Ok(Self::Mismatch {
1997 running: decode_running_image_evidence(
1998 ordered_field(&value, "running")
1999 .cloned()
2000 .ok_or_else(|| D::Error::custom("tagged object has no `running` field"))?,
2001 )
2002 .map_err(D::Error::custom)?,
2003 disk: decode_running_image_evidence(
2004 ordered_field(&value, "disk")
2005 .cloned()
2006 .ok_or_else(|| D::Error::custom("tagged object has no `disk` field"))?,
2007 )
2008 .map_err(D::Error::custom)?,
2009 }),
2010 "unavailable" => Ok(Self::Unavailable {
2011 reason: serde_json::from_value(
2012 ordered_field(&value, "reason")
2013 .cloned()
2014 .ok_or_else(|| D::Error::custom("tagged object has no `reason` field"))?
2015 .into_value(),
2016 )
2017 .map_err(D::Error::custom)?,
2018 }),
2019 _ => Ok(Self::Unknown { tag, body: value }),
2020 }
2021 }
2022}
2023
2024impl Serialize for ChildResourceUsage {
2025 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2026 where
2027 S: Serializer,
2028 {
2029 match self {
2030 Self::Measured(reading) => {
2031 ChildResourceUsageWire::Measured(reading.clone()).serialize(serializer)
2032 }
2033 Self::Unavailable { reason } => ChildResourceUsageWire::Unavailable {
2034 reason: reason.clone(),
2035 }
2036 .serialize(serializer),
2037 Self::Unknown { body, .. } => body.serialize(serializer),
2038 }
2039 }
2040}
2041
2042impl<'de> Deserialize<'de> for ChildResourceUsage {
2043 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2044 where
2045 D: Deserializer<'de>,
2046 {
2047 let (tag, body) = read_tagged(deserializer, "status")?;
2048 match tag.as_str() {
2049 "measured" | "unavailable" => {
2050 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
2051 ChildResourceUsageWire::Measured(reading) => Ok(Self::Measured(reading)),
2052 ChildResourceUsageWire::Unavailable { reason } => {
2053 Ok(Self::Unavailable { reason })
2054 }
2055 }
2056 }
2057 _ => Ok(Self::Unknown { tag, body }),
2058 }
2059 }
2060}
2061
2062impl Serialize for RunningImageEvidence {
2063 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2064 where
2065 S: Serializer,
2066 {
2067 match self {
2068 Self::LinuxProcSha256 { digest } => RunningImageEvidenceWire::LinuxProcSha256 {
2069 digest: digest.clone(),
2070 }
2071 .serialize(serializer),
2072 Self::MacosSpawnInode { device, inode } => RunningImageEvidenceWire::MacosSpawnInode {
2073 device: *device,
2074 inode: *inode,
2075 }
2076 .serialize(serializer),
2077 Self::WindowsSpawnFileId {
2078 volume_serial_number,
2079 file_id,
2080 } => RunningImageEvidenceWire::WindowsSpawnFileId {
2081 volume_serial_number: *volume_serial_number,
2082 file_id: *file_id,
2083 }
2084 .serialize(serializer),
2085 Self::Unknown { body, .. } => body.serialize(serializer),
2086 }
2087 }
2088}
2089
2090impl<'de> Deserialize<'de> for RunningImageEvidence {
2091 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2092 where
2093 D: serde::Deserializer<'de>,
2094 {
2095 let (tag, value) = read_tagged(deserializer, "method")?;
2096 match tag.as_str() {
2097 "linux_proc_sha256" => {
2098 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2099 RunningImageEvidenceWire::LinuxProcSha256 { digest } => {
2100 Ok(Self::LinuxProcSha256 { digest })
2101 }
2102 _ => unreachable!(),
2103 }
2104 }
2105 "macos_spawn_inode" => {
2106 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2107 RunningImageEvidenceWire::MacosSpawnInode { device, inode } => {
2108 Ok(Self::MacosSpawnInode { device, inode })
2109 }
2110 _ => unreachable!(),
2111 }
2112 }
2113 "windows_spawn_file_id" => {
2114 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2115 RunningImageEvidenceWire::WindowsSpawnFileId {
2116 volume_serial_number,
2117 file_id,
2118 } => Ok(Self::WindowsSpawnFileId {
2119 volume_serial_number,
2120 file_id,
2121 }),
2122 _ => unreachable!(),
2123 }
2124 }
2125 _ => Ok(Self::Unknown { tag, body: value }),
2126 }
2127 }
2128}
2129
2130impl Serialize for SupervisorRouteConsumer {
2131 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2132 where
2133 S: Serializer,
2134 {
2135 match self {
2136 Self::Reserved { module_id } => SupervisorRouteConsumerWire::Reserved {
2137 module_id: module_id.clone(),
2138 }
2139 .serialize(serializer),
2140 Self::Direct { connection_id } => SupervisorRouteConsumerWire::Direct {
2141 connection_id: *connection_id,
2142 }
2143 .serialize(serializer),
2144 Self::Unknown { body, .. } => body.serialize(serializer),
2145 }
2146 }
2147}
2148
2149impl<'de> Deserialize<'de> for SupervisorRouteConsumer {
2150 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2151 where
2152 D: serde::Deserializer<'de>,
2153 {
2154 let (tag, value) = read_tagged(deserializer, "kind")?;
2155 match tag.as_str() {
2156 "reserved" => {
2157 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2158 SupervisorRouteConsumerWire::Reserved { module_id } => {
2159 Ok(Self::Reserved { module_id })
2160 }
2161 _ => unreachable!(),
2162 }
2163 }
2164 "direct" => {
2165 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2166 SupervisorRouteConsumerWire::Direct { connection_id } => {
2167 Ok(Self::Direct { connection_id })
2168 }
2169 _ => unreachable!(),
2170 }
2171 }
2172 _ => Ok(Self::Unknown { tag, body: value }),
2173 }
2174 }
2175}
2176
2177impl Serialize for StderrCaptureState {
2178 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2179 where
2180 S: Serializer,
2181 {
2182 match self {
2183 Self::Captured => StderrCaptureStateWire::Captured.serialize(serializer),
2184 Self::Incomplete { reason } => StderrCaptureStateWire::Incomplete {
2185 reason: reason.clone(),
2186 }
2187 .serialize(serializer),
2188 Self::NotCaptured { reason } => StderrCaptureStateWire::NotCaptured {
2189 reason: reason.clone(),
2190 }
2191 .serialize(serializer),
2192 Self::Unknown { body, .. } => body.serialize(serializer),
2193 }
2194 }
2195}
2196
2197impl<'de> Deserialize<'de> for StderrCaptureState {
2198 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2199 where
2200 D: serde::Deserializer<'de>,
2201 {
2202 let (tag, value) = read_tagged(deserializer, "state")?;
2203 match tag.as_str() {
2204 "captured" => {
2205 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2206 StderrCaptureStateWire::Captured => Ok(Self::Captured),
2207 _ => unreachable!(),
2208 }
2209 }
2210 "incomplete" => match serde_json::from_value(value.into_value())
2211 .map_err(D::Error::custom)?
2212 {
2213 StderrCaptureStateWire::Incomplete { reason } => Ok(Self::Incomplete { reason }),
2214 _ => unreachable!(),
2215 },
2216 "not_captured" => match serde_json::from_value(value.into_value())
2217 .map_err(D::Error::custom)?
2218 {
2219 StderrCaptureStateWire::NotCaptured { reason } => Ok(Self::NotCaptured { reason }),
2220 _ => unreachable!(),
2221 },
2222 _ => Ok(Self::Unknown { tag, body: value }),
2223 }
2224 }
2225}
2226
2227impl Serialize for StderrTailEntry {
2228 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2229 where
2230 S: Serializer,
2231 {
2232 match self {
2233 Self::Line {
2234 text,
2235 truncated,
2236 at_ms,
2237 } => StderrTailEntryWire::Line {
2238 text: text.clone(),
2239 truncated: *truncated,
2240 at_ms: *at_ms,
2241 }
2242 .serialize(serializer),
2243 Self::ProcessStart => StderrTailEntryWire::ProcessStart.serialize(serializer),
2244 Self::Unknown { body, .. } => body.serialize(serializer),
2245 }
2246 }
2247}
2248
2249impl<'de> Deserialize<'de> for StderrTailEntry {
2250 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2251 where
2252 D: serde::Deserializer<'de>,
2253 {
2254 let (tag, value) = read_tagged(deserializer, "kind")?;
2255 match tag.as_str() {
2256 "line" => match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2257 StderrTailEntryWire::Line {
2258 text,
2259 truncated,
2260 at_ms,
2261 } => Ok(Self::Line {
2262 text,
2263 truncated,
2264 at_ms,
2265 }),
2266 _ => unreachable!(),
2267 },
2268 "process_start" => {
2269 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2270 StderrTailEntryWire::ProcessStart => Ok(Self::ProcessStart),
2271 _ => unreachable!(),
2272 }
2273 }
2274 _ => Ok(Self::Unknown { tag, body: value }),
2275 }
2276 }
2277}
2278
2279fn is_zero_u64(value: &u64) -> bool {
2280 *value == 0
2281}
2282
2283fn default_true() -> bool {
2284 true
2285}
2286
2287#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2289pub struct TerminalHistory {
2290 pub daemon_started_at_ms: u64,
2292 pub entries: Vec<TerminalEntry>,
2293 #[serde(default, skip_serializing_if = "is_zero_u64")]
2296 pub dropped: u64,
2297 #[serde(default, skip_serializing_if = "is_zero_u64")]
2300 pub journal_skipped_lines: u64,
2301 #[serde(default, skip_serializing_if = "is_zero_u64")]
2303 pub journal_read_errors: u64,
2304 #[serde(default, skip_serializing_if = "is_zero_u64")]
2306 pub journal_write_failures: u64,
2307}
2308
2309#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2311pub struct TerminalEntry {
2312 #[serde(default, skip_serializing_if = "Option::is_none")]
2315 pub daemon_incarnation: Option<String>,
2316 #[serde(default, skip_serializing_if = "Option::is_none")]
2317 pub exit_code: Option<i32>,
2318 #[serde(default, skip_serializing_if = "Option::is_none")]
2319 pub exit_signal: Option<i32>,
2320 pub at_ms: u64,
2321 pub disposition: TerminalDisposition,
2322 #[serde(default, skip_serializing_if = "Option::is_none")]
2326 pub exit_kind: Option<TerminalExitKind>,
2327 #[serde(default, skip_serializing_if = "Option::is_none")]
2334 pub disposition_detail: Option<String>,
2335}
2336
2337#[derive(Debug, Clone, PartialEq, Eq)]
2342pub enum TerminalExitKind {
2343 Clean,
2344 Crash,
2345 DeliberateSeverance,
2346 Unknown(String),
2347}
2348
2349impl TerminalExitKind {
2350 fn wire_name(&self) -> &str {
2351 match self {
2352 Self::Clean => "clean",
2353 Self::Crash => "crash",
2354 Self::DeliberateSeverance => "deliberate_severance",
2355 Self::Unknown(value) => value,
2356 }
2357 }
2358}
2359
2360impl Serialize for TerminalExitKind {
2361 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2362 where
2363 S: serde::Serializer,
2364 {
2365 serializer.serialize_str(self.wire_name())
2366 }
2367}
2368
2369impl<'de> Deserialize<'de> for TerminalExitKind {
2370 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2371 where
2372 D: serde::Deserializer<'de>,
2373 {
2374 let value = String::deserialize(deserializer)?;
2375 Ok(match value.as_str() {
2376 "clean" => Self::Clean,
2377 "crash" => Self::Crash,
2378 "deliberate_severance" => Self::DeliberateSeverance,
2379 _ => Self::Unknown(value),
2380 })
2381 }
2382}
2383
2384open_string_enum! {
2385 TerminalDisposition {
2387 Stopped => "stopped",
2388 Disabled => "disabled",
2389 Failed => "failed",
2390 Restarting => "restarting",
2391 DaemonShutdown => "daemon_shutdown",
2396 }
2397}
2398
2399#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2400#[serde(rename_all = "snake_case")]
2401pub enum PollKind {
2402 Status,
2403 Liveness,
2404}
2405
2406#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2418#[non_exhaustive]
2419pub struct CatalogEntry {
2420 pub module_id: String,
2421 #[serde(default, skip_serializing_if = "Option::is_none")]
2423 pub display_name: Option<String>,
2424 #[serde(default = "default_true")]
2435 pub ready: bool,
2436 #[serde(default, skip_serializing_if = "Option::is_none")]
2440 pub not_ready: Option<NotReadyReason>,
2441 #[serde(default, skip_serializing_if = "Option::is_none")]
2462 pub module_version: Option<String>,
2463 #[serde(default, skip_serializing_if = "Option::is_none")]
2466 pub provenance: Option<ManifestProvenance>,
2467 pub roles: Vec<ProviderRole>,
2468 pub control_ops: Vec<String>,
2469 #[serde(default, skip_serializing_if = "Option::is_none")]
2474 pub capabilities: Option<CapabilityDeclarations>,
2475 #[serde(default, skip_serializing_if = "Option::is_none")]
2478 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
2479 #[serde(default, skip_serializing_if = "Option::is_none")]
2483 pub events: Option<Vec<EventDeclaration>>,
2484 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2487 pub operation_delivery: BTreeMap<String, OperationDelivery>,
2488 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2491 pub operation_payload: BTreeMap<String, OperationPayload>,
2492 #[serde(default, skip_serializing_if = "Option::is_none")]
2498 pub flow_operations: Option<Vec<String>>,
2499 #[serde(default, skip_serializing_if = "Option::is_none")]
2501 pub operation_deferral: Option<BTreeMap<String, bool>>,
2502 #[serde(default, skip_serializing_if = "Option::is_none")]
2508 pub confirm_operations: Option<Vec<String>>,
2509 #[serde(default, skip_serializing_if = "Option::is_none")]
2512 pub rich_ui: Option<RichUiDescriptor>,
2513 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2516 pub role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2517 #[serde(default, skip_serializing_if = "is_false")]
2522 pub nonce_verified: bool,
2523 #[serde(default, skip_serializing_if = "Option::is_none")]
2526 pub incarnation: Option<String>,
2527 #[serde(
2528 default,
2529 skip_serializing_if = "Option::is_none",
2530 deserialize_with = "deserialize_optional_attestation_integer"
2531 )]
2532 pub spawn: Option<u64>,
2533 #[serde(default, skip_serializing_if = "Option::is_none")]
2534 pub first_party: Option<bool>,
2535 #[serde(default, skip_serializing_if = "Option::is_none")]
2536 pub origin: Option<CatalogOrigin>,
2537 #[serde(default, skip_serializing_if = "Option::is_none")]
2538 pub requested_declarations_digest: Option<String>,
2539 #[serde(default, skip_serializing_if = "Option::is_none")]
2540 pub approved_declarations_digest: Option<String>,
2541 #[serde(default, skip_serializing_if = "Option::is_none")]
2544 pub approved_declarations: Option<ProviderDeclarations>,
2545 #[serde(default, skip_serializing_if = "Option::is_none")]
2546 pub requested_declarations: Option<ProviderDeclarations>,
2547}
2548
2549impl CatalogEntry {
2550 #[must_use]
2552 pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
2553 self.display_name = display_name;
2554 self
2555 }
2556
2557 #[must_use]
2559 pub fn new(
2560 module_id: impl Into<String>,
2561 roles: Vec<ProviderRole>,
2562 control_ops: Vec<String>,
2563 ) -> Self {
2564 Self {
2565 module_id: module_id.into(),
2566 ready: default_true(),
2567 display_name: None,
2568 not_ready: None,
2569 module_version: None,
2570 provenance: None,
2571 roles,
2572 control_ops,
2573 capabilities: None,
2574 self_signals: None,
2575 events: None,
2576 operation_delivery: BTreeMap::new(),
2577 operation_payload: BTreeMap::new(),
2578 flow_operations: None,
2579 operation_deferral: None,
2580 confirm_operations: None,
2581 rich_ui: None,
2582 role_declarations: BTreeMap::new(),
2583 nonce_verified: false,
2584 incarnation: None,
2585 spawn: None,
2586 first_party: None,
2587 origin: None,
2588 requested_declarations_digest: None,
2589 approved_declarations_digest: None,
2590 approved_declarations: None,
2591 requested_declarations: None,
2592 }
2593 }
2594
2595 #[must_use]
2597 pub fn with_operation_payload(
2598 mut self,
2599 operation_payload: BTreeMap<String, OperationPayload>,
2600 ) -> Self {
2601 self.operation_payload = operation_payload;
2602 self
2603 }
2604
2605 #[must_use]
2608 pub fn with_flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
2609 self.flow_operations = flow_operations;
2610 self
2611 }
2612
2613 #[must_use]
2615 pub fn with_operation_deferral(mut self, operations: Option<BTreeMap<String, bool>>) -> Self {
2616 self.operation_deferral = operations;
2617 self
2618 }
2619
2620 #[must_use]
2623 pub fn with_confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
2624 self.confirm_operations = confirm_operations;
2625 self
2626 }
2627
2628 #[must_use]
2630 pub fn with_ready(mut self, ready: bool) -> Self {
2631 self.ready = ready;
2632 self
2633 }
2634
2635 #[must_use]
2637 pub fn with_not_ready(mut self, not_ready: Option<NotReadyReason>) -> Self {
2638 self.not_ready = not_ready;
2639 self
2640 }
2641
2642 #[must_use]
2644 pub fn with_module_version(mut self, module_version: Option<String>) -> Self {
2645 self.module_version = module_version;
2646 self
2647 }
2648
2649 #[must_use]
2651 pub fn with_provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
2652 self.provenance = provenance;
2653 self
2654 }
2655
2656 #[must_use]
2658 pub fn with_capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
2659 self.capabilities = capabilities;
2660 self
2661 }
2662
2663 #[must_use]
2665 pub fn with_self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
2666 self.self_signals = self_signals;
2667 self
2668 }
2669
2670 #[must_use]
2672 pub fn with_events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
2673 self.events = events;
2674 self
2675 }
2676
2677 #[must_use]
2680 pub fn with_operation_delivery(
2681 mut self,
2682 operation_delivery: BTreeMap<String, OperationDelivery>,
2683 ) -> Self {
2684 self.operation_delivery = operation_delivery;
2685 self
2686 }
2687
2688 #[must_use]
2690 pub fn with_rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
2691 self.rich_ui = rich_ui;
2692 self
2693 }
2694
2695 #[must_use]
2697 pub fn with_role_declarations(
2698 mut self,
2699 role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2700 ) -> Self {
2701 self.role_declarations = role_declarations;
2702 self
2703 }
2704
2705 #[must_use]
2707 pub fn with_nonce_verified(mut self, nonce_verified: bool) -> Self {
2708 self.nonce_verified = nonce_verified;
2709 self
2710 }
2711}
2712
2713fn is_false(value: &bool) -> bool {
2714 !value
2715}
2716
2717#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2719pub struct NotReadyReason {
2720 pub reason: String,
2725 #[serde(default, skip_serializing_if = "Option::is_none")]
2728 pub capability: Option<String>,
2729}
2730
2731impl NotReadyReason {
2732 pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
2733 pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
2734}
2735
2736#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2737pub struct CapabilityRequirementStatus {
2738 pub consumer: String,
2739 pub capability: String,
2740 pub need: String,
2741 pub verdict: String,
2742 pub episode_seq: u64,
2743 pub config_satisfiable: bool,
2744 pub runtime_available: bool,
2745 pub detail: String,
2746}
2747
2748#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2749pub struct SupervisorRescanResult {
2750 pub added: Vec<String>,
2751 pub removed: Vec<String>,
2752 pub changed_pending_reload: Vec<String>,
2753 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2766 pub enabled_changes: Vec<String>,
2767 pub unchanged: u32,
2768 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2776 pub preview: bool,
2777 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2795 pub restart_required: Vec<String>,
2796 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2800 pub capability_warnings: Vec<String>,
2801 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2808 pub module_actions: Vec<RescanModuleAction>,
2809 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2813 pub earlier_pending: Vec<String>,
2814 #[serde(default, skip_serializing_if = "Option::is_none")]
2817 pub expect: Option<RescanExpect>,
2818}
2819
2820#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
2836#[serde(rename_all = "snake_case")]
2837pub enum ModuleProtocol {
2838 #[default]
2842 Subc,
2843 None,
2852}
2853
2854#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2866#[non_exhaustive]
2867pub struct SupervisorEntry {
2868 #[serde(default, skip_serializing_if = "Option::is_none")]
2871 pub waiting_for_previous_pid: Option<u32>,
2872 pub module_id: String,
2873 pub state: String,
2874 #[serde(default, skip_serializing_if = "Option::is_none")]
2878 pub admission_refused: Option<String>,
2879 #[serde(default, skip_serializing_if = "Option::is_none")]
2883 pub next_retry_at_ms: Option<u64>,
2884 pub enabled: bool,
2885 #[serde(default, skip_serializing_if = "Option::is_none")]
2888 pub configured_enabled: Option<bool>,
2889 pub live: bool,
2899 #[serde(default)]
2903 pub protocol: ModuleProtocol,
2904 #[serde(default, skip_serializing_if = "Option::is_none")]
2907 pub launch_nonce_env: Option<bool>,
2908 #[serde(default, skip_serializing_if = "Option::is_none")]
2914 pub launch_nonce_source: Option<String>,
2915 pub health: SupervisorHealthStatus,
2916 #[serde(default, skip_serializing_if = "Option::is_none")]
2919 pub pending_reload: Option<PendingReloadVerdict>,
2920 #[serde(default)]
2926 pub last_probe_ms: Option<u64>,
2927 #[serde(default, skip_serializing_if = "Option::is_none")]
2931 pub last_exit_code: Option<i32>,
2932 #[serde(default, skip_serializing_if = "Option::is_none")]
2936 pub last_exit_signal: Option<i32>,
2937 #[serde(default, skip_serializing_if = "Option::is_none")]
2941 pub last_exit_ms: Option<u64>,
2942 #[serde(default, skip_serializing_if = "Option::is_none")]
2945 pub last_exit_kind: Option<TerminalExitKind>,
2946 #[serde(default, skip_serializing_if = "Option::is_none")]
2963 pub restart_count: Option<u32>,
2964 #[serde(default, skip_serializing_if = "Option::is_none")]
2967 pub max_restarts: Option<u32>,
2968 #[serde(default, skip_serializing_if = "Option::is_none")]
2971 pub lifetime_restarts: Option<u32>,
2972 #[serde(default, skip_serializing_if = "Option::is_none")]
2976 pub spawn_generation: Option<u64>,
2977 #[serde(default, skip_serializing_if = "Option::is_none")]
2987 pub restart_window_secs: Option<u64>,
2988 #[serde(default, skip_serializing_if = "Option::is_none")]
2992 pub drain_timeout_ms: Option<u64>,
2993 #[serde(default, skip_serializing_if = "Option::is_none")]
2996 pub restart_backoff_ms: Option<u64>,
2997 #[serde(default, skip_serializing_if = "Option::is_none")]
3000 pub restart_max_backoff_ms: Option<u64>,
3001 #[serde(default, skip_serializing_if = "Option::is_none")]
3014 pub resources: Option<ChildResourceUsage>,
3015 #[serde(default, skip_serializing_if = "Option::is_none")]
3017 pub tree: Option<TreeReading>,
3018 #[serde(default, skip_serializing_if = "Option::is_none")]
3024 pub tree_unavailable: Option<String>,
3025 #[serde(default, skip_serializing_if = "Option::is_none")]
3027 pub cpu_last_hour: Option<CpuLastHour>,
3028}
3029
3030impl SupervisorEntry {
3031 #[must_use]
3033 pub fn with_next_retry_at_ms(mut self, next_retry_at_ms: Option<u64>) -> Self {
3034 self.next_retry_at_ms = next_retry_at_ms;
3035 self
3036 }
3037
3038 #[must_use]
3040 pub fn new(
3041 module_id: impl Into<String>,
3042 state: impl Into<String>,
3043 enabled: bool,
3044 live: bool,
3045 health: SupervisorHealthStatus,
3046 ) -> Self {
3047 Self {
3048 module_id: module_id.into(),
3049 state: state.into(),
3050 admission_refused: None,
3051 next_retry_at_ms: None,
3052 waiting_for_previous_pid: None,
3053 enabled,
3054 configured_enabled: None,
3055 live,
3056 protocol: ModuleProtocol::default(),
3057 launch_nonce_env: None,
3058 launch_nonce_source: None,
3059 health,
3060 pending_reload: None,
3061 last_probe_ms: None,
3062 last_exit_code: None,
3063 last_exit_signal: None,
3064 last_exit_ms: None,
3065 last_exit_kind: None,
3066 restart_count: None,
3067 max_restarts: None,
3068 lifetime_restarts: None,
3069 spawn_generation: None,
3070 restart_window_secs: None,
3071 drain_timeout_ms: None,
3072 restart_backoff_ms: None,
3073 restart_max_backoff_ms: None,
3074 resources: None,
3075 tree: None,
3076 tree_unavailable: None,
3077 cpu_last_hour: None,
3078 }
3079 }
3080
3081 #[must_use]
3083 pub fn with_admission_refused(mut self, reason: Option<String>) -> Self {
3084 self.admission_refused = reason;
3085 self
3086 }
3087
3088 #[must_use]
3090 pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
3091 self.protocol = protocol;
3092 self
3093 }
3094
3095 #[must_use]
3097 pub fn with_configured_enabled(mut self, configured_enabled: Option<bool>) -> Self {
3098 self.configured_enabled = configured_enabled;
3099 self
3100 }
3101
3102 #[must_use]
3104 pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
3105 self.launch_nonce_env = launch_nonce_env;
3106 self
3107 }
3108
3109 pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
3110 self.launch_nonce_source = source;
3111 self
3112 }
3113
3114 #[must_use]
3115 pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
3116 self.waiting_for_previous_pid = pid;
3117 self
3118 }
3119
3120 #[must_use]
3122 pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
3123 self.pending_reload = pending_reload;
3124 self
3125 }
3126
3127 #[must_use]
3129 pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
3130 self.last_probe_ms = last_probe_ms;
3131 self
3132 }
3133
3134 #[must_use]
3136 pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
3137 self.last_exit_code = last_exit_code;
3138 self
3139 }
3140
3141 #[must_use]
3143 pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
3144 self.last_exit_signal = last_exit_signal;
3145 self
3146 }
3147
3148 #[must_use]
3150 pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
3151 self.last_exit_ms = last_exit_ms;
3152 self
3153 }
3154
3155 #[must_use]
3157 pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
3158 self.last_exit_kind = last_exit_kind;
3159 self
3160 }
3161
3162 #[must_use]
3164 pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
3165 self.restart_count = restart_count;
3166 self
3167 }
3168
3169 #[must_use]
3171 pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
3172 self.max_restarts = max_restarts;
3173 self
3174 }
3175
3176 #[must_use]
3178 pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
3179 self.lifetime_restarts = lifetime_restarts;
3180 self
3181 }
3182
3183 #[must_use]
3185 pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
3186 self.spawn_generation = spawn_generation;
3187 self
3188 }
3189
3190 #[must_use]
3192 pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
3193 self.restart_window_secs = restart_window_secs;
3194 self
3195 }
3196
3197 #[must_use]
3199 pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
3200 self.drain_timeout_ms = drain_timeout_ms;
3201 self
3202 }
3203
3204 #[must_use]
3206 pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
3207 self.restart_backoff_ms = restart_backoff_ms;
3208 self
3209 }
3210
3211 #[must_use]
3213 pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
3214 self.restart_max_backoff_ms = restart_max_backoff_ms;
3215 self
3216 }
3217
3218 #[must_use]
3220 pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
3221 self.resources = resources;
3222 self
3223 }
3224
3225 #[must_use]
3227 pub fn with_tree(mut self, tree: Option<TreeReading>) -> Self {
3228 self.tree = tree;
3229 self
3230 }
3231
3232 #[must_use]
3234 pub fn with_tree_unavailable(mut self, reason: Option<String>) -> Self {
3235 self.tree_unavailable = reason;
3236 self
3237 }
3238}
3239
3240#[derive(Debug, Clone, PartialEq)]
3243pub enum ChildResourceUsage {
3244 Measured(ChildResourceReading),
3245 Unavailable {
3246 reason: ChildResourceUnavailableReason,
3247 },
3248 Unknown {
3251 tag: String,
3252 body: OrderedJsonObject,
3253 },
3254}
3255
3256#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3259#[non_exhaustive]
3260pub struct ChildResourceReading {
3261 pub memory_bytes: u64,
3264 pub memory_kind: ChildMemoryKind,
3265 #[serde(default, skip_serializing_if = "Option::is_none")]
3268 pub swap_bytes: Option<u64>,
3269 pub cpu_user_ms: u64,
3273 pub cpu_system_ms: u64,
3276}
3277
3278impl ChildResourceReading {
3279 #[must_use]
3281 pub fn new(
3282 memory_bytes: u64,
3283 memory_kind: ChildMemoryKind,
3284 cpu_user_ms: u64,
3285 cpu_system_ms: u64,
3286 ) -> Self {
3287 Self {
3288 memory_bytes,
3289 memory_kind,
3290 cpu_user_ms,
3291 cpu_system_ms,
3292 swap_bytes: None,
3293 }
3294 }
3295
3296 #[must_use]
3298 pub fn with_swap_bytes(mut self, swap_bytes: Option<u64>) -> Self {
3299 self.swap_bytes = swap_bytes;
3300 self
3301 }
3302}
3303
3304open_string_enum! {
3305 ChildMemoryKind {
3307 PhysFootprint => "phys_footprint",
3311 ResidentSet => "resident_set",
3314 WindowsWorkingSet => "windows_working_set",
3317 }
3318}
3319
3320open_string_enum! {
3321 ChildResourceUnavailableReason {
3323 NotRunning => "not_running",
3325 UnsupportedPlatform => "unsupported_platform",
3327 Unreadable => "unreadable",
3330 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
3333 }
3334}
3335
3336#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
3337#[serde(rename_all = "snake_case")]
3338pub enum SupervisorHealthStatus {
3339 Ok,
3340 Degraded,
3341 Failing,
3342 Unresponsive,
3343 Unknown,
3344}
3345
3346#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3347pub struct SupervisorHealthEntry {
3348 pub module_id: String,
3349 pub status: SupervisorHealthStatus,
3350 #[serde(default, skip_serializing_if = "Option::is_none")]
3356 pub detail: Option<String>,
3357 #[serde(default, skip_serializing_if = "Option::is_none")]
3362 pub metrics: Option<serde_json::Value>,
3363 pub consecutive_failures: u32,
3364 #[serde(default)]
3367 pub late_answer_count: u64,
3368 #[serde(default, skip_serializing_if = "Option::is_none")]
3370 pub last_late_answer_latency_ms: Option<u64>,
3371 #[serde(default)]
3376 pub last_action: Option<String>,
3377 #[serde(default)]
3380 pub last_action_ms: Option<u64>,
3381 #[serde(default, skip_serializing_if = "Option::is_none")]
3394 pub last_probe_ms: Option<u64>,
3395}
3396
3397#[cfg(test)]
3398mod tests {
3399 #[test]
3400 fn configured_enabled_omission_preserves_exact_old_list_bytes() {
3401 let entry = r#"{"module_id":"provider","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null}"#;
3402 let decoded: SupervisorEntry = serde_json::from_str(entry).unwrap();
3403 assert_eq!(decoded.configured_enabled, None);
3404 assert_eq!(serde_json::to_string(&decoded).unwrap(), entry);
3405 }
3406
3407 #[test]
3408 fn configured_enabled_values_round_trip_in_list() {
3409 for enabled in [false, true] {
3410 let entry = SupervisorEntry::new(
3411 "provider",
3412 "running",
3413 true,
3414 true,
3415 SupervisorHealthStatus::Unknown,
3416 )
3417 .with_configured_enabled(Some(enabled));
3418 let entry_json = serde_json::to_value(&entry).unwrap();
3419 assert_eq!(entry_json["configured_enabled"], enabled);
3420 assert_eq!(
3421 serde_json::from_value::<SupervisorEntry>(entry_json).unwrap(),
3422 entry
3423 );
3424 }
3425 }
3426
3427 #[test]
3428 fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
3429 let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
3430 volume_serial_number: u64::MAX,
3431 file_id: [
3432 0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
3433 ],
3434 };
3435 let agreement = super::RunningImageAgreement::Match { evidence };
3436 let encoded = serde_json::to_string(&agreement).unwrap();
3437 assert!(encoded.contains("windows_spawn_file_id"));
3438 assert_eq!(
3439 serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
3440 agreement
3441 );
3442 }
3443
3444 #[test]
3445 fn unix_running_image_evidence_keeps_original_wire_bytes() {
3446 assert_eq!(
3447 serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
3448 device: 7,
3449 inode: 11
3450 })
3451 .unwrap(),
3452 "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
3453 );
3454 assert_eq!(
3455 serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
3456 digest: "abc".to_owned()
3457 })
3458 .unwrap(),
3459 "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
3460 );
3461 }
3462 use super::*;
3463 use subc_protocol::{BindIdentity, RouteTarget};
3464
3465 #[test]
3466 fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
3467 let entry = TerminalEntry {
3468 daemon_incarnation: Some("daemon-before-restart".into()),
3469 exit_code: Some(1),
3470 exit_signal: None,
3471 at_ms: 1_700_000_000_123,
3472 disposition: TerminalDisposition::Restarting,
3473 exit_kind: Some(TerminalExitKind::DeliberateSeverance),
3474 disposition_detail: None,
3475 };
3476 let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
3477 assert_eq!(
3478 serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
3479 ["exit_kind"],
3480 "deliberate_severance"
3481 );
3482
3483 #[derive(serde::Deserialize)]
3484 struct LegacyTerminalEntry {
3485 exit_code: Option<i32>,
3486 exit_signal: Option<i32>,
3487 at_ms: u64,
3488 disposition: TerminalDisposition,
3489 }
3490
3491 let decoded: LegacyTerminalEntry =
3492 serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
3493 assert_eq!(decoded.exit_code, Some(1));
3494 assert_eq!(decoded.exit_signal, None);
3495 assert_eq!(decoded.at_ms, 1_700_000_000_123);
3496 assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
3497
3498 let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
3499 let future: TerminalEntry =
3500 serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
3501 assert_eq!(
3502 future.exit_kind,
3503 Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
3504 );
3505 }
3506
3507 #[test]
3508 fn terminal_incarnation_is_optional_for_older_daemons() {
3509 let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
3510 "at_ms": 123,
3511 "disposition": "stopped"
3512 }))
3513 .unwrap();
3514 let encoded = serde_json::to_value(&entry).unwrap();
3515 assert_eq!(
3516 (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
3517 (None, None)
3518 );
3519 }
3520
3521 #[test]
3522 fn route_poll_uses_kind_field() {
3523 let body = serde_json::to_value(ClientControlRequest::RoutePoll {
3524 route_channel: 7,
3525 route_epoch: 11,
3526 kind: PollKind::Status,
3527 })
3528 .unwrap();
3529
3530 assert_eq!(body["op"], "route.poll");
3531 assert_eq!(body["route_epoch"], 11);
3532 assert_eq!(body["kind"], "status");
3533 assert!(body.get("op").is_some());
3534 }
3535
3536 #[test]
3537 fn route_open_is_internally_tagged() {
3538 let request = ClientControlRequest::RouteOpen {
3539 busy_refusals: None,
3540 target: RouteTarget::ToolProvider {
3541 module_id: "aft".to_string(),
3542 },
3543 identity: BindIdentity::new("opencode", "session-1"),
3544 consumer_identity: None,
3545 consumer_capabilities: None,
3546 role_versions: None,
3547 admission_facts: None,
3548 scope: None,
3549 };
3550
3551 let body = serde_json::to_value(request).unwrap();
3552 assert_eq!(body["op"], "route.open");
3553 assert_eq!(body["target"]["kind"], "tool_provider");
3554 assert!(body.get("consumer_identity").is_none());
3555 assert!(body.get("consumer_capabilities").is_none());
3556 assert!(body.get("role_versions").is_none());
3557 }
3558
3559 #[test]
3560 fn route_open_without_optional_fields_still_decodes() {
3561 let body = serde_json::json!({
3562 "op": "route.open",
3563 "target": { "kind": "tool_provider", "module_id": "aft" },
3564 "identity": {
3565 "project_root": "/tmp/project",
3566 "harness": "opencode",
3567 "session": "session-1"
3568 }
3569 });
3570
3571 let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
3572 let ClientControlRequest::RouteOpen {
3573 consumer_identity,
3574 consumer_capabilities,
3575 role_versions,
3576 admission_facts,
3577 ..
3578 } = decoded
3579 else {
3580 panic!("decoded wrong request variant");
3581 };
3582 assert_eq!(consumer_identity, None);
3583 assert_eq!(consumer_capabilities, None);
3584 assert_eq!(role_versions, None);
3585 assert_eq!(admission_facts, None);
3586 }
3587
3588 #[test]
3589 fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
3590 let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
3591 let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
3592 match decoded {
3593 ClientControlPush::RouteClosed {
3594 excluded_subscriptions,
3595 terminal,
3596 ..
3597 } => {
3598 assert_eq!(excluded_subscriptions, 0);
3599 assert_eq!(terminal, None);
3600 }
3601 other => panic!("unexpected push: {other:?}"),
3602 }
3603 assert!(!serde_json::to_string(&decoded)
3604 .unwrap()
3605 .contains("terminal"));
3606 }
3607
3608 #[test]
3609 fn old_route_closed_decoder_ignores_new_terminal_field() {
3610 #[derive(serde::Deserialize)]
3611 #[serde(tag = "op")]
3612 enum LegacyClientControlPush {
3613 #[serde(rename = "route.closed")]
3614 RouteClosed {
3615 module_id: String,
3616 reason: RouteCloseReason,
3617 drained: bool,
3618 abandoned: u32,
3619 },
3620 }
3621
3622 let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
3623 let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
3624 match decoded {
3625 LegacyClientControlPush::RouteClosed {
3626 module_id,
3627 reason,
3628 drained,
3629 abandoned,
3630 } => {
3631 assert_eq!(module_id, "aft-tools");
3632 assert_eq!(reason, RouteCloseReason::Crash);
3633 assert!(!drained);
3634 assert_eq!(abandoned, 0);
3635 }
3636 }
3637 }
3638
3639 #[test]
3640 fn supervisor_routes_is_a_control_plane_request() {
3641 let body = serde_json::json!({
3642 "op": "supervisor.routes",
3643 "module_id": "aft"
3644 });
3645
3646 let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
3647 assert_eq!(serde_json::to_value(request).unwrap(), body);
3648 }
3649
3650 #[test]
3651 fn diagnostic_string_enums_retain_unknown_wire_values() {
3652 let reason: RunningImageUnavailableReason =
3653 serde_json::from_str("\"future_reason\"").unwrap();
3654 let disposition: TerminalDisposition =
3655 serde_json::from_str("\"future_disposition\"").unwrap();
3656
3657 assert_eq!(
3658 reason,
3659 RunningImageUnavailableReason::Unknown("future_reason".to_string())
3660 );
3661 assert_eq!(
3662 disposition,
3663 TerminalDisposition::Unknown("future_disposition".to_string())
3664 );
3665 }
3666
3667 #[test]
3668 fn diagnostic_string_enums_preserve_existing_wire_names() {
3669 let names = [
3670 (RunningImageUnavailableReason::NotRunning, "not_running"),
3671 (
3672 RunningImageUnavailableReason::UnsupportedPlatform,
3673 "unsupported_platform",
3674 ),
3675 (
3676 RunningImageUnavailableReason::RunningExecutableUnreadable,
3677 "running_executable_unreadable",
3678 ),
3679 (
3680 RunningImageUnavailableReason::RunningExecutablePermissionDenied,
3681 "running_executable_permission_denied",
3682 ),
3683 (
3684 RunningImageUnavailableReason::ProcessHidden,
3685 "process_hidden",
3686 ),
3687 (
3688 RunningImageUnavailableReason::SpawnedPathUnreadable,
3689 "spawned_path_unreadable",
3690 ),
3691 (RunningImageUnavailableReason::HashFailed, "hash_failed"),
3692 (
3693 RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
3694 "process_identity_unconfirmed",
3695 ),
3696 ];
3697 for (value, expected) in names {
3698 let wire = serde_json::to_string(&value).unwrap();
3699 assert_eq!(wire, format!("\"{expected}\""));
3700 let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
3701 assert_eq!(decoded, value);
3702 }
3703
3704 for (value, expected) in [
3705 (TerminalDisposition::Stopped, "stopped"),
3706 (TerminalDisposition::Disabled, "disabled"),
3707 (TerminalDisposition::Failed, "failed"),
3708 (TerminalDisposition::Restarting, "restarting"),
3709 (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
3710 ] {
3711 let wire = serde_json::to_string(&value).unwrap();
3712 assert_eq!(wire, format!("\"{expected}\""));
3713 let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
3714 assert_eq!(decoded, value);
3715 }
3716 }
3717
3718 #[test]
3719 fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
3720 let entry = SupervisorEntry::new(
3721 "waiting-module",
3722 "starting",
3723 true,
3724 false,
3725 SupervisorHealthStatus::Unknown,
3726 );
3727 let old_wire = serde_json::to_value(&entry).unwrap();
3728 assert!(old_wire.get("waiting_for_previous_pid").is_none());
3729 let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3730 assert_eq!(decoded.waiting_for_previous_pid, None);
3731 let entry = entry.with_waiting_for_previous_pid(Some(42));
3732 let wire = serde_json::to_value(&entry).unwrap();
3733 assert_eq!(wire["waiting_for_previous_pid"], 42);
3734 let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3735 assert_eq!(decoded.waiting_for_previous_pid, Some(42));
3736 }
3737
3738 #[test]
3739 fn diagnostic_string_enums_reject_non_string_bodies() {
3740 assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
3741 assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
3742 }
3743
3744 #[test]
3745 fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
3746 let body = serde_json::json!({
3747 "op": "supervisor.provenance",
3748 "daemon": {
3749 "daemon_build": {},
3750 "daemon_observed": {
3751 "running_image": {
3752 "status": "unavailable",
3753 "reason": "not_running"
3754 }
3755 }
3756 },
3757 "modules": [
3758 {
3759 "module_id": "future",
3760 "module_declared": { "status": "unverifiable" },
3761 "daemon_observed": {
3762 "running_image": {
3763 "status": "unavailable",
3764 "reason": "future_reason"
3765 }
3766 }
3767 },
3768 {
3769 "module_id": "healthy-a",
3770 "module_declared": { "status": "unverifiable" },
3771 "daemon_observed": {
3772 "running_image": {
3773 "status": "match",
3774 "evidence": {
3775 "method": "linux_proc_sha256",
3776 "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3777 }
3778 }
3779 }
3780 },
3781 {
3782 "module_id": "healthy-b",
3783 "module_declared": { "status": "unverifiable" },
3784 "daemon_observed": {
3785 "running_image": {
3786 "status": "unavailable",
3787 "reason": "unsupported_platform"
3788 }
3789 }
3790 }
3791 ]
3792 });
3793
3794 let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
3795 let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
3796 panic!("decoded wrong response variant");
3797 };
3798 assert_eq!(modules.len(), 3);
3799 assert_eq!(modules[0].module_id, "future");
3800 assert_eq!(
3801 modules[0].daemon_observed.running_image,
3802 RunningImageAgreement::Unavailable {
3803 reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
3804 }
3805 );
3806 assert_eq!(modules[1].module_id, "healthy-a");
3807 assert_eq!(modules[2].module_id, "healthy-b");
3808 }
3809
3810 #[test]
3811 fn tagged_unknown_values_retain_tag_and_body() {
3812 macro_rules! assert_unknown_round_trip {
3813 ($ty:ident, $field:literal, $value:expr) => {
3814 let value = $value;
3815 let wire = serde_json::to_string(&value).unwrap();
3816 let decoded: $ty = serde_json::from_str(&wire).unwrap();
3817 match decoded {
3818 $ty::Unknown { tag, body } => {
3819 assert_eq!(tag, value[$field].as_str().unwrap());
3820 assert_eq!(serde_json::to_value(&body).unwrap(), value);
3821 }
3822 _ => panic!("decoded known variant"),
3823 }
3824 };
3825 }
3826
3827 assert_unknown_round_trip!(
3828 ModuleDeclaredProvenance,
3829 "status",
3830 serde_json::json!({"status": "future", "build": {"version": 7}})
3831 );
3832 assert_unknown_round_trip!(
3833 RunningImageAgreement,
3834 "status",
3835 serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
3836 );
3837 assert_unknown_round_trip!(
3838 RunningImageEvidence,
3839 "method",
3840 serde_json::json!({"method": "future", "digest": "abc"})
3841 );
3842 assert_unknown_round_trip!(
3843 SupervisorRouteConsumer,
3844 "kind",
3845 serde_json::json!({"kind": "future", "module_id": "m"})
3846 );
3847 assert_unknown_round_trip!(
3848 StderrCaptureState,
3849 "state",
3850 serde_json::json!({"state": "future", "reason": "because"})
3851 );
3852 assert_unknown_round_trip!(
3853 StderrTailEntry,
3854 "kind",
3855 serde_json::json!({"kind": "future", "text": "line"})
3856 );
3857 assert_unknown_round_trip!(
3858 ChildResourceUsage,
3859 "status",
3860 serde_json::json!({"status": "future", "memory_bytes": 1})
3861 );
3862 }
3863
3864 #[test]
3865 fn child_resource_usage_round_trips_both_known_states() {
3866 let measured = ChildResourceUsage::Measured(ChildResourceReading {
3867 memory_bytes: 0,
3868 memory_kind: ChildMemoryKind::ResidentSet,
3869 swap_bytes: Some(0),
3870 cpu_user_ms: 0,
3871 cpu_system_ms: 0,
3872 });
3873 let wire = serde_json::to_value(&measured).unwrap();
3874 assert_eq!(
3875 wire,
3876 serde_json::json!({
3877 "status": "measured",
3878 "memory_bytes": 0,
3879 "memory_kind": "resident_set",
3880 "swap_bytes": 0,
3881 "cpu_user_ms": 0,
3882 "cpu_system_ms": 0
3883 })
3884 );
3885 assert_eq!(
3886 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3887 measured
3888 );
3889
3890 let unavailable = ChildResourceUsage::Unavailable {
3891 reason: ChildResourceUnavailableReason::NotRunning,
3892 };
3893 let wire = serde_json::to_value(&unavailable).unwrap();
3894 assert_eq!(
3895 wire,
3896 serde_json::json!({"status": "unavailable", "reason": "not_running"})
3897 );
3898 assert_eq!(
3899 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3900 unavailable
3901 );
3902 }
3903
3904 #[test]
3905 fn a_stderr_line_decodes_with_and_without_its_capture_time() {
3906 let stamped: StderrTailEntry = serde_json::from_str(
3910 r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
3911 )
3912 .unwrap();
3913 assert_eq!(
3914 stamped,
3915 StderrTailEntry::Line {
3916 text: "boom".to_string(),
3917 truncated: true,
3918 at_ms: Some(1_789_801_440_685),
3919 }
3920 );
3921 let unstamped: StderrTailEntry =
3922 serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
3923 assert_eq!(
3924 unstamped,
3925 StderrTailEntry::Line {
3926 text: "boom".to_string(),
3927 truncated: false,
3928 at_ms: None,
3929 }
3930 );
3931 assert_eq!(
3934 serde_json::to_string(&unstamped).unwrap(),
3935 r#"{"kind":"line","text":"boom"}"#
3936 );
3937 assert_eq!(
3938 serde_json::to_value(&stamped).unwrap()["at_ms"],
3939 serde_json::json!(1_789_801_440_685u64)
3940 );
3941 }
3942
3943 #[test]
3944 fn tagged_unknown_values_round_trip_the_original_json() {
3945 let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
3946 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3947 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3948 }
3949
3950 #[test]
3951 fn tagged_unknown_values_round_trip_trailing_tag() {
3952 let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
3953 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3954 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3955
3956 let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
3957 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3958 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3959 }
3960
3961 #[test]
3962 fn tagged_unknown_values_round_trip_middle_tag() {
3963 let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
3964 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3965 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3966
3967 let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
3968 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3969 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3970 }
3971
3972 #[test]
3973 fn tagged_unknown_values_round_trip_deep_payload() {
3974 let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
3975 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3976 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3977
3978 let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
3979 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3980 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3981 }
3982
3983 #[test]
3984 fn tagged_unknown_values_reject_non_object_bodies() {
3985 for wire in ["42", r#""future""#, "[]"] {
3986 assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
3987 assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
3988 }
3989 }
3990
3991 #[test]
3992 fn duplicate_discriminators_reject_without_panicking() {
3993 assert_eq!(
3994 serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
3995 .unwrap(),
3996 ModuleDeclaredProvenance::Unverifiable
3997 );
3998 match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
3999 .unwrap()
4000 {
4001 ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
4002 _ => panic!("future discriminator decoded as a known variant"),
4003 }
4004
4005 let wires = [
4006 r#"{"status":"reported","status":"unverifiable"}"#,
4007 r#"{"status":"unverifiable","status":"reported"}"#,
4008 r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
4009 r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
4010 ];
4011
4012 for wire in wires {
4013 let result =
4014 std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
4015 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
4016 assert!(
4017 result.unwrap().is_err(),
4018 "duplicate discriminator decoded: {wire}"
4019 );
4020 }
4021
4022 let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
4023 let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
4024 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
4025 assert!(
4026 result.unwrap().is_err(),
4027 "duplicate discriminator decoded: {wire}"
4028 );
4029 }
4030
4031 #[test]
4032 fn nested_unknown_values_round_trip_without_normalizing_member_order() {
4033 let known_wire =
4034 r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
4035 let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
4036 assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
4037
4038 for wire in [
4039 r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
4040 r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
4041 ] {
4042 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
4043 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4044 }
4045
4046 for wire in [
4047 r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
4048 r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
4049 ] {
4050 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
4051 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4052 }
4053
4054 let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
4055 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
4056 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4057
4058 let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
4059 let decoded: StderrTail = serde_json::from_str(wire).unwrap();
4060 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4061 }
4062
4063 #[test]
4064 fn tagged_unknown_member_does_not_discard_known_siblings() {
4065 let body = serde_json::json!({
4066 "modules": [{
4067 "module_id": "target",
4068 "routes": [
4069 {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
4070 {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
4071 ]
4072 }]
4073 });
4074 let decoded: ClientControlResponse = serde_json::from_value(
4075 serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
4076 )
4077 .unwrap();
4078 let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
4079 panic!("decoded wrong response variant");
4080 };
4081 assert_eq!(modules[0].routes.len(), 2);
4082 assert_eq!(
4083 modules[0].routes[1].consumer,
4084 SupervisorRouteConsumer::Direct { connection_id: 7 }
4085 );
4086 }
4087}
4088
4089#[cfg(test)]
4090mod launch_nonce_redaction_tests {
4091 use super::*;
4092
4093 const NONCE: &str = "nonce-f00dfeed1234abcd";
4094
4095 fn identity() -> ConsumerIdentity {
4096 ConsumerIdentity {
4097 module_id: "wernicke".to_string(),
4098 launch_nonce: NONCE.to_string(),
4099 }
4100 }
4101
4102 #[test]
4103 fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
4104 let printed = format!("{:?}", identity());
4105 assert!(printed.contains("wernicke"), "{printed}");
4106 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
4107 }
4108
4109 #[test]
4110 fn route_open_request_debug_never_prints_the_nonce() {
4111 let request = ClientControlRequest::RouteOpen {
4112 busy_refusals: None,
4113 target: subc_protocol::RouteTarget::ToolProvider {
4114 module_id: "broca".to_string(),
4115 },
4116 identity: subc_protocol::BindIdentity::new("test".to_string(), "session".to_string()),
4117 consumer_identity: Some(identity()),
4118 consumer_capabilities: None,
4119 role_versions: None,
4120 admission_facts: None,
4121 scope: None,
4122 };
4123 let printed = format!("{request:?}");
4124 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
4125 }
4126}
4127
4128#[cfg(test)]
4129mod reader_skew_tests {
4130 use super::*;
4131 use serde_json::{json, Value};
4132
4133 fn catalog() -> Value {
4134 json!({"module_id": "provider", "roles": [], "control_ops": []})
4135 }
4136
4137 fn reply() -> Value {
4138 json!({"op": "route.open", "route_channel": 7, "route_epoch": 11})
4139 }
4140
4141 fn target() -> Value {
4142 json!({
4143 "incarnation": "daemon", "kind": "spawn", "spawn": 17,
4144 "authority_epoch": 23, "first_party": true,
4145 "approved_declarations_digest": "approved"
4146 })
4147 }
4148
4149 fn request() -> Value {
4150 json!({
4151 "op": "route.open",
4152 "target": {"kind": "tool_provider", "module_id": "provider"},
4153 "identity": {"harness": "test", "session": "session-1"}
4154 })
4155 }
4156
4157 #[test]
4158 fn reader_skew_catalog_optional_spawn_fields_and_legacy_omission() {
4159 let old: CatalogEntry = serde_json::from_value(catalog()).unwrap();
4160 let built = CatalogEntry::new("provider", vec![], vec![]);
4161 assert_eq!(old, built);
4162 assert_eq!(old.first_party, None);
4163 let old_bytes = serde_json::to_value(&old).unwrap();
4164 let additions = json!({
4165 "incarnation": "daemon", "spawn": 17, "first_party": false,
4166 "origin": "development", "requested_declarations_digest": "requested",
4167 "approved_declarations_digest": "approved"
4168 });
4169 let mut body = catalog();
4170 for (key, value) in additions.as_object().unwrap() {
4171 assert!(old_bytes.get(key).is_none(), "{key}");
4172 body[key] = value.clone();
4173 }
4174 let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
4175 let encoded = serde_json::to_value(&decoded).unwrap();
4176 for (key, value) in additions.as_object().unwrap() {
4177 assert_eq!(&encoded[key], value, "{key}");
4178 }
4179 assert_eq!(decoded.first_party, Some(false));
4180 assert_eq!(decoded.origin, Some(CatalogOrigin::Development));
4181 }
4182
4183 #[test]
4184 fn reader_skew_catalog_filtered_declarations_keep_provider_owned_keys() {
4185 let mut body = catalog();
4186 body["requested_declarations"] = json!({"provider": {"future": {"scope": ["write"]}}});
4187 body["approved_declarations"] = json!({"provider": {"future": {"scope": ["read"]}}});
4188 let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
4189 let encoded = serde_json::to_value(decoded).unwrap();
4190 for key in ["requested_declarations", "approved_declarations"] {
4191 assert_eq!(encoded[key], body[key]);
4192 }
4193 let unfiltered: CatalogEntry = serde_json::from_value(catalog()).unwrap();
4194 assert_eq!(unfiltered.approved_declarations, None);
4195 assert_eq!(unfiltered.requested_declarations, None);
4196 }
4197
4198 #[test]
4199 fn reader_skew_catalog_unknown_origin_is_other() {
4200 let mut body = catalog();
4201 body["origin"] = json!("future-origin");
4202 let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
4203 assert_eq!(decoded.origin, Some(CatalogOrigin::Other));
4204 }
4205
4206 #[test]
4207 fn reader_skew_catalog_spawn_refuses_unsafe_integers() {
4208 let mut body = catalog();
4209 body["spawn"] = json!(9_007_199_254_740_991_u64);
4210 let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
4211 assert_eq!(decoded.spawn, Some(9_007_199_254_740_991));
4212 for invalid in [
4213 json!(9_007_199_254_740_992_u64),
4214 json!(-1),
4215 json!(1.5),
4216 json!("17"),
4217 ] {
4218 body["spawn"] = invalid;
4219 assert!(serde_json::from_value::<CatalogEntry>(body.clone()).is_err());
4220 }
4221 }
4222
4223 #[test]
4224 fn reader_skew_catalog_watch_request_uses_subscription_op() {
4225 let body = json!({"op": "catalog.watch"});
4226 let request: CatalogWatchRequest = serde_json::from_value(body.clone()).unwrap();
4227 assert_eq!(request, CatalogWatchRequest::new());
4228 assert_eq!(serde_json::to_value(request).unwrap(), body);
4229 assert_eq!(CatalogWatchRequest::OP, "catalog.watch");
4230 for invalid in [json!({}), json!({"op": "activity.subscribe"})] {
4231 assert!(serde_json::from_value::<CatalogWatchRequest>(invalid).is_err());
4232 }
4233 }
4234
4235 #[test]
4236 fn reader_skew_catalog_watch_push_carries_generation_without_ack() {
4237 for generation in [0, 19, 42] {
4238 let body = json!({"op": "catalog.watch", "generation": generation});
4239 let push: CatalogWatchResponse = serde_json::from_value(body.clone()).unwrap();
4240 assert_eq!(push, CatalogWatchResponse::new(generation));
4241 assert_eq!(serde_json::to_value(push).unwrap(), body);
4242 }
4243 assert_eq!(CatalogWatchResponse::OP, "catalog.watch");
4244 for invalid in [
4245 json!({"op": "catalog.watch"}),
4246 json!({"op": "activity.subscribe", "generation": 1}),
4247 ] {
4248 assert!(serde_json::from_value::<CatalogWatchResponse>(invalid).is_err());
4249 }
4250 }
4251
4252 #[test]
4253 fn reader_skew_route_open_reply_helpers_preserve_existing_decoder() {
4254 let mut body = reply();
4255 let legacy: ClientControlResponse = serde_json::from_value(body.clone()).unwrap();
4256 let empty = RouteOpenReplyExt::read_from(&body).unwrap();
4257 assert_eq!(empty, RouteOpenReplyExt::new());
4258 empty.write_to(&mut body).unwrap();
4259 assert_eq!(body, reply());
4260 body["target"] = target();
4261 let decoded = RouteOpenReplyExt::read_from(&body).unwrap();
4262 assert_eq!(
4263 decoded.target.as_ref().unwrap().kind,
4264 RouteOpenTargetKind::Spawn
4265 );
4266 let mut encoded = reply();
4267 RouteOpenReplyExt::new()
4268 .with_target(decoded.target)
4269 .write_to(&mut encoded)
4270 .unwrap();
4271 assert_eq!(encoded, body);
4272 assert_eq!(
4273 serde_json::from_value::<ClientControlResponse>(encoded.clone()).unwrap(),
4274 legacy
4275 );
4276 RouteOpenReplyExt::new().write_to(&mut encoded).unwrap();
4277 assert_eq!(encoded, reply());
4278 }
4279
4280 #[test]
4281 fn reader_skew_route_open_incomplete_target_is_unmarked() {
4282 let mut body = reply();
4283 body["target"] = target();
4284 assert!(RouteOpenReplyExt::read_from(&body)
4285 .unwrap()
4286 .target
4287 .is_some());
4288 for key in [
4289 "incarnation",
4290 "kind",
4291 "spawn",
4292 "authority_epoch",
4293 "first_party",
4294 "approved_declarations_digest",
4295 ] {
4296 let mut incomplete = body.clone();
4297 incomplete["target"].as_object_mut().unwrap().remove(key);
4298 assert_eq!(
4299 RouteOpenReplyExt::read_from(&incomplete).unwrap().target,
4300 None,
4301 "{key}"
4302 );
4303 }
4304 body["target"] = Value::Null;
4305 assert_eq!(RouteOpenReplyExt::read_from(&body).unwrap().target, None);
4306 }
4307
4308 #[test]
4309 fn reader_skew_route_open_non_spawn_kinds_ignore_spawn_authority() {
4310 for (kind, expected) in [
4311 ("prefix", RouteOpenTargetKind::Prefix),
4312 ("unsupervised", RouteOpenTargetKind::Unsupervised),
4313 ] {
4314 let mut body = reply();
4315 body["target"] = target();
4316 body["target"]["kind"] = json!(kind);
4317 body["target"]["spawn"] = json!("not-a-spawn");
4319 body["target"]["authority_epoch"] = json!(9_007_199_254_740_992_u64);
4320 body["target"]["approved_declarations_digest"] = json!(["not-a-digest"]);
4321 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4322 let target = ext.target.as_ref().unwrap();
4323 assert_eq!(target.kind, expected);
4324 assert_eq!(target.spawn, None);
4325 assert_eq!(target.authority_epoch, None);
4326 assert_eq!(target.approved_declarations_digest, None);
4327 assert!(!target.first_party);
4328 let mut encoded = reply();
4329 ext.write_to(&mut encoded).unwrap();
4330 for key in ["spawn", "authority_epoch", "approved_declarations_digest"] {
4331 assert!(encoded["target"].get(key).is_none());
4332 }
4333 }
4334 }
4335
4336 #[test]
4337 fn reader_skew_route_open_unknown_kind_is_not_spawn() {
4338 let mut body = reply();
4339 body["target"] = target();
4340 body["target"]["kind"] = json!("future-kind");
4341 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4342 let target = ext.target.unwrap();
4343 assert_eq!(target.kind, RouteOpenTargetKind::Unknown);
4344 assert_eq!(target.spawn, None);
4345 assert_eq!(target.authority_epoch, None);
4346 assert_eq!(target.approved_declarations_digest, None);
4347 assert!(!target.first_party);
4348 }
4349
4350 #[test]
4351 fn reader_skew_route_open_spawn_and_epoch_refuse_unsafe_integers() {
4352 for field in ["spawn", "authority_epoch"] {
4353 let mut body = reply();
4354 body["target"] = target();
4355 body["target"][field] = json!(9_007_199_254_740_991_u64);
4356 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4357 assert_eq!(
4358 serde_json::to_value(ext).unwrap()["target"][field],
4359 9_007_199_254_740_991_u64
4360 );
4361 for invalid in [
4362 json!(9_007_199_254_740_992_u64),
4363 json!(-1),
4364 json!(1.5),
4365 json!("17"),
4366 ] {
4367 body["target"][field] = invalid;
4368 assert!(RouteOpenReplyExt::read_from(&body).is_err(), "{field}");
4369 let mut incomplete = body.clone();
4370 incomplete["target"]
4371 .as_object_mut()
4372 .unwrap()
4373 .remove("incarnation");
4374 assert!(
4375 RouteOpenReplyExt::read_from(&incomplete).is_err(),
4376 "{field}"
4377 );
4378 }
4379 }
4380 }
4381
4382 #[test]
4383 fn reader_skew_route_open_request_helpers_preserve_existing_decoder() {
4384 let mut body = request();
4385 let legacy: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
4386 assert_eq!(
4387 RouteOpenRequestExt::read_from(&body).unwrap(),
4388 RouteOpenRequestExt::new()
4389 );
4390 RouteOpenRequestExt::new().write_to(&mut body).unwrap();
4391 assert_eq!(body, request());
4392 body["accepts_close_reasons"] = json!(["authority_changed", "future-reason"]);
4393 let decoded = RouteOpenRequestExt::read_from(&body).unwrap();
4394 assert_eq!(
4395 decoded.accepts_close_reasons,
4396 Some(vec!["authority_changed".into(), "future-reason".into()])
4397 );
4398 let mut encoded = request();
4399 RouteOpenRequestExt::new()
4400 .with_accepts_close_reasons(decoded.accepts_close_reasons)
4401 .write_to(&mut encoded)
4402 .unwrap();
4403 assert_eq!(encoded, body);
4404 assert_eq!(
4405 serde_json::from_value::<ClientControlRequest>(encoded.clone()).unwrap(),
4406 legacy
4407 );
4408 RouteOpenRequestExt::new().write_to(&mut encoded).unwrap();
4409 assert_eq!(encoded, request());
4410 assert_eq!(ROUTE_CLOSE_REASONS_CAPABILITY, "route-close-reasons/v1");
4411 }
4412
4413 #[test]
4414 fn reader_skew_route_open_helpers_refuse_other_bodies() {
4415 for mut body in [json!({}), json!([]), json!({"op": "catalog.list"})] {
4416 assert!(RouteOpenRequestExt::read_from(&body).is_err());
4417 assert!(RouteOpenReplyExt::read_from(&body).is_err());
4418 assert!(RouteOpenRequestExt::new().write_to(&mut body).is_err());
4419 assert!(RouteOpenReplyExt::new().write_to(&mut body).is_err());
4420 }
4421 }
4422
4423 #[test]
4424 fn reader_skew_route_open_target_constructor_validates_like_reader() {
4425 let spawn = RouteOpenTarget::new(
4426 "daemon",
4427 RouteOpenTargetKind::Spawn,
4428 Some(17),
4429 Some(23),
4430 true,
4431 Some("approved".into()),
4432 )
4433 .unwrap();
4434 assert_eq!(serde_json::to_value(spawn).unwrap(), target());
4435 for (spawn, epoch) in [(9_007_199_254_740_992, 23), (17, 9_007_199_254_740_992)] {
4436 assert!(RouteOpenTarget::new(
4437 "daemon",
4438 RouteOpenTargetKind::Spawn,
4439 Some(spawn),
4440 Some(epoch),
4441 true,
4442 Some("approved".into())
4443 )
4444 .is_err());
4445 }
4446 }
4447}
4448
4449#[cfg(test)]
4450mod claim_wire_tests {
4451 use super::*;
4452 use serde_json::{json, Value};
4453
4454 fn legacy_provenance() -> SupervisorModuleProvenance {
4455 SupervisorModuleProvenance {
4456 module_id: "worker".into(),
4457 module_declared: ModuleDeclaredProvenance::Unverifiable,
4458 daemon_observed: SupervisorObservedProcess {
4459 launch_nonce_source: None,
4460 pid: None,
4461 spawned_at_ms: None,
4462 spawned_from: None,
4463 running_image: RunningImageAgreement::Unavailable {
4464 reason: RunningImageUnavailableReason::NotRunning,
4465 },
4466 },
4467 }
4468 }
4469
4470 #[test]
4471 fn provenance_registration_companion_round_trip_preserves_legacy_entry() {
4472 let legacy = legacy_provenance();
4473 let original = serde_json::to_value(&legacy).unwrap();
4474 let absent = SupervisorModuleProvenanceExt::read_from(&original).unwrap();
4475 assert_eq!(absent.registration, None);
4476 let mut wire = original.clone();
4477 absent.write_to(&mut wire).unwrap();
4478 assert_eq!(wire, original);
4479 for (method, spelling) in [
4480 (RegistrationMethod::Channel, "channel"),
4481 (RegistrationMethod::Nonce, "nonce"),
4482 ] {
4483 let ext = SupervisorModuleProvenanceExt::new().with_registration(Some(method.clone()));
4484 ext.write_to(&mut wire).unwrap();
4485 assert_eq!(wire["registration"], spelling);
4486 assert_eq!(
4487 SupervisorModuleProvenanceExt::read_from(&wire).unwrap(),
4488 ext
4489 );
4490 let old_reader: SupervisorModuleProvenance =
4491 serde_json::from_value(wire.clone()).unwrap();
4492 assert_eq!(old_reader, legacy);
4493 assert_eq!(serde_json::to_value(old_reader).unwrap(), original);
4494 }
4495 absent.write_to(&mut wire).unwrap();
4496 assert_eq!(wire, original);
4497 for mut invalid in [Value::Null, json!([]), json!("entry")] {
4498 assert!(SupervisorModuleProvenanceExt::read_from(&invalid).is_err());
4499 assert!(absent.write_to(&mut invalid).is_err());
4500 }
4501 }
4502
4503 #[test]
4504 fn provenance_unknown_registration_is_not_channel_or_nonce() {
4505 let mut wire = serde_json::to_value(legacy_provenance()).unwrap();
4506 wire["registration"] = json!("future_method");
4507 let ext = SupervisorModuleProvenanceExt::read_from(&wire).unwrap();
4508 assert_eq!(ext.registration, Some(RegistrationMethod::Unknown));
4509 assert_ne!(ext.registration, Some(RegistrationMethod::Channel));
4510 assert_ne!(ext.registration, Some(RegistrationMethod::Nonce));
4511 wire["registration"] = json!(false);
4512 assert!(SupervisorModuleProvenanceExt::read_from(&wire).is_err());
4513 }
4514
4515 #[test]
4516 fn registration_declaration_golden_is_optional_open_and_source_compatible() {
4517 let original = serde_json::to_value(legacy_provenance()).unwrap();
4518 for declaration in ["declared", "undeclared", "not_applicable", "future_support"] {
4519 let mut golden = original.clone();
4520 golden["registration_declaration"] = json!(declaration);
4521 let extension = SupervisorModuleProvenanceExt::read_from(&golden).unwrap();
4522 assert_eq!(
4523 serde_json::to_value(&extension).unwrap(),
4524 json!({
4525 "registration_declaration": declaration
4526 })
4527 );
4528 let mut written = original.clone();
4529 extension.write_to(&mut written).unwrap();
4530 assert_eq!(written, golden);
4531 assert_eq!(
4532 serde_json::from_value::<SupervisorModuleProvenance>(golden).unwrap(),
4533 legacy_provenance()
4534 );
4535 SupervisorModuleProvenanceExt::new()
4536 .write_to(&mut written)
4537 .unwrap();
4538 assert_eq!(written, original);
4539 }
4540 }
4541
4542 #[test]
4543 fn admission_refusal_is_optional_and_open() {
4544 let entry = SupervisorEntry::new(
4545 "worker",
4546 "stopped",
4547 true,
4548 false,
4549 SupervisorHealthStatus::Unknown,
4550 );
4551 let original = serde_json::to_value(&entry).unwrap();
4552 assert!(original.get("admission_refused").is_none());
4553 let read: SupervisorEntry = serde_json::from_value(original.clone()).unwrap();
4554 assert_eq!(read.admission_refused, None);
4555 assert_eq!(serde_json::to_value(read).unwrap(), original);
4556 assert_eq!(
4557 REGISTRATION_CHANNEL_UNSUPPORTED,
4558 "registration_channel_unsupported"
4559 );
4560 for reason in [REGISTRATION_CHANNEL_UNSUPPORTED, "future_reason"] {
4561 let mut wire = original.clone();
4562 wire["admission_refused"] = json!(reason);
4563 let read: SupervisorEntry = serde_json::from_value(wire.clone()).unwrap();
4564 assert_eq!(read.admission_refused.as_deref(), Some(reason));
4565 assert_eq!(serde_json::to_value(read).unwrap(), wire);
4566 let built = entry.clone().with_admission_refused(Some(reason.into()));
4567 assert_eq!(serde_json::to_value(built).unwrap(), wire);
4568 }
4569 }
4570}