Skip to main content

subc_control/
config.rs

1//! Opt-in config-gate client wire. Plans never commit until `config.apply` is
2//! approved; a terminal's claim to have displayed a diff grants no authority.
3
4use serde::{Deserialize, Serialize};
5pub use subc_config::{ApprovalChannel, Digest, Generation, Plan};
6
7pub const CONFIG_GATE_CAPABILITY: &str = "config.gate";
8
9/// Standalone bodies keep additions out of the legacy exhaustive control enum.
10/// Unknown request fields are refused, including caller-authored review claims.
11#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
12#[serde(tag = "op", deny_unknown_fields)]
13#[non_exhaustive]
14pub enum ConfigControlRequest {
15    #[serde(rename = "config.status")]
16    Status {},
17    #[serde(rename = "config.plan")]
18    Plan {},
19    #[serde(rename = "config.apply")]
20    Apply { digest: Digest },
21    #[serde(rename = "config.stamp")]
22    Stamp {},
23    #[serde(rename = "config.unstamp")]
24    Unstamp {},
25    #[serde(rename = "config.history")]
26    History {},
27    #[serde(rename = "config.rollback")]
28    Rollback { generation: u64 },
29    #[serde(rename = "config.place_program")]
30    PlaceProgram {
31        module_id: String,
32        path: String,
33        sha256: Digest,
34        /// Offline manifest reported by the placement tool, not executed by the daemon.
35        #[serde(default, skip_serializing_if = "Option::is_none")]
36        manifest: Option<serde_json::Value>,
37    },
38}
39
40impl ConfigControlRequest {
41    pub fn op(&self) -> &'static str {
42        match self {
43            Self::Status {} => "config.status",
44            Self::Plan {} => "config.plan",
45            Self::Apply { .. } => "config.apply",
46            Self::Stamp {} => "config.stamp",
47            Self::Unstamp {} => "config.unstamp",
48            Self::History {} => "config.history",
49            Self::Rollback { .. } => "config.rollback",
50            Self::PlaceProgram { .. } => "config.place_program",
51        }
52    }
53}
54
55/// The trusted surface renders the entire plan, not just the digest.
56#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
57#[non_exhaustive]
58pub struct ConfigPlanView {
59    pub digest: Digest,
60    pub base_revision: u64,
61    pub plan: Plan,
62}
63
64impl ConfigPlanView {
65    pub fn new(plan: Plan) -> Result<Self, subc_config::CanonicalError> {
66        Ok(Self {
67            digest: plan.digest()?,
68            base_revision: plan.base_revision,
69            plan,
70        })
71    }
72}
73
74/// The durable review channel for a retained or pruned generation.
75#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
76#[non_exhaustive]
77pub struct ConfigApprovalRecord {
78    pub generation: u64,
79    pub channel: ApprovalChannel,
80}
81
82impl ConfigApprovalRecord {
83    pub fn new(generation: u64, channel: ApprovalChannel) -> Self {
84        Self {
85            generation,
86            channel,
87        }
88    }
89}
90
91/// Diagnostic strings are extensible; they never grant approval authority.
92#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
93#[non_exhaustive]
94pub struct ConfigStatus {
95    pub approval_channels: Vec<ConfigApprovalRecord>,
96    pub state: String,
97    pub integrity: String,
98    pub revision: u64,
99    pub base_revision: u64,
100    pub pending_proposals: u64,
101    pub anchor_pending: bool,
102    pub ungated_modules: Vec<String>,
103    pub ungated_inputs: Vec<String>,
104    pub gated_modules: Vec<String>,
105    pub interpreter_only_covered: Vec<String>,
106    pub approved_but_inactive: Vec<serde_json::Value>,
107    pub development_switches: Vec<String>,
108    pub missing_approval_surfaces: Vec<String>,
109    pub warnings: Vec<String>,
110}
111
112#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
113#[serde(tag = "op")]
114#[non_exhaustive]
115pub enum ConfigControlResponse {
116    #[serde(rename = "config.status")]
117    Status { status: ConfigStatus },
118    #[serde(rename = "config.plan")]
119    Plan { view: ConfigPlanView },
120    #[serde(rename = "config.stamp")]
121    Stamp { view: ConfigPlanView },
122    #[serde(rename = "config.unstamp")]
123    Unstamp { view: ConfigPlanView },
124    #[serde(rename = "config.rollback")]
125    Rollback { view: ConfigPlanView },
126    #[serde(rename = "config.apply")]
127    Applied {
128        generation: u64,
129        #[serde(default)]
130        restart_required: bool,
131    },
132    #[serde(rename = "config.history")]
133    History {
134        generations: Vec<Generation>,
135        pruned: Vec<serde_json::Value>,
136    },
137    #[serde(rename = "config.place_program")]
138    ProgramPlaced {
139        #[serde(default, skip_serializing_if = "Option::is_none")]
140        generation: Option<u64>,
141    },
142}
143
144#[cfg(test)]
145mod tests {
146    #[test]
147    fn config_wire_program_placement_names_and_optional_generation() {
148        use super::*;
149        let body = serde_json::json!({"op":"config.place_program","module_id":"demo","path":"/bin/demo","sha256":format!("sha256:{}", "a".repeat(64))});
150        let request: ConfigControlRequest = serde_json::from_value(body.clone()).unwrap();
151        assert_eq!(request.op(), "config.place_program");
152        assert_eq!(serde_json::to_value(request).unwrap(), body);
153        assert!(matches!(
154            serde_json::from_value::<ConfigControlResponse>(
155                serde_json::json!({"op":"config.place_program"})
156            )
157            .unwrap(),
158            ConfigControlResponse::ProgramPlaced { generation: None }
159        ));
160        let response = ConfigControlResponse::ProgramPlaced {
161            generation: Some(3),
162        };
163        assert_eq!(
164            serde_json::to_value(response).unwrap(),
165            serde_json::json!({"op":"config.place_program","generation":3})
166        );
167    }
168    #[test]
169    fn config_wire_applied_reports_restart_required_and_defaults_absent_to_false() {
170        use super::*;
171        let response = ConfigControlResponse::Applied {
172            generation: 7,
173            restart_required: true,
174        };
175        assert_eq!(
176            serde_json::to_value(response).unwrap(),
177            serde_json::json!({"op":"config.apply", "generation":7, "restart_required":true})
178        );
179        assert_eq!(
180            serde_json::from_value::<ConfigControlResponse>(
181                serde_json::json!({"op":"config.apply", "generation":7})
182            )
183            .unwrap(),
184            ConfigControlResponse::Applied {
185                generation: 7,
186                restart_required: false,
187            }
188        );
189        assert_eq!(
190            serde_json::to_value(ConfigControlResponse::Applied {
191                generation: 7,
192                restart_required: false,
193            })
194            .unwrap()["restart_required"],
195            false
196        );
197    }
198
199    #[test]
200    fn config_wire_status_and_history_preserve_unverified_approval_channel() {
201        use super::*;
202        let channel = ApprovalChannel::UnverifiedDevelopmentDesktop;
203        let mut status = ConfigStatus::default();
204        status
205            .approval_channels
206            .push(ConfigApprovalRecord::new(1, channel));
207        let generation = Generation::new(
208            1,
209            channel,
210            subc_config::raw_digest(b"plan"),
211            subc_config::InputVector::default(),
212            subc_config::Changeset::new(),
213        );
214        for response in [
215            ConfigControlResponse::Status { status },
216            ConfigControlResponse::History {
217                generations: vec![generation],
218                pruned: vec![],
219            },
220        ] {
221            let encoded = serde_json::to_string(&response).unwrap();
222            assert!(encoded.contains("unverified_development_desktop"));
223            assert_eq!(
224                serde_json::from_str::<ConfigControlResponse>(&encoded).unwrap(),
225                response
226            );
227        }
228    }
229    use super::*;
230    use serde_json::json;
231
232    #[test]
233    fn config_wire_requests_are_strict_and_round_trip() {
234        for body in [
235            json!({"op":"config.status"}),
236            json!({"op":"config.plan"}),
237            json!({"op":"config.apply", "digest":subc_config::raw_digest(b"plan")}),
238            json!({"op":"config.stamp"}),
239            json!({"op":"config.unstamp"}),
240            json!({"op":"config.history"}),
241            json!({"op":"config.rollback", "generation":4}),
242        ] {
243            let request: ConfigControlRequest = serde_json::from_value(body.clone()).unwrap();
244            assert_eq!(body["op"], request.op());
245            assert_eq!(serde_json::to_value(&request).unwrap(), body);
246            let mut claimed = body;
247            claimed["reviewed"] = json!(true);
248            assert!(serde_json::from_value::<ConfigControlRequest>(claimed).is_err());
249        }
250        assert!(
251            serde_json::from_value::<ConfigControlRequest>(json!({"op":"config.apply"})).is_err()
252        );
253    }
254
255    #[test]
256    fn config_wire_plan_view_and_status_tolerate_reply_extensions() {
257        let plan = Plan::new(7, 3, "daemon", Default::default(), Default::default());
258        let view = ConfigPlanView::new(plan.clone()).unwrap();
259        assert_eq!(view.digest, plan.digest().unwrap());
260        let response = ConfigControlResponse::Stamp { view };
261        let mut body = serde_json::to_value(&response).unwrap();
262        body["future"] = json!(true);
263        assert_eq!(
264            serde_json::from_value::<ConfigControlResponse>(body).unwrap(),
265            response
266        );
267        let status = ConfigControlResponse::Status {
268            status: ConfigStatus::default(),
269        };
270        assert_eq!(
271            serde_json::from_value::<ConfigControlResponse>(serde_json::to_value(&status).unwrap())
272                .unwrap(),
273            status
274        );
275    }
276}