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,
915 pub pid: u32,
916 pub spawned_at_ms: u64,
917}
918
919#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
921pub struct SpawnSnapshot {
922 pub cursor: SpawnCursor,
923 pub ring_bound: u64,
925 pub live: Vec<LiveSpawn>,
926}
927
928#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
930#[serde(rename_all = "snake_case")]
931pub enum SpawnEventKind {
932 Spawned,
933 Exited,
934}
935
936#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
942pub struct SpawnEvent {
943 pub cursor: SpawnCursor,
944 pub kind: SpawnEventKind,
945 pub module_id: String,
946 pub spawn_generation: u64,
947 pub pid: u32,
948 #[serde(default, skip_serializing_if = "Option::is_none")]
949 pub exit_code: Option<i32>,
950 #[serde(default, skip_serializing_if = "Option::is_none")]
951 pub exit_signal: Option<i32>,
952}
953
954#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
956pub struct StderrTail {
957 pub capture: StderrCaptureState,
958 pub entries: Vec<StderrTailEntry>,
959 #[serde(default, skip_serializing_if = "is_zero_u64")]
968 pub dropped_lines: u64,
969}
970
971#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
973pub struct SupervisorRouteModule {
974 pub module_id: String,
975 pub routes: Vec<SupervisorRoute>,
976}
977
978#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
980pub struct SupervisorRoute {
981 pub consumer: SupervisorRouteConsumer,
982 pub age_ms: u64,
984 pub draining: bool,
987 #[serde(default, skip_serializing_if = "Option::is_none")]
993 pub drain_reason: Option<RouteCloseReason>,
994}
995
996#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
998pub struct SupervisorModuleProvenance {
999 pub module_id: String,
1000 pub module_declared: ModuleDeclaredProvenance,
1001 pub daemon_observed: SupervisorObservedProcess,
1002}
1003
1004#[non_exhaustive]
1007#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
1008pub struct SupervisorModuleProvenanceExt {
1009 #[serde(default, skip_serializing_if = "Option::is_none")]
1011 pub registration: Option<RegistrationMethod>,
1012 #[serde(default, skip_serializing_if = "Option::is_none")]
1016 pub registration_declaration: Option<String>,
1017}
1018
1019impl SupervisorModuleProvenanceExt {
1020 pub fn new() -> Self {
1021 Self::default()
1022 }
1023
1024 #[must_use]
1025 pub fn with_registration(mut self, registration: Option<RegistrationMethod>) -> Self {
1026 self.registration = registration;
1027 self
1028 }
1029
1030 pub fn read_from(entry: &serde_json::Value) -> serde_json::Result<Self> {
1032 if !entry.is_object() {
1033 return Err(serde_json::Error::custom(
1034 "expected a module provenance entry object",
1035 ));
1036 }
1037 serde_json::from_value(entry.clone())
1038 }
1039
1040 pub fn write_to(&self, entry: &mut serde_json::Value) -> serde_json::Result<()> {
1043 let object = entry.as_object_mut().ok_or_else(|| {
1044 serde_json::Error::custom("expected a module provenance entry object")
1045 })?;
1046 object.remove("registration");
1047 if let Some(method) = &self.registration {
1048 object.insert("registration".into(), serde_json::to_value(method)?);
1049 }
1050 object.remove("registration_declaration");
1051 if let Some(declaration) = &self.registration_declaration {
1052 object.insert(
1053 "registration_declaration".into(),
1054 declaration.clone().into(),
1055 );
1056 }
1057 Ok(())
1058 }
1059}
1060
1061#[non_exhaustive]
1064#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1065#[serde(rename_all = "snake_case")]
1066pub enum RegistrationMethod {
1067 Channel,
1068 Nonce,
1069 #[serde(other)]
1070 Unknown,
1071}
1072
1073pub const REGISTRATION_CHANNEL_UNSUPPORTED: &str = "registration_channel_unsupported";
1076
1077#[derive(Debug, Clone, PartialEq)]
1079pub enum ModuleDeclaredProvenance {
1080 Reported {
1081 build: ManifestProvenance,
1082 },
1083 Unverifiable,
1084 Unknown {
1087 tag: String,
1088 body: OrderedJsonObject,
1089 },
1090}
1091
1092#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1097pub struct SupervisorObservedProcess {
1098 #[serde(default, skip_serializing_if = "Option::is_none")]
1104 pub launch_nonce_source: Option<String>,
1105 #[serde(default, skip_serializing_if = "Option::is_none")]
1106 pub pid: Option<u32>,
1107 #[serde(default, skip_serializing_if = "Option::is_none")]
1108 pub spawned_at_ms: Option<u64>,
1109 #[serde(default, skip_serializing_if = "Option::is_none")]
1110 pub spawned_from: Option<PathBuf>,
1111 pub running_image: RunningImageAgreement,
1112}
1113
1114#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1131#[non_exhaustive]
1132pub struct PendingReloadVerdict {
1133 pub path: ReloadPathAgreement,
1134 pub image: RunningImageAgreement,
1135 #[serde(default, skip_serializing_if = "Option::is_none")]
1136 pub spec: Option<LaunchSpecAgreement>,
1137}
1138
1139impl PendingReloadVerdict {
1140 #[must_use]
1142 pub fn new(path: ReloadPathAgreement, image: RunningImageAgreement) -> Self {
1143 Self {
1144 path,
1145 image,
1146 spec: None,
1147 }
1148 }
1149
1150 #[must_use]
1152 pub fn with_spec(mut self, spec: Option<LaunchSpecAgreement>) -> Self {
1153 self.spec = spec;
1154 self
1155 }
1156}
1157
1158#[cfg(test)]
1159mod launch_spec_wire_tests {
1160 use super::*;
1161
1162 #[test]
1163 fn older_daemon_omission_is_not_reported_and_unknown_status_round_trips() {
1164 let old = r#"{"path":{"status":"match"},"image":{"status":"unavailable","reason":"not_running"}}"#;
1165 let parsed: PendingReloadVerdict = serde_json::from_str(old).unwrap();
1166 assert_eq!(parsed.spec, None);
1167 assert_eq!(serde_json::to_string(&parsed).unwrap(), old);
1168 let future = r#"{"status":"future_spec","detail":{"z":1,"a":2}}"#;
1169 let parsed: LaunchSpecAgreement = serde_json::from_str(future).unwrap();
1170 assert!(
1171 matches!(parsed, LaunchSpecAgreement::Unknown { ref tag, .. } if tag == "future_spec")
1172 );
1173 assert_eq!(serde_json::to_string(&parsed).unwrap(), future);
1174 let unavailable = LaunchSpecAgreement::Unavailable {
1175 reason: LaunchSpecUnavailableReason::SpawnedSpecUnavailable,
1176 };
1177 let encoded = serde_json::to_string(&unavailable).unwrap();
1178 assert_eq!(
1179 encoded,
1180 r#"{"status":"unavailable","reason":"spawned_spec_unavailable"}"#
1181 );
1182 assert_eq!(
1183 serde_json::from_str::<LaunchSpecAgreement>(&encoded).unwrap(),
1184 unavailable
1185 );
1186 }
1187}
1188
1189#[derive(Debug, Clone, PartialEq)]
1192pub enum LaunchSpecAgreement {
1193 Match,
1194 Mismatch,
1195 Unavailable {
1196 reason: LaunchSpecUnavailableReason,
1197 },
1198 Unknown {
1199 tag: String,
1200 body: OrderedJsonObject,
1201 },
1202}
1203
1204open_string_enum! {
1205 LaunchSpecUnavailableReason {
1206 NotRunning => "not_running",
1207 SpawnedSpecUnavailable => "spawned_spec_unavailable",
1208 }
1209}
1210
1211#[derive(Debug, Clone, PartialEq)]
1213pub enum ReloadPathAgreement {
1214 Match,
1215 Mismatch {
1216 configured: PathBuf,
1217 spawned_from: PathBuf,
1218 },
1219 Unavailable {
1220 reason: ReloadPathUnavailableReason,
1221 },
1222 Unknown {
1223 tag: String,
1224 body: OrderedJsonObject,
1225 },
1226}
1227
1228open_string_enum! {
1229 ReloadPathUnavailableReason {
1231 NotRunning => "not_running",
1232 SpawnedPathUnavailable => "spawned_path_unavailable",
1233 }
1234}
1235
1236#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1238pub struct SupervisorDaemonProvenance {
1239 pub daemon_build: DaemonBuildProvenance,
1240 pub daemon_observed: DaemonObservedProcess,
1241}
1242
1243#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1245pub struct DaemonBuildProvenance {
1246 #[serde(default, skip_serializing_if = "Option::is_none")]
1247 pub build_git_sha: Option<String>,
1248 #[serde(default, skip_serializing_if = "Option::is_none")]
1249 pub build_lock_digest: Option<String>,
1250}
1251
1252#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1254pub struct DaemonObservedProcess {
1255 #[serde(default, skip_serializing_if = "Option::is_none")]
1256 pub pid: Option<u32>,
1257 #[serde(default, skip_serializing_if = "Option::is_none")]
1262 pub started_at_ms: Option<u64>,
1263 pub running_image: RunningImageAgreement,
1264}
1265
1266#[derive(Debug, Clone, PartialEq)]
1268pub enum RunningImageAgreement {
1269 Match {
1270 evidence: RunningImageEvidence,
1271 },
1272 Mismatch {
1273 running: RunningImageEvidence,
1274 disk: RunningImageEvidence,
1275 },
1276 Unavailable {
1277 reason: RunningImageUnavailableReason,
1278 },
1279 Unknown {
1282 tag: String,
1283 body: OrderedJsonObject,
1284 },
1285}
1286
1287#[derive(Debug, Clone, PartialEq)]
1289pub enum RunningImageEvidence {
1290 LinuxProcSha256 {
1291 digest: String,
1292 },
1293 MacosSpawnInode {
1294 device: u64,
1295 inode: u64,
1296 },
1297 WindowsSpawnFileId {
1299 volume_serial_number: u64,
1300 file_id: [u8; 16],
1301 },
1302 Unknown {
1305 tag: String,
1306 body: OrderedJsonObject,
1307 },
1308}
1309
1310open_string_enum! {
1311 RunningImageUnavailableReason {
1313 NotRunning => "not_running",
1314 NotYetMeasured => "not_yet_measured",
1315 UnsupportedPlatform => "unsupported_platform",
1316 RunningExecutableUnreadable => "running_executable_unreadable",
1317 RunningExecutablePermissionDenied => "running_executable_permission_denied",
1318 ProcessHidden => "process_hidden",
1319 SpawnedPathUnreadable => "spawned_path_unreadable",
1320 HashFailed => "hash_failed",
1321 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
1322 }
1323}
1324
1325#[derive(Debug, Clone, PartialEq)]
1331pub enum SupervisorRouteConsumer {
1332 Reserved {
1333 module_id: String,
1334 },
1335 Direct {
1336 connection_id: u64,
1337 },
1338 Unknown {
1341 tag: String,
1342 body: OrderedJsonObject,
1343 },
1344}
1345
1346#[derive(Debug, Clone, PartialEq)]
1353pub enum StderrCaptureState {
1354 Captured,
1357 Incomplete { reason: String },
1359 NotCaptured { reason: String },
1361 Unknown {
1364 tag: String,
1365 body: OrderedJsonObject,
1366 },
1367}
1368
1369#[derive(Debug, Clone, PartialEq)]
1370pub enum StderrTailEntry {
1371 Line {
1372 text: String,
1373 truncated: bool,
1378 at_ms: Option<u64>,
1382 },
1383 ProcessStart,
1388 Unknown {
1391 tag: String,
1392 body: OrderedJsonObject,
1393 },
1394}
1395
1396#[derive(Debug, Serialize, Deserialize)]
1397#[serde(tag = "status", rename_all = "snake_case")]
1398enum ModuleDeclaredProvenanceWire {
1399 Reported { build: ManifestProvenance },
1400 Unverifiable,
1401}
1402
1403#[derive(Debug, Serialize, Deserialize)]
1404#[serde(tag = "status", rename_all = "snake_case")]
1405enum RunningImageAgreementWire {
1406 Match {
1407 evidence: RunningImageEvidence,
1408 },
1409 Mismatch {
1410 running: RunningImageEvidence,
1411 disk: RunningImageEvidence,
1412 },
1413 Unavailable {
1414 reason: RunningImageUnavailableReason,
1415 },
1416}
1417
1418#[derive(Debug, Serialize, Deserialize)]
1419#[serde(tag = "status", rename_all = "snake_case")]
1420enum ReloadPathAgreementWire {
1421 Match,
1422 Mismatch {
1423 configured: PathBuf,
1424 spawned_from: PathBuf,
1425 },
1426 Unavailable {
1427 reason: ReloadPathUnavailableReason,
1428 },
1429}
1430
1431#[derive(Debug, Serialize, Deserialize)]
1432#[serde(tag = "status", rename_all = "snake_case")]
1433enum LaunchSpecAgreementWire {
1434 Match,
1435 Mismatch,
1436 Unavailable { reason: LaunchSpecUnavailableReason },
1437}
1438
1439#[derive(Debug, Serialize, Deserialize)]
1440#[serde(tag = "method", rename_all = "snake_case")]
1441enum RunningImageEvidenceWire {
1442 LinuxProcSha256 {
1443 digest: String,
1444 },
1445 MacosSpawnInode {
1446 device: u64,
1447 inode: u64,
1448 },
1449 WindowsSpawnFileId {
1450 volume_serial_number: u64,
1451 file_id: [u8; 16],
1452 },
1453}
1454
1455#[derive(Debug, Serialize, Deserialize)]
1456#[serde(tag = "kind", rename_all = "snake_case")]
1457enum SupervisorRouteConsumerWire {
1458 Reserved { module_id: String },
1459 Direct { connection_id: u64 },
1460}
1461
1462#[derive(Debug, Serialize, Deserialize)]
1463#[serde(tag = "state", rename_all = "snake_case")]
1464enum StderrCaptureStateWire {
1465 Captured,
1466 Incomplete { reason: String },
1467 NotCaptured { reason: String },
1468}
1469
1470#[derive(Debug, Serialize, Deserialize)]
1471#[serde(tag = "status", rename_all = "snake_case")]
1472enum ChildResourceUsageWire {
1473 Measured(ChildResourceReading),
1474 Unavailable {
1475 reason: ChildResourceUnavailableReason,
1476 },
1477}
1478
1479#[derive(Debug, Serialize, Deserialize)]
1480#[serde(tag = "kind", rename_all = "snake_case")]
1481enum StderrTailEntryWire {
1482 Line {
1483 text: String,
1484 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1485 truncated: bool,
1486 #[serde(default, skip_serializing_if = "Option::is_none")]
1489 at_ms: Option<u64>,
1490 },
1491 ProcessStart,
1492}
1493
1494#[derive(Debug, Clone, PartialEq)]
1496pub enum OrderedJsonValue {
1497 Null,
1498 Bool(bool),
1499 Number(serde_json::Number),
1500 String(String),
1501 Array(Vec<Self>),
1502 Object(OrderedJsonObject),
1503}
1504
1505#[derive(Debug, Clone, PartialEq)]
1507pub struct OrderedJsonObject(Vec<(String, OrderedJsonValue)>);
1508
1509impl OrderedJsonObject {
1510 pub fn as_entries(&self) -> &[(String, OrderedJsonValue)] {
1512 &self.0
1513 }
1514
1515 fn into_value(self) -> serde_json::Value {
1516 serde_json::Value::Object(
1517 self.0
1518 .into_iter()
1519 .map(|(key, value)| (key, value.into_value()))
1520 .collect(),
1521 )
1522 }
1523}
1524
1525impl OrderedJsonValue {
1526 fn into_value(self) -> serde_json::Value {
1527 match self {
1528 Self::Null => serde_json::Value::Null,
1529 Self::Bool(value) => serde_json::Value::Bool(value),
1530 Self::Number(value) => serde_json::Value::Number(value),
1531 Self::String(value) => serde_json::Value::String(value),
1532 Self::Array(values) => {
1533 serde_json::Value::Array(values.into_iter().map(Self::into_value).collect())
1534 }
1535 Self::Object(value) => value.into_value(),
1536 }
1537 }
1538}
1539
1540impl Serialize for OrderedJsonValue {
1541 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1542 where
1543 S: Serializer,
1544 {
1545 match self {
1546 Self::Null => serializer.serialize_unit(),
1547 Self::Bool(value) => serializer.serialize_bool(*value),
1548 Self::Number(value) => value.serialize(serializer),
1549 Self::String(value) => serializer.serialize_str(value),
1550 Self::Array(values) => values.serialize(serializer),
1551 Self::Object(value) => value.serialize(serializer),
1552 }
1553 }
1554}
1555
1556impl<'de> Deserialize<'de> for OrderedJsonValue {
1557 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1558 where
1559 D: Deserializer<'de>,
1560 {
1561 struct OrderedValueVisitor;
1562
1563 impl<'de> Visitor<'de> for OrderedValueVisitor {
1564 type Value = OrderedJsonValue;
1565
1566 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1567 formatter.write_str("a JSON value with ordered object members")
1568 }
1569
1570 fn visit_unit<E>(self) -> Result<Self::Value, E>
1571 where
1572 E: serde::de::Error,
1573 {
1574 Ok(OrderedJsonValue::Null)
1575 }
1576
1577 fn visit_none<E>(self) -> Result<Self::Value, E>
1578 where
1579 E: serde::de::Error,
1580 {
1581 Ok(OrderedJsonValue::Null)
1582 }
1583
1584 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1585 where
1586 D: Deserializer<'de>,
1587 {
1588 OrderedJsonValue::deserialize(deserializer)
1589 }
1590
1591 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
1592 where
1593 E: serde::de::Error,
1594 {
1595 Ok(OrderedJsonValue::Bool(value))
1596 }
1597
1598 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
1599 where
1600 E: serde::de::Error,
1601 {
1602 Ok(OrderedJsonValue::Number(value.into()))
1603 }
1604
1605 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
1606 where
1607 E: serde::de::Error,
1608 {
1609 Ok(OrderedJsonValue::Number(value.into()))
1610 }
1611
1612 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1613 where
1614 E: serde::de::Error,
1615 {
1616 serde_json::Number::from_f64(value)
1617 .map(OrderedJsonValue::Number)
1618 .ok_or_else(|| E::custom("non-finite JSON number"))
1619 }
1620
1621 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1622 where
1623 E: serde::de::Error,
1624 {
1625 Ok(OrderedJsonValue::String(value.to_owned()))
1626 }
1627
1628 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
1629 where
1630 E: serde::de::Error,
1631 {
1632 Ok(OrderedJsonValue::String(value))
1633 }
1634
1635 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1636 where
1637 A: SeqAccess<'de>,
1638 {
1639 let mut values = Vec::new();
1640 while let Some(value) = sequence.next_element()? {
1641 values.push(value);
1642 }
1643 Ok(OrderedJsonValue::Array(values))
1644 }
1645
1646 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1647 where
1648 A: MapAccess<'de>,
1649 {
1650 let mut entries = Vec::new();
1651 while let Some((key, value)) = map.next_entry()? {
1652 entries.push((key, value));
1653 }
1654 Ok(OrderedJsonValue::Object(OrderedJsonObject(entries)))
1655 }
1656 }
1657
1658 deserializer.deserialize_any(OrderedValueVisitor)
1659 }
1660}
1661
1662impl Serialize for OrderedJsonObject {
1663 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1664 where
1665 S: Serializer,
1666 {
1667 let mut map = serializer.serialize_map(Some(self.0.len()))?;
1668 for (key, value) in &self.0 {
1669 map.serialize_entry(key, value)?;
1670 }
1671 map.end()
1672 }
1673}
1674
1675impl<'de> Deserialize<'de> for OrderedJsonObject {
1676 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1677 where
1678 D: Deserializer<'de>,
1679 {
1680 struct OrderedObjectVisitor;
1681
1682 impl<'de> Visitor<'de> for OrderedObjectVisitor {
1683 type Value = OrderedJsonObject;
1684
1685 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1686 formatter.write_str("an object with ordered JSON members")
1687 }
1688
1689 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1690 where
1691 A: MapAccess<'de>,
1692 {
1693 let mut entries = Vec::new();
1694 while let Some((key, value)) = map.next_entry()? {
1695 entries.push((key, value));
1696 }
1697 Ok(OrderedJsonObject(entries))
1698 }
1699 }
1700
1701 deserializer.deserialize_map(OrderedObjectVisitor)
1702 }
1703}
1704
1705fn read_tagged<'de, D>(
1706 deserializer: D,
1707 field: &'static str,
1708) -> Result<(String, OrderedJsonObject), D::Error>
1709where
1710 D: Deserializer<'de>,
1711{
1712 let body = OrderedJsonObject::deserialize(deserializer)?;
1713 let mut tag = None;
1714 for (key, value) in body.as_entries() {
1715 if key != field {
1716 continue;
1717 }
1718 if tag.is_some() {
1719 return Err(D::Error::custom(format!(
1720 "tagged object has duplicate `{field}` field"
1721 )));
1722 }
1723 let OrderedJsonValue::String(value) = value else {
1724 return Err(D::Error::custom(format!(
1725 "tagged object has no string `{field}` field"
1726 )));
1727 };
1728 tag = Some(value);
1729 }
1730 let Some(tag) = tag else {
1731 return Err(D::Error::custom(format!(
1732 "tagged object has no string `{field}` field"
1733 )));
1734 };
1735 Ok((tag.to_string(), body))
1736}
1737
1738fn read_ordered_tagged(
1739 value: OrderedJsonValue,
1740 field: &'static str,
1741) -> Result<(String, OrderedJsonObject), String> {
1742 let OrderedJsonValue::Object(body) = value else {
1743 return Err(format!("expected tagged object with `{field}` field"));
1744 };
1745 let mut tag = None;
1746 for (key, value) in body.as_entries() {
1747 if key != field {
1748 continue;
1749 }
1750 if tag.is_some() {
1751 return Err(format!("tagged object has duplicate `{field}` field"));
1752 }
1753 let OrderedJsonValue::String(value) = value else {
1754 return Err(format!("tagged object has no string `{field}` field"));
1755 };
1756 tag = Some(value);
1757 }
1758 let Some(tag) = tag else {
1759 return Err(format!("tagged object has no string `{field}` field"));
1760 };
1761 Ok((tag.to_string(), body))
1762}
1763
1764fn ordered_field<'a>(body: &'a OrderedJsonObject, field: &str) -> Option<&'a OrderedJsonValue> {
1765 body.as_entries()
1766 .iter()
1767 .find_map(|(key, value)| (key == field).then_some(value))
1768}
1769
1770fn ordered_string(body: &OrderedJsonObject, field: &str) -> Result<String, String> {
1771 match ordered_field(body, field) {
1772 Some(OrderedJsonValue::String(value)) => Ok(value.clone()),
1773 Some(_) => Err(format!("tagged object field `{field}` is not a string")),
1774 None => Err(format!("tagged object has no `{field}` field")),
1775 }
1776}
1777
1778fn decode_running_image_evidence(value: OrderedJsonValue) -> Result<RunningImageEvidence, String> {
1779 let (tag, body) = read_ordered_tagged(value, "method")?;
1780 match tag.as_str() {
1781 "linux_proc_sha256" => Ok(RunningImageEvidence::LinuxProcSha256 {
1782 digest: ordered_string(&body, "digest")?,
1783 }),
1784 "macos_spawn_inode" => {
1785 let device = ordered_field(&body, "device")
1786 .and_then(|value| match value {
1787 OrderedJsonValue::Number(number) => number.as_u64(),
1788 _ => None,
1789 })
1790 .ok_or_else(|| "tagged object has no unsigned `device` field".to_string())?;
1791 let inode = ordered_field(&body, "inode")
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 `inode` field".to_string())?;
1797 Ok(RunningImageEvidence::MacosSpawnInode { device, inode })
1798 }
1799 "windows_spawn_file_id" => {
1800 let wire: RunningImageEvidenceWire = serde_json::from_value(
1801 serde_json::to_value(&body).map_err(|error| error.to_string())?,
1802 )
1803 .map_err(|error| error.to_string())?;
1804 match wire {
1805 RunningImageEvidenceWire::WindowsSpawnFileId {
1806 volume_serial_number,
1807 file_id,
1808 } => Ok(RunningImageEvidence::WindowsSpawnFileId {
1809 volume_serial_number,
1810 file_id,
1811 }),
1812 _ => unreachable!(),
1813 }
1814 }
1815 _ => Ok(RunningImageEvidence::Unknown { tag, body }),
1816 }
1817}
1818
1819impl Serialize for ModuleDeclaredProvenance {
1820 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1821 where
1822 S: Serializer,
1823 {
1824 match self {
1825 Self::Reported { build } => ModuleDeclaredProvenanceWire::Reported {
1826 build: build.clone(),
1827 }
1828 .serialize(serializer),
1829 Self::Unverifiable => ModuleDeclaredProvenanceWire::Unverifiable.serialize(serializer),
1830 Self::Unknown { body, .. } => body.serialize(serializer),
1831 }
1832 }
1833}
1834
1835impl<'de> Deserialize<'de> for ModuleDeclaredProvenance {
1836 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1837 where
1838 D: serde::Deserializer<'de>,
1839 {
1840 let (tag, value) = read_tagged(deserializer, "status")?;
1841 match tag.as_str() {
1842 "reported" => match serde_json::from_value(value.into_value())
1843 .map_err(D::Error::custom)?
1844 {
1845 ModuleDeclaredProvenanceWire::Reported { build } => Ok(Self::Reported { build }),
1846 ModuleDeclaredProvenanceWire::Unverifiable => unreachable!(),
1847 },
1848 "unverifiable" => {
1849 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1850 ModuleDeclaredProvenanceWire::Unverifiable => Ok(Self::Unverifiable),
1851 ModuleDeclaredProvenanceWire::Reported { .. } => unreachable!(),
1852 }
1853 }
1854 _ => Ok(Self::Unknown { tag, body: value }),
1855 }
1856 }
1857}
1858
1859impl Serialize for RunningImageAgreement {
1860 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1861 where
1862 S: Serializer,
1863 {
1864 match self {
1865 Self::Match { evidence } => RunningImageAgreementWire::Match {
1866 evidence: evidence.clone(),
1867 }
1868 .serialize(serializer),
1869 Self::Mismatch { running, disk } => RunningImageAgreementWire::Mismatch {
1870 running: running.clone(),
1871 disk: disk.clone(),
1872 }
1873 .serialize(serializer),
1874 Self::Unavailable { reason } => RunningImageAgreementWire::Unavailable {
1875 reason: reason.clone(),
1876 }
1877 .serialize(serializer),
1878 Self::Unknown { body, .. } => body.serialize(serializer),
1879 }
1880 }
1881}
1882
1883impl Serialize for ReloadPathAgreement {
1884 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1885 where
1886 S: Serializer,
1887 {
1888 match self {
1889 Self::Match => ReloadPathAgreementWire::Match.serialize(serializer),
1890 Self::Mismatch {
1891 configured,
1892 spawned_from,
1893 } => ReloadPathAgreementWire::Mismatch {
1894 configured: configured.clone(),
1895 spawned_from: spawned_from.clone(),
1896 }
1897 .serialize(serializer),
1898 Self::Unavailable { reason } => ReloadPathAgreementWire::Unavailable {
1899 reason: reason.clone(),
1900 }
1901 .serialize(serializer),
1902 Self::Unknown { body, .. } => body.serialize(serializer),
1903 }
1904 }
1905}
1906
1907impl Serialize for LaunchSpecAgreement {
1908 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1909 where
1910 S: Serializer,
1911 {
1912 match self {
1913 Self::Match => LaunchSpecAgreementWire::Match.serialize(serializer),
1914 Self::Mismatch => LaunchSpecAgreementWire::Mismatch.serialize(serializer),
1915 Self::Unavailable { reason } => LaunchSpecAgreementWire::Unavailable {
1916 reason: reason.clone(),
1917 }
1918 .serialize(serializer),
1919 Self::Unknown { body, .. } => body.serialize(serializer),
1920 }
1921 }
1922}
1923
1924impl<'de> Deserialize<'de> for LaunchSpecAgreement {
1925 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1926 where
1927 D: Deserializer<'de>,
1928 {
1929 let (tag, body) = read_tagged(deserializer, "status")?;
1930 match tag.as_str() {
1931 "match" => Ok(Self::Match),
1932 "mismatch" => Ok(Self::Mismatch),
1933 "unavailable" => match serde_json::from_value(body.into_value())
1934 .map_err(D::Error::custom)?
1935 {
1936 LaunchSpecAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1937 _ => unreachable!(),
1938 },
1939 _ => Ok(Self::Unknown { tag, body }),
1940 }
1941 }
1942}
1943
1944impl<'de> Deserialize<'de> for ReloadPathAgreement {
1945 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1946 where
1947 D: Deserializer<'de>,
1948 {
1949 let (tag, body) = read_tagged(deserializer, "status")?;
1950 match tag.as_str() {
1951 "match" => Ok(Self::Match),
1952 "mismatch" => {
1953 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1954 ReloadPathAgreementWire::Mismatch {
1955 configured,
1956 spawned_from,
1957 } => Ok(Self::Mismatch {
1958 configured,
1959 spawned_from,
1960 }),
1961 _ => unreachable!(),
1962 }
1963 }
1964 "unavailable" => match serde_json::from_value(body.into_value())
1965 .map_err(D::Error::custom)?
1966 {
1967 ReloadPathAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1968 _ => unreachable!(),
1969 },
1970 _ => Ok(Self::Unknown { tag, body }),
1971 }
1972 }
1973}
1974
1975impl<'de> Deserialize<'de> for RunningImageAgreement {
1976 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1977 where
1978 D: serde::Deserializer<'de>,
1979 {
1980 let (tag, value) = read_tagged(deserializer, "status")?;
1981 match tag.as_str() {
1982 "match" => Ok(Self::Match {
1983 evidence: decode_running_image_evidence(
1984 ordered_field(&value, "evidence")
1985 .cloned()
1986 .ok_or_else(|| D::Error::custom("tagged object has no `evidence` field"))?,
1987 )
1988 .map_err(D::Error::custom)?,
1989 }),
1990 "mismatch" => Ok(Self::Mismatch {
1991 running: decode_running_image_evidence(
1992 ordered_field(&value, "running")
1993 .cloned()
1994 .ok_or_else(|| D::Error::custom("tagged object has no `running` field"))?,
1995 )
1996 .map_err(D::Error::custom)?,
1997 disk: decode_running_image_evidence(
1998 ordered_field(&value, "disk")
1999 .cloned()
2000 .ok_or_else(|| D::Error::custom("tagged object has no `disk` field"))?,
2001 )
2002 .map_err(D::Error::custom)?,
2003 }),
2004 "unavailable" => Ok(Self::Unavailable {
2005 reason: serde_json::from_value(
2006 ordered_field(&value, "reason")
2007 .cloned()
2008 .ok_or_else(|| D::Error::custom("tagged object has no `reason` field"))?
2009 .into_value(),
2010 )
2011 .map_err(D::Error::custom)?,
2012 }),
2013 _ => Ok(Self::Unknown { tag, body: value }),
2014 }
2015 }
2016}
2017
2018impl Serialize for ChildResourceUsage {
2019 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2020 where
2021 S: Serializer,
2022 {
2023 match self {
2024 Self::Measured(reading) => {
2025 ChildResourceUsageWire::Measured(reading.clone()).serialize(serializer)
2026 }
2027 Self::Unavailable { reason } => ChildResourceUsageWire::Unavailable {
2028 reason: reason.clone(),
2029 }
2030 .serialize(serializer),
2031 Self::Unknown { body, .. } => body.serialize(serializer),
2032 }
2033 }
2034}
2035
2036impl<'de> Deserialize<'de> for ChildResourceUsage {
2037 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2038 where
2039 D: Deserializer<'de>,
2040 {
2041 let (tag, body) = read_tagged(deserializer, "status")?;
2042 match tag.as_str() {
2043 "measured" | "unavailable" => {
2044 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
2045 ChildResourceUsageWire::Measured(reading) => Ok(Self::Measured(reading)),
2046 ChildResourceUsageWire::Unavailable { reason } => {
2047 Ok(Self::Unavailable { reason })
2048 }
2049 }
2050 }
2051 _ => Ok(Self::Unknown { tag, body }),
2052 }
2053 }
2054}
2055
2056impl Serialize for RunningImageEvidence {
2057 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2058 where
2059 S: Serializer,
2060 {
2061 match self {
2062 Self::LinuxProcSha256 { digest } => RunningImageEvidenceWire::LinuxProcSha256 {
2063 digest: digest.clone(),
2064 }
2065 .serialize(serializer),
2066 Self::MacosSpawnInode { device, inode } => RunningImageEvidenceWire::MacosSpawnInode {
2067 device: *device,
2068 inode: *inode,
2069 }
2070 .serialize(serializer),
2071 Self::WindowsSpawnFileId {
2072 volume_serial_number,
2073 file_id,
2074 } => RunningImageEvidenceWire::WindowsSpawnFileId {
2075 volume_serial_number: *volume_serial_number,
2076 file_id: *file_id,
2077 }
2078 .serialize(serializer),
2079 Self::Unknown { body, .. } => body.serialize(serializer),
2080 }
2081 }
2082}
2083
2084impl<'de> Deserialize<'de> for RunningImageEvidence {
2085 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2086 where
2087 D: serde::Deserializer<'de>,
2088 {
2089 let (tag, value) = read_tagged(deserializer, "method")?;
2090 match tag.as_str() {
2091 "linux_proc_sha256" => {
2092 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2093 RunningImageEvidenceWire::LinuxProcSha256 { digest } => {
2094 Ok(Self::LinuxProcSha256 { digest })
2095 }
2096 _ => unreachable!(),
2097 }
2098 }
2099 "macos_spawn_inode" => {
2100 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2101 RunningImageEvidenceWire::MacosSpawnInode { device, inode } => {
2102 Ok(Self::MacosSpawnInode { device, inode })
2103 }
2104 _ => unreachable!(),
2105 }
2106 }
2107 "windows_spawn_file_id" => {
2108 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2109 RunningImageEvidenceWire::WindowsSpawnFileId {
2110 volume_serial_number,
2111 file_id,
2112 } => Ok(Self::WindowsSpawnFileId {
2113 volume_serial_number,
2114 file_id,
2115 }),
2116 _ => unreachable!(),
2117 }
2118 }
2119 _ => Ok(Self::Unknown { tag, body: value }),
2120 }
2121 }
2122}
2123
2124impl Serialize for SupervisorRouteConsumer {
2125 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2126 where
2127 S: Serializer,
2128 {
2129 match self {
2130 Self::Reserved { module_id } => SupervisorRouteConsumerWire::Reserved {
2131 module_id: module_id.clone(),
2132 }
2133 .serialize(serializer),
2134 Self::Direct { connection_id } => SupervisorRouteConsumerWire::Direct {
2135 connection_id: *connection_id,
2136 }
2137 .serialize(serializer),
2138 Self::Unknown { body, .. } => body.serialize(serializer),
2139 }
2140 }
2141}
2142
2143impl<'de> Deserialize<'de> for SupervisorRouteConsumer {
2144 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2145 where
2146 D: serde::Deserializer<'de>,
2147 {
2148 let (tag, value) = read_tagged(deserializer, "kind")?;
2149 match tag.as_str() {
2150 "reserved" => {
2151 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2152 SupervisorRouteConsumerWire::Reserved { module_id } => {
2153 Ok(Self::Reserved { module_id })
2154 }
2155 _ => unreachable!(),
2156 }
2157 }
2158 "direct" => {
2159 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2160 SupervisorRouteConsumerWire::Direct { connection_id } => {
2161 Ok(Self::Direct { connection_id })
2162 }
2163 _ => unreachable!(),
2164 }
2165 }
2166 _ => Ok(Self::Unknown { tag, body: value }),
2167 }
2168 }
2169}
2170
2171impl Serialize for StderrCaptureState {
2172 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2173 where
2174 S: Serializer,
2175 {
2176 match self {
2177 Self::Captured => StderrCaptureStateWire::Captured.serialize(serializer),
2178 Self::Incomplete { reason } => StderrCaptureStateWire::Incomplete {
2179 reason: reason.clone(),
2180 }
2181 .serialize(serializer),
2182 Self::NotCaptured { reason } => StderrCaptureStateWire::NotCaptured {
2183 reason: reason.clone(),
2184 }
2185 .serialize(serializer),
2186 Self::Unknown { body, .. } => body.serialize(serializer),
2187 }
2188 }
2189}
2190
2191impl<'de> Deserialize<'de> for StderrCaptureState {
2192 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2193 where
2194 D: serde::Deserializer<'de>,
2195 {
2196 let (tag, value) = read_tagged(deserializer, "state")?;
2197 match tag.as_str() {
2198 "captured" => {
2199 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2200 StderrCaptureStateWire::Captured => Ok(Self::Captured),
2201 _ => unreachable!(),
2202 }
2203 }
2204 "incomplete" => match serde_json::from_value(value.into_value())
2205 .map_err(D::Error::custom)?
2206 {
2207 StderrCaptureStateWire::Incomplete { reason } => Ok(Self::Incomplete { reason }),
2208 _ => unreachable!(),
2209 },
2210 "not_captured" => match serde_json::from_value(value.into_value())
2211 .map_err(D::Error::custom)?
2212 {
2213 StderrCaptureStateWire::NotCaptured { reason } => Ok(Self::NotCaptured { reason }),
2214 _ => unreachable!(),
2215 },
2216 _ => Ok(Self::Unknown { tag, body: value }),
2217 }
2218 }
2219}
2220
2221impl Serialize for StderrTailEntry {
2222 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2223 where
2224 S: Serializer,
2225 {
2226 match self {
2227 Self::Line {
2228 text,
2229 truncated,
2230 at_ms,
2231 } => StderrTailEntryWire::Line {
2232 text: text.clone(),
2233 truncated: *truncated,
2234 at_ms: *at_ms,
2235 }
2236 .serialize(serializer),
2237 Self::ProcessStart => StderrTailEntryWire::ProcessStart.serialize(serializer),
2238 Self::Unknown { body, .. } => body.serialize(serializer),
2239 }
2240 }
2241}
2242
2243impl<'de> Deserialize<'de> for StderrTailEntry {
2244 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2245 where
2246 D: serde::Deserializer<'de>,
2247 {
2248 let (tag, value) = read_tagged(deserializer, "kind")?;
2249 match tag.as_str() {
2250 "line" => match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2251 StderrTailEntryWire::Line {
2252 text,
2253 truncated,
2254 at_ms,
2255 } => Ok(Self::Line {
2256 text,
2257 truncated,
2258 at_ms,
2259 }),
2260 _ => unreachable!(),
2261 },
2262 "process_start" => {
2263 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2264 StderrTailEntryWire::ProcessStart => Ok(Self::ProcessStart),
2265 _ => unreachable!(),
2266 }
2267 }
2268 _ => Ok(Self::Unknown { tag, body: value }),
2269 }
2270 }
2271}
2272
2273fn is_zero_u64(value: &u64) -> bool {
2274 *value == 0
2275}
2276
2277fn default_true() -> bool {
2278 true
2279}
2280
2281#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2283pub struct TerminalHistory {
2284 pub daemon_started_at_ms: u64,
2286 pub entries: Vec<TerminalEntry>,
2287 #[serde(default, skip_serializing_if = "is_zero_u64")]
2290 pub dropped: u64,
2291 #[serde(default, skip_serializing_if = "is_zero_u64")]
2294 pub journal_skipped_lines: u64,
2295 #[serde(default, skip_serializing_if = "is_zero_u64")]
2297 pub journal_read_errors: u64,
2298 #[serde(default, skip_serializing_if = "is_zero_u64")]
2300 pub journal_write_failures: u64,
2301}
2302
2303#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2305pub struct TerminalEntry {
2306 #[serde(default, skip_serializing_if = "Option::is_none")]
2309 pub daemon_incarnation: Option<String>,
2310 #[serde(default, skip_serializing_if = "Option::is_none")]
2311 pub exit_code: Option<i32>,
2312 #[serde(default, skip_serializing_if = "Option::is_none")]
2313 pub exit_signal: Option<i32>,
2314 pub at_ms: u64,
2315 pub disposition: TerminalDisposition,
2316 #[serde(default, skip_serializing_if = "Option::is_none")]
2320 pub exit_kind: Option<TerminalExitKind>,
2321 #[serde(default, skip_serializing_if = "Option::is_none")]
2328 pub disposition_detail: Option<String>,
2329}
2330
2331#[derive(Debug, Clone, PartialEq, Eq)]
2336pub enum TerminalExitKind {
2337 Clean,
2338 Crash,
2339 DeliberateSeverance,
2340 Unknown(String),
2341}
2342
2343impl TerminalExitKind {
2344 fn wire_name(&self) -> &str {
2345 match self {
2346 Self::Clean => "clean",
2347 Self::Crash => "crash",
2348 Self::DeliberateSeverance => "deliberate_severance",
2349 Self::Unknown(value) => value,
2350 }
2351 }
2352}
2353
2354impl Serialize for TerminalExitKind {
2355 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2356 where
2357 S: serde::Serializer,
2358 {
2359 serializer.serialize_str(self.wire_name())
2360 }
2361}
2362
2363impl<'de> Deserialize<'de> for TerminalExitKind {
2364 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2365 where
2366 D: serde::Deserializer<'de>,
2367 {
2368 let value = String::deserialize(deserializer)?;
2369 Ok(match value.as_str() {
2370 "clean" => Self::Clean,
2371 "crash" => Self::Crash,
2372 "deliberate_severance" => Self::DeliberateSeverance,
2373 _ => Self::Unknown(value),
2374 })
2375 }
2376}
2377
2378open_string_enum! {
2379 TerminalDisposition {
2381 Stopped => "stopped",
2382 Disabled => "disabled",
2383 Failed => "failed",
2384 Restarting => "restarting",
2385 DaemonShutdown => "daemon_shutdown",
2390 }
2391}
2392
2393#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2394#[serde(rename_all = "snake_case")]
2395pub enum PollKind {
2396 Status,
2397 Liveness,
2398}
2399
2400#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2412#[non_exhaustive]
2413pub struct CatalogEntry {
2414 pub module_id: String,
2415 #[serde(default, skip_serializing_if = "Option::is_none")]
2417 pub display_name: Option<String>,
2418 #[serde(default = "default_true")]
2429 pub ready: bool,
2430 #[serde(default, skip_serializing_if = "Option::is_none")]
2434 pub not_ready: Option<NotReadyReason>,
2435 #[serde(default, skip_serializing_if = "Option::is_none")]
2456 pub module_version: Option<String>,
2457 #[serde(default, skip_serializing_if = "Option::is_none")]
2460 pub provenance: Option<ManifestProvenance>,
2461 pub roles: Vec<ProviderRole>,
2462 pub control_ops: Vec<String>,
2463 #[serde(default, skip_serializing_if = "Option::is_none")]
2468 pub capabilities: Option<CapabilityDeclarations>,
2469 #[serde(default, skip_serializing_if = "Option::is_none")]
2472 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
2473 #[serde(default, skip_serializing_if = "Option::is_none")]
2477 pub events: Option<Vec<EventDeclaration>>,
2478 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2481 pub operation_delivery: BTreeMap<String, OperationDelivery>,
2482 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2485 pub operation_payload: BTreeMap<String, OperationPayload>,
2486 #[serde(default, skip_serializing_if = "Option::is_none")]
2492 pub flow_operations: Option<Vec<String>>,
2493 #[serde(default, skip_serializing_if = "Option::is_none")]
2495 pub operation_deferral: Option<BTreeMap<String, bool>>,
2496 #[serde(default, skip_serializing_if = "Option::is_none")]
2502 pub confirm_operations: Option<Vec<String>>,
2503 #[serde(default, skip_serializing_if = "Option::is_none")]
2506 pub rich_ui: Option<RichUiDescriptor>,
2507 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2510 pub role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2511 #[serde(default, skip_serializing_if = "is_false")]
2516 pub nonce_verified: bool,
2517 #[serde(default, skip_serializing_if = "Option::is_none")]
2520 pub incarnation: Option<String>,
2521 #[serde(
2522 default,
2523 skip_serializing_if = "Option::is_none",
2524 deserialize_with = "deserialize_optional_attestation_integer"
2525 )]
2526 pub spawn: Option<u64>,
2527 #[serde(default, skip_serializing_if = "Option::is_none")]
2528 pub first_party: Option<bool>,
2529 #[serde(default, skip_serializing_if = "Option::is_none")]
2530 pub origin: Option<CatalogOrigin>,
2531 #[serde(default, skip_serializing_if = "Option::is_none")]
2532 pub requested_declarations_digest: Option<String>,
2533 #[serde(default, skip_serializing_if = "Option::is_none")]
2534 pub approved_declarations_digest: Option<String>,
2535 #[serde(default, skip_serializing_if = "Option::is_none")]
2538 pub approved_declarations: Option<ProviderDeclarations>,
2539 #[serde(default, skip_serializing_if = "Option::is_none")]
2540 pub requested_declarations: Option<ProviderDeclarations>,
2541}
2542
2543impl CatalogEntry {
2544 #[must_use]
2546 pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
2547 self.display_name = display_name;
2548 self
2549 }
2550
2551 #[must_use]
2553 pub fn new(
2554 module_id: impl Into<String>,
2555 roles: Vec<ProviderRole>,
2556 control_ops: Vec<String>,
2557 ) -> Self {
2558 Self {
2559 module_id: module_id.into(),
2560 ready: default_true(),
2561 display_name: None,
2562 not_ready: None,
2563 module_version: None,
2564 provenance: None,
2565 roles,
2566 control_ops,
2567 capabilities: None,
2568 self_signals: None,
2569 events: None,
2570 operation_delivery: BTreeMap::new(),
2571 operation_payload: BTreeMap::new(),
2572 flow_operations: None,
2573 operation_deferral: None,
2574 confirm_operations: None,
2575 rich_ui: None,
2576 role_declarations: BTreeMap::new(),
2577 nonce_verified: false,
2578 incarnation: None,
2579 spawn: None,
2580 first_party: None,
2581 origin: None,
2582 requested_declarations_digest: None,
2583 approved_declarations_digest: None,
2584 approved_declarations: None,
2585 requested_declarations: None,
2586 }
2587 }
2588
2589 #[must_use]
2591 pub fn with_operation_payload(
2592 mut self,
2593 operation_payload: BTreeMap<String, OperationPayload>,
2594 ) -> Self {
2595 self.operation_payload = operation_payload;
2596 self
2597 }
2598
2599 #[must_use]
2602 pub fn with_flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
2603 self.flow_operations = flow_operations;
2604 self
2605 }
2606
2607 #[must_use]
2609 pub fn with_operation_deferral(mut self, operations: Option<BTreeMap<String, bool>>) -> Self {
2610 self.operation_deferral = operations;
2611 self
2612 }
2613
2614 #[must_use]
2617 pub fn with_confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
2618 self.confirm_operations = confirm_operations;
2619 self
2620 }
2621
2622 #[must_use]
2624 pub fn with_ready(mut self, ready: bool) -> Self {
2625 self.ready = ready;
2626 self
2627 }
2628
2629 #[must_use]
2631 pub fn with_not_ready(mut self, not_ready: Option<NotReadyReason>) -> Self {
2632 self.not_ready = not_ready;
2633 self
2634 }
2635
2636 #[must_use]
2638 pub fn with_module_version(mut self, module_version: Option<String>) -> Self {
2639 self.module_version = module_version;
2640 self
2641 }
2642
2643 #[must_use]
2645 pub fn with_provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
2646 self.provenance = provenance;
2647 self
2648 }
2649
2650 #[must_use]
2652 pub fn with_capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
2653 self.capabilities = capabilities;
2654 self
2655 }
2656
2657 #[must_use]
2659 pub fn with_self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
2660 self.self_signals = self_signals;
2661 self
2662 }
2663
2664 #[must_use]
2666 pub fn with_events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
2667 self.events = events;
2668 self
2669 }
2670
2671 #[must_use]
2674 pub fn with_operation_delivery(
2675 mut self,
2676 operation_delivery: BTreeMap<String, OperationDelivery>,
2677 ) -> Self {
2678 self.operation_delivery = operation_delivery;
2679 self
2680 }
2681
2682 #[must_use]
2684 pub fn with_rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
2685 self.rich_ui = rich_ui;
2686 self
2687 }
2688
2689 #[must_use]
2691 pub fn with_role_declarations(
2692 mut self,
2693 role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2694 ) -> Self {
2695 self.role_declarations = role_declarations;
2696 self
2697 }
2698
2699 #[must_use]
2701 pub fn with_nonce_verified(mut self, nonce_verified: bool) -> Self {
2702 self.nonce_verified = nonce_verified;
2703 self
2704 }
2705}
2706
2707fn is_false(value: &bool) -> bool {
2708 !value
2709}
2710
2711#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2713pub struct NotReadyReason {
2714 pub reason: String,
2719 #[serde(default, skip_serializing_if = "Option::is_none")]
2722 pub capability: Option<String>,
2723}
2724
2725impl NotReadyReason {
2726 pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
2727 pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
2728}
2729
2730#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2731pub struct CapabilityRequirementStatus {
2732 pub consumer: String,
2733 pub capability: String,
2734 pub need: String,
2735 pub verdict: String,
2736 pub episode_seq: u64,
2737 pub config_satisfiable: bool,
2738 pub runtime_available: bool,
2739 pub detail: String,
2740}
2741
2742#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2743pub struct SupervisorRescanResult {
2744 pub added: Vec<String>,
2745 pub removed: Vec<String>,
2746 pub changed_pending_reload: Vec<String>,
2747 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2760 pub enabled_changes: Vec<String>,
2761 pub unchanged: u32,
2762 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2770 pub preview: bool,
2771 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2789 pub restart_required: Vec<String>,
2790 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2794 pub capability_warnings: Vec<String>,
2795 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2802 pub module_actions: Vec<RescanModuleAction>,
2803 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2807 pub earlier_pending: Vec<String>,
2808 #[serde(default, skip_serializing_if = "Option::is_none")]
2811 pub expect: Option<RescanExpect>,
2812}
2813
2814#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
2830#[serde(rename_all = "snake_case")]
2831pub enum ModuleProtocol {
2832 #[default]
2836 Subc,
2837 None,
2846}
2847
2848#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2860#[non_exhaustive]
2861pub struct SupervisorEntry {
2862 #[serde(default, skip_serializing_if = "Option::is_none")]
2865 pub waiting_for_previous_pid: Option<u32>,
2866 pub module_id: String,
2867 pub state: String,
2868 #[serde(default, skip_serializing_if = "Option::is_none")]
2872 pub admission_refused: Option<String>,
2873 #[serde(default, skip_serializing_if = "Option::is_none")]
2877 pub next_retry_at_ms: Option<u64>,
2878 pub enabled: bool,
2879 #[serde(default, skip_serializing_if = "Option::is_none")]
2882 pub configured_enabled: Option<bool>,
2883 pub live: bool,
2893 #[serde(default)]
2897 pub protocol: ModuleProtocol,
2898 #[serde(default, skip_serializing_if = "Option::is_none")]
2901 pub launch_nonce_env: Option<bool>,
2902 #[serde(default, skip_serializing_if = "Option::is_none")]
2908 pub launch_nonce_source: Option<String>,
2909 pub health: SupervisorHealthStatus,
2910 #[serde(default, skip_serializing_if = "Option::is_none")]
2913 pub pending_reload: Option<PendingReloadVerdict>,
2914 #[serde(default)]
2920 pub last_probe_ms: Option<u64>,
2921 #[serde(default, skip_serializing_if = "Option::is_none")]
2925 pub last_exit_code: Option<i32>,
2926 #[serde(default, skip_serializing_if = "Option::is_none")]
2930 pub last_exit_signal: Option<i32>,
2931 #[serde(default, skip_serializing_if = "Option::is_none")]
2935 pub last_exit_ms: Option<u64>,
2936 #[serde(default, skip_serializing_if = "Option::is_none")]
2939 pub last_exit_kind: Option<TerminalExitKind>,
2940 #[serde(default, skip_serializing_if = "Option::is_none")]
2957 pub restart_count: Option<u32>,
2958 #[serde(default, skip_serializing_if = "Option::is_none")]
2961 pub max_restarts: Option<u32>,
2962 #[serde(default, skip_serializing_if = "Option::is_none")]
2965 pub lifetime_restarts: Option<u32>,
2966 #[serde(default, skip_serializing_if = "Option::is_none")]
2970 pub spawn_generation: Option<u64>,
2971 #[serde(default, skip_serializing_if = "Option::is_none")]
2981 pub restart_window_secs: Option<u64>,
2982 #[serde(default, skip_serializing_if = "Option::is_none")]
2986 pub drain_timeout_ms: Option<u64>,
2987 #[serde(default, skip_serializing_if = "Option::is_none")]
2990 pub restart_backoff_ms: Option<u64>,
2991 #[serde(default, skip_serializing_if = "Option::is_none")]
2994 pub restart_max_backoff_ms: Option<u64>,
2995 #[serde(default, skip_serializing_if = "Option::is_none")]
3008 pub resources: Option<ChildResourceUsage>,
3009 #[serde(default, skip_serializing_if = "Option::is_none")]
3011 pub tree: Option<TreeReading>,
3012 #[serde(default, skip_serializing_if = "Option::is_none")]
3018 pub tree_unavailable: Option<String>,
3019 #[serde(default, skip_serializing_if = "Option::is_none")]
3021 pub cpu_last_hour: Option<CpuLastHour>,
3022}
3023
3024impl SupervisorEntry {
3025 #[must_use]
3027 pub fn with_next_retry_at_ms(mut self, next_retry_at_ms: Option<u64>) -> Self {
3028 self.next_retry_at_ms = next_retry_at_ms;
3029 self
3030 }
3031
3032 #[must_use]
3034 pub fn new(
3035 module_id: impl Into<String>,
3036 state: impl Into<String>,
3037 enabled: bool,
3038 live: bool,
3039 health: SupervisorHealthStatus,
3040 ) -> Self {
3041 Self {
3042 module_id: module_id.into(),
3043 state: state.into(),
3044 admission_refused: None,
3045 next_retry_at_ms: None,
3046 waiting_for_previous_pid: None,
3047 enabled,
3048 configured_enabled: None,
3049 live,
3050 protocol: ModuleProtocol::default(),
3051 launch_nonce_env: None,
3052 launch_nonce_source: None,
3053 health,
3054 pending_reload: None,
3055 last_probe_ms: None,
3056 last_exit_code: None,
3057 last_exit_signal: None,
3058 last_exit_ms: None,
3059 last_exit_kind: None,
3060 restart_count: None,
3061 max_restarts: None,
3062 lifetime_restarts: None,
3063 spawn_generation: None,
3064 restart_window_secs: None,
3065 drain_timeout_ms: None,
3066 restart_backoff_ms: None,
3067 restart_max_backoff_ms: None,
3068 resources: None,
3069 tree: None,
3070 tree_unavailable: None,
3071 cpu_last_hour: None,
3072 }
3073 }
3074
3075 #[must_use]
3077 pub fn with_admission_refused(mut self, reason: Option<String>) -> Self {
3078 self.admission_refused = reason;
3079 self
3080 }
3081
3082 #[must_use]
3084 pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
3085 self.protocol = protocol;
3086 self
3087 }
3088
3089 #[must_use]
3091 pub fn with_configured_enabled(mut self, configured_enabled: Option<bool>) -> Self {
3092 self.configured_enabled = configured_enabled;
3093 self
3094 }
3095
3096 #[must_use]
3098 pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
3099 self.launch_nonce_env = launch_nonce_env;
3100 self
3101 }
3102
3103 pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
3104 self.launch_nonce_source = source;
3105 self
3106 }
3107
3108 #[must_use]
3109 pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
3110 self.waiting_for_previous_pid = pid;
3111 self
3112 }
3113
3114 #[must_use]
3116 pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
3117 self.pending_reload = pending_reload;
3118 self
3119 }
3120
3121 #[must_use]
3123 pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
3124 self.last_probe_ms = last_probe_ms;
3125 self
3126 }
3127
3128 #[must_use]
3130 pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
3131 self.last_exit_code = last_exit_code;
3132 self
3133 }
3134
3135 #[must_use]
3137 pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
3138 self.last_exit_signal = last_exit_signal;
3139 self
3140 }
3141
3142 #[must_use]
3144 pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
3145 self.last_exit_ms = last_exit_ms;
3146 self
3147 }
3148
3149 #[must_use]
3151 pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
3152 self.last_exit_kind = last_exit_kind;
3153 self
3154 }
3155
3156 #[must_use]
3158 pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
3159 self.restart_count = restart_count;
3160 self
3161 }
3162
3163 #[must_use]
3165 pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
3166 self.max_restarts = max_restarts;
3167 self
3168 }
3169
3170 #[must_use]
3172 pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
3173 self.lifetime_restarts = lifetime_restarts;
3174 self
3175 }
3176
3177 #[must_use]
3179 pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
3180 self.spawn_generation = spawn_generation;
3181 self
3182 }
3183
3184 #[must_use]
3186 pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
3187 self.restart_window_secs = restart_window_secs;
3188 self
3189 }
3190
3191 #[must_use]
3193 pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
3194 self.drain_timeout_ms = drain_timeout_ms;
3195 self
3196 }
3197
3198 #[must_use]
3200 pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
3201 self.restart_backoff_ms = restart_backoff_ms;
3202 self
3203 }
3204
3205 #[must_use]
3207 pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
3208 self.restart_max_backoff_ms = restart_max_backoff_ms;
3209 self
3210 }
3211
3212 #[must_use]
3214 pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
3215 self.resources = resources;
3216 self
3217 }
3218
3219 #[must_use]
3221 pub fn with_tree(mut self, tree: Option<TreeReading>) -> Self {
3222 self.tree = tree;
3223 self
3224 }
3225
3226 #[must_use]
3228 pub fn with_tree_unavailable(mut self, reason: Option<String>) -> Self {
3229 self.tree_unavailable = reason;
3230 self
3231 }
3232}
3233
3234#[derive(Debug, Clone, PartialEq)]
3237pub enum ChildResourceUsage {
3238 Measured(ChildResourceReading),
3239 Unavailable {
3240 reason: ChildResourceUnavailableReason,
3241 },
3242 Unknown {
3245 tag: String,
3246 body: OrderedJsonObject,
3247 },
3248}
3249
3250#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3253#[non_exhaustive]
3254pub struct ChildResourceReading {
3255 pub memory_bytes: u64,
3258 pub memory_kind: ChildMemoryKind,
3259 #[serde(default, skip_serializing_if = "Option::is_none")]
3262 pub swap_bytes: Option<u64>,
3263 pub cpu_user_ms: u64,
3267 pub cpu_system_ms: u64,
3270}
3271
3272impl ChildResourceReading {
3273 #[must_use]
3275 pub fn new(
3276 memory_bytes: u64,
3277 memory_kind: ChildMemoryKind,
3278 cpu_user_ms: u64,
3279 cpu_system_ms: u64,
3280 ) -> Self {
3281 Self {
3282 memory_bytes,
3283 memory_kind,
3284 cpu_user_ms,
3285 cpu_system_ms,
3286 swap_bytes: None,
3287 }
3288 }
3289
3290 #[must_use]
3292 pub fn with_swap_bytes(mut self, swap_bytes: Option<u64>) -> Self {
3293 self.swap_bytes = swap_bytes;
3294 self
3295 }
3296}
3297
3298open_string_enum! {
3299 ChildMemoryKind {
3301 PhysFootprint => "phys_footprint",
3305 ResidentSet => "resident_set",
3308 WindowsWorkingSet => "windows_working_set",
3311 }
3312}
3313
3314open_string_enum! {
3315 ChildResourceUnavailableReason {
3317 NotRunning => "not_running",
3319 UnsupportedPlatform => "unsupported_platform",
3321 Unreadable => "unreadable",
3324 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
3327 }
3328}
3329
3330#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
3331#[serde(rename_all = "snake_case")]
3332pub enum SupervisorHealthStatus {
3333 Ok,
3334 Degraded,
3335 Failing,
3336 Unresponsive,
3337 Unknown,
3338}
3339
3340#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3341pub struct SupervisorHealthEntry {
3342 pub module_id: String,
3343 pub status: SupervisorHealthStatus,
3344 #[serde(default, skip_serializing_if = "Option::is_none")]
3350 pub detail: Option<String>,
3351 #[serde(default, skip_serializing_if = "Option::is_none")]
3356 pub metrics: Option<serde_json::Value>,
3357 pub consecutive_failures: u32,
3358 #[serde(default)]
3361 pub late_answer_count: u64,
3362 #[serde(default, skip_serializing_if = "Option::is_none")]
3364 pub last_late_answer_latency_ms: Option<u64>,
3365 #[serde(default)]
3370 pub last_action: Option<String>,
3371 #[serde(default)]
3374 pub last_action_ms: Option<u64>,
3375 #[serde(default, skip_serializing_if = "Option::is_none")]
3388 pub last_probe_ms: Option<u64>,
3389}
3390
3391#[cfg(test)]
3392mod tests {
3393 #[test]
3394 fn configured_enabled_omission_preserves_exact_old_list_bytes() {
3395 let entry = r#"{"module_id":"provider","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null}"#;
3396 let decoded: SupervisorEntry = serde_json::from_str(entry).unwrap();
3397 assert_eq!(decoded.configured_enabled, None);
3398 assert_eq!(serde_json::to_string(&decoded).unwrap(), entry);
3399 }
3400
3401 #[test]
3402 fn configured_enabled_values_round_trip_in_list() {
3403 for enabled in [false, true] {
3404 let entry = SupervisorEntry::new(
3405 "provider",
3406 "running",
3407 true,
3408 true,
3409 SupervisorHealthStatus::Unknown,
3410 )
3411 .with_configured_enabled(Some(enabled));
3412 let entry_json = serde_json::to_value(&entry).unwrap();
3413 assert_eq!(entry_json["configured_enabled"], enabled);
3414 assert_eq!(
3415 serde_json::from_value::<SupervisorEntry>(entry_json).unwrap(),
3416 entry
3417 );
3418 }
3419 }
3420
3421 #[test]
3422 fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
3423 let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
3424 volume_serial_number: u64::MAX,
3425 file_id: [
3426 0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
3427 ],
3428 };
3429 let agreement = super::RunningImageAgreement::Match { evidence };
3430 let encoded = serde_json::to_string(&agreement).unwrap();
3431 assert!(encoded.contains("windows_spawn_file_id"));
3432 assert_eq!(
3433 serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
3434 agreement
3435 );
3436 }
3437
3438 #[test]
3439 fn unix_running_image_evidence_keeps_original_wire_bytes() {
3440 assert_eq!(
3441 serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
3442 device: 7,
3443 inode: 11
3444 })
3445 .unwrap(),
3446 "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
3447 );
3448 assert_eq!(
3449 serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
3450 digest: "abc".to_owned()
3451 })
3452 .unwrap(),
3453 "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
3454 );
3455 }
3456 use super::*;
3457 use subc_protocol::{BindIdentity, RouteTarget};
3458
3459 #[test]
3460 fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
3461 let entry = TerminalEntry {
3462 daemon_incarnation: Some("daemon-before-restart".into()),
3463 exit_code: Some(1),
3464 exit_signal: None,
3465 at_ms: 1_700_000_000_123,
3466 disposition: TerminalDisposition::Restarting,
3467 exit_kind: Some(TerminalExitKind::DeliberateSeverance),
3468 disposition_detail: None,
3469 };
3470 let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
3471 assert_eq!(
3472 serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
3473 ["exit_kind"],
3474 "deliberate_severance"
3475 );
3476
3477 #[derive(serde::Deserialize)]
3478 struct LegacyTerminalEntry {
3479 exit_code: Option<i32>,
3480 exit_signal: Option<i32>,
3481 at_ms: u64,
3482 disposition: TerminalDisposition,
3483 }
3484
3485 let decoded: LegacyTerminalEntry =
3486 serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
3487 assert_eq!(decoded.exit_code, Some(1));
3488 assert_eq!(decoded.exit_signal, None);
3489 assert_eq!(decoded.at_ms, 1_700_000_000_123);
3490 assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
3491
3492 let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
3493 let future: TerminalEntry =
3494 serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
3495 assert_eq!(
3496 future.exit_kind,
3497 Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
3498 );
3499 }
3500
3501 #[test]
3502 fn terminal_incarnation_is_optional_for_older_daemons() {
3503 let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
3504 "at_ms": 123,
3505 "disposition": "stopped"
3506 }))
3507 .unwrap();
3508 let encoded = serde_json::to_value(&entry).unwrap();
3509 assert_eq!(
3510 (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
3511 (None, None)
3512 );
3513 }
3514
3515 #[test]
3516 fn route_poll_uses_kind_field() {
3517 let body = serde_json::to_value(ClientControlRequest::RoutePoll {
3518 route_channel: 7,
3519 route_epoch: 11,
3520 kind: PollKind::Status,
3521 })
3522 .unwrap();
3523
3524 assert_eq!(body["op"], "route.poll");
3525 assert_eq!(body["route_epoch"], 11);
3526 assert_eq!(body["kind"], "status");
3527 assert!(body.get("op").is_some());
3528 }
3529
3530 #[test]
3531 fn route_open_is_internally_tagged() {
3532 let request = ClientControlRequest::RouteOpen {
3533 busy_refusals: None,
3534 target: RouteTarget::ToolProvider {
3535 module_id: "aft".to_string(),
3536 },
3537 identity: BindIdentity::new("opencode", "session-1"),
3538 consumer_identity: None,
3539 consumer_capabilities: None,
3540 role_versions: None,
3541 admission_facts: None,
3542 scope: None,
3543 };
3544
3545 let body = serde_json::to_value(request).unwrap();
3546 assert_eq!(body["op"], "route.open");
3547 assert_eq!(body["target"]["kind"], "tool_provider");
3548 assert!(body.get("consumer_identity").is_none());
3549 assert!(body.get("consumer_capabilities").is_none());
3550 assert!(body.get("role_versions").is_none());
3551 }
3552
3553 #[test]
3554 fn route_open_without_optional_fields_still_decodes() {
3555 let body = serde_json::json!({
3556 "op": "route.open",
3557 "target": { "kind": "tool_provider", "module_id": "aft" },
3558 "identity": {
3559 "project_root": "/tmp/project",
3560 "harness": "opencode",
3561 "session": "session-1"
3562 }
3563 });
3564
3565 let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
3566 let ClientControlRequest::RouteOpen {
3567 consumer_identity,
3568 consumer_capabilities,
3569 role_versions,
3570 admission_facts,
3571 ..
3572 } = decoded
3573 else {
3574 panic!("decoded wrong request variant");
3575 };
3576 assert_eq!(consumer_identity, None);
3577 assert_eq!(consumer_capabilities, None);
3578 assert_eq!(role_versions, None);
3579 assert_eq!(admission_facts, None);
3580 }
3581
3582 #[test]
3583 fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
3584 let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
3585 let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
3586 match decoded {
3587 ClientControlPush::RouteClosed {
3588 excluded_subscriptions,
3589 terminal,
3590 ..
3591 } => {
3592 assert_eq!(excluded_subscriptions, 0);
3593 assert_eq!(terminal, None);
3594 }
3595 other => panic!("unexpected push: {other:?}"),
3596 }
3597 assert!(!serde_json::to_string(&decoded)
3598 .unwrap()
3599 .contains("terminal"));
3600 }
3601
3602 #[test]
3603 fn old_route_closed_decoder_ignores_new_terminal_field() {
3604 #[derive(serde::Deserialize)]
3605 #[serde(tag = "op")]
3606 enum LegacyClientControlPush {
3607 #[serde(rename = "route.closed")]
3608 RouteClosed {
3609 module_id: String,
3610 reason: RouteCloseReason,
3611 drained: bool,
3612 abandoned: u32,
3613 },
3614 }
3615
3616 let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
3617 let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
3618 match decoded {
3619 LegacyClientControlPush::RouteClosed {
3620 module_id,
3621 reason,
3622 drained,
3623 abandoned,
3624 } => {
3625 assert_eq!(module_id, "aft-tools");
3626 assert_eq!(reason, RouteCloseReason::Crash);
3627 assert!(!drained);
3628 assert_eq!(abandoned, 0);
3629 }
3630 }
3631 }
3632
3633 #[test]
3634 fn supervisor_routes_is_a_control_plane_request() {
3635 let body = serde_json::json!({
3636 "op": "supervisor.routes",
3637 "module_id": "aft"
3638 });
3639
3640 let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
3641 assert_eq!(serde_json::to_value(request).unwrap(), body);
3642 }
3643
3644 #[test]
3645 fn diagnostic_string_enums_retain_unknown_wire_values() {
3646 let reason: RunningImageUnavailableReason =
3647 serde_json::from_str("\"future_reason\"").unwrap();
3648 let disposition: TerminalDisposition =
3649 serde_json::from_str("\"future_disposition\"").unwrap();
3650
3651 assert_eq!(
3652 reason,
3653 RunningImageUnavailableReason::Unknown("future_reason".to_string())
3654 );
3655 assert_eq!(
3656 disposition,
3657 TerminalDisposition::Unknown("future_disposition".to_string())
3658 );
3659 }
3660
3661 #[test]
3662 fn diagnostic_string_enums_preserve_existing_wire_names() {
3663 let names = [
3664 (RunningImageUnavailableReason::NotRunning, "not_running"),
3665 (
3666 RunningImageUnavailableReason::UnsupportedPlatform,
3667 "unsupported_platform",
3668 ),
3669 (
3670 RunningImageUnavailableReason::RunningExecutableUnreadable,
3671 "running_executable_unreadable",
3672 ),
3673 (
3674 RunningImageUnavailableReason::RunningExecutablePermissionDenied,
3675 "running_executable_permission_denied",
3676 ),
3677 (
3678 RunningImageUnavailableReason::ProcessHidden,
3679 "process_hidden",
3680 ),
3681 (
3682 RunningImageUnavailableReason::SpawnedPathUnreadable,
3683 "spawned_path_unreadable",
3684 ),
3685 (RunningImageUnavailableReason::HashFailed, "hash_failed"),
3686 (
3687 RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
3688 "process_identity_unconfirmed",
3689 ),
3690 ];
3691 for (value, expected) in names {
3692 let wire = serde_json::to_string(&value).unwrap();
3693 assert_eq!(wire, format!("\"{expected}\""));
3694 let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
3695 assert_eq!(decoded, value);
3696 }
3697
3698 for (value, expected) in [
3699 (TerminalDisposition::Stopped, "stopped"),
3700 (TerminalDisposition::Disabled, "disabled"),
3701 (TerminalDisposition::Failed, "failed"),
3702 (TerminalDisposition::Restarting, "restarting"),
3703 (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
3704 ] {
3705 let wire = serde_json::to_string(&value).unwrap();
3706 assert_eq!(wire, format!("\"{expected}\""));
3707 let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
3708 assert_eq!(decoded, value);
3709 }
3710 }
3711
3712 #[test]
3713 fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
3714 let entry = SupervisorEntry::new(
3715 "waiting-module",
3716 "starting",
3717 true,
3718 false,
3719 SupervisorHealthStatus::Unknown,
3720 );
3721 let old_wire = serde_json::to_value(&entry).unwrap();
3722 assert!(old_wire.get("waiting_for_previous_pid").is_none());
3723 let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3724 assert_eq!(decoded.waiting_for_previous_pid, None);
3725 let entry = entry.with_waiting_for_previous_pid(Some(42));
3726 let wire = serde_json::to_value(&entry).unwrap();
3727 assert_eq!(wire["waiting_for_previous_pid"], 42);
3728 let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3729 assert_eq!(decoded.waiting_for_previous_pid, Some(42));
3730 }
3731
3732 #[test]
3733 fn diagnostic_string_enums_reject_non_string_bodies() {
3734 assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
3735 assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
3736 }
3737
3738 #[test]
3739 fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
3740 let body = serde_json::json!({
3741 "op": "supervisor.provenance",
3742 "daemon": {
3743 "daemon_build": {},
3744 "daemon_observed": {
3745 "running_image": {
3746 "status": "unavailable",
3747 "reason": "not_running"
3748 }
3749 }
3750 },
3751 "modules": [
3752 {
3753 "module_id": "future",
3754 "module_declared": { "status": "unverifiable" },
3755 "daemon_observed": {
3756 "running_image": {
3757 "status": "unavailable",
3758 "reason": "future_reason"
3759 }
3760 }
3761 },
3762 {
3763 "module_id": "healthy-a",
3764 "module_declared": { "status": "unverifiable" },
3765 "daemon_observed": {
3766 "running_image": {
3767 "status": "match",
3768 "evidence": {
3769 "method": "linux_proc_sha256",
3770 "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3771 }
3772 }
3773 }
3774 },
3775 {
3776 "module_id": "healthy-b",
3777 "module_declared": { "status": "unverifiable" },
3778 "daemon_observed": {
3779 "running_image": {
3780 "status": "unavailable",
3781 "reason": "unsupported_platform"
3782 }
3783 }
3784 }
3785 ]
3786 });
3787
3788 let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
3789 let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
3790 panic!("decoded wrong response variant");
3791 };
3792 assert_eq!(modules.len(), 3);
3793 assert_eq!(modules[0].module_id, "future");
3794 assert_eq!(
3795 modules[0].daemon_observed.running_image,
3796 RunningImageAgreement::Unavailable {
3797 reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
3798 }
3799 );
3800 assert_eq!(modules[1].module_id, "healthy-a");
3801 assert_eq!(modules[2].module_id, "healthy-b");
3802 }
3803
3804 #[test]
3805 fn tagged_unknown_values_retain_tag_and_body() {
3806 macro_rules! assert_unknown_round_trip {
3807 ($ty:ident, $field:literal, $value:expr) => {
3808 let value = $value;
3809 let wire = serde_json::to_string(&value).unwrap();
3810 let decoded: $ty = serde_json::from_str(&wire).unwrap();
3811 match decoded {
3812 $ty::Unknown { tag, body } => {
3813 assert_eq!(tag, value[$field].as_str().unwrap());
3814 assert_eq!(serde_json::to_value(&body).unwrap(), value);
3815 }
3816 _ => panic!("decoded known variant"),
3817 }
3818 };
3819 }
3820
3821 assert_unknown_round_trip!(
3822 ModuleDeclaredProvenance,
3823 "status",
3824 serde_json::json!({"status": "future", "build": {"version": 7}})
3825 );
3826 assert_unknown_round_trip!(
3827 RunningImageAgreement,
3828 "status",
3829 serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
3830 );
3831 assert_unknown_round_trip!(
3832 RunningImageEvidence,
3833 "method",
3834 serde_json::json!({"method": "future", "digest": "abc"})
3835 );
3836 assert_unknown_round_trip!(
3837 SupervisorRouteConsumer,
3838 "kind",
3839 serde_json::json!({"kind": "future", "module_id": "m"})
3840 );
3841 assert_unknown_round_trip!(
3842 StderrCaptureState,
3843 "state",
3844 serde_json::json!({"state": "future", "reason": "because"})
3845 );
3846 assert_unknown_round_trip!(
3847 StderrTailEntry,
3848 "kind",
3849 serde_json::json!({"kind": "future", "text": "line"})
3850 );
3851 assert_unknown_round_trip!(
3852 ChildResourceUsage,
3853 "status",
3854 serde_json::json!({"status": "future", "memory_bytes": 1})
3855 );
3856 }
3857
3858 #[test]
3859 fn child_resource_usage_round_trips_both_known_states() {
3860 let measured = ChildResourceUsage::Measured(ChildResourceReading {
3861 memory_bytes: 0,
3862 memory_kind: ChildMemoryKind::ResidentSet,
3863 swap_bytes: Some(0),
3864 cpu_user_ms: 0,
3865 cpu_system_ms: 0,
3866 });
3867 let wire = serde_json::to_value(&measured).unwrap();
3868 assert_eq!(
3869 wire,
3870 serde_json::json!({
3871 "status": "measured",
3872 "memory_bytes": 0,
3873 "memory_kind": "resident_set",
3874 "swap_bytes": 0,
3875 "cpu_user_ms": 0,
3876 "cpu_system_ms": 0
3877 })
3878 );
3879 assert_eq!(
3880 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3881 measured
3882 );
3883
3884 let unavailable = ChildResourceUsage::Unavailable {
3885 reason: ChildResourceUnavailableReason::NotRunning,
3886 };
3887 let wire = serde_json::to_value(&unavailable).unwrap();
3888 assert_eq!(
3889 wire,
3890 serde_json::json!({"status": "unavailable", "reason": "not_running"})
3891 );
3892 assert_eq!(
3893 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3894 unavailable
3895 );
3896 }
3897
3898 #[test]
3899 fn a_stderr_line_decodes_with_and_without_its_capture_time() {
3900 let stamped: StderrTailEntry = serde_json::from_str(
3904 r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
3905 )
3906 .unwrap();
3907 assert_eq!(
3908 stamped,
3909 StderrTailEntry::Line {
3910 text: "boom".to_string(),
3911 truncated: true,
3912 at_ms: Some(1_789_801_440_685),
3913 }
3914 );
3915 let unstamped: StderrTailEntry =
3916 serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
3917 assert_eq!(
3918 unstamped,
3919 StderrTailEntry::Line {
3920 text: "boom".to_string(),
3921 truncated: false,
3922 at_ms: None,
3923 }
3924 );
3925 assert_eq!(
3928 serde_json::to_string(&unstamped).unwrap(),
3929 r#"{"kind":"line","text":"boom"}"#
3930 );
3931 assert_eq!(
3932 serde_json::to_value(&stamped).unwrap()["at_ms"],
3933 serde_json::json!(1_789_801_440_685u64)
3934 );
3935 }
3936
3937 #[test]
3938 fn tagged_unknown_values_round_trip_the_original_json() {
3939 let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
3940 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3941 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3942 }
3943
3944 #[test]
3945 fn tagged_unknown_values_round_trip_trailing_tag() {
3946 let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
3947 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3948 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3949
3950 let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
3951 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3952 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3953 }
3954
3955 #[test]
3956 fn tagged_unknown_values_round_trip_middle_tag() {
3957 let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
3958 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3959 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3960
3961 let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
3962 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3963 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3964 }
3965
3966 #[test]
3967 fn tagged_unknown_values_round_trip_deep_payload() {
3968 let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
3969 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3970 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3971
3972 let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
3973 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3974 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3975 }
3976
3977 #[test]
3978 fn tagged_unknown_values_reject_non_object_bodies() {
3979 for wire in ["42", r#""future""#, "[]"] {
3980 assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
3981 assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
3982 }
3983 }
3984
3985 #[test]
3986 fn duplicate_discriminators_reject_without_panicking() {
3987 assert_eq!(
3988 serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
3989 .unwrap(),
3990 ModuleDeclaredProvenance::Unverifiable
3991 );
3992 match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
3993 .unwrap()
3994 {
3995 ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
3996 _ => panic!("future discriminator decoded as a known variant"),
3997 }
3998
3999 let wires = [
4000 r#"{"status":"reported","status":"unverifiable"}"#,
4001 r#"{"status":"unverifiable","status":"reported"}"#,
4002 r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
4003 r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
4004 ];
4005
4006 for wire in wires {
4007 let result =
4008 std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
4009 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
4010 assert!(
4011 result.unwrap().is_err(),
4012 "duplicate discriminator decoded: {wire}"
4013 );
4014 }
4015
4016 let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
4017 let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
4018 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
4019 assert!(
4020 result.unwrap().is_err(),
4021 "duplicate discriminator decoded: {wire}"
4022 );
4023 }
4024
4025 #[test]
4026 fn nested_unknown_values_round_trip_without_normalizing_member_order() {
4027 let known_wire =
4028 r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
4029 let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
4030 assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
4031
4032 for wire in [
4033 r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
4034 r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
4035 ] {
4036 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
4037 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4038 }
4039
4040 for wire in [
4041 r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
4042 r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
4043 ] {
4044 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
4045 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4046 }
4047
4048 let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
4049 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
4050 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4051
4052 let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
4053 let decoded: StderrTail = serde_json::from_str(wire).unwrap();
4054 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4055 }
4056
4057 #[test]
4058 fn tagged_unknown_member_does_not_discard_known_siblings() {
4059 let body = serde_json::json!({
4060 "modules": [{
4061 "module_id": "target",
4062 "routes": [
4063 {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
4064 {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
4065 ]
4066 }]
4067 });
4068 let decoded: ClientControlResponse = serde_json::from_value(
4069 serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
4070 )
4071 .unwrap();
4072 let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
4073 panic!("decoded wrong response variant");
4074 };
4075 assert_eq!(modules[0].routes.len(), 2);
4076 assert_eq!(
4077 modules[0].routes[1].consumer,
4078 SupervisorRouteConsumer::Direct { connection_id: 7 }
4079 );
4080 }
4081}
4082
4083#[cfg(test)]
4084mod launch_nonce_redaction_tests {
4085 use super::*;
4086
4087 const NONCE: &str = "nonce-f00dfeed1234abcd";
4088
4089 fn identity() -> ConsumerIdentity {
4090 ConsumerIdentity {
4091 module_id: "wernicke".to_string(),
4092 launch_nonce: NONCE.to_string(),
4093 }
4094 }
4095
4096 #[test]
4097 fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
4098 let printed = format!("{:?}", identity());
4099 assert!(printed.contains("wernicke"), "{printed}");
4100 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
4101 }
4102
4103 #[test]
4104 fn route_open_request_debug_never_prints_the_nonce() {
4105 let request = ClientControlRequest::RouteOpen {
4106 busy_refusals: None,
4107 target: subc_protocol::RouteTarget::ToolProvider {
4108 module_id: "broca".to_string(),
4109 },
4110 identity: subc_protocol::BindIdentity::new("test".to_string(), "session".to_string()),
4111 consumer_identity: Some(identity()),
4112 consumer_capabilities: None,
4113 role_versions: None,
4114 admission_facts: None,
4115 scope: None,
4116 };
4117 let printed = format!("{request:?}");
4118 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
4119 }
4120}
4121
4122#[cfg(test)]
4123mod reader_skew_tests {
4124 use super::*;
4125 use serde_json::{json, Value};
4126
4127 fn catalog() -> Value {
4128 json!({"module_id": "provider", "roles": [], "control_ops": []})
4129 }
4130
4131 fn reply() -> Value {
4132 json!({"op": "route.open", "route_channel": 7, "route_epoch": 11})
4133 }
4134
4135 fn target() -> Value {
4136 json!({
4137 "incarnation": "daemon", "kind": "spawn", "spawn": 17,
4138 "authority_epoch": 23, "first_party": true,
4139 "approved_declarations_digest": "approved"
4140 })
4141 }
4142
4143 fn request() -> Value {
4144 json!({
4145 "op": "route.open",
4146 "target": {"kind": "tool_provider", "module_id": "provider"},
4147 "identity": {"harness": "test", "session": "session-1"}
4148 })
4149 }
4150
4151 #[test]
4152 fn reader_skew_catalog_optional_spawn_fields_and_legacy_omission() {
4153 let old: CatalogEntry = serde_json::from_value(catalog()).unwrap();
4154 let built = CatalogEntry::new("provider", vec![], vec![]);
4155 assert_eq!(old, built);
4156 assert_eq!(old.first_party, None);
4157 let old_bytes = serde_json::to_value(&old).unwrap();
4158 let additions = json!({
4159 "incarnation": "daemon", "spawn": 17, "first_party": false,
4160 "origin": "development", "requested_declarations_digest": "requested",
4161 "approved_declarations_digest": "approved"
4162 });
4163 let mut body = catalog();
4164 for (key, value) in additions.as_object().unwrap() {
4165 assert!(old_bytes.get(key).is_none(), "{key}");
4166 body[key] = value.clone();
4167 }
4168 let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
4169 let encoded = serde_json::to_value(&decoded).unwrap();
4170 for (key, value) in additions.as_object().unwrap() {
4171 assert_eq!(&encoded[key], value, "{key}");
4172 }
4173 assert_eq!(decoded.first_party, Some(false));
4174 assert_eq!(decoded.origin, Some(CatalogOrigin::Development));
4175 }
4176
4177 #[test]
4178 fn reader_skew_catalog_filtered_declarations_keep_provider_owned_keys() {
4179 let mut body = catalog();
4180 body["requested_declarations"] = json!({"provider": {"future": {"scope": ["write"]}}});
4181 body["approved_declarations"] = json!({"provider": {"future": {"scope": ["read"]}}});
4182 let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
4183 let encoded = serde_json::to_value(decoded).unwrap();
4184 for key in ["requested_declarations", "approved_declarations"] {
4185 assert_eq!(encoded[key], body[key]);
4186 }
4187 let unfiltered: CatalogEntry = serde_json::from_value(catalog()).unwrap();
4188 assert_eq!(unfiltered.approved_declarations, None);
4189 assert_eq!(unfiltered.requested_declarations, None);
4190 }
4191
4192 #[test]
4193 fn reader_skew_catalog_unknown_origin_is_other() {
4194 let mut body = catalog();
4195 body["origin"] = json!("future-origin");
4196 let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
4197 assert_eq!(decoded.origin, Some(CatalogOrigin::Other));
4198 }
4199
4200 #[test]
4201 fn reader_skew_catalog_spawn_refuses_unsafe_integers() {
4202 let mut body = catalog();
4203 body["spawn"] = json!(9_007_199_254_740_991_u64);
4204 let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
4205 assert_eq!(decoded.spawn, Some(9_007_199_254_740_991));
4206 for invalid in [
4207 json!(9_007_199_254_740_992_u64),
4208 json!(-1),
4209 json!(1.5),
4210 json!("17"),
4211 ] {
4212 body["spawn"] = invalid;
4213 assert!(serde_json::from_value::<CatalogEntry>(body.clone()).is_err());
4214 }
4215 }
4216
4217 #[test]
4218 fn reader_skew_catalog_watch_request_uses_subscription_op() {
4219 let body = json!({"op": "catalog.watch"});
4220 let request: CatalogWatchRequest = serde_json::from_value(body.clone()).unwrap();
4221 assert_eq!(request, CatalogWatchRequest::new());
4222 assert_eq!(serde_json::to_value(request).unwrap(), body);
4223 assert_eq!(CatalogWatchRequest::OP, "catalog.watch");
4224 for invalid in [json!({}), json!({"op": "activity.subscribe"})] {
4225 assert!(serde_json::from_value::<CatalogWatchRequest>(invalid).is_err());
4226 }
4227 }
4228
4229 #[test]
4230 fn reader_skew_catalog_watch_push_carries_generation_without_ack() {
4231 for generation in [0, 19, 42] {
4232 let body = json!({"op": "catalog.watch", "generation": generation});
4233 let push: CatalogWatchResponse = serde_json::from_value(body.clone()).unwrap();
4234 assert_eq!(push, CatalogWatchResponse::new(generation));
4235 assert_eq!(serde_json::to_value(push).unwrap(), body);
4236 }
4237 assert_eq!(CatalogWatchResponse::OP, "catalog.watch");
4238 for invalid in [
4239 json!({"op": "catalog.watch"}),
4240 json!({"op": "activity.subscribe", "generation": 1}),
4241 ] {
4242 assert!(serde_json::from_value::<CatalogWatchResponse>(invalid).is_err());
4243 }
4244 }
4245
4246 #[test]
4247 fn reader_skew_route_open_reply_helpers_preserve_existing_decoder() {
4248 let mut body = reply();
4249 let legacy: ClientControlResponse = serde_json::from_value(body.clone()).unwrap();
4250 let empty = RouteOpenReplyExt::read_from(&body).unwrap();
4251 assert_eq!(empty, RouteOpenReplyExt::new());
4252 empty.write_to(&mut body).unwrap();
4253 assert_eq!(body, reply());
4254 body["target"] = target();
4255 let decoded = RouteOpenReplyExt::read_from(&body).unwrap();
4256 assert_eq!(
4257 decoded.target.as_ref().unwrap().kind,
4258 RouteOpenTargetKind::Spawn
4259 );
4260 let mut encoded = reply();
4261 RouteOpenReplyExt::new()
4262 .with_target(decoded.target)
4263 .write_to(&mut encoded)
4264 .unwrap();
4265 assert_eq!(encoded, body);
4266 assert_eq!(
4267 serde_json::from_value::<ClientControlResponse>(encoded.clone()).unwrap(),
4268 legacy
4269 );
4270 RouteOpenReplyExt::new().write_to(&mut encoded).unwrap();
4271 assert_eq!(encoded, reply());
4272 }
4273
4274 #[test]
4275 fn reader_skew_route_open_incomplete_target_is_unmarked() {
4276 let mut body = reply();
4277 body["target"] = target();
4278 assert!(RouteOpenReplyExt::read_from(&body)
4279 .unwrap()
4280 .target
4281 .is_some());
4282 for key in [
4283 "incarnation",
4284 "kind",
4285 "spawn",
4286 "authority_epoch",
4287 "first_party",
4288 "approved_declarations_digest",
4289 ] {
4290 let mut incomplete = body.clone();
4291 incomplete["target"].as_object_mut().unwrap().remove(key);
4292 assert_eq!(
4293 RouteOpenReplyExt::read_from(&incomplete).unwrap().target,
4294 None,
4295 "{key}"
4296 );
4297 }
4298 body["target"] = Value::Null;
4299 assert_eq!(RouteOpenReplyExt::read_from(&body).unwrap().target, None);
4300 }
4301
4302 #[test]
4303 fn reader_skew_route_open_non_spawn_kinds_ignore_spawn_authority() {
4304 for (kind, expected) in [
4305 ("prefix", RouteOpenTargetKind::Prefix),
4306 ("unsupervised", RouteOpenTargetKind::Unsupervised),
4307 ] {
4308 let mut body = reply();
4309 body["target"] = target();
4310 body["target"]["kind"] = json!(kind);
4311 body["target"]["spawn"] = json!("not-a-spawn");
4313 body["target"]["authority_epoch"] = json!(9_007_199_254_740_992_u64);
4314 body["target"]["approved_declarations_digest"] = json!(["not-a-digest"]);
4315 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4316 let target = ext.target.as_ref().unwrap();
4317 assert_eq!(target.kind, expected);
4318 assert_eq!(target.spawn, None);
4319 assert_eq!(target.authority_epoch, None);
4320 assert_eq!(target.approved_declarations_digest, None);
4321 assert!(!target.first_party);
4322 let mut encoded = reply();
4323 ext.write_to(&mut encoded).unwrap();
4324 for key in ["spawn", "authority_epoch", "approved_declarations_digest"] {
4325 assert!(encoded["target"].get(key).is_none());
4326 }
4327 }
4328 }
4329
4330 #[test]
4331 fn reader_skew_route_open_unknown_kind_is_not_spawn() {
4332 let mut body = reply();
4333 body["target"] = target();
4334 body["target"]["kind"] = json!("future-kind");
4335 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4336 let target = ext.target.unwrap();
4337 assert_eq!(target.kind, RouteOpenTargetKind::Unknown);
4338 assert_eq!(target.spawn, None);
4339 assert_eq!(target.authority_epoch, None);
4340 assert_eq!(target.approved_declarations_digest, None);
4341 assert!(!target.first_party);
4342 }
4343
4344 #[test]
4345 fn reader_skew_route_open_spawn_and_epoch_refuse_unsafe_integers() {
4346 for field in ["spawn", "authority_epoch"] {
4347 let mut body = reply();
4348 body["target"] = target();
4349 body["target"][field] = json!(9_007_199_254_740_991_u64);
4350 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4351 assert_eq!(
4352 serde_json::to_value(ext).unwrap()["target"][field],
4353 9_007_199_254_740_991_u64
4354 );
4355 for invalid in [
4356 json!(9_007_199_254_740_992_u64),
4357 json!(-1),
4358 json!(1.5),
4359 json!("17"),
4360 ] {
4361 body["target"][field] = invalid;
4362 assert!(RouteOpenReplyExt::read_from(&body).is_err(), "{field}");
4363 let mut incomplete = body.clone();
4364 incomplete["target"]
4365 .as_object_mut()
4366 .unwrap()
4367 .remove("incarnation");
4368 assert!(
4369 RouteOpenReplyExt::read_from(&incomplete).is_err(),
4370 "{field}"
4371 );
4372 }
4373 }
4374 }
4375
4376 #[test]
4377 fn reader_skew_route_open_request_helpers_preserve_existing_decoder() {
4378 let mut body = request();
4379 let legacy: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
4380 assert_eq!(
4381 RouteOpenRequestExt::read_from(&body).unwrap(),
4382 RouteOpenRequestExt::new()
4383 );
4384 RouteOpenRequestExt::new().write_to(&mut body).unwrap();
4385 assert_eq!(body, request());
4386 body["accepts_close_reasons"] = json!(["authority_changed", "future-reason"]);
4387 let decoded = RouteOpenRequestExt::read_from(&body).unwrap();
4388 assert_eq!(
4389 decoded.accepts_close_reasons,
4390 Some(vec!["authority_changed".into(), "future-reason".into()])
4391 );
4392 let mut encoded = request();
4393 RouteOpenRequestExt::new()
4394 .with_accepts_close_reasons(decoded.accepts_close_reasons)
4395 .write_to(&mut encoded)
4396 .unwrap();
4397 assert_eq!(encoded, body);
4398 assert_eq!(
4399 serde_json::from_value::<ClientControlRequest>(encoded.clone()).unwrap(),
4400 legacy
4401 );
4402 RouteOpenRequestExt::new().write_to(&mut encoded).unwrap();
4403 assert_eq!(encoded, request());
4404 assert_eq!(ROUTE_CLOSE_REASONS_CAPABILITY, "route-close-reasons/v1");
4405 }
4406
4407 #[test]
4408 fn reader_skew_route_open_helpers_refuse_other_bodies() {
4409 for mut body in [json!({}), json!([]), json!({"op": "catalog.list"})] {
4410 assert!(RouteOpenRequestExt::read_from(&body).is_err());
4411 assert!(RouteOpenReplyExt::read_from(&body).is_err());
4412 assert!(RouteOpenRequestExt::new().write_to(&mut body).is_err());
4413 assert!(RouteOpenReplyExt::new().write_to(&mut body).is_err());
4414 }
4415 }
4416
4417 #[test]
4418 fn reader_skew_route_open_target_constructor_validates_like_reader() {
4419 let spawn = RouteOpenTarget::new(
4420 "daemon",
4421 RouteOpenTargetKind::Spawn,
4422 Some(17),
4423 Some(23),
4424 true,
4425 Some("approved".into()),
4426 )
4427 .unwrap();
4428 assert_eq!(serde_json::to_value(spawn).unwrap(), target());
4429 for (spawn, epoch) in [(9_007_199_254_740_992, 23), (17, 9_007_199_254_740_992)] {
4430 assert!(RouteOpenTarget::new(
4431 "daemon",
4432 RouteOpenTargetKind::Spawn,
4433 Some(spawn),
4434 Some(epoch),
4435 true,
4436 Some("approved".into())
4437 )
4438 .is_err());
4439 }
4440 }
4441}
4442
4443#[cfg(test)]
4444mod claim_wire_tests {
4445 use super::*;
4446 use serde_json::{json, Value};
4447
4448 fn legacy_provenance() -> SupervisorModuleProvenance {
4449 SupervisorModuleProvenance {
4450 module_id: "worker".into(),
4451 module_declared: ModuleDeclaredProvenance::Unverifiable,
4452 daemon_observed: SupervisorObservedProcess {
4453 launch_nonce_source: None,
4454 pid: None,
4455 spawned_at_ms: None,
4456 spawned_from: None,
4457 running_image: RunningImageAgreement::Unavailable {
4458 reason: RunningImageUnavailableReason::NotRunning,
4459 },
4460 },
4461 }
4462 }
4463
4464 #[test]
4465 fn provenance_registration_companion_round_trip_preserves_legacy_entry() {
4466 let legacy = legacy_provenance();
4467 let original = serde_json::to_value(&legacy).unwrap();
4468 let absent = SupervisorModuleProvenanceExt::read_from(&original).unwrap();
4469 assert_eq!(absent.registration, None);
4470 let mut wire = original.clone();
4471 absent.write_to(&mut wire).unwrap();
4472 assert_eq!(wire, original);
4473 for (method, spelling) in [
4474 (RegistrationMethod::Channel, "channel"),
4475 (RegistrationMethod::Nonce, "nonce"),
4476 ] {
4477 let ext = SupervisorModuleProvenanceExt::new().with_registration(Some(method.clone()));
4478 ext.write_to(&mut wire).unwrap();
4479 assert_eq!(wire["registration"], spelling);
4480 assert_eq!(
4481 SupervisorModuleProvenanceExt::read_from(&wire).unwrap(),
4482 ext
4483 );
4484 let old_reader: SupervisorModuleProvenance =
4485 serde_json::from_value(wire.clone()).unwrap();
4486 assert_eq!(old_reader, legacy);
4487 assert_eq!(serde_json::to_value(old_reader).unwrap(), original);
4488 }
4489 absent.write_to(&mut wire).unwrap();
4490 assert_eq!(wire, original);
4491 for mut invalid in [Value::Null, json!([]), json!("entry")] {
4492 assert!(SupervisorModuleProvenanceExt::read_from(&invalid).is_err());
4493 assert!(absent.write_to(&mut invalid).is_err());
4494 }
4495 }
4496
4497 #[test]
4498 fn provenance_unknown_registration_is_not_channel_or_nonce() {
4499 let mut wire = serde_json::to_value(legacy_provenance()).unwrap();
4500 wire["registration"] = json!("future_method");
4501 let ext = SupervisorModuleProvenanceExt::read_from(&wire).unwrap();
4502 assert_eq!(ext.registration, Some(RegistrationMethod::Unknown));
4503 assert_ne!(ext.registration, Some(RegistrationMethod::Channel));
4504 assert_ne!(ext.registration, Some(RegistrationMethod::Nonce));
4505 wire["registration"] = json!(false);
4506 assert!(SupervisorModuleProvenanceExt::read_from(&wire).is_err());
4507 }
4508
4509 #[test]
4510 fn registration_declaration_golden_is_optional_open_and_source_compatible() {
4511 let original = serde_json::to_value(legacy_provenance()).unwrap();
4512 for declaration in ["declared", "undeclared", "not_applicable", "future_support"] {
4513 let mut golden = original.clone();
4514 golden["registration_declaration"] = json!(declaration);
4515 let extension = SupervisorModuleProvenanceExt::read_from(&golden).unwrap();
4516 assert_eq!(
4517 serde_json::to_value(&extension).unwrap(),
4518 json!({
4519 "registration_declaration": declaration
4520 })
4521 );
4522 let mut written = original.clone();
4523 extension.write_to(&mut written).unwrap();
4524 assert_eq!(written, golden);
4525 assert_eq!(
4526 serde_json::from_value::<SupervisorModuleProvenance>(golden).unwrap(),
4527 legacy_provenance()
4528 );
4529 SupervisorModuleProvenanceExt::new()
4530 .write_to(&mut written)
4531 .unwrap();
4532 assert_eq!(written, original);
4533 }
4534 }
4535
4536 #[test]
4537 fn admission_refusal_is_optional_and_open() {
4538 let entry = SupervisorEntry::new(
4539 "worker",
4540 "stopped",
4541 true,
4542 false,
4543 SupervisorHealthStatus::Unknown,
4544 );
4545 let original = serde_json::to_value(&entry).unwrap();
4546 assert!(original.get("admission_refused").is_none());
4547 let read: SupervisorEntry = serde_json::from_value(original.clone()).unwrap();
4548 assert_eq!(read.admission_refused, None);
4549 assert_eq!(serde_json::to_value(read).unwrap(), original);
4550 assert_eq!(
4551 REGISTRATION_CHANNEL_UNSUPPORTED,
4552 "registration_channel_unsupported"
4553 );
4554 for reason in [REGISTRATION_CHANNEL_UNSUPPORTED, "future_reason"] {
4555 let mut wire = original.clone();
4556 wire["admission_refused"] = json!(reason);
4557 let read: SupervisorEntry = serde_json::from_value(wire.clone()).unwrap();
4558 assert_eq!(read.admission_refused.as_deref(), Some(reason));
4559 assert_eq!(serde_json::to_value(read).unwrap(), wire);
4560 let built = entry.clone().with_admission_refused(Some(reason.into()));
4561 assert_eq!(serde_json::to_value(built).unwrap(), wire);
4562 }
4563 }
4564}