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#[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 #[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 pub fn with_rule(mut self, rule: RefusalRule) -> Self {
74 self.rule = Some(Box::new(rule));
75 self
76 }
77}
78
79#[derive(Clone, Debug, PartialEq, Eq)]
82#[non_exhaustive]
83pub enum RefusalRule {
84 Type { expected: Vec<String> },
86 Const { value: Value },
88 Enum { values: Vec<Value> },
90 ClosedOption,
92 Credential,
94 Variant,
96 Expansion,
98 Reference,
100 MinLength { bound: u64 },
102 MaxLength { bound: u64 },
104 Pattern { pattern: String },
106 Minimum {
108 bound: serde_json::Number,
109 exclusive: bool,
110 },
111 Maximum {
113 bound: serde_json::Number,
114 exclusive: bool,
115 },
116 MinItems { bound: u64 },
118 MaxItems { bound: u64 },
120 UniqueItems,
122 DuplicateId,
124 Undeclared,
126 Required { key: String },
128 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#[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#[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 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#[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#[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#[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 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, ¤t).is_ok());
436 current.inputs.insert("project".into(), InputState::Absent);
437 assert_eq!(
438 plan.check_fresh(7, ¤t).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}