Skip to main content

vault_core/
rotation.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! The rotation state machine (R13): rotate a credential at its issuer, deploy it to the things that
4//! use it, check them, and revoke the old credential only when that is safe.
5//!
6//! The engine owns the order of steps and the safety rules; it knows nothing about any one issuer or
7//! deployment. Those arrive as traits ([`IssuerConnector`], [`Consumers`], [`EntryStore`]), so the
8//! same state machine runs against PostgreSQL, Cloudflare or a fake that injects faults, and the
9//! properties below are tested against the fake.
10//!
11//! The rules, in the order they matter:
12//!
13//! 1. **The old credential stays valid until the end.** It is revoked last, and only when the revoke
14//!    rule is met: by default every required consumer has been deployed to and has passed its check
15//!    in this run ([`RevokeRule::AfterAllChecked`]).
16//! 2. **A value the client chose is stored before the issuer hears of it** (`rotation_pending`),
17//!    so a lost response never leaves a credential at the issuer that nobody has.
18//! 3. **No blind retry of anything destructive.** A response lost after a destructive call is
19//!    `uncertain`; the connector is asked what happened ([`IssuerConnector::reconcile`]) and the
20//!    step is repeated only when the answer is "not done". An in-place roll that is lost cannot be
21//!    reconciled (the old value is gone and the new one never arrived) and stops as `needs_attention`.
22//! 4. **Store first.** The new value is written to the entry (a new generation, the old value in its
23//!    history) before it is deployed, so a crash after the issuer changed cannot lose it.
24//! 5. **Every transition is persisted** ([`RunStore`]), so a crash, a lock or a restart resumes at
25//!    the step that was in flight and never starts over.
26
27use serde::{Deserialize, Serialize};
28use std::collections::BTreeMap;
29
30/// What a connector can do. The class decides the steps.
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
32#[serde(rename_all = "snake_case")]
33pub enum Class {
34    /// The issuer can hold the old and a new credential at once (a second API token, a second role).
35    CreateOverlapping,
36    /// UnENVerse generates the value and tells the issuer to use it (`ALTER ROLE ... PASSWORD`).
37    SetValueClientGenerated,
38    /// The issuer generates a new value in place and the old one stops working at once.
39    RollProviderGenerated,
40}
41
42#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
43pub struct Credential {
44    pub id: String,
45    pub value: String,
46}
47
48/// Why an issuer call did not succeed.
49#[derive(Clone, Debug, PartialEq, Eq)]
50pub enum IssuerError {
51    /// The issuer said no, definitely: nothing changed.
52    Rejected(String),
53    /// The call may or may not have taken effect (a timeout, a dropped connection).
54    Lost(String),
55}
56
57#[derive(Clone, Debug, PartialEq, Eq)]
58pub enum Reconcile {
59    /// The step took effect.
60    Done,
61    /// It did not; repeating it is safe.
62    NotDone,
63    /// The connector cannot tell. The engine stops and asks for a person.
64    Unknown,
65}
66
67/// The step a reconcile is about.
68#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
69#[serde(rename_all = "snake_case")]
70pub enum StepKind {
71    Create,
72    SetValue,
73    Roll,
74    Revoke,
75}
76
77pub trait IssuerConnector {
78    fn capabilities(&self) -> Vec<Class>;
79    /// Does this credential work at the issuer right now?
80    fn verify(&mut self, credential: &Credential) -> Result<(), IssuerError>;
81    /// Overlapping: make a new credential called `name` (the name carries the entry, generation and
82    /// run id, so it can be found again).
83    fn create(&mut self, name: &str) -> Result<Credential, IssuerError>;
84    /// Client-generated: what the new credential is called at the issuer. The default is the run's
85    /// name; a connector with fixed identities (two database roles taking turns) returns the one
86    /// that is not `current_id`.
87    fn set_target(&self, _current_id: &str, run_name: &str) -> String {
88        run_name.to_string()
89    }
90    /// Client-generated: tell the issuer to use `value` for `name`. Idempotent.
91    fn set_value(&mut self, name: &str, value: &str) -> Result<(), IssuerError>;
92    /// Provider-generated: roll `current` in place. The old value stops working.
93    fn roll(&mut self, current: &Credential) -> Result<Credential, IssuerError>;
94    /// Remove a credential. Called last, and only when the revoke rule is met.
95    fn revoke(&mut self, credential: &Credential) -> Result<(), IssuerError>;
96    /// Did `step` take effect? Asked only after a lost response.
97    fn reconcile(&mut self, step: &StepKind, name: &str) -> Result<Reconcile, IssuerError>;
98}
99
100#[derive(Clone, Debug, PartialEq, Eq)]
101pub enum Outcome {
102    Ok,
103    Failed(String),
104    /// Not reachable now; try again later. Not a failure of the rotation.
105    Offline,
106}
107
108/// What uses the credential, usually node targets. Each consumer is identified by a stable id.
109pub trait Consumers {
110    fn required(&self) -> Vec<String>;
111    fn deploy(&mut self, id: &str, credential: &Credential, generation: u64) -> Outcome;
112    fn check(&mut self, id: &str) -> Outcome;
113    /// Put the previous credential back (the rollback rule).
114    fn redeploy_previous(&mut self, id: &str) -> Outcome;
115}
116
117/// The vault entry being rotated.
118pub trait EntryStore {
119    fn current(&self) -> Credential;
120    /// Writes the new value as the next generation, with the old one kept in history.
121    fn commit(&mut self, new: &Credential, generation: u64) -> Result<(), String>;
122    /// Puts the old value back as the current one (a rollback).
123    fn restore(&mut self, old: &Credential) -> Result<(), String>;
124}
125
126#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
127#[serde(rename_all = "snake_case")]
128pub enum RevokeRule {
129    /// Revoke when every required consumer was deployed to and checked in this run.
130    AfterAllChecked,
131    /// Never revoke automatically; leave it for a person.
132    Never,
133}
134
135#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
136#[serde(rename_all = "snake_case")]
137pub enum RollbackRule {
138    /// A consumer that fails to deploy or check puts the old credential back everywhere.
139    RestoreOnFailure,
140    /// Leave things as they are and stop for a person.
141    Stop,
142}
143
144#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
145pub struct Policy {
146    pub revoke: RevokeRule,
147    pub rollback: RollbackRule,
148}
149
150impl Default for Policy {
151    fn default() -> Self {
152        Self {
153            revoke: RevokeRule::AfterAllChecked,
154            rollback: RollbackRule::RestoreOnFailure,
155        }
156    }
157}
158
159#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
160#[serde(rename_all = "snake_case")]
161pub enum Step {
162    Planned,
163    /// The issuer is being asked for a new credential.
164    Issuing,
165    Verifying,
166    /// The new value is written to the entry (store first).
167    Committing,
168    Deploying,
169    Checking,
170    Revoking,
171    Finished,
172}
173
174#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
175#[serde(rename_all = "snake_case", tag = "status", content = "detail")]
176pub enum Status {
177    Running,
178    Succeeded,
179    /// Everything worked except revocation: a required consumer was offline or the policy says never.
180    /// The old credential is still valid.
181    RevocationPending(String),
182    /// A person has to look: something is uncertain or a destructive call was lost.
183    NeedsAttention(String),
184    /// Stopped before any issuer change that matters; nothing to undo.
185    Failed(String),
186    /// A consumer failed and the old credential was put back everywhere.
187    RolledBack(String),
188}
189
190#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
191pub struct Run {
192    pub id: String,
193    pub entry: String,
194    pub generation: u64,
195    pub class: Class,
196    pub policy: Policy,
197    pub step: Step,
198    pub status: Status,
199    /// The name every credential created for this run carries, so it can be found again.
200    pub name: String,
201    pub old_id: String,
202    pub new_id: Option<String>,
203    /// Per consumer: `deployed`, `checked`, `offline`, `failed:<reason>`.
204    pub consumers: BTreeMap<String, String>,
205    /// Whether the revoke call was made. Checked by the safety property, and by a resumed run so it
206    /// never revokes twice.
207    pub revoked: bool,
208}
209
210/// Where runs and pending values are kept between steps.
211pub trait RunStore {
212    fn save(&mut self, run: &Run) -> Result<(), String>;
213    /// A value chosen by the client, stored before the issuer is told (rule 2).
214    fn put_pending(&mut self, run_id: &str, value: &str) -> Result<(), String>;
215    fn pending(&self, run_id: &str) -> Option<String>;
216    fn clear_pending(&mut self, run_id: &str) -> Result<(), String>;
217}
218
219pub fn run_name(entry: &str, generation: u64, run_id: &str) -> String {
220    format!("unv:{entry}:g{generation}:{run_id}")
221}
222
223impl Run {
224    pub fn plan(
225        id: &str,
226        entry: &str,
227        generation: u64,
228        class: Class,
229        policy: Policy,
230        old_id: &str,
231    ) -> Self {
232        Self {
233            id: id.into(),
234            entry: entry.into(),
235            generation,
236            class,
237            policy,
238            step: Step::Planned,
239            status: Status::Running,
240            name: run_name(entry, generation, id),
241            old_id: old_id.into(),
242            new_id: None,
243            consumers: BTreeMap::new(),
244            revoked: false,
245        }
246    }
247
248    pub fn is_finished(&self) -> bool {
249        !matches!(self.status, Status::Running)
250    }
251}
252
253pub struct Engine<'a> {
254    pub issuer: &'a mut dyn IssuerConnector,
255    pub consumers: &'a mut dyn Consumers,
256    pub entry: &'a mut dyn EntryStore,
257    pub store: &'a mut dyn RunStore,
258    /// Generates the value for [`Class::SetValueClientGenerated`].
259    pub generate: &'a dyn Fn() -> String,
260}
261
262fn stop(run: &mut Run, status: Status) {
263    run.status = status;
264}
265
266impl Engine<'_> {
267    fn persist(&mut self, run: &Run) -> Result<(), String> {
268        self.store.save(run)
269    }
270
271    /// Runs the machine until it finishes or needs a person, saving after every transition.
272    pub fn run(&mut self, run: &mut Run) -> Result<(), String> {
273        let mut guard = 0;
274        while !run.is_finished() {
275            self.step(run)?;
276            self.persist(run)?;
277            guard += 1;
278            if guard > 64 {
279                stop(run, Status::NeedsAttention("the run did not finish".into()));
280                self.persist(run)?;
281            }
282        }
283        Ok(())
284    }
285
286    /// One transition. The run is the whole state: calling this on a run loaded from the store
287    /// resumes exactly where the previous process stopped.
288    pub fn step(&mut self, run: &mut Run) -> Result<(), String> {
289        match run.step {
290            Step::Planned => {
291                if !self.issuer.capabilities().contains(&run.class) {
292                    stop(
293                        run,
294                        Status::Failed("the issuer cannot rotate this way".into()),
295                    );
296                } else {
297                    for id in self.consumers.required() {
298                        run.consumers.entry(id).or_insert_with(|| "pending".into());
299                    }
300                    run.step = Step::Issuing;
301                }
302            }
303            Step::Issuing => self.issue(run)?,
304            Step::Verifying => self.verify(run)?,
305            Step::Committing => {
306                let Some(new) = self.new_credential(run) else {
307                    stop(
308                        run,
309                        Status::NeedsAttention("the new credential is missing".into()),
310                    );
311                    return Ok(());
312                };
313                match self.entry.commit(&new, run.generation) {
314                    Ok(()) => {
315                        let _ = self.store.clear_pending(&run.id);
316                        run.step = Step::Deploying;
317                    }
318                    Err(e) => stop(
319                        run,
320                        Status::NeedsAttention(format!(
321                            "could not write the new value to the entry: {e}"
322                        )),
323                    ),
324                }
325            }
326            Step::Deploying => self.deploy(run),
327            Step::Checking => self.check(run),
328            Step::Revoking => self.revoke(run),
329            Step::Finished => {
330                if run.status == Status::Running {
331                    run.status = Status::Succeeded;
332                }
333            }
334        }
335        Ok(())
336    }
337
338    /// The new credential, from wherever this class keeps it.
339    fn new_credential(&self, run: &Run) -> Option<Credential> {
340        match run.class {
341            Class::SetValueClientGenerated => self
342                .store
343                .pending(&run.id)
344                .map(|value| Credential {
345                    id: run.new_id.clone().unwrap_or_else(|| run.name.clone()),
346                    value,
347                })
348                .or_else(|| {
349                    // Already committed: the entry holds it.
350                    let current = self.entry.current();
351                    (run.step > Step::Committing).then_some(current)
352                }),
353            _ => {
354                // The pending value wins while it exists: a rolled credential keeps its id, so the
355                // entry's current credential has the same id as the new one until it is committed.
356                if let Some((value, id)) = self.store.pending(&run.id).zip(run.new_id.clone()) {
357                    return Some(Credential { id, value });
358                }
359                let current = self.entry.current();
360                (run.new_id.as_deref() == Some(current.id.as_str())).then_some(current)
361            }
362        }
363    }
364
365    fn issue(&mut self, run: &mut Run) -> Result<(), String> {
366        match run.class {
367            Class::CreateOverlapping => match self.issuer.create(&run.name) {
368                Ok(c) => {
369                    // Provider-generated: the value only exists now. Keep it safe before anything else.
370                    self.store.put_pending(&run.id, &c.value)?;
371                    run.new_id = Some(c.id);
372                    run.step = Step::Verifying;
373                }
374                Err(IssuerError::Rejected(e)) => stop(run, Status::Failed(e)),
375                Err(IssuerError::Lost(e)) => {
376                    match self.issuer.reconcile(&StepKind::Create, &run.name) {
377                        // The credential exists at the issuer but its value never reached us. It is a
378                        // new, unused credential, so removing it and asking again is safe.
379                        Ok(Reconcile::Done) => {
380                            stop(
381                            run,
382                            Status::NeedsAttention(format!(
383                                "the issuer created a credential named {} but the answer was lost ({e}); delete it there and run again",
384                                run.name
385                            )),
386                        );
387                        }
388                        Ok(Reconcile::NotDone) => {} // stay on this step: safe to repeat
389                        _ => stop(
390                            run,
391                            Status::NeedsAttention(format!("uncertain create: {e}")),
392                        ),
393                    }
394                }
395            },
396            Class::SetValueClientGenerated => {
397                // Choose the value and keep it before the issuer is told.
398                let value = match self.store.pending(&run.id) {
399                    Some(v) => v,
400                    None => {
401                        let v = (self.generate)();
402                        self.store.put_pending(&run.id, &v)?;
403                        v
404                    }
405                };
406                let target = self.issuer.set_target(&run.old_id, &run.name);
407                match self.issuer.set_value(&target, &value) {
408                    Ok(()) => {
409                        run.new_id = Some(target.clone());
410                        run.step = Step::Verifying;
411                    }
412                    Err(IssuerError::Rejected(e)) => stop(run, Status::Failed(e)),
413                    Err(IssuerError::Lost(e)) => {
414                        match self.issuer.reconcile(&StepKind::SetValue, &target) {
415                            Ok(Reconcile::Done) => {
416                                run.new_id = Some(target.clone());
417                                run.step = Step::Verifying;
418                            }
419                            Ok(Reconcile::NotDone) => {} // repeat: set_value is idempotent
420                            _ => stop(
421                                run,
422                                Status::NeedsAttention(format!("uncertain set_value: {e}")),
423                            ),
424                        }
425                    }
426                }
427            }
428            Class::RollProviderGenerated => {
429                let current = self.entry.current();
430                match self.issuer.roll(&current) {
431                    Ok(c) => {
432                        self.store.put_pending(&run.id, &c.value)?;
433                        run.new_id = Some(c.id);
434                        run.step = Step::Verifying;
435                    }
436                    Err(IssuerError::Rejected(e)) => stop(run, Status::Failed(e)),
437                    // The old value stopped working and the new one never arrived. Nothing to
438                    // reconcile and nothing safe to retry.
439                    Err(IssuerError::Lost(e)) => stop(
440                        run,
441                        Status::NeedsAttention(format!(
442                            "the roll's answer was lost ({e}); the old value may no longer work and the new one was not received. Issue a new credential at the provider"
443                        )),
444                    ),
445                }
446            }
447        }
448        Ok(())
449    }
450
451    fn verify(&mut self, run: &mut Run) -> Result<(), String> {
452        let Some(new) = self.new_credential(run) else {
453            stop(
454                run,
455                Status::NeedsAttention("the new credential is missing".into()),
456            );
457            return Ok(());
458        };
459        match self.issuer.verify(&new) {
460            Ok(()) => run.step = Step::Committing,
461            Err(IssuerError::Rejected(e)) | Err(IssuerError::Lost(e)) => {
462                // The new credential does not work. The old one is untouched (overlapping and
463                // client-generated keep both); a rolled credential is already the only one.
464                let status = if run.class == Class::RollProviderGenerated {
465                    Status::NeedsAttention(format!("the rolled credential did not verify: {e}"))
466                } else {
467                    Status::Failed(format!("the new credential did not verify: {e}"))
468                };
469                stop(run, status);
470            }
471        }
472        Ok(())
473    }
474
475    fn deploy(&mut self, run: &mut Run) {
476        let Some(new) = self.new_credential(run) else {
477            stop(
478                run,
479                Status::NeedsAttention("the new credential is missing".into()),
480            );
481            return;
482        };
483        for id in self.consumers.required() {
484            if matches!(
485                run.consumers.get(&id).map(String::as_str),
486                Some("deployed" | "checked")
487            ) {
488                continue;
489            }
490            match self.consumers.deploy(&id, &new, run.generation) {
491                Outcome::Ok => {
492                    run.consumers.insert(id, "deployed".into());
493                }
494                Outcome::Offline => {
495                    run.consumers.insert(id, "offline".into());
496                }
497                Outcome::Failed(e) => {
498                    run.consumers.insert(id.clone(), format!("failed:{e}"));
499                    self.fail_consumer(run, &id, &e);
500                    return;
501                }
502            }
503        }
504        run.step = Step::Checking;
505    }
506
507    fn check(&mut self, run: &mut Run) {
508        for id in self.consumers.required() {
509            match run.consumers.get(&id).map(String::as_str) {
510                Some("checked") => continue,
511                Some("deployed") => {}
512                // Never deployed (offline): it cannot have passed a check.
513                _ => continue,
514            }
515            match self.consumers.check(&id) {
516                Outcome::Ok => {
517                    run.consumers.insert(id, "checked".into());
518                }
519                Outcome::Offline => {
520                    run.consumers.insert(id, "offline".into());
521                }
522                Outcome::Failed(e) => {
523                    run.consumers.insert(id.clone(), format!("failed:{e}"));
524                    self.fail_consumer(run, &id, &e);
525                    return;
526                }
527            }
528        }
529        run.step = Step::Revoking;
530    }
531
532    /// A consumer failed after the new value was committed. The old credential is still valid, so
533    /// the rollback rule can put it back everywhere.
534    fn fail_consumer(&mut self, run: &mut Run, id: &str, reason: &str) {
535        if run.policy.rollback == RollbackRule::Stop {
536            stop(
537                run,
538                Status::NeedsAttention(format!("{id} failed ({reason}); left as it is")),
539            );
540            return;
541        }
542        let mut ok = true;
543        for c in self.consumers.required() {
544            if matches!(
545                run.consumers.get(&c).map(String::as_str),
546                Some("deployed" | "checked")
547            ) && !matches!(self.consumers.redeploy_previous(&c), Outcome::Ok)
548            {
549                ok = false;
550            }
551        }
552        let restored = self
553            .entry
554            .restore(&Credential {
555                id: run.old_id.clone(),
556                value: String::new(),
557            })
558            .is_ok();
559        if ok && restored {
560            stop(run, Status::RolledBack(format!("{id} failed: {reason}")));
561        } else {
562            stop(
563                run,
564                Status::NeedsAttention(format!(
565                    "{id} failed ({reason}) and putting the old credential back did not fully succeed"
566                )),
567            );
568        }
569    }
570
571    fn revoke(&mut self, run: &mut Run) {
572        // Rule 1, checked here and nowhere else: revocation needs every required consumer checked.
573        let all_checked = self
574            .consumers
575            .required()
576            .iter()
577            .all(|id| run.consumers.get(id).map(String::as_str) == Some("checked"));
578        let offline: Vec<String> = run
579            .consumers
580            .iter()
581            .filter(|(_, s)| s.as_str() == "offline")
582            .map(|(k, _)| k.clone())
583            .collect();
584        if run.policy.revoke == RevokeRule::Never {
585            stop(
586                run,
587                Status::RevocationPending("the policy never revokes automatically".into()),
588            );
589            run.step = Step::Finished;
590            return;
591        }
592        if !all_checked {
593            let why = if offline.is_empty() {
594                "not every consumer passed its check".to_string()
595            } else {
596                format!("waiting for {} to come back", offline.join(", "))
597            };
598            stop(run, Status::RevocationPending(why));
599            run.step = Step::Finished;
600            return;
601        }
602        if run.revoked {
603            run.step = Step::Finished;
604            run.status = Status::Succeeded;
605            return;
606        }
607        if run.class == Class::RollProviderGenerated {
608            // A roll replaced the value under the same id: the old value died when the new one was
609            // issued, and a revoke by id would delete the credential just rotated.
610            run.revoked = true;
611            run.step = Step::Finished;
612            run.status = Status::Succeeded;
613            return;
614        }
615        let old = Credential {
616            id: run.old_id.clone(),
617            value: String::new(),
618        };
619        match self.issuer.revoke(&old) {
620            Ok(()) => {
621                run.revoked = true;
622                run.step = Step::Finished;
623                run.status = Status::Succeeded;
624            }
625            Err(IssuerError::Rejected(e)) => {
626                stop(
627                    run,
628                    Status::RevocationPending(format!(
629                        "the issuer refused to revoke the old credential: {e}"
630                    )),
631                );
632                run.step = Step::Finished;
633            }
634            Err(IssuerError::Lost(e)) => {
635                match self.issuer.reconcile(&StepKind::Revoke, &run.old_id) {
636                    Ok(Reconcile::Done) => {
637                        run.revoked = true;
638                        run.step = Step::Finished;
639                        run.status = Status::Succeeded;
640                    }
641                    // Not done: repeating revoke is safe (the old credential is simply still there),
642                    // but there is no reason to rush; leave it pending for the next run.
643                    Ok(Reconcile::NotDone) => {
644                        stop(
645                            run,
646                            Status::RevocationPending(
647                                "the revoke did not take effect; try again".into(),
648                            ),
649                        );
650                        run.step = Step::Finished;
651                    }
652                    _ => {
653                        stop(
654                            run,
655                            Status::NeedsAttention(format!("uncertain revoke: {e}")),
656                        );
657                        run.step = Step::Finished;
658                    }
659                }
660            }
661        }
662    }
663}
664
665// ── SQLite persistence ──────────────────────────────────────────────────────
666
667/// Creates the rotation tables inside the encrypted vault database. Runs hold ids and states, never
668/// values; `rotation_pending` holds the one value that exists nowhere else yet.
669pub fn init_schema(conn: &rusqlite::Connection) -> Result<(), String> {
670    conn.execute_batch(
671        "CREATE TABLE IF NOT EXISTS rotation_runs (
672             id TEXT PRIMARY KEY, entry TEXT NOT NULL, state TEXT NOT NULL, updated_at TEXT NOT NULL
673         );
674         CREATE TABLE IF NOT EXISTS rotation_pending (
675             run_id TEXT PRIMARY KEY, value TEXT NOT NULL, created_at TEXT NOT NULL
676         );",
677    )
678    .map_err(|e| e.to_string())
679}
680
681pub struct SqlStore<'a> {
682    pub conn: &'a rusqlite::Connection,
683}
684
685impl RunStore for SqlStore<'_> {
686    fn save(&mut self, run: &Run) -> Result<(), String> {
687        let state = serde_json::to_string(run).map_err(|e| e.to_string())?;
688        self.conn
689            .execute(
690                "INSERT INTO rotation_runs (id, entry, state, updated_at) VALUES (?1, ?2, ?3, ?4)
691                 ON CONFLICT(id) DO UPDATE SET state = excluded.state, updated_at = excluded.updated_at",
692                rusqlite::params![run.id, run.entry, state, crate::iso_now()],
693            )
694            .map(|_| ())
695            .map_err(|e| e.to_string())
696    }
697
698    fn put_pending(&mut self, run_id: &str, value: &str) -> Result<(), String> {
699        self.conn
700            .execute(
701                "INSERT OR REPLACE INTO rotation_pending (run_id, value, created_at) VALUES (?1, ?2, ?3)",
702                rusqlite::params![run_id, value, crate::iso_now()],
703            )
704            .map(|_| ())
705            .map_err(|e| e.to_string())
706    }
707
708    fn pending(&self, run_id: &str) -> Option<String> {
709        self.conn
710            .query_row(
711                "SELECT value FROM rotation_pending WHERE run_id = ?1",
712                [run_id],
713                |r| r.get(0),
714            )
715            .ok()
716    }
717
718    fn clear_pending(&mut self, run_id: &str) -> Result<(), String> {
719        self.conn
720            .execute("DELETE FROM rotation_pending WHERE run_id = ?1", [run_id])
721            .map(|_| ())
722            .map_err(|e| e.to_string())
723    }
724}
725
726/// A run saved by [`SqlStore`], to resume after a crash or an unlock.
727pub fn load_run(conn: &rusqlite::Connection, id: &str) -> Result<Option<Run>, String> {
728    use rusqlite::OptionalExtension;
729    let text: Option<String> = conn
730        .query_row("SELECT state FROM rotation_runs WHERE id = ?1", [id], |r| {
731            r.get(0)
732        })
733        .optional()
734        .map_err(|e| e.to_string())?;
735    text.map(|t| serde_json::from_str(&t).map_err(|e| e.to_string()))
736        .transpose()
737}
738
739pub fn list_runs(conn: &rusqlite::Connection) -> Result<Vec<Run>, String> {
740    let mut stmt = conn
741        .prepare("SELECT state FROM rotation_runs ORDER BY updated_at DESC")
742        .map_err(|e| e.to_string())?;
743    let rows = stmt
744        .query_map([], |r| r.get::<_, String>(0))
745        .map_err(|e| e.to_string())?;
746    rows.map(|r| {
747        r.map_err(|e| e.to_string())
748            .and_then(|t| serde_json::from_str(&t).map_err(|e| e.to_string()))
749    })
750    .collect()
751}
752
753#[cfg(test)]
754pub(crate) mod fakes {
755    //! A fake issuer, consumers and entry that inject faults at chosen calls, shared by the engine's
756    //! tests and by connector-independent property tests.
757    use super::*;
758    use std::collections::{BTreeMap, BTreeSet};
759
760    #[derive(Default)]
761    pub struct World {
762        /// Credentials that exist at the issuer, by id, with their values.
763        pub issuer: BTreeMap<String, String>,
764        pub revoked: BTreeSet<String>,
765        pub revoke_calls: Vec<String>,
766        /// Every call, in order, for ordering assertions.
767        pub calls: Vec<String>,
768    }
769
770    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
771    pub enum Fault {
772        None,
773        /// The call fails definitively.
774        Reject,
775        /// The call takes effect and the answer is lost.
776        LostAfter,
777        /// The call does not take effect and the answer is lost.
778        LostBefore,
779    }
780
781    pub struct FakeIssuer<'w> {
782        pub world: &'w std::cell::RefCell<World>,
783        pub classes: Vec<Class>,
784        pub create: Fault,
785        pub set_value: Fault,
786        pub roll: Fault,
787        pub verify: Fault,
788        pub revoke: Fault,
789        /// Reconcile cannot tell what happened.
790        pub reconcile_unknown: bool,
791        pub seq: u32,
792    }
793
794    impl<'w> FakeIssuer<'w> {
795        pub fn new(world: &'w std::cell::RefCell<World>, class: Class) -> Self {
796            world
797                .borrow_mut()
798                .issuer
799                .insert("old".into(), "old-value".into());
800            Self {
801                world,
802                classes: vec![class],
803                create: Fault::None,
804                set_value: Fault::None,
805                roll: Fault::None,
806                verify: Fault::None,
807                revoke: Fault::None,
808                reconcile_unknown: false,
809                seq: 0,
810            }
811        }
812    }
813
814    fn lost(f: Fault) -> Option<IssuerError> {
815        match f {
816            Fault::LostAfter | Fault::LostBefore => Some(IssuerError::Lost("timeout".into())),
817            Fault::Reject => Some(IssuerError::Rejected("no".into())),
818            Fault::None => None,
819        }
820    }
821
822    impl IssuerConnector for FakeIssuer<'_> {
823        fn capabilities(&self) -> Vec<Class> {
824            self.classes.clone()
825        }
826        fn verify(&mut self, c: &Credential) -> Result<(), IssuerError> {
827            self.world.borrow_mut().calls.push("verify".into());
828            if let Some(e) = lost(self.verify) {
829                return Err(e);
830            }
831            let w = self.world.borrow();
832            if w.issuer.get(&c.id) == Some(&c.value) && !w.revoked.contains(&c.id) {
833                Ok(())
834            } else {
835                Err(IssuerError::Rejected("does not work".into()))
836            }
837        }
838        fn create(&mut self, name: &str) -> Result<Credential, IssuerError> {
839            self.world.borrow_mut().calls.push("create".into());
840            self.seq += 1;
841            let c = Credential {
842                id: name.to_string(),
843                value: format!("provider-value-{}", self.seq),
844            };
845            match self.create {
846                Fault::Reject => return Err(IssuerError::Rejected("no".into())),
847                Fault::LostBefore => return Err(IssuerError::Lost("timeout".into())),
848                Fault::LostAfter => {
849                    self.world
850                        .borrow_mut()
851                        .issuer
852                        .insert(c.id.clone(), c.value.clone());
853                    // Only the first attempt is lost: a retry after a "not done" must succeed.
854                    self.create = Fault::None;
855                    return Err(IssuerError::Lost("timeout".into()));
856                }
857                Fault::None => {}
858            }
859            self.world
860                .borrow_mut()
861                .issuer
862                .insert(c.id.clone(), c.value.clone());
863            Ok(c)
864        }
865        fn set_value(&mut self, name: &str, value: &str) -> Result<(), IssuerError> {
866            self.world.borrow_mut().calls.push("set_value".into());
867            match self.set_value {
868                Fault::Reject => return Err(IssuerError::Rejected("no".into())),
869                Fault::LostBefore => {
870                    self.set_value = Fault::None;
871                    return Err(IssuerError::Lost("timeout".into()));
872                }
873                Fault::LostAfter => {
874                    self.world
875                        .borrow_mut()
876                        .issuer
877                        .insert(name.into(), value.into());
878                    self.set_value = Fault::None;
879                    return Err(IssuerError::Lost("timeout".into()));
880                }
881                Fault::None => {}
882            }
883            self.world
884                .borrow_mut()
885                .issuer
886                .insert(name.into(), value.into());
887            Ok(())
888        }
889        fn roll(&mut self, current: &Credential) -> Result<Credential, IssuerError> {
890            self.world.borrow_mut().calls.push("roll".into());
891            self.seq += 1;
892            let new = Credential {
893                id: current.id.clone(),
894                value: format!("rolled-{}", self.seq),
895            };
896            match self.roll {
897                Fault::Reject => return Err(IssuerError::Rejected("no".into())),
898                Fault::LostBefore => return Err(IssuerError::Lost("timeout".into())),
899                Fault::LostAfter => {
900                    self.world
901                        .borrow_mut()
902                        .issuer
903                        .insert(new.id.clone(), new.value.clone());
904                    return Err(IssuerError::Lost("timeout".into()));
905                }
906                Fault::None => {}
907            }
908            self.world
909                .borrow_mut()
910                .issuer
911                .insert(new.id.clone(), new.value.clone());
912            Ok(new)
913        }
914        fn revoke(&mut self, c: &Credential) -> Result<(), IssuerError> {
915            {
916                let mut w = self.world.borrow_mut();
917                w.calls.push("revoke".into());
918                w.revoke_calls.push(c.id.clone());
919            }
920            match self.revoke {
921                Fault::Reject => return Err(IssuerError::Rejected("no".into())),
922                Fault::LostBefore => return Err(IssuerError::Lost("timeout".into())),
923                Fault::LostAfter => {
924                    self.world.borrow_mut().revoked.insert(c.id.clone());
925                    return Err(IssuerError::Lost("timeout".into()));
926                }
927                Fault::None => {}
928            }
929            self.world.borrow_mut().revoked.insert(c.id.clone());
930            Ok(())
931        }
932        fn reconcile(&mut self, step: &StepKind, name: &str) -> Result<Reconcile, IssuerError> {
933            self.world.borrow_mut().calls.push("reconcile".into());
934            if self.reconcile_unknown {
935                return Ok(Reconcile::Unknown);
936            }
937            let w = self.world.borrow();
938            Ok(match step {
939                StepKind::Create | StepKind::SetValue => {
940                    if w.issuer.contains_key(name) {
941                        Reconcile::Done
942                    } else {
943                        Reconcile::NotDone
944                    }
945                }
946                StepKind::Revoke => {
947                    if w.revoked.contains(name) {
948                        Reconcile::Done
949                    } else {
950                        Reconcile::NotDone
951                    }
952                }
953                StepKind::Roll => Reconcile::Unknown,
954            })
955        }
956    }
957
958    pub struct FakeConsumers {
959        pub ids: Vec<String>,
960        /// What each consumer does on `deploy` and `check`.
961        pub deploy: BTreeMap<String, Outcome>,
962        pub check: BTreeMap<String, Outcome>,
963        pub deployed: BTreeMap<String, String>,
964        pub redeployed: Vec<String>,
965        pub redeploy_fails: bool,
966    }
967
968    impl FakeConsumers {
969        pub fn new(ids: &[&str]) -> Self {
970            Self {
971                ids: ids.iter().map(|s| s.to_string()).collect(),
972                deploy: BTreeMap::new(),
973                check: BTreeMap::new(),
974                deployed: BTreeMap::new(),
975                redeployed: Vec::new(),
976                redeploy_fails: false,
977            }
978        }
979    }
980
981    impl Consumers for FakeConsumers {
982        fn required(&self) -> Vec<String> {
983            self.ids.clone()
984        }
985        fn deploy(&mut self, id: &str, c: &Credential, _g: u64) -> Outcome {
986            let out = self.deploy.get(id).cloned().unwrap_or(Outcome::Ok);
987            if out == Outcome::Ok {
988                self.deployed.insert(id.into(), c.value.clone());
989            }
990            out
991        }
992        fn check(&mut self, id: &str) -> Outcome {
993            self.check.get(id).cloned().unwrap_or(Outcome::Ok)
994        }
995        fn redeploy_previous(&mut self, id: &str) -> Outcome {
996            self.redeployed.push(id.into());
997            if self.redeploy_fails {
998                return Outcome::Failed("cannot".into());
999            }
1000            self.deployed.insert(id.into(), "old-value".into());
1001            Outcome::Ok
1002        }
1003    }
1004
1005    pub struct FakeEntry {
1006        pub current: Credential,
1007        pub history: Vec<Credential>,
1008        pub fail_commit: bool,
1009        pub fail_restore: bool,
1010    }
1011
1012    impl FakeEntry {
1013        pub fn new() -> Self {
1014            Self {
1015                current: Credential {
1016                    id: "old".into(),
1017                    value: "old-value".into(),
1018                },
1019                history: Vec::new(),
1020                fail_commit: false,
1021                fail_restore: false,
1022            }
1023        }
1024    }
1025
1026    impl EntryStore for FakeEntry {
1027        fn current(&self) -> Credential {
1028            self.current.clone()
1029        }
1030        fn commit(&mut self, new: &Credential, _g: u64) -> Result<(), String> {
1031            if self.fail_commit {
1032                return Err("disk full".into());
1033            }
1034            self.history.push(self.current.clone());
1035            self.current = new.clone();
1036            Ok(())
1037        }
1038        fn restore(&mut self, _old: &Credential) -> Result<(), String> {
1039            if self.fail_restore {
1040                return Err("read-only".into());
1041            }
1042            if let Some(prev) = self.history.pop() {
1043                self.current = prev;
1044            }
1045            Ok(())
1046        }
1047    }
1048
1049    #[derive(Default)]
1050    pub struct MemStore {
1051        pub saved: Vec<Run>,
1052        pub pending: BTreeMap<String, String>,
1053    }
1054
1055    impl RunStore for MemStore {
1056        fn save(&mut self, run: &Run) -> Result<(), String> {
1057            self.saved.push(run.clone());
1058            Ok(())
1059        }
1060        fn put_pending(&mut self, run_id: &str, value: &str) -> Result<(), String> {
1061            self.pending.insert(run_id.into(), value.into());
1062            Ok(())
1063        }
1064        fn pending(&self, run_id: &str) -> Option<String> {
1065            self.pending.get(run_id).cloned()
1066        }
1067        fn clear_pending(&mut self, run_id: &str) -> Result<(), String> {
1068            self.pending.remove(run_id);
1069            Ok(())
1070        }
1071    }
1072}
1073
1074#[cfg(test)]
1075mod tests {
1076    use super::fakes::*;
1077    use super::*;
1078    use std::cell::RefCell;
1079
1080    fn engine_run(
1081        class: Class,
1082        configure: impl FnOnce(&mut FakeIssuer<'_>, &mut FakeConsumers, &mut FakeEntry),
1083        consumers: &[&str],
1084    ) -> (Run, RefCell<World>, FakeConsumers, FakeEntry, MemStore) {
1085        let world = RefCell::new(World::default());
1086        let mut run = Run::plan("r1", "Entry", 2, class, Policy::default(), "old");
1087        let mut cons = FakeConsumers::new(consumers);
1088        let mut entry = FakeEntry::new();
1089        let mut store = MemStore::default();
1090        {
1091            let mut issuer = FakeIssuer::new(&world, class);
1092            configure(&mut issuer, &mut cons, &mut entry);
1093            let gen = || "client-generated-value".to_string();
1094            let mut engine = Engine {
1095                issuer: &mut issuer,
1096                consumers: &mut cons,
1097                entry: &mut entry,
1098                store: &mut store,
1099                generate: &gen,
1100            };
1101            engine.run(&mut run).unwrap();
1102        }
1103        (run, world, cons, entry, store)
1104    }
1105
1106    #[test]
1107    fn an_overlapping_rotation_creates_deploys_checks_then_revokes_last() {
1108        let (run, world, cons, entry, store) =
1109            engine_run(Class::CreateOverlapping, |_, _, _| {}, &["web", "worker"]);
1110        assert_eq!(run.status, Status::Succeeded);
1111        assert!(run.revoked);
1112        let calls = world.borrow().calls.clone();
1113        assert_eq!(calls.first().map(String::as_str), Some("create"));
1114        assert_eq!(
1115            calls.last().map(String::as_str),
1116            Some("revoke"),
1117            "{calls:?}"
1118        );
1119        assert_eq!(entry.current.value, "provider-value-1");
1120        assert_eq!(
1121            entry.history.len(),
1122            1,
1123            "the old value is kept in the entry's history"
1124        );
1125        assert!(cons.deployed.values().all(|v| v == "provider-value-1"));
1126        assert!(
1127            store.pending.is_empty(),
1128            "the pending value is cleared once it is in the entry"
1129        );
1130        assert_eq!(world.borrow().revoke_calls, vec!["old".to_string()]);
1131    }
1132
1133    #[test]
1134    fn a_client_generated_value_is_stored_before_the_issuer_is_told() {
1135        let world = RefCell::new(World::default());
1136        let mut issuer = FakeIssuer::new(&world, Class::SetValueClientGenerated);
1137        // The issuer rejects: the value must already have been stored (rule 2) and nothing revoked.
1138        issuer.set_value = Fault::Reject;
1139        let mut run = Run::plan(
1140            "r1",
1141            "E",
1142            2,
1143            Class::SetValueClientGenerated,
1144            Policy::default(),
1145            "old",
1146        );
1147        let mut cons = FakeConsumers::new(&["web"]);
1148        let mut entry = FakeEntry::new();
1149        let mut store = MemStore::default();
1150        let gen = || "chosen-by-the-client".to_string();
1151        Engine {
1152            issuer: &mut issuer,
1153            consumers: &mut cons,
1154            entry: &mut entry,
1155            store: &mut store,
1156            generate: &gen,
1157        }
1158        .run(&mut run)
1159        .unwrap();
1160        assert!(matches!(run.status, Status::Failed(_)));
1161        assert_eq!(
1162            store.pending.get("r1").map(String::as_str),
1163            Some("chosen-by-the-client")
1164        );
1165        assert!(world.borrow().revoke_calls.is_empty());
1166        assert_eq!(entry.current.value, "old-value", "the entry is untouched");
1167    }
1168
1169    #[test]
1170    fn a_response_lost_after_create_is_found_by_name_and_stops_for_a_person() {
1171        let (run, world, _, entry, _) = engine_run(
1172            Class::CreateOverlapping,
1173            |i, _, _| i.create = Fault::LostAfter,
1174            &["web"],
1175        );
1176        assert!(
1177            matches!(run.status, Status::NeedsAttention(_)),
1178            "{:?}",
1179            run.status
1180        );
1181        assert!(world.borrow().calls.contains(&"reconcile".to_string()));
1182        assert!(
1183            world.borrow().revoke_calls.is_empty(),
1184            "nothing is revoked on an uncertain create"
1185        );
1186        assert_eq!(entry.current.value, "old-value");
1187    }
1188
1189    #[test]
1190    fn a_response_lost_before_create_is_retried_safely() {
1191        let (run, world, _, entry, _) = engine_run(
1192            Class::CreateOverlapping,
1193            |i, _, _| i.create = Fault::LostBefore,
1194            &["web"],
1195        );
1196        // LostBefore keeps failing in the fake, so reconcile says NotDone each time and the guard
1197        // stops the run; the point is that nothing was revoked and the entry is untouched.
1198        assert!(
1199            matches!(run.status, Status::NeedsAttention(_) | Status::Failed(_)),
1200            "{:?}",
1201            run.status
1202        );
1203        assert!(world.borrow().revoke_calls.is_empty());
1204        assert_eq!(entry.current.value, "old-value");
1205    }
1206
1207    #[test]
1208    fn a_lost_client_generated_set_value_is_reconciled_then_the_run_continues() {
1209        for fault in [Fault::LostAfter, Fault::LostBefore] {
1210            let (run, world, _, entry, _) = engine_run(
1211                Class::SetValueClientGenerated,
1212                |i, _, _| i.set_value = fault,
1213                &["web"],
1214            );
1215            assert_eq!(run.status, Status::Succeeded, "{fault:?}: {:?}", run.status);
1216            assert_eq!(entry.current.value, "client-generated-value");
1217            assert!(world.borrow().calls.contains(&"reconcile".to_string()));
1218        }
1219    }
1220
1221    #[test]
1222    fn a_lost_in_place_roll_is_never_retried_and_needs_a_person() {
1223        let (run, world, _, entry, _) = engine_run(
1224            Class::RollProviderGenerated,
1225            |i, _, _| i.roll = Fault::LostAfter,
1226            &["web"],
1227        );
1228        assert!(matches!(run.status, Status::NeedsAttention(_)));
1229        assert_eq!(
1230            world.borrow().calls.iter().filter(|c| *c == "roll").count(),
1231            1,
1232            "a destructive call is never repeated"
1233        );
1234        assert!(world.borrow().revoke_calls.is_empty());
1235        assert_eq!(entry.current.value, "old-value");
1236    }
1237
1238    #[test]
1239    fn a_successful_roll_deploys_the_rolled_value_and_never_revokes_by_id() {
1240        // Bug: a rolled credential keeps its id, so the engine verified and deployed the entry's
1241        // old value (same id) and then revoked the credential it had just rotated.
1242        let (run, world, cons, entry, _) =
1243            engine_run(Class::RollProviderGenerated, |_, _, _| {}, &["web"]);
1244        assert_eq!(run.status, Status::Succeeded, "{:?}", run.status);
1245        assert_eq!(entry.current.value, "rolled-1");
1246        assert_eq!(cons.deployed["web"], "rolled-1");
1247        assert!(world.borrow().revoke_calls.is_empty());
1248    }
1249
1250    #[test]
1251    fn a_connector_with_fixed_identities_names_the_other_one_as_the_new_credential() {
1252        struct Roles<'a>(&'a RefCell<World>);
1253        impl IssuerConnector for Roles<'_> {
1254            fn capabilities(&self) -> Vec<Class> {
1255                vec![Class::SetValueClientGenerated]
1256            }
1257            fn verify(&mut self, _: &Credential) -> Result<(), IssuerError> {
1258                Ok(())
1259            }
1260            fn create(&mut self, _: &str) -> Result<Credential, IssuerError> {
1261                Err(IssuerError::Rejected("no".into()))
1262            }
1263            fn set_target(&self, current: &str, _: &str) -> String {
1264                if current == "app_a" { "app_b" } else { "app_a" }.into()
1265            }
1266            fn set_value(&mut self, name: &str, value: &str) -> Result<(), IssuerError> {
1267                self.0.borrow_mut().issuer.insert(name.into(), value.into());
1268                Ok(())
1269            }
1270            fn roll(&mut self, _: &Credential) -> Result<Credential, IssuerError> {
1271                Err(IssuerError::Rejected("no".into()))
1272            }
1273            fn revoke(&mut self, c: &Credential) -> Result<(), IssuerError> {
1274                self.0.borrow_mut().revoke_calls.push(c.id.clone());
1275                Ok(())
1276            }
1277            fn reconcile(&mut self, _: &StepKind, _: &str) -> Result<Reconcile, IssuerError> {
1278                Ok(Reconcile::NotDone)
1279            }
1280        }
1281        let world = RefCell::new(World::default());
1282        let mut issuer = Roles(&world);
1283        let mut run = Run::plan(
1284            "r1",
1285            "Db",
1286            2,
1287            Class::SetValueClientGenerated,
1288            Policy::default(),
1289            "app_a",
1290        );
1291        let mut cons = FakeConsumers::new(&["web"]);
1292        let mut entry = FakeEntry::new();
1293        let mut store = MemStore::default();
1294        let gen = || "fresh-password".to_string();
1295        Engine {
1296            issuer: &mut issuer,
1297            consumers: &mut cons,
1298            entry: &mut entry,
1299            store: &mut store,
1300            generate: &gen,
1301        }
1302        .run(&mut run)
1303        .unwrap();
1304        assert_eq!(run.status, Status::Succeeded, "{:?}", run.status);
1305        assert_eq!(
1306            entry.current.id, "app_b",
1307            "the entry now names the other role"
1308        );
1309        assert_eq!(world.borrow().revoke_calls, vec!["app_a".to_string()]);
1310    }
1311
1312    /// Runs `run` (already placed at some step) with the given doubles and returns it.
1313    fn resume(
1314        mut run: Run,
1315        class: Class,
1316        configure: impl FnOnce(&mut FakeIssuer<'_>, &mut FakeConsumers, &mut FakeEntry, &mut MemStore),
1317        consumers: &[&str],
1318    ) -> (Run, RefCell<World>) {
1319        let world = RefCell::new(World::default());
1320        let mut cons = FakeConsumers::new(consumers);
1321        let mut entry = FakeEntry::new();
1322        let mut store = MemStore::default();
1323        {
1324            let mut issuer = FakeIssuer::new(&world, class);
1325            configure(&mut issuer, &mut cons, &mut entry, &mut store);
1326            let gen = || "generated".to_string();
1327            Engine {
1328                issuer: &mut issuer,
1329                consumers: &mut cons,
1330                entry: &mut entry,
1331                store: &mut store,
1332                generate: &gen,
1333            }
1334            .run(&mut run)
1335            .unwrap();
1336        }
1337        (run, world)
1338    }
1339
1340    fn at(step: Step, class: Class) -> Run {
1341        let mut r = Run::plan("r1", "E", 2, class, Policy::default(), "old");
1342        r.step = step;
1343        r
1344    }
1345
1346    #[test]
1347    fn a_run_that_lost_its_new_value_stops_for_a_person_at_every_step_that_needs_it() {
1348        // A run resumed after the pending value was lost (a restored backup, a cleared table) has
1349        // nothing to verify, store or deploy, and must not invent a value.
1350        for step in [Step::Verifying, Step::Committing, Step::Deploying] {
1351            let (run, world) = resume(
1352                at(step, Class::CreateOverlapping),
1353                Class::CreateOverlapping,
1354                |_, _, _, _| {},
1355                &["web"],
1356            );
1357            assert!(
1358                matches!(&run.status, Status::NeedsAttention(m) if m.contains("missing")),
1359                "{step:?}: {:?}",
1360                run.status
1361            );
1362            assert!(world.borrow().revoke_calls.is_empty());
1363        }
1364        let (run, _) = resume(
1365            at(Step::Committing, Class::SetValueClientGenerated),
1366            Class::SetValueClientGenerated,
1367            |_, _, _, _| {},
1368            &["web"],
1369        );
1370        assert!(
1371            matches!(run.status, Status::NeedsAttention(_)),
1372            "{:?}",
1373            run.status
1374        );
1375    }
1376
1377    #[test]
1378    fn a_run_saved_as_finished_but_still_running_is_completed_without_new_calls() {
1379        let (run, world) = resume(
1380            at(Step::Finished, Class::CreateOverlapping),
1381            Class::CreateOverlapping,
1382            |_, _, _, _| {},
1383            &[],
1384        );
1385        assert_eq!(run.status, Status::Succeeded);
1386        assert!(world.borrow().calls.is_empty());
1387    }
1388
1389    #[test]
1390    fn a_revoke_that_already_happened_is_not_repeated_when_a_run_resumes() {
1391        let mut r = at(Step::Revoking, Class::CreateOverlapping);
1392        r.revoked = true;
1393        r.consumers.insert("web".into(), "checked".into());
1394        let (run, world) = resume(r, Class::CreateOverlapping, |_, _, _, _| {}, &["web"]);
1395        assert_eq!(run.status, Status::Succeeded);
1396        assert!(world.borrow().revoke_calls.is_empty());
1397    }
1398
1399    #[test]
1400    fn a_consumer_that_never_reported_keeps_revocation_pending_with_a_reason() {
1401        let mut r = at(Step::Revoking, Class::CreateOverlapping);
1402        r.consumers.insert("web".into(), "checked".into());
1403        // "worker" is required but has no state: it was added after planning.
1404        let (run, world) = resume(
1405            r,
1406            Class::CreateOverlapping,
1407            |_, _, _, _| {},
1408            &["web", "worker"],
1409        );
1410        assert!(
1411            matches!(&run.status, Status::RevocationPending(m) if m.contains("not every consumer")),
1412            "{:?}",
1413            run.status
1414        );
1415        assert!(world.borrow().revoke_calls.is_empty());
1416    }
1417
1418    #[test]
1419    fn a_connector_that_cannot_tell_what_happened_stops_the_run_instead_of_guessing() {
1420        let (run, world, ..) = engine_run(
1421            Class::CreateOverlapping,
1422            |i, _, _| {
1423                i.create = Fault::LostBefore;
1424                i.reconcile_unknown = true;
1425            },
1426            &["web"],
1427        );
1428        assert!(
1429            matches!(&run.status, Status::NeedsAttention(m) if m.contains("uncertain create")),
1430            "{:?}",
1431            run.status
1432        );
1433        assert!(world.borrow().revoke_calls.is_empty());
1434
1435        let (run, ..) = engine_run(
1436            Class::SetValueClientGenerated,
1437            |i, _, _| {
1438                i.set_value = Fault::LostBefore;
1439                i.reconcile_unknown = true;
1440            },
1441            &["web"],
1442        );
1443        assert!(
1444            matches!(&run.status, Status::NeedsAttention(m) if m.contains("uncertain set_value")),
1445            "{:?}",
1446            run.status
1447        );
1448
1449        let (run, world, ..) = engine_run(
1450            Class::CreateOverlapping,
1451            |i, _, _| {
1452                i.revoke = Fault::LostAfter;
1453                i.reconcile_unknown = true;
1454            },
1455            &["web"],
1456        );
1457        assert!(
1458            matches!(&run.status, Status::NeedsAttention(m) if m.contains("uncertain revoke")),
1459            "{:?}",
1460            run.status
1461        );
1462        assert_eq!(world.borrow().revoke_calls.len(), 1, "never repeated");
1463    }
1464
1465    #[test]
1466    fn a_rollback_that_cannot_put_the_old_credential_back_says_so() {
1467        // A consumer fails its check and putting the old credential back fails too.
1468        for (redeploy_fails, fail_restore) in [(true, false), (false, true)] {
1469            let (run, ..) = engine_run(
1470                Class::CreateOverlapping,
1471                |_, c, e| {
1472                    c.check
1473                        .insert("worker".into(), Outcome::Failed("503".into()));
1474                    c.redeploy_fails = redeploy_fails;
1475                    e.fail_restore = fail_restore;
1476                },
1477                &["web", "worker"],
1478            );
1479            assert!(
1480                matches!(&run.status, Status::NeedsAttention(m) if m.contains("did not fully succeed")),
1481                "{redeploy_fails} {fail_restore}: {:?}",
1482                run.status
1483            );
1484        }
1485    }
1486
1487    #[test]
1488    fn a_rejected_verification_of_a_rolled_credential_needs_a_person_but_others_just_fail() {
1489        let (run, ..) = engine_run(
1490            Class::RollProviderGenerated,
1491            |i, _, _| i.verify = Fault::Reject,
1492            &["web"],
1493        );
1494        assert!(
1495            matches!(&run.status, Status::NeedsAttention(m) if m.contains("rolled credential")),
1496            "{:?}",
1497            run.status
1498        );
1499        let (run, ..) = engine_run(
1500            Class::CreateOverlapping,
1501            |i, _, _| i.verify = Fault::Reject,
1502            &["web"],
1503        );
1504        assert!(
1505            matches!(&run.status, Status::Failed(m) if m.contains("did not verify")),
1506            "{:?}",
1507            run.status
1508        );
1509    }
1510
1511    #[test]
1512    fn a_run_that_cannot_make_progress_is_stopped_by_the_guard() {
1513        // A connector that is always "not done" for a lost create would loop for ever.
1514        let (run, ..) = engine_run(
1515            Class::CreateOverlapping,
1516            |i, _, _| i.create = Fault::LostBefore,
1517            &["web"],
1518        );
1519        assert!(
1520            matches!(run.status, Status::NeedsAttention(_) | Status::Failed(_)),
1521            "{:?}",
1522            run.status
1523        );
1524    }
1525
1526    #[test]
1527    fn an_offline_required_consumer_leaves_revocation_pending_and_the_old_credential_valid() {
1528        let (run, world, _, _, _) = engine_run(
1529            Class::CreateOverlapping,
1530            |_, c, _| {
1531                c.deploy.insert("worker".into(), Outcome::Offline);
1532            },
1533            &["web", "worker"],
1534        );
1535        assert!(
1536            matches!(run.status, Status::RevocationPending(_)),
1537            "{:?}",
1538            run.status
1539        );
1540        assert!(world.borrow().revoke_calls.is_empty());
1541        assert!(!world.borrow().revoked.contains("old"));
1542        assert_eq!(run.consumers["worker"], "offline");
1543    }
1544
1545    #[test]
1546    fn a_failing_consumer_rolls_everything_back_while_the_old_credential_is_still_valid() {
1547        let (run, world, cons, entry, _) = engine_run(
1548            Class::CreateOverlapping,
1549            |_, c, _| {
1550                c.check
1551                    .insert("worker".into(), Outcome::Failed("503".into()));
1552            },
1553            &["web", "worker"],
1554        );
1555        assert!(
1556            matches!(run.status, Status::RolledBack(_)),
1557            "{:?}",
1558            run.status
1559        );
1560        assert_eq!(entry.current.value, "old-value");
1561        assert!(cons.redeployed.contains(&"web".to_string()));
1562        assert!(
1563            world.borrow().revoke_calls.is_empty(),
1564            "the old credential was never revoked"
1565        );
1566    }
1567
1568    #[test]
1569    fn the_stop_rollback_rule_leaves_things_for_a_person() {
1570        let world = RefCell::new(World::default());
1571        let mut issuer = FakeIssuer::new(&world, Class::CreateOverlapping);
1572        let mut run = Run::plan(
1573            "r1",
1574            "E",
1575            2,
1576            Class::CreateOverlapping,
1577            Policy {
1578                revoke: RevokeRule::AfterAllChecked,
1579                rollback: RollbackRule::Stop,
1580            },
1581            "old",
1582        );
1583        let mut cons = FakeConsumers::new(&["web"]);
1584        cons.check
1585            .insert("web".into(), Outcome::Failed("down".into()));
1586        let mut entry = FakeEntry::new();
1587        let mut store = MemStore::default();
1588        let gen = || String::new();
1589        Engine {
1590            issuer: &mut issuer,
1591            consumers: &mut cons,
1592            entry: &mut entry,
1593            store: &mut store,
1594            generate: &gen,
1595        }
1596        .run(&mut run)
1597        .unwrap();
1598        assert!(matches!(run.status, Status::NeedsAttention(_)));
1599        assert!(cons.redeployed.is_empty());
1600    }
1601
1602    #[test]
1603    fn a_lost_revoke_is_reconciled_and_never_blindly_repeated() {
1604        let (run, world, _, _, _) = engine_run(
1605            Class::CreateOverlapping,
1606            |i, _, _| i.revoke = Fault::LostAfter,
1607            &["web"],
1608        );
1609        assert_eq!(run.status, Status::Succeeded);
1610        assert_eq!(
1611            world
1612                .borrow()
1613                .calls
1614                .iter()
1615                .filter(|c| *c == "revoke")
1616                .count(),
1617            1,
1618            "the lost revoke was reconciled as done, not repeated"
1619        );
1620        // A lost revoke that did not take effect leaves it pending, with the old credential valid.
1621        let (run, world, _, _, _) = engine_run(
1622            Class::CreateOverlapping,
1623            |i, _, _| i.revoke = Fault::LostBefore,
1624            &["web"],
1625        );
1626        assert!(
1627            matches!(run.status, Status::RevocationPending(_)),
1628            "{:?}",
1629            run.status
1630        );
1631        assert!(!world.borrow().revoked.contains("old"));
1632    }
1633
1634    #[test]
1635    fn the_never_policy_and_a_failed_commit_stop_before_any_revoke() {
1636        let world = RefCell::new(World::default());
1637        let mut issuer = FakeIssuer::new(&world, Class::CreateOverlapping);
1638        let mut run = Run::plan(
1639            "r1",
1640            "E",
1641            2,
1642            Class::CreateOverlapping,
1643            Policy {
1644                revoke: RevokeRule::Never,
1645                rollback: RollbackRule::RestoreOnFailure,
1646            },
1647            "old",
1648        );
1649        let mut cons = FakeConsumers::new(&["web"]);
1650        let mut entry = FakeEntry::new();
1651        let mut store = MemStore::default();
1652        let gen = || String::new();
1653        Engine {
1654            issuer: &mut issuer,
1655            consumers: &mut cons,
1656            entry: &mut entry,
1657            store: &mut store,
1658            generate: &gen,
1659        }
1660        .run(&mut run)
1661        .unwrap();
1662        assert!(matches!(run.status, Status::RevocationPending(_)));
1663        assert!(world.borrow().revoke_calls.is_empty());
1664
1665        let (run, world, cons, _, _) = engine_run(
1666            Class::CreateOverlapping,
1667            |_, _, e| e.fail_commit = true,
1668            &["web"],
1669        );
1670        assert!(
1671            matches!(run.status, Status::NeedsAttention(_)),
1672            "{:?}",
1673            run.status
1674        );
1675        assert!(
1676            cons.deployed.is_empty(),
1677            "nothing is deployed before the value is stored"
1678        );
1679        assert!(world.borrow().revoke_calls.is_empty());
1680    }
1681
1682    #[test]
1683    fn an_issuer_that_cannot_rotate_this_way_fails_before_touching_anything() {
1684        let world = RefCell::new(World::default());
1685        let mut issuer = FakeIssuer::new(&world, Class::CreateOverlapping);
1686        let mut run = Run::plan(
1687            "r1",
1688            "E",
1689            2,
1690            Class::RollProviderGenerated,
1691            Policy::default(),
1692            "old",
1693        );
1694        let mut cons = FakeConsumers::new(&["web"]);
1695        let mut entry = FakeEntry::new();
1696        let mut store = MemStore::default();
1697        let gen = || String::new();
1698        Engine {
1699            issuer: &mut issuer,
1700            consumers: &mut cons,
1701            entry: &mut entry,
1702            store: &mut store,
1703            generate: &gen,
1704        }
1705        .run(&mut run)
1706        .unwrap();
1707        assert!(matches!(run.status, Status::Failed(_)));
1708        assert!(world.borrow().calls.is_empty());
1709    }
1710
1711    /// Rule 1 as a property: whatever steps fail, in whatever combination, `revoke` is never
1712    /// called unless every required consumer was deployed to and checked in this run.
1713    #[test]
1714    fn revocation_never_precedes_checks_over_every_combination_of_step_failures() {
1715        let faults = [
1716            Fault::None,
1717            Fault::Reject,
1718            Fault::LostAfter,
1719            Fault::LostBefore,
1720        ];
1721        let outcomes = [Outcome::Ok, Outcome::Failed("x".into()), Outcome::Offline];
1722        let classes = [
1723            Class::CreateOverlapping,
1724            Class::SetValueClientGenerated,
1725            Class::RollProviderGenerated,
1726        ];
1727        let mut runs = 0;
1728        for class in classes {
1729            for create in faults {
1730                for set_value in faults {
1731                    for roll in faults {
1732                        for verify in faults {
1733                            for revoke in faults {
1734                                for deploy in &outcomes {
1735                                    for check in &outcomes {
1736                                        let (run, world, cons, _, _) = engine_run(
1737                                            class,
1738                                            |i, c, _| {
1739                                                i.create = create;
1740                                                i.set_value = set_value;
1741                                                i.roll = roll;
1742                                                i.verify = verify;
1743                                                i.revoke = revoke;
1744                                                c.deploy.insert("b".into(), deploy.clone());
1745                                                c.check.insert("b".into(), check.clone());
1746                                            },
1747                                            &["a", "b"],
1748                                        );
1749                                        runs += 1;
1750                                        let revoked_called =
1751                                            !world.borrow().revoke_calls.is_empty();
1752                                        if revoked_called {
1753                                            let all =
1754                                                run.consumers.values().all(|s| s == "checked")
1755                                                    && run.consumers.len() == 2;
1756                                            assert!(
1757                                                all,
1758                                                "revoked before every consumer was checked: {class:?} {create:?} {set_value:?} {roll:?} {verify:?} {revoke:?} {deploy:?} {check:?} => {:?} {:?}",
1759                                                run.status, run.consumers
1760                                            );
1761                                            assert!(cons.deployed.len() == 2);
1762                                        }
1763                                        assert!(
1764                                            world.borrow().revoke_calls.len() <= 1,
1765                                            "revoked twice"
1766                                        );
1767                                        assert!(runs > 0);
1768                                    }
1769                                }
1770                            }
1771                        }
1772                    }
1773                }
1774            }
1775        }
1776        assert!(runs > 5000, "the property was exercised over {runs} runs");
1777    }
1778
1779    /// Rule 5: a process that stops after any transition resumes from the saved run and reaches the
1780    /// same end, without issuing a second credential or revoking twice.
1781    #[test]
1782    fn a_run_resumes_from_every_saved_transition_without_repeating_a_destructive_step() {
1783        // First, record the uninterrupted run's saved states.
1784        let (_, _, _, _, full) =
1785            engine_run(Class::CreateOverlapping, |_, _, _| {}, &["web", "worker"]);
1786        assert!(full.saved.len() >= 6);
1787        for (n, snapshot) in full.saved.iter().enumerate() {
1788            let world = RefCell::new(World::default());
1789            // The issuer state at that point: replay what the saved steps imply by starting fresh
1790            // for steps before issuing, or with the credential created for later ones.
1791            let mut issuer = FakeIssuer::new(&world, Class::CreateOverlapping);
1792            let mut entry = FakeEntry::new();
1793            let mut store = MemStore::default();
1794            let mut cons = FakeConsumers::new(&["web", "worker"]);
1795            if snapshot.new_id.is_some() {
1796                world
1797                    .borrow_mut()
1798                    .issuer
1799                    .insert(snapshot.name.clone(), "provider-value-1".into());
1800                store.put_pending(&snapshot.id, "provider-value-1").unwrap();
1801                issuer.seq = 1;
1802            }
1803            if snapshot.step > Step::Committing {
1804                entry
1805                    .commit(
1806                        &Credential {
1807                            id: snapshot.name.clone(),
1808                            value: "provider-value-1".into(),
1809                        },
1810                        2,
1811                    )
1812                    .unwrap();
1813                store.clear_pending(&snapshot.id).unwrap();
1814            }
1815            for (id, state) in &snapshot.consumers {
1816                if state == "deployed" || state == "checked" {
1817                    cons.deployed.insert(id.clone(), "provider-value-1".into());
1818                }
1819            }
1820            let mut resumed = snapshot.clone();
1821            let gen = || String::new();
1822            Engine {
1823                issuer: &mut issuer,
1824                consumers: &mut cons,
1825                entry: &mut entry,
1826                store: &mut store,
1827                generate: &gen,
1828            }
1829            .run(&mut resumed)
1830            .unwrap();
1831            assert_eq!(resumed.status, Status::Succeeded, "resuming after save {n}");
1832            let calls = world.borrow().calls.clone();
1833            assert!(
1834                calls.iter().filter(|c| *c == "create").count() <= 1,
1835                "{n}: {calls:?}"
1836            );
1837            assert_eq!(
1838                world.borrow().revoke_calls.len() + usize::from(snapshot.revoked),
1839                1,
1840                "{n}: revoked exactly once"
1841            );
1842        }
1843    }
1844
1845    #[test]
1846    fn runs_and_the_pending_value_are_persisted_in_the_vault_database() {
1847        let dir = std::env::temp_dir().join(format!("vc-rot-{}", crate::new_uuid()));
1848        std::fs::create_dir_all(&dir).unwrap();
1849        let key =
1850            crate::derive_key(&crate::new_uuid(), &crate::new_uuid().as_bytes()[..16]).unwrap();
1851        let conn = crate::open_db(&dir.join("vault.db"), &key).unwrap();
1852        crate::init_schema(&conn).unwrap();
1853        init_schema(&conn).unwrap();
1854        let mut store = SqlStore { conn: &conn };
1855        let run = Run::plan(
1856            "r9",
1857            "Entry",
1858            3,
1859            Class::SetValueClientGenerated,
1860            Policy::default(),
1861            "old",
1862        );
1863        store.save(&run).unwrap();
1864        store.put_pending("r9", "pending-value").unwrap();
1865        assert_eq!(load_run(&conn, "r9").unwrap().unwrap(), run);
1866        assert_eq!(store.pending("r9").as_deref(), Some("pending-value"));
1867        assert!(
1868            !serde_json::to_string(&run)
1869                .unwrap()
1870                .contains("pending-value"),
1871            "runs hold no values"
1872        );
1873        store.clear_pending("r9").unwrap();
1874        assert!(store.pending("r9").is_none());
1875        assert_eq!(list_runs(&conn).unwrap().len(), 1);
1876        let _ = std::fs::remove_dir_all(&dir);
1877    }
1878}