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 NewSessions,
28}
29
30#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
31#[serde(rename_all = "snake_case")]
32#[non_exhaustive]
33pub enum Bound {
34 RaiseOnly,
35 LowerOnly,
36 SubsetOnly,
37}
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
41#[serde(rename_all = "snake_case")]
42#[non_exhaustive]
43pub enum RefusalCode {
44 SchemaInvalid,
45 LayerForbidden,
46 ValueInvalid,
47 BoundViolated,
48 CredentialShared,
49 PlanStale,
50}
51
52#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
53#[non_exhaustive]
54pub struct Refusal {
55 pub code: RefusalCode,
56 pub path: String,
57 pub project_id: Option<String>,
58 #[serde(skip)]
63 pub rule: Option<Box<RefusalRule>>,
64}
65impl Refusal {
66 pub fn new(code: RefusalCode, path: impl Into<String>, project_id: Option<String>) -> Self {
67 Self {
68 code,
69 path: path.into(),
70 project_id,
71 rule: None,
72 }
73 }
74
75 pub fn with_rule(mut self, rule: RefusalRule) -> Self {
77 self.rule = Some(Box::new(rule));
78 self
79 }
80}
81
82#[derive(Clone, Debug, PartialEq, Eq)]
85#[non_exhaustive]
86pub enum RefusalRule {
87 Type { expected: Vec<String> },
89 Const { value: Value },
91 Enum { values: Vec<Value> },
93 ClosedOption,
95 Credential,
97 Variant,
99 Expansion,
101 Reference,
103 MinLength { bound: u64 },
105 MaxLength { bound: u64 },
107 Pattern { pattern: String },
109 Minimum {
111 bound: serde_json::Number,
112 exclusive: bool,
113 },
114 Maximum {
116 bound: serde_json::Number,
117 exclusive: bool,
118 },
119 MinItems { bound: u64 },
121 MaxItems { bound: u64 },
123 UniqueItems,
125 DuplicateId,
127 Undeclared,
129 Required { key: String },
131 Bound { bound: Bound },
134}
135impl std::fmt::Display for Refusal {
136 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
137 write!(
138 f,
139 "{:?} at {} ({:?})",
140 self.code, self.path, self.project_id
141 )
142 }
143}
144impl std::error::Error for Refusal {}
145
146#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
149#[serde(tag = "kind", rename_all = "snake_case")]
150#[non_exhaustive]
151pub enum RecordedValue {
152 Value { value: Value },
153 Redacted { digest: Digest, redacted: bool },
154}
155impl RecordedValue {
156 pub fn new(value: Value) -> Self {
157 Self::Value { value }
158 }
159 pub fn redacted(value: &Value) -> Result<Self, CanonicalError> {
160 Ok(Self::Redacted {
161 digest: digest(PURPOSE_VALUE, value)?,
162 redacted: true,
163 })
164 }
165}
166
167#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
169#[serde(tag = "state", rename_all = "snake_case")]
170#[non_exhaustive]
171pub enum InputState {
172 Absent,
173 Present { digest: Digest },
174}
175
176#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
177#[non_exhaustive]
178pub struct InputVector {
179 pub inputs: BTreeMap<String, InputState>,
180}
181impl InputVector {
182 pub fn new(inputs: BTreeMap<String, InputState>) -> Self {
183 Self { inputs }
184 }
185 pub fn matches(&self, current: &Self) -> bool {
187 self.inputs
188 .iter()
189 .all(|(key, state)| current.inputs.get(key) == Some(state))
190 }
191}
192
193#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
194#[non_exhaustive]
195pub struct FieldChange {
196 pub module_id: String,
197 pub project_id: Option<String>,
198 pub path: String,
199 pub old: RecordedValue,
200 pub new: RecordedValue,
201 pub old_source: Layer,
202 pub new_source: Layer,
203 pub apply: ApplyKind,
204 pub reasons: Vec<String>,
205}
206impl FieldChange {
207 pub fn new(
208 module_id: impl Into<String>,
209 path: impl Into<String>,
210 old: RecordedValue,
211 new: RecordedValue,
212 apply: ApplyKind,
213 ) -> Self {
214 Self {
215 module_id: module_id.into(),
216 path: path.into(),
217 project_id: None,
218 old,
219 new,
220 old_source: Layer::Default,
221 new_source: Layer::Default,
222 apply,
223 reasons: Vec::new(),
224 }
225 }
226}
227
228#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
229#[non_exhaustive]
230pub struct Changeset {
231 pub fields: Vec<FieldChange>,
232 pub affected_projects: Vec<String>,
233 pub policy_changes: Vec<Value>,
234 pub launch_manifests: BTreeMap<String, Value>,
235 pub apply_plan: Value,
236}
237impl Changeset {
238 pub fn new() -> Self {
239 Self::default()
240 }
241}
242
243#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
246#[non_exhaustive]
247pub struct Plan {
248 pub base_revision: u64,
249 pub base_generation: u64,
250 pub active_generations: BTreeMap<String, u64>,
251 pub daemon_incarnation: String,
252 pub input_vector: InputVector,
253 pub changeset: Changeset,
254}
255impl Plan {
256 pub fn new(
257 base_revision: u64,
258 base_generation: u64,
259 daemon_incarnation: impl Into<String>,
260 input_vector: InputVector,
261 changeset: Changeset,
262 ) -> Self {
263 Self {
264 base_revision,
265 base_generation,
266 daemon_incarnation: daemon_incarnation.into(),
267 active_generations: BTreeMap::new(),
268 input_vector,
269 changeset,
270 }
271 }
272 pub fn digest(&self) -> Result<Digest, CanonicalError> {
273 digest(
274 PURPOSE_PLAN,
275 &serde_json::to_value(self).map_err(|_| CanonicalError::Serialization)?,
276 )
277 }
278 pub fn check_fresh(&self, base_revision: u64, current: &InputVector) -> Result<(), Refusal> {
279 if self.base_revision != base_revision || !self.input_vector.matches(current) {
280 return Err(Refusal::new(RefusalCode::PlanStale, "", None));
281 }
282 Ok(())
283 }
284}
285
286#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
288#[serde(deny_unknown_fields)]
289#[non_exhaustive]
290pub struct ApplyRequest {
291 pub digest: Digest,
292}
293impl ApplyRequest {
294 pub fn new(digest: Digest) -> Self {
295 Self { digest }
296 }
297}
298
299#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
300#[serde(rename_all = "snake_case")]
301#[non_exhaustive]
302pub enum GenerationState {
303 Planned,
304 Approved,
305 Pending,
306 Warming,
307 Active,
308 Failed,
309}
310
311#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
314#[serde(rename_all = "snake_case")]
315pub enum ApprovalChannel {
316 OsPrompt,
317 PhoneCard,
318 AttestedDesktop,
319 UnverifiedDevelopmentDesktop,
320 DevelopmentPlacement,
323}
324
325impl ApprovalChannel {
326 pub const fn description(self) -> &'static str {
327 match self {
328 Self::OsPrompt => "OS prompt",
329 Self::PhoneCard => "phone card",
330 Self::AttestedDesktop => "attested desktop",
331 Self::UnverifiedDevelopmentDesktop => "development desktop (unverified)",
332 Self::DevelopmentPlacement => "development placement (no approval)",
333 }
334 }
335}
336
337#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
338#[non_exhaustive]
339pub struct Generation {
340 pub id: u64,
341 pub approval_channel: ApprovalChannel,
342 pub plan_digest: Digest,
343 pub input_vector: InputVector,
344 pub declaration_digests: BTreeMap<String, Digest>,
345 pub module_states: BTreeMap<String, GenerationState>,
346 pub active_generations: BTreeMap<String, u64>,
347 pub never_redeliver: Vec<String>,
348 pub development: bool,
349 pub changeset: Changeset,
350}
351impl Generation {
352 pub fn new(
353 id: u64,
354 approval_channel: ApprovalChannel,
355 plan_digest: Digest,
356 input_vector: InputVector,
357 changeset: Changeset,
358 ) -> Self {
359 Self {
360 id,
361 approval_channel,
362 plan_digest,
363 input_vector,
364 changeset,
365 declaration_digests: BTreeMap::new(),
366 module_states: BTreeMap::new(),
367 active_generations: BTreeMap::new(),
368 never_redeliver: Vec::new(),
369 development: false,
370 }
371 }
372}
373
374#[cfg(test)]
375mod approval_channel_tests {
376 use super::*;
377
378 #[test]
379 fn approval_channel_is_required_closed_and_preserves_unverified_wording() {
380 for (channel, wire, words) in [
381 (
382 ApprovalChannel::DevelopmentPlacement,
383 "development_placement",
384 "development placement (no approval)",
385 ),
386 (ApprovalChannel::OsPrompt, "os_prompt", "OS prompt"),
387 (ApprovalChannel::PhoneCard, "phone_card", "phone card"),
388 (
389 ApprovalChannel::AttestedDesktop,
390 "attested_desktop",
391 "attested desktop",
392 ),
393 (
394 ApprovalChannel::UnverifiedDevelopmentDesktop,
395 "unverified_development_desktop",
396 "development desktop (unverified)",
397 ),
398 ] {
399 assert_eq!(serde_json::to_value(channel).unwrap(), wire);
400 assert_eq!(channel.description(), words);
401 let generation = Generation::new(
402 1,
403 channel,
404 crate::raw_digest(b"plan"),
405 InputVector::default(),
406 Changeset::new(),
407 );
408 let mut encoded = serde_json::to_value(&generation).unwrap();
409 assert_eq!(
410 serde_json::from_value::<Generation>(encoded.clone()).unwrap(),
411 generation
412 );
413 encoded.as_object_mut().unwrap().remove("approval_channel");
414 assert!(serde_json::from_value::<Generation>(encoded).is_err());
415 }
416 assert!(
417 serde_json::from_str::<ApprovalChannel>("\"verified_development_desktop\"").is_err()
418 );
419 }
420}
421
422#[cfg(test)]
423mod tests {
424 use super::*;
425 use serde_json::json;
426 #[test]
427 fn records_contract_plan_binding_and_evolution() {
428 let d = digest(PURPOSE_VALUE, &json!(1)).unwrap();
429 let input = InputVector::new(BTreeMap::from([
430 ("subc.jsonc".into(), InputState::Absent),
431 ("project".into(), InputState::Present { digest: d }),
432 ]));
433 let plan = Plan::new(7, 2, "incarnation", input.clone(), Changeset::new());
434 let mut current = input.clone();
435 current
436 .inputs
437 .insert("unrelated".into(), InputState::Absent);
438 assert!(plan.check_fresh(7, ¤t).is_ok());
439 current.inputs.insert("project".into(), InputState::Absent);
440 assert_eq!(
441 plan.check_fresh(7, ¤t).unwrap_err().code,
442 RefusalCode::PlanStale
443 );
444 assert!(plan.check_fresh(8, &input).is_err());
445 let mut changed = plan.clone();
446 changed.base_revision += 1;
447 assert_ne!(plan.digest().unwrap(), changed.digest().unwrap());
448 let mut wire = serde_json::to_value(&plan).unwrap();
449 wire["future"] = json!(true);
450 assert!(serde_json::from_value::<Plan>(wire).is_ok());
451 let request = json!({"digest":plan.digest().unwrap(), "future":true});
452 assert!(serde_json::from_value::<ApplyRequest>(request).is_err());
453 }
454}