subc-config 0.1.12

Shared configuration policy, canonical digests and approval records for subc.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
use crate::{digest, CanonicalError, Digest, PURPOSE_PLAN, PURPOSE_VALUE};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Layer {
    Default,
    User,
    Workspace,
    Project,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ApplyKind {
    Live,
    ModuleRestart,
    DaemonRestart,
    NextSupervision,
    RouteRebind,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Bound {
    RaiseOnly,
    LowerOnly,
    SubsetOnly,
}

/// Serializable refusals deliberately contain no submitted values or schema text.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum RefusalCode {
    SchemaInvalid,
    LayerForbidden,
    ValueInvalid,
    BoundViolated,
    CredentialShared,
    PlanStale,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Refusal {
    pub code: RefusalCode,
    pub path: String,
    pub project_id: Option<String>,
    /// The schema rule the value at `path` broke, when validation can name a
    /// single one. It holds schema text, so it is never serialized: a
    /// serialized refusal keeps only the code and the pointer. Boxed so the
    /// many `Result<_, Refusal>` returns stay small.
    #[serde(skip)]
    pub rule: Option<Box<RefusalRule>>,
}
impl Refusal {
    pub fn new(code: RefusalCode, path: impl Into<String>, project_id: Option<String>) -> Self {
        Self {
            code,
            path: path.into(),
            project_id,
            rule: None,
        }
    }

    /// The same refusal, naming the rule that failed.
    pub fn with_rule(mut self, rule: RefusalRule) -> Self {
        self.rule = Some(Box::new(rule));
        self
    }
}

/// The rule a refused settings value broke, with the bound or the allowed
/// values the schema declares. It never holds the refused value itself.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum RefusalRule {
    /// `type`: the value, or a null, is not one of these JSON types.
    Type { expected: Vec<String> },
    /// `const`: only this value is allowed.
    Const { value: Value },
    /// `enum`: only these values are allowed.
    Enum { values: Vec<Value> },
    /// `x-ck-options` with `closed`: the value is not among the offered options.
    ClosedOption,
    /// `x-ck-kind: credential_ref`: only a vault reference is allowed.
    Credential,
    /// `oneOf`: the value matches none of the tagged variants.
    Variant,
    /// Text holds an `{env:...}` or `{file:...}` expansion.
    Expansion,
    /// An object is the old `{"env": ...}` or `{"file": ...}` reference form.
    Reference,
    /// `minLength`, counted in characters.
    MinLength { bound: u64 },
    /// `maxLength`, counted in characters.
    MaxLength { bound: u64 },
    /// `pattern`: text must match this regular expression.
    Pattern { pattern: String },
    /// `minimum`, or `exclusiveMinimum` when `exclusive`.
    Minimum {
        bound: serde_json::Number,
        exclusive: bool,
    },
    /// `maximum`, or `exclusiveMaximum` when `exclusive`.
    Maximum {
        bound: serde_json::Number,
        exclusive: bool,
    },
    /// `minItems`.
    MinItems { bound: u64 },
    /// `maxItems`.
    MaxItems { bound: u64 },
    /// `uniqueItems`: two list items are the same value.
    UniqueItems,
    /// Two list items carry the same `id`.
    DuplicateId,
    /// The object key is not declared by the schema.
    Undeclared,
    /// `required` or `x-ck-required`: the key is missing.
    Required { key: String },
    /// `x-ck-bound`: a workspace or project value moves the inherited value
    /// the way the bound forbids.
    Bound { bound: Bound },
}
impl std::fmt::Display for Refusal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{:?} at {} ({:?})",
            self.code, self.path, self.project_id
        )
    }
}
impl std::error::Error for Refusal {}

/// A rejected literal and an accepted vault reference use the same redacted
/// record. Neither the opaque reference id nor a literal is retained in views.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[non_exhaustive]
pub enum RecordedValue {
    Value { value: Value },
    Redacted { digest: Digest, redacted: bool },
}
impl RecordedValue {
    pub fn new(value: Value) -> Self {
        Self::Value { value }
    }
    pub fn redacted(value: &Value) -> Result<Self, CanonicalError> {
        Ok(Self::Redacted {
            digest: digest(PURPOSE_VALUE, value)?,
            redacted: true,
        })
    }
}

/// Missing files are inputs, distinct from the digest of an empty document.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case")]
#[non_exhaustive]
pub enum InputState {
    Absent,
    Present { digest: Digest },
}

#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct InputVector {
    pub inputs: BTreeMap<String, InputState>,
}
impl InputVector {
    pub fn new(inputs: BTreeMap<String, InputState>) -> Self {
        Self { inputs }
    }
    /// Compare the saved read set only. Unrelated writes do not stale a plan.
    pub fn matches(&self, current: &Self) -> bool {
        self.inputs
            .iter()
            .all(|(key, state)| current.inputs.get(key) == Some(state))
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct FieldChange {
    pub module_id: String,
    pub project_id: Option<String>,
    pub path: String,
    pub old: RecordedValue,
    pub new: RecordedValue,
    pub old_source: Layer,
    pub new_source: Layer,
    pub apply: ApplyKind,
    pub reasons: Vec<String>,
}
impl FieldChange {
    pub fn new(
        module_id: impl Into<String>,
        path: impl Into<String>,
        old: RecordedValue,
        new: RecordedValue,
        apply: ApplyKind,
    ) -> Self {
        Self {
            module_id: module_id.into(),
            path: path.into(),
            project_id: None,
            old,
            new,
            old_source: Layer::Default,
            new_source: Layer::Default,
            apply,
            reasons: Vec::new(),
        }
    }
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Changeset {
    pub fields: Vec<FieldChange>,
    pub affected_projects: Vec<String>,
    pub policy_changes: Vec<Value>,
    pub launch_manifests: BTreeMap<String, Value>,
    pub apply_plan: Value,
}
impl Changeset {
    pub fn new() -> Self {
        Self::default()
    }
}

/// Immutable approval payload. The input vector includes subc.jsonc and every
/// touched module's layers, declaration and covered program identities.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Plan {
    pub base_revision: u64,
    pub base_generation: u64,
    pub active_generations: BTreeMap<String, u64>,
    pub daemon_incarnation: String,
    pub input_vector: InputVector,
    pub changeset: Changeset,
}
impl Plan {
    pub fn new(
        base_revision: u64,
        base_generation: u64,
        daemon_incarnation: impl Into<String>,
        input_vector: InputVector,
        changeset: Changeset,
    ) -> Self {
        Self {
            base_revision,
            base_generation,
            daemon_incarnation: daemon_incarnation.into(),
            active_generations: BTreeMap::new(),
            input_vector,
            changeset,
        }
    }
    pub fn digest(&self) -> Result<Digest, CanonicalError> {
        digest(
            PURPOSE_PLAN,
            &serde_json::to_value(self).map_err(|_| CanonicalError::Serialization)?,
        )
    }
    pub fn check_fresh(&self, base_revision: u64, current: &InputVector) -> Result<(), Refusal> {
        if self.base_revision != base_revision || !self.input_vector.matches(current) {
            return Err(Refusal::new(RefusalCode::PlanStale, "", None));
        }
        Ok(())
    }
}

/// Requests are strict; stored records and replies tolerate added fields.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct ApplyRequest {
    pub digest: Digest,
}
impl ApplyRequest {
    pub fn new(digest: Digest) -> Self {
        Self { digest }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum GenerationState {
    Planned,
    Approved,
    Pending,
    Warming,
    Active,
    Failed,
}

/// The review surface actually checked for an approval, not a claim supplied by
/// its requester. Development desktop review never implies app attestation.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApprovalChannel {
    OsPrompt,
    PhoneCard,
    AttestedDesktop,
    UnverifiedDevelopmentDesktop,
    /// A development placement under the compiled switch committed without
    /// any approval surface.
    DevelopmentPlacement,
}

impl ApprovalChannel {
    pub const fn description(self) -> &'static str {
        match self {
            Self::OsPrompt => "OS prompt",
            Self::PhoneCard => "phone card",
            Self::AttestedDesktop => "attested desktop",
            Self::UnverifiedDevelopmentDesktop => "development desktop (unverified)",
            Self::DevelopmentPlacement => "development placement (no approval)",
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Generation {
    pub id: u64,
    pub approval_channel: ApprovalChannel,
    pub plan_digest: Digest,
    pub input_vector: InputVector,
    pub declaration_digests: BTreeMap<String, Digest>,
    pub module_states: BTreeMap<String, GenerationState>,
    pub active_generations: BTreeMap<String, u64>,
    pub never_redeliver: Vec<String>,
    pub development: bool,
    pub changeset: Changeset,
}
impl Generation {
    pub fn new(
        id: u64,
        approval_channel: ApprovalChannel,
        plan_digest: Digest,
        input_vector: InputVector,
        changeset: Changeset,
    ) -> Self {
        Self {
            id,
            approval_channel,
            plan_digest,
            input_vector,
            changeset,
            declaration_digests: BTreeMap::new(),
            module_states: BTreeMap::new(),
            active_generations: BTreeMap::new(),
            never_redeliver: Vec::new(),
            development: false,
        }
    }
}

#[cfg(test)]
mod approval_channel_tests {
    use super::*;

    #[test]
    fn approval_channel_is_required_closed_and_preserves_unverified_wording() {
        for (channel, wire, words) in [
            (
                ApprovalChannel::DevelopmentPlacement,
                "development_placement",
                "development placement (no approval)",
            ),
            (ApprovalChannel::OsPrompt, "os_prompt", "OS prompt"),
            (ApprovalChannel::PhoneCard, "phone_card", "phone card"),
            (
                ApprovalChannel::AttestedDesktop,
                "attested_desktop",
                "attested desktop",
            ),
            (
                ApprovalChannel::UnverifiedDevelopmentDesktop,
                "unverified_development_desktop",
                "development desktop (unverified)",
            ),
        ] {
            assert_eq!(serde_json::to_value(channel).unwrap(), wire);
            assert_eq!(channel.description(), words);
            let generation = Generation::new(
                1,
                channel,
                crate::raw_digest(b"plan"),
                InputVector::default(),
                Changeset::new(),
            );
            let mut encoded = serde_json::to_value(&generation).unwrap();
            assert_eq!(
                serde_json::from_value::<Generation>(encoded.clone()).unwrap(),
                generation
            );
            encoded.as_object_mut().unwrap().remove("approval_channel");
            assert!(serde_json::from_value::<Generation>(encoded).is_err());
        }
        assert!(
            serde_json::from_str::<ApprovalChannel>("\"verified_development_desktop\"").is_err()
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    #[test]
    fn records_contract_plan_binding_and_evolution() {
        let d = digest(PURPOSE_VALUE, &json!(1)).unwrap();
        let input = InputVector::new(BTreeMap::from([
            ("subc.jsonc".into(), InputState::Absent),
            ("project".into(), InputState::Present { digest: d }),
        ]));
        let plan = Plan::new(7, 2, "incarnation", input.clone(), Changeset::new());
        let mut current = input.clone();
        current
            .inputs
            .insert("unrelated".into(), InputState::Absent);
        assert!(plan.check_fresh(7, &current).is_ok());
        current.inputs.insert("project".into(), InputState::Absent);
        assert_eq!(
            plan.check_fresh(7, &current).unwrap_err().code,
            RefusalCode::PlanStale
        );
        assert!(plan.check_fresh(8, &input).is_err());
        let mut changed = plan.clone();
        changed.base_revision += 1;
        assert_ne!(plan.digest().unwrap(), changed.digest().unwrap());
        let mut wire = serde_json::to_value(&plan).unwrap();
        wire["future"] = json!(true);
        assert!(serde_json::from_value::<Plan>(wire).is_ok());
        let request = json!({"digest":plan.digest().unwrap(), "future":true});
        assert!(serde_json::from_value::<ApplyRequest>(request).is_err());
    }
}