Skip to main content

subc_config/
records.rs

1use crate::{digest, CanonicalError, Digest, PURPOSE_PLAN, PURPOSE_VALUE};
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4use std::collections::BTreeMap;
5
6#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
7#[serde(rename_all = "snake_case")]
8#[non_exhaustive]
9pub enum Layer {
10    Default,
11    User,
12    Workspace,
13    Project,
14}
15
16#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
17#[serde(rename_all = "snake_case")]
18#[non_exhaustive]
19pub enum ApplyKind {
20    Live,
21    ModuleRestart,
22    DaemonRestart,
23    NextSupervision,
24    RouteRebind,
25}
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(rename_all = "snake_case")]
29#[non_exhaustive]
30pub enum Bound {
31    RaiseOnly,
32    LowerOnly,
33    SubsetOnly,
34}
35
36/// Serializable refusals deliberately contain no submitted values or schema text.
37#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(rename_all = "snake_case")]
39#[non_exhaustive]
40pub enum RefusalCode {
41    SchemaInvalid,
42    LayerForbidden,
43    ValueInvalid,
44    BoundViolated,
45    CredentialShared,
46    PlanStale,
47}
48
49#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
50#[non_exhaustive]
51pub struct Refusal {
52    pub code: RefusalCode,
53    pub path: String,
54    pub project_id: Option<String>,
55}
56impl Refusal {
57    pub fn new(code: RefusalCode, path: impl Into<String>, project_id: Option<String>) -> Self {
58        Self {
59            code,
60            path: path.into(),
61            project_id,
62        }
63    }
64}
65impl std::fmt::Display for Refusal {
66    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67        write!(
68            f,
69            "{:?} at {} ({:?})",
70            self.code, self.path, self.project_id
71        )
72    }
73}
74impl std::error::Error for Refusal {}
75
76/// A rejected literal and an accepted vault reference use the same redacted
77/// record. Neither the opaque reference id nor a literal is retained in views.
78#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
79#[serde(tag = "kind", rename_all = "snake_case")]
80#[non_exhaustive]
81pub enum RecordedValue {
82    Value { value: Value },
83    Redacted { digest: Digest, redacted: bool },
84}
85impl RecordedValue {
86    pub fn new(value: Value) -> Self {
87        Self::Value { value }
88    }
89    pub fn redacted(value: &Value) -> Result<Self, CanonicalError> {
90        Ok(Self::Redacted {
91            digest: digest(PURPOSE_VALUE, value)?,
92            redacted: true,
93        })
94    }
95}
96
97/// Missing files are inputs, distinct from the digest of an empty document.
98#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
99#[serde(tag = "state", rename_all = "snake_case")]
100#[non_exhaustive]
101pub enum InputState {
102    Absent,
103    Present { digest: Digest },
104}
105
106#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
107#[non_exhaustive]
108pub struct InputVector {
109    pub inputs: BTreeMap<String, InputState>,
110}
111impl InputVector {
112    pub fn new(inputs: BTreeMap<String, InputState>) -> Self {
113        Self { inputs }
114    }
115    /// Compare the saved read set only. Unrelated writes do not stale a plan.
116    pub fn matches(&self, current: &Self) -> bool {
117        self.inputs
118            .iter()
119            .all(|(key, state)| current.inputs.get(key) == Some(state))
120    }
121}
122
123#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
124#[non_exhaustive]
125pub struct FieldChange {
126    pub module_id: String,
127    pub project_id: Option<String>,
128    pub path: String,
129    pub old: RecordedValue,
130    pub new: RecordedValue,
131    pub old_source: Layer,
132    pub new_source: Layer,
133    pub apply: ApplyKind,
134    pub reasons: Vec<String>,
135}
136impl FieldChange {
137    pub fn new(
138        module_id: impl Into<String>,
139        path: impl Into<String>,
140        old: RecordedValue,
141        new: RecordedValue,
142        apply: ApplyKind,
143    ) -> Self {
144        Self {
145            module_id: module_id.into(),
146            path: path.into(),
147            project_id: None,
148            old,
149            new,
150            old_source: Layer::Default,
151            new_source: Layer::Default,
152            apply,
153            reasons: Vec::new(),
154        }
155    }
156}
157
158#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
159#[non_exhaustive]
160pub struct Changeset {
161    pub fields: Vec<FieldChange>,
162    pub affected_projects: Vec<String>,
163    pub policy_changes: Vec<Value>,
164    pub launch_manifests: BTreeMap<String, Value>,
165    pub apply_plan: Value,
166}
167impl Changeset {
168    pub fn new() -> Self {
169        Self::default()
170    }
171}
172
173/// Immutable approval payload. The input vector includes subc.jsonc and every
174/// touched module's layers, declaration and covered program identities.
175#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
176#[non_exhaustive]
177pub struct Plan {
178    pub base_revision: u64,
179    pub base_generation: u64,
180    pub active_generations: BTreeMap<String, u64>,
181    pub daemon_incarnation: String,
182    pub input_vector: InputVector,
183    pub changeset: Changeset,
184}
185impl Plan {
186    pub fn new(
187        base_revision: u64,
188        base_generation: u64,
189        daemon_incarnation: impl Into<String>,
190        input_vector: InputVector,
191        changeset: Changeset,
192    ) -> Self {
193        Self {
194            base_revision,
195            base_generation,
196            daemon_incarnation: daemon_incarnation.into(),
197            active_generations: BTreeMap::new(),
198            input_vector,
199            changeset,
200        }
201    }
202    pub fn digest(&self) -> Result<Digest, CanonicalError> {
203        digest(
204            PURPOSE_PLAN,
205            &serde_json::to_value(self).map_err(|_| CanonicalError::Serialization)?,
206        )
207    }
208    pub fn check_fresh(&self, base_revision: u64, current: &InputVector) -> Result<(), Refusal> {
209        if self.base_revision != base_revision || !self.input_vector.matches(current) {
210            return Err(Refusal::new(RefusalCode::PlanStale, "", None));
211        }
212        Ok(())
213    }
214}
215
216/// Requests are strict; stored records and replies tolerate added fields.
217#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
218#[serde(deny_unknown_fields)]
219#[non_exhaustive]
220pub struct ApplyRequest {
221    pub digest: Digest,
222}
223impl ApplyRequest {
224    pub fn new(digest: Digest) -> Self {
225        Self { digest }
226    }
227}
228
229#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
230#[serde(rename_all = "snake_case")]
231#[non_exhaustive]
232pub enum GenerationState {
233    Planned,
234    Approved,
235    Pending,
236    Warming,
237    Active,
238    Failed,
239}
240
241/// The review surface actually checked for an approval, not a claim supplied by
242/// its requester. Development desktop review never implies app attestation.
243#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
244#[serde(rename_all = "snake_case")]
245pub enum ApprovalChannel {
246    OsPrompt,
247    PhoneCard,
248    AttestedDesktop,
249    UnverifiedDevelopmentDesktop,
250    /// A development placement under the compiled switch committed without
251    /// any approval surface.
252    DevelopmentPlacement,
253}
254
255impl ApprovalChannel {
256    pub const fn description(self) -> &'static str {
257        match self {
258            Self::OsPrompt => "OS prompt",
259            Self::PhoneCard => "phone card",
260            Self::AttestedDesktop => "attested desktop",
261            Self::UnverifiedDevelopmentDesktop => "development desktop (unverified)",
262            Self::DevelopmentPlacement => "development placement (no approval)",
263        }
264    }
265}
266
267#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
268#[non_exhaustive]
269pub struct Generation {
270    pub id: u64,
271    pub approval_channel: ApprovalChannel,
272    pub plan_digest: Digest,
273    pub input_vector: InputVector,
274    pub declaration_digests: BTreeMap<String, Digest>,
275    pub module_states: BTreeMap<String, GenerationState>,
276    pub active_generations: BTreeMap<String, u64>,
277    pub never_redeliver: Vec<String>,
278    pub development: bool,
279    pub changeset: Changeset,
280}
281impl Generation {
282    pub fn new(
283        id: u64,
284        approval_channel: ApprovalChannel,
285        plan_digest: Digest,
286        input_vector: InputVector,
287        changeset: Changeset,
288    ) -> Self {
289        Self {
290            id,
291            approval_channel,
292            plan_digest,
293            input_vector,
294            changeset,
295            declaration_digests: BTreeMap::new(),
296            module_states: BTreeMap::new(),
297            active_generations: BTreeMap::new(),
298            never_redeliver: Vec::new(),
299            development: false,
300        }
301    }
302}
303
304#[cfg(test)]
305mod approval_channel_tests {
306    use super::*;
307
308    #[test]
309    fn approval_channel_is_required_closed_and_preserves_unverified_wording() {
310        for (channel, wire, words) in [
311            (
312                ApprovalChannel::DevelopmentPlacement,
313                "development_placement",
314                "development placement (no approval)",
315            ),
316            (ApprovalChannel::OsPrompt, "os_prompt", "OS prompt"),
317            (ApprovalChannel::PhoneCard, "phone_card", "phone card"),
318            (
319                ApprovalChannel::AttestedDesktop,
320                "attested_desktop",
321                "attested desktop",
322            ),
323            (
324                ApprovalChannel::UnverifiedDevelopmentDesktop,
325                "unverified_development_desktop",
326                "development desktop (unverified)",
327            ),
328        ] {
329            assert_eq!(serde_json::to_value(channel).unwrap(), wire);
330            assert_eq!(channel.description(), words);
331            let generation = Generation::new(
332                1,
333                channel,
334                crate::raw_digest(b"plan"),
335                InputVector::default(),
336                Changeset::new(),
337            );
338            let mut encoded = serde_json::to_value(&generation).unwrap();
339            assert_eq!(
340                serde_json::from_value::<Generation>(encoded.clone()).unwrap(),
341                generation
342            );
343            encoded.as_object_mut().unwrap().remove("approval_channel");
344            assert!(serde_json::from_value::<Generation>(encoded).is_err());
345        }
346        assert!(
347            serde_json::from_str::<ApprovalChannel>("\"verified_development_desktop\"").is_err()
348        );
349    }
350}
351
352#[cfg(test)]
353mod tests {
354    use super::*;
355    use serde_json::json;
356    #[test]
357    fn records_contract_plan_binding_and_evolution() {
358        let d = digest(PURPOSE_VALUE, &json!(1)).unwrap();
359        let input = InputVector::new(BTreeMap::from([
360            ("subc.jsonc".into(), InputState::Absent),
361            ("project".into(), InputState::Present { digest: d }),
362        ]));
363        let plan = Plan::new(7, 2, "incarnation", input.clone(), Changeset::new());
364        let mut current = input.clone();
365        current
366            .inputs
367            .insert("unrelated".into(), InputState::Absent);
368        assert!(plan.check_fresh(7, &current).is_ok());
369        current.inputs.insert("project".into(), InputState::Absent);
370        assert_eq!(
371            plan.check_fresh(7, &current).unwrap_err().code,
372            RefusalCode::PlanStale
373        );
374        assert!(plan.check_fresh(8, &input).is_err());
375        let mut changed = plan.clone();
376        changed.base_revision += 1;
377        assert_ne!(plan.digest().unwrap(), changed.digest().unwrap());
378        let mut wire = serde_json::to_value(&plan).unwrap();
379        wire["future"] = json!(true);
380        assert!(serde_json::from_value::<Plan>(wire).is_ok());
381        let request = json!({"digest":plan.digest().unwrap(), "future":true});
382        assert!(serde_json::from_value::<ApplyRequest>(request).is_err());
383    }
384}