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    /// The schema rule the value at `path` broke, when validation can name a
56    /// single one. It holds schema text, so it is never serialized: a
57    /// serialized refusal keeps only the code and the pointer. Boxed so the
58    /// many `Result<_, Refusal>` returns stay small.
59    #[serde(skip)]
60    pub rule: Option<Box<RefusalRule>>,
61}
62impl Refusal {
63    pub fn new(code: RefusalCode, path: impl Into<String>, project_id: Option<String>) -> Self {
64        Self {
65            code,
66            path: path.into(),
67            project_id,
68            rule: None,
69        }
70    }
71
72    /// The same refusal, naming the rule that failed.
73    pub fn with_rule(mut self, rule: RefusalRule) -> Self {
74        self.rule = Some(Box::new(rule));
75        self
76    }
77}
78
79/// The rule a refused settings value broke, with the bound or the allowed
80/// values the schema declares. It never holds the refused value itself.
81#[derive(Clone, Debug, PartialEq, Eq)]
82#[non_exhaustive]
83pub enum RefusalRule {
84    /// `type`: the value, or a null, is not one of these JSON types.
85    Type { expected: Vec<String> },
86    /// `const`: only this value is allowed.
87    Const { value: Value },
88    /// `enum`: only these values are allowed.
89    Enum { values: Vec<Value> },
90    /// `x-ck-options` with `closed`: the value is not among the offered options.
91    ClosedOption,
92    /// `x-ck-kind: credential_ref`: only a vault reference is allowed.
93    Credential,
94    /// `oneOf`: the value matches none of the tagged variants.
95    Variant,
96    /// Text holds an `{env:...}` or `{file:...}` expansion.
97    Expansion,
98    /// An object is the old `{"env": ...}` or `{"file": ...}` reference form.
99    Reference,
100    /// `minLength`, counted in characters.
101    MinLength { bound: u64 },
102    /// `maxLength`, counted in characters.
103    MaxLength { bound: u64 },
104    /// `pattern`: text must match this regular expression.
105    Pattern { pattern: String },
106    /// `minimum`, or `exclusiveMinimum` when `exclusive`.
107    Minimum {
108        bound: serde_json::Number,
109        exclusive: bool,
110    },
111    /// `maximum`, or `exclusiveMaximum` when `exclusive`.
112    Maximum {
113        bound: serde_json::Number,
114        exclusive: bool,
115    },
116    /// `minItems`.
117    MinItems { bound: u64 },
118    /// `maxItems`.
119    MaxItems { bound: u64 },
120    /// `uniqueItems`: two list items are the same value.
121    UniqueItems,
122    /// Two list items carry the same `id`.
123    DuplicateId,
124    /// The object key is not declared by the schema.
125    Undeclared,
126    /// `required` or `x-ck-required`: the key is missing.
127    Required { key: String },
128    /// `x-ck-bound`: a workspace or project value moves the inherited value
129    /// the way the bound forbids.
130    Bound { bound: Bound },
131}
132impl std::fmt::Display for Refusal {
133    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134        write!(
135            f,
136            "{:?} at {} ({:?})",
137            self.code, self.path, self.project_id
138        )
139    }
140}
141impl std::error::Error for Refusal {}
142
143/// A rejected literal and an accepted vault reference use the same redacted
144/// record. Neither the opaque reference id nor a literal is retained in views.
145#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
146#[serde(tag = "kind", rename_all = "snake_case")]
147#[non_exhaustive]
148pub enum RecordedValue {
149    Value { value: Value },
150    Redacted { digest: Digest, redacted: bool },
151}
152impl RecordedValue {
153    pub fn new(value: Value) -> Self {
154        Self::Value { value }
155    }
156    pub fn redacted(value: &Value) -> Result<Self, CanonicalError> {
157        Ok(Self::Redacted {
158            digest: digest(PURPOSE_VALUE, value)?,
159            redacted: true,
160        })
161    }
162}
163
164/// Missing files are inputs, distinct from the digest of an empty document.
165#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
166#[serde(tag = "state", rename_all = "snake_case")]
167#[non_exhaustive]
168pub enum InputState {
169    Absent,
170    Present { digest: Digest },
171}
172
173#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
174#[non_exhaustive]
175pub struct InputVector {
176    pub inputs: BTreeMap<String, InputState>,
177}
178impl InputVector {
179    pub fn new(inputs: BTreeMap<String, InputState>) -> Self {
180        Self { inputs }
181    }
182    /// Compare the saved read set only. Unrelated writes do not stale a plan.
183    pub fn matches(&self, current: &Self) -> bool {
184        self.inputs
185            .iter()
186            .all(|(key, state)| current.inputs.get(key) == Some(state))
187    }
188}
189
190#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
191#[non_exhaustive]
192pub struct FieldChange {
193    pub module_id: String,
194    pub project_id: Option<String>,
195    pub path: String,
196    pub old: RecordedValue,
197    pub new: RecordedValue,
198    pub old_source: Layer,
199    pub new_source: Layer,
200    pub apply: ApplyKind,
201    pub reasons: Vec<String>,
202}
203impl FieldChange {
204    pub fn new(
205        module_id: impl Into<String>,
206        path: impl Into<String>,
207        old: RecordedValue,
208        new: RecordedValue,
209        apply: ApplyKind,
210    ) -> Self {
211        Self {
212            module_id: module_id.into(),
213            path: path.into(),
214            project_id: None,
215            old,
216            new,
217            old_source: Layer::Default,
218            new_source: Layer::Default,
219            apply,
220            reasons: Vec::new(),
221        }
222    }
223}
224
225#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
226#[non_exhaustive]
227pub struct Changeset {
228    pub fields: Vec<FieldChange>,
229    pub affected_projects: Vec<String>,
230    pub policy_changes: Vec<Value>,
231    pub launch_manifests: BTreeMap<String, Value>,
232    pub apply_plan: Value,
233}
234impl Changeset {
235    pub fn new() -> Self {
236        Self::default()
237    }
238}
239
240/// Immutable approval payload. The input vector includes subc.jsonc and every
241/// touched module's layers, declaration and covered program identities.
242#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
243#[non_exhaustive]
244pub struct Plan {
245    pub base_revision: u64,
246    pub base_generation: u64,
247    pub active_generations: BTreeMap<String, u64>,
248    pub daemon_incarnation: String,
249    pub input_vector: InputVector,
250    pub changeset: Changeset,
251}
252impl Plan {
253    pub fn new(
254        base_revision: u64,
255        base_generation: u64,
256        daemon_incarnation: impl Into<String>,
257        input_vector: InputVector,
258        changeset: Changeset,
259    ) -> Self {
260        Self {
261            base_revision,
262            base_generation,
263            daemon_incarnation: daemon_incarnation.into(),
264            active_generations: BTreeMap::new(),
265            input_vector,
266            changeset,
267        }
268    }
269    pub fn digest(&self) -> Result<Digest, CanonicalError> {
270        digest(
271            PURPOSE_PLAN,
272            &serde_json::to_value(self).map_err(|_| CanonicalError::Serialization)?,
273        )
274    }
275    pub fn check_fresh(&self, base_revision: u64, current: &InputVector) -> Result<(), Refusal> {
276        if self.base_revision != base_revision || !self.input_vector.matches(current) {
277            return Err(Refusal::new(RefusalCode::PlanStale, "", None));
278        }
279        Ok(())
280    }
281}
282
283/// Requests are strict; stored records and replies tolerate added fields.
284#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
285#[serde(deny_unknown_fields)]
286#[non_exhaustive]
287pub struct ApplyRequest {
288    pub digest: Digest,
289}
290impl ApplyRequest {
291    pub fn new(digest: Digest) -> Self {
292        Self { digest }
293    }
294}
295
296#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
297#[serde(rename_all = "snake_case")]
298#[non_exhaustive]
299pub enum GenerationState {
300    Planned,
301    Approved,
302    Pending,
303    Warming,
304    Active,
305    Failed,
306}
307
308/// The review surface actually checked for an approval, not a claim supplied by
309/// its requester. Development desktop review never implies app attestation.
310#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
311#[serde(rename_all = "snake_case")]
312pub enum ApprovalChannel {
313    OsPrompt,
314    PhoneCard,
315    AttestedDesktop,
316    UnverifiedDevelopmentDesktop,
317    /// A development placement under the compiled switch committed without
318    /// any approval surface.
319    DevelopmentPlacement,
320}
321
322impl ApprovalChannel {
323    pub const fn description(self) -> &'static str {
324        match self {
325            Self::OsPrompt => "OS prompt",
326            Self::PhoneCard => "phone card",
327            Self::AttestedDesktop => "attested desktop",
328            Self::UnverifiedDevelopmentDesktop => "development desktop (unverified)",
329            Self::DevelopmentPlacement => "development placement (no approval)",
330        }
331    }
332}
333
334#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
335#[non_exhaustive]
336pub struct Generation {
337    pub id: u64,
338    pub approval_channel: ApprovalChannel,
339    pub plan_digest: Digest,
340    pub input_vector: InputVector,
341    pub declaration_digests: BTreeMap<String, Digest>,
342    pub module_states: BTreeMap<String, GenerationState>,
343    pub active_generations: BTreeMap<String, u64>,
344    pub never_redeliver: Vec<String>,
345    pub development: bool,
346    pub changeset: Changeset,
347}
348impl Generation {
349    pub fn new(
350        id: u64,
351        approval_channel: ApprovalChannel,
352        plan_digest: Digest,
353        input_vector: InputVector,
354        changeset: Changeset,
355    ) -> Self {
356        Self {
357            id,
358            approval_channel,
359            plan_digest,
360            input_vector,
361            changeset,
362            declaration_digests: BTreeMap::new(),
363            module_states: BTreeMap::new(),
364            active_generations: BTreeMap::new(),
365            never_redeliver: Vec::new(),
366            development: false,
367        }
368    }
369}
370
371#[cfg(test)]
372mod approval_channel_tests {
373    use super::*;
374
375    #[test]
376    fn approval_channel_is_required_closed_and_preserves_unverified_wording() {
377        for (channel, wire, words) in [
378            (
379                ApprovalChannel::DevelopmentPlacement,
380                "development_placement",
381                "development placement (no approval)",
382            ),
383            (ApprovalChannel::OsPrompt, "os_prompt", "OS prompt"),
384            (ApprovalChannel::PhoneCard, "phone_card", "phone card"),
385            (
386                ApprovalChannel::AttestedDesktop,
387                "attested_desktop",
388                "attested desktop",
389            ),
390            (
391                ApprovalChannel::UnverifiedDevelopmentDesktop,
392                "unverified_development_desktop",
393                "development desktop (unverified)",
394            ),
395        ] {
396            assert_eq!(serde_json::to_value(channel).unwrap(), wire);
397            assert_eq!(channel.description(), words);
398            let generation = Generation::new(
399                1,
400                channel,
401                crate::raw_digest(b"plan"),
402                InputVector::default(),
403                Changeset::new(),
404            );
405            let mut encoded = serde_json::to_value(&generation).unwrap();
406            assert_eq!(
407                serde_json::from_value::<Generation>(encoded.clone()).unwrap(),
408                generation
409            );
410            encoded.as_object_mut().unwrap().remove("approval_channel");
411            assert!(serde_json::from_value::<Generation>(encoded).is_err());
412        }
413        assert!(
414            serde_json::from_str::<ApprovalChannel>("\"verified_development_desktop\"").is_err()
415        );
416    }
417}
418
419#[cfg(test)]
420mod tests {
421    use super::*;
422    use serde_json::json;
423    #[test]
424    fn records_contract_plan_binding_and_evolution() {
425        let d = digest(PURPOSE_VALUE, &json!(1)).unwrap();
426        let input = InputVector::new(BTreeMap::from([
427            ("subc.jsonc".into(), InputState::Absent),
428            ("project".into(), InputState::Present { digest: d }),
429        ]));
430        let plan = Plan::new(7, 2, "incarnation", input.clone(), Changeset::new());
431        let mut current = input.clone();
432        current
433            .inputs
434            .insert("unrelated".into(), InputState::Absent);
435        assert!(plan.check_fresh(7, &current).is_ok());
436        current.inputs.insert("project".into(), InputState::Absent);
437        assert_eq!(
438            plan.check_fresh(7, &current).unwrap_err().code,
439            RefusalCode::PlanStale
440        );
441        assert!(plan.check_fresh(8, &input).is_err());
442        let mut changed = plan.clone();
443        changed.base_revision += 1;
444        assert_ne!(plan.digest().unwrap(), changed.digest().unwrap());
445        let mut wire = serde_json::to_value(&plan).unwrap();
446        wire["future"] = json!(true);
447        assert!(serde_json::from_value::<Plan>(wire).is_ok());
448        let request = json!({"digest":plan.digest().unwrap(), "future":true});
449        assert!(serde_json::from_value::<ApplyRequest>(request).is_err());
450    }
451}