From e9b382afe9c8179df01696efe4b1e5542c1247b9 Mon Sep 17 00:00:00 2001 From: Anthony Rocha Date: Mon, 16 Nov 2026 23:19:00 -0800 Subject: [PATCH] orchestrator driver: make verification non-blocking PlatformDriver::execute(VerifyFirmware) called the verifier inline and returned the verdict, so a slow verifier (a crypto service over IPC) blocked the whole dispatch, against the platform rule that replies return as events. The Verifier trait is now start, poll and cancel. One check is outstanding at a time, so poll and cancel name no component. VerifyStatus is Pending, Done(result) or TimedOut. The driver starts a check in execute and collects the result from poll_verify(now_millis). A timeout is not a verification result, so the driver reports it as VerificationFailed and the machine recovers the component instead of locking. A verifier that stops answering signals nothing, so Pending carries the check's deadline, as the boot walks already do. The driver remembers it. poll takes the current time so a verifier with no clock can end a late check. PlatformDriver::poll is the one call a run loop makes: it polls the verification and then the boot walks, and returns DriverPoll::Event for the first event or DriverPoll::Idle with the earliest wake-up of the two. The loop dispatches an event, calls poll again, and sleeps only on Idle. That order is what keeps it from sleeping on a check it has not polled yet, since a new check's deadline is learnt only from its first poll. poll_verify and poll_boot_walks stay as the building blocks. DriverPoll and BootWalkPoll are must_use, because dropping one loses an event the driver has already marked as delivered. The driver cancels any outstanding check when a new one starts or the image is re-staged, so a stale answer is never recorded or emitted. It voids the recorded SVN before the verifier is asked to start, so an earlier reading cannot reach the irreversible floor commit even if the start fails. The old synchronous Verifier and verify_firmware are removed. No production Verifier exists yet; this is the seam it will implement. The existing tests keep passing through a test-local adapter, and new tests cover pending polls, timeout, fault, re-stage, restart, SVN voiding (including a failed start), the machine waiting for a slow verdict, a timeout asking for recovery, the deadline, and poll. Fixes #736 Co-Authored-By: Claude Sonnet 5.5 --- services/orchestrator/driver/README.md | 41 +- services/orchestrator/driver/src/board.rs | 100 ++- services/orchestrator/driver/src/driver.rs | 179 +++++- services/orchestrator/driver/src/lib.rs | 23 +- services/orchestrator/driver/src/tests.rs | 667 +++++++++++++++++++-- 5 files changed, 913 insertions(+), 97 deletions(-) diff --git a/services/orchestrator/driver/README.md b/services/orchestrator/driver/README.md index 2cb47cea9..38a637fd0 100644 --- a/services/orchestrator/driver/README.md +++ b/services/orchestrator/driver/README.md @@ -11,26 +11,45 @@ An effect whose capability is not composed yet returns `EffectError` from `execute`; the SM fail-closes on it. Everything device-specific arrives through the seams in `board.rs` -(`ImageSource`, `Verifier`, `BootControl`, `BootWatch`, bundled in `Board`). -Synchronous results (the verification verdict) return through `execute` and -settle within the same dispatch run — there is no driver-side event queue. +(`ImageSource`, `Verifier`, `BootControl`, `BootWatch`, bundled in `Board`). Nothing the +driver executes waits on a slow service. Short local calls (reset lines, the +SVN floor, reports) complete inside `execute`; the two long reads, the +verification verdict and the boot-walk verdicts, are polled. There is no +driver-side event queue. -Boot-walk verdicts are the one asynchronous read. `ReleaseReset` arms the -component's walk; the run loop polls and dispatches until quiet, then sleeps -until the earliest walk deadline: +`VerifyFirmware` starts a check and returns. The verdict arrives from +`poll_verify` as `VerificationPassed` or `VerificationFailed`; a verifier that +ran past its deadline reports `VerifyStatus::TimedOut`, which the driver +reports as `VerificationFailed` so the machine recovers the component. Starting +a check, or re-staging the image, cancels any check still outstanding, and its +answer is discarded. `ReleaseReset` arms the component's boot walk. The run +loop calls `poll`, dispatches each `Event` it returns, then sleeps on `Idle` until +`next_wake_millis` (the earlier of the earliest walk deadline and the verifier's +deadline) or a signal. It never sleeps without polling after the last dispatch, +because a new check's deadline is learnt only from its first poll. A +verifier that stops answering signals nothing, so its deadline is the only wake-up +that turns its silence into a failed verification: ```rust orch.dispatch(&mut driver, event); loop { - let poll = driver.poll_boot_walks(now_millis); - match poll.event { - Some(ev) => orch.dispatch(&mut driver, ev), - None => break, // poll.next_deadline_millis = next wake-up + // Read the clock each round. + match driver.poll(now_millis) { + // Something is ready: dispatch it, then poll again before sleeping. + Ok(DriverPoll::Event(ev)) => orch.dispatch(&mut driver, ev), + // Quiet: the only place the loop blocks. It wakes when a service + // signals or next_wake_millis passes, then polls again. + Ok(DriverPoll::Idle { next_wake_millis }) => { + object_wait(wait_group, Signals::READABLE, next_wake_millis)?; + } + // The check could not be carried through: fail closed, as an + // executor error does. + Err(_) => orch.dispatch(&mut driver, Event::EffectFailed), } } ``` -Implemented executors: `ReadFirmware`, `VerifyFirmware`, `ReleaseReset` +Implemented executors: `ReadFirmware`, `VerifyFirmware` (starts the check), `ReleaseReset` (arms the boot walk), `AssertReset` (stops it). Everything else fails closed until its pillar lands (recovery, update path, attestation, reporting, lockdown latch). diff --git a/services/orchestrator/driver/src/board.rs b/services/orchestrator/driver/src/board.rs index dc8659169..e434caa4d 100644 --- a/services/orchestrator/driver/src/board.rs +++ b/services/orchestrator/driver/src/board.rs @@ -47,41 +47,97 @@ impl ImageSource for &mut S { } } -/// Judges a component's firmware image; board wiring decides what counts -/// as authenticated. +/// Verifies a component's firmware image without making the caller wait. +/// +/// The split mirrors `util_transport::AsyncTransport`: `start` begins a check +/// and returns, `poll` reports whether it has finished, and `cancel` abandons +/// it. A board whose check is a request to a crypto service implements this +/// directly, so the orchestrator keeps serving timers and events while the +/// image is hashed. A board whose check is fast and local completes it inside +/// `start` and answers `Done` on the first `poll`. +/// +/// # How the run loop uses it +/// +/// One check is outstanding at a time. The driver cancels before starting +/// another, so an implementation never holds two, and `poll` and `cancel` +/// name no component: they mean the check in flight. +/// +/// 1. Call `start`, then call `poll` once straight away. A check that +/// finished inside `start` sends no signal, and the first `poll` is also +/// what reports the check's deadline. +/// 2. Sleep until the verifier signals or that deadline passes, then `poll` +/// again with the current time. A verifier that has stopped answering +/// sends no signal, so the deadline is the only thing that turns its +/// silence into [`VerifyStatus::TimedOut`]. +/// +/// Not object safe by design: `start` is generic over the image source, and a +/// board names its verifier through [`BoardCapabilities::Verifier`]. pub trait Verifier { /// The error type reported by this verifier. type Error: core::error::Error; - /// Judges `id`'s image, reading it from `image`. + /// Begins verifying `id`'s image. An implementation that reaches the image + /// itself, such as a service that reads it from the device server, may + /// ignore `image`. /// /// # Errors /// - /// Only when the check could not be performed (crypto fault, missing - /// key, unreadable source). A checked-and-bad image is - /// `Ok(Verdict::Rejected)` — an actuation fault must not forge a - /// verdict. - fn verify( - &mut self, - id: ComponentId, - image: &mut impl ImageSource, - ) -> Result; + /// Only when the check could not be started. A checked-and-bad image is + /// a [`Verdict::Rejected`] from `poll`, not an error here. + fn start(&mut self, id: ComponentId, image: &mut impl ImageSource) -> Result<(), Self::Error>; + + /// Reports the outcome of the check in flight. Never waits. `now_millis` + /// is the current time, so an implementation with no clock of its own can + /// end a check that has run past its deadline with + /// [`VerifyStatus::TimedOut`]. + /// + /// # Errors + /// + /// Only when the check could not be carried through (the service + /// failed, the transport broke). That is a fault, not a verdict. An + /// error ends the check. + fn poll(&mut self, now_millis: u64) -> Result; + + /// Abandons the check in flight. Its answer, if one arrives later, is + /// discarded. + fn cancel(&mut self) -> Result<(), Self::Error>; } impl Verifier for &mut V { type Error = V::Error; #[inline(always)] - fn verify( - &mut self, - id: ComponentId, - image: &mut impl ImageSource, - ) -> Result { - (**self).verify(id, image) + fn start(&mut self, id: ComponentId, image: &mut impl ImageSource) -> Result<(), Self::Error> { + (**self).start(id, image) + } + + #[inline(always)] + fn poll(&mut self, now_millis: u64) -> Result { + (**self).poll(now_millis) + } + + #[inline(always)] + fn cancel(&mut self) -> Result<(), Self::Error> { + (**self).cancel() } } -/// A [`Verifier`]'s judgment of one image. +/// Where an asynchronous check stands. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum VerifyStatus { + /// Still running. `deadline_millis` is when the check will give up, on the + /// same clock as `poll`'s `now_millis`, or `None` if it has no deadline. + /// The run loop wakes then to poll again. + Pending { deadline_millis: Option }, + /// Finished with a verification result. + Done(Verdict), + /// Ran past the implementation's deadline with no answer. Not a verdict: + /// nothing was verified. The driver reports it as a failed verification, so + /// the machine recovers the component instead of trusting or locking. + TimedOut, +} + +/// A verifier's result for one image. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Verdict { /// Reported as `Event::VerificationPassed`. Carries the image's @@ -164,7 +220,7 @@ impl ReportSink for &mut S { pub trait BoardCapabilities { /// Image access for the managed components. type Image: ImageSource; - /// Judges images for every component. + /// Verifies images for every component, without making the driver wait. type Verifier: Verifier; /// Reset actuation for the managed components. type BootControl: BootControl; @@ -199,7 +255,7 @@ pub enum SvnFloorBinding { /// struct Ast1060Board; /// impl BoardCapabilities for Ast1060Board { /// type Image = SpiFlashImage; // interposed flash, offsets from the slot layout -/// type Verifier = ManifestVerifier; // signature + SVN via the crypto engine +/// type Verifier = ManifestVerifier; // signature + SVN via the crypto engine /// type BootControl = ExtrstGpio; // per-component reset line /// type BootWatch = CheckpointWalk; // GPIO checkpoint walk over the boot window /// type SvnFloor = OtpSvnFloor; // fuse-backed anti-rollback floor @@ -219,7 +275,7 @@ pub struct Board { /// `images[i]` belongs to `ComponentId(i)` — device index = chain /// position = table declaration order. pub images: [B::Image; N], - /// Judges images for every component. + /// Verifies images for every component. pub verifier: B::Verifier, /// `boot_controls[i]` actuates `ComponentId(i)`'s reset, same indexing /// as `images`. diff --git a/services/orchestrator/driver/src/driver.rs b/services/orchestrator/driver/src/driver.rs index 901aea5f8..ef794bfde 100644 --- a/services/orchestrator/driver/src/driver.rs +++ b/services/orchestrator/driver/src/driver.rs @@ -10,6 +10,7 @@ use openprot_orchestrator_sm::{ use crate::board::{ Board, BoardCapabilities, ImageSource, Report, ReportSink, SvnFloorBinding, Verdict, Verifier, + VerifyStatus, }; use orchestrator_capabilities::{BootControl, BootWatch, FailureCause, Svn, SvnFloor, WalkVerdict}; @@ -56,6 +57,12 @@ pub struct PlatformDriver { board: Board, /// Component whose image is staged (source opened) for verification. staged: Option, + /// Component whose verification is outstanding with the verifier. At most + /// one: a new start or a re-stage cancels the old one, so its answer can + /// never be taken for the current image's. + verifying: Option, + /// When the outstanding check will give up, as of the last `poll_verify`. + verify_deadline: Option, /// `watching[i]`: `ComponentId(i)` is out of reset with a walk in /// flight. Set on `ReleaseReset`, cleared on `AssertReset` and on a /// terminal verdict. Only watched walks are polled, so a finished or @@ -74,6 +81,8 @@ impl PlatformDriver { Self { board, staged: None, + verifying: None, + verify_deadline: None, watching: [false; N], verified_svn: [None; N], } @@ -97,40 +106,124 @@ impl PlatformDriver { } /// Stage `id`'s image: open its source so - /// [`verify_firmware`](Self::verify_firmware) can read it. + /// [`start_verify`](Self::start_verify) can read it. + /// + /// # Errors + /// + /// [`DriverError::UnknownComponent`] for an id the driver has no device + /// for, [`DriverError::ImageUnavailable`] when the image cannot be + /// opened, and [`DriverError::VerifierFault`] when cancelling a check + /// still outstanding fails. pub fn stage_firmware(&mut self, id: ComponentId) -> Result<(), DriverError> { self.staged = None; + // A new staging replaces the image an outstanding check was verifying. + self.cancel_verify()?; let source = Self::source(&mut self.board.images, id)?; source.open().map_err(|_| DriverError::ImageUnavailable)?; self.staged = Some(id); Ok(()) } - /// Judge the staged image via the [`Verifier`] and return the verdict: + /// Abandon the outstanding verification, if any. Its answer is discarded. + fn cancel_verify(&mut self) -> Result<(), DriverError> { + self.verify_deadline = None; + if self.verifying.take().is_some() { + self.board + .verifier + .cancel() + .map_err(|_| DriverError::VerifierFault)?; + } + Ok(()) + } + + /// Begin verifying the staged image. Returns at once; the verdict arrives + /// from [`poll`](Self::poll) as /// `Event::VerificationPassed(id)` or `Event::VerificationFailed(id)`. - pub fn verify_firmware(&mut self, id: ComponentId) -> Result { + /// + /// Starting supersedes any check still outstanding, and voids `id`'s + /// recorded SVN: until this check answers, no earlier authenticated + /// reading may reach the anti-rollback commit. + /// + /// # Errors + /// + /// [`DriverError::UnknownComponent`] for an id the driver has no device + /// for, [`DriverError::NotStaged`] when `id`'s image was not staged, and + /// [`DriverError::VerifierFault`] when the verifier could not cancel the + /// old check or start the new one. Either way the recorded SVN is already + /// void. + pub fn start_verify(&mut self, id: ComponentId) -> Result<(), DriverError> { // Id validity first: an unknown component is UnknownComponent even // though it can never be staged. - let source = Self::source(&mut self.board.images, id)?; + Self::source(&mut self.board.images, id)?; if self.staged != Some(id) { return Err(DriverError::NotStaged); } - let verdict = self - .board + self.cancel_verify()?; + // Void the recorded SVN before the verifier is asked, so it is gone + // even if the verifier cannot start: no earlier reading may reach the + // anti-rollback commit until a new check answers. + self.verified_svn[id.get() as usize] = None; + let source = Self::source(&mut self.board.images, id)?; + self.board .verifier - .verify(id, source) + .start(id, source) .map_err(|_| DriverError::VerifierFault)?; + self.verifying = Some(id); + Ok(()) + } + + /// Collect the outstanding verification's outcome, if it has one. Never + /// waits. A run loop calls [`poll`](Self::poll), which includes this and + /// the boot walks; call this directly only to poll the verification alone. + /// + /// A passed check records the image's SVN for the floor commit; a + /// rejection or a timeout clears it and reports + /// `Event::VerificationFailed(id)`. A check that is still pending + /// refreshes the deadline [`next_verify_deadline`](Self::next_verify_deadline) + /// returns, so poll once after [`start_verify`](Self::start_verify) + /// before relying on it. + /// + /// An error means the check could not be carried through. It ends the + /// check, and the run loop should dispatch `Event::EffectFailed`, the same + /// fail-closed answer an executor error gets. + pub fn poll_verify(&mut self, now_millis: u64) -> Result, DriverError> { + let Some(id) = self.verifying else { + return Ok(None); + }; let idx = id.get() as usize; - Ok(match verdict { - Verdict::Authenticated { svn } => { + match self.board.verifier.poll(now_millis) { + Err(_) => { + self.verifying = None; + self.verify_deadline = None; + Err(DriverError::VerifierFault) + } + Ok(VerifyStatus::Pending { deadline_millis }) => { + self.verify_deadline = deadline_millis; + Ok(None) + } + Ok(VerifyStatus::Done(Verdict::Authenticated { svn })) => { + self.verifying = None; + self.verify_deadline = None; self.verified_svn[idx] = Some(svn); - Event::VerificationPassed(id) + Ok(Some(Event::VerificationPassed(id))) } - Verdict::Rejected => { + Ok(VerifyStatus::Done(Verdict::Rejected) | VerifyStatus::TimedOut) => { + self.verifying = None; + self.verify_deadline = None; self.verified_svn[idx] = None; - Event::VerificationFailed(id) + Ok(Some(Event::VerificationFailed(id))) } - }) + } + } + + /// When the outstanding verification will give up, as of the last + /// [`poll_verify`](Self::poll_verify), or `None` if none is outstanding or + /// it has no deadline. The run loop must wake no later than this and poll + /// again: a verifier that has stopped answering signals nothing, so the + /// deadline is the only wake-up that turns its silence into a failed + /// verification. + pub fn next_verify_deadline(&self) -> Option { + self.verify_deadline } /// Advance `id`'s anti-rollback floor to its verified image's SVN. @@ -246,6 +339,37 @@ impl PlatformDriver { } } + /// One round of everything the run loop must poll: the verification, then + /// the boot walks. Returns [`DriverPoll::Event`] at the first event, so + /// dispatch it and call again. When nothing is ready it returns + /// [`DriverPoll::Idle`] with the earliest deadline among the outstanding + /// verification and the waiting walks: the loop sleeps until then or until + /// a service signals, and polls again. + /// + /// Calling this after every dispatch, and sleeping only on `Idle`, is what + /// keeps the loop from sleeping on a check it has not polled yet: a new + /// check's deadline is learnt only from its first poll. + /// + /// # Errors + /// + /// [`DriverError::VerifierFault`] when the verification could not be + /// carried through. Dispatch `Event::EffectFailed`, as for an executor + /// error. + pub fn poll(&mut self, now_millis: u64) -> Result { + if let Some(event) = self.poll_verify(now_millis)? { + return Ok(DriverPoll::Event(event)); + } + let walks = self.poll_boot_walks(now_millis); + if let Some(event) = walks.event { + return Ok(DriverPoll::Event(event)); + } + let next_wake_millis = match (walks.next_deadline_millis, self.verify_deadline) { + (Some(walk), Some(verify)) => Some(walk.min(verify)), + (walk, verify) => walk.or(verify), + }; + Ok(DriverPoll::Idle { next_wake_millis }) + } + /// Hands one report to the board's sink. Cannot fail, so reporting stays /// off the fail-closed path; reports arrive in the order the SM emitted /// them. @@ -254,7 +378,23 @@ impl PlatformDriver { } } -/// One [`PlatformDriver::poll_boot_walks`] round. +/// One [`PlatformDriver::poll`] round. Dropping it loses an event the driver +/// has already marked as delivered. +#[must_use] +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum DriverPoll { + /// The first event from the verification or a boot walk. Dispatch it, then + /// poll again. + Event(Event), + /// Nothing is ready. Sleep until a service signals or `next_wake_millis` + /// (the earliest deadline among the outstanding verification and the + /// waiting walks, `None` if there is none), then poll again. + Idle { next_wake_millis: Option }, +} + +/// One [`PlatformDriver::poll_boot_walks`] round. Dropping it loses an event +/// the driver has already marked as delivered. +#[must_use] #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub struct BootWalkPoll { /// The first terminal verdict's event; `None` when every watched walk @@ -268,14 +408,15 @@ pub struct BootWalkPoll { impl Platform for PlatformDriver { /// Routes each effect to its executor. Exhaustive: a new [`Effect`] - /// variant must get an executor before this compiles. Synchronous - /// results (the verification verdict) come back as the returned event; - /// every executor error reports as [`EffectError`] — the SM treats all - /// actuation failures the same, fail-closed. + /// variant must get an executor before this compiles. Nothing here waits + /// on a slow service: the verification verdict, for one, arrives later + /// from [`poll`](PlatformDriver::poll). Every executor + /// error reports as [`EffectError`] — the SM treats all actuation + /// failures the same, fail-closed. fn execute(&mut self, effect: Effect) -> Result, EffectError> { match effect { Effect::ReadFirmware(id) => self.stage_firmware(id).map(|_| None), - Effect::VerifyFirmware(id) => self.verify_firmware(id).map(Some), + Effect::VerifyFirmware(id) => self.start_verify(id).map(|_| None), Effect::ReleaseReset(id) => self.release_reset(id).map(|_| None), Effect::AssertReset(id) => self.assert_reset(id).map(|_| None), Effect::CommitSvnFloor(id) => self.commit_svn_floor(id).map(|_| None), diff --git a/services/orchestrator/driver/src/lib.rs b/services/orchestrator/driver/src/lib.rs index d2f9e2df3..90e35322c 100644 --- a/services/orchestrator/driver/src/lib.rs +++ b/services/orchestrator/driver/src/lib.rs @@ -10,20 +10,24 @@ //! capability is not composed yet fail closed in `execute`; the driver grows //! an executor only when the capability it delegates to exists. //! -//! Synchronous results (the verification verdict) return through `execute`; -//! the SM queues and settles them within the same dispatch run. There is no -//! driver-side event queue. +//! Nothing the driver executes waits on a slow service. `VerifyFirmware` +//! starts a check and returns; the verdict comes back later from +//! [`PlatformDriver::poll`] as an event for the run loop to dispatch. +//! There is no driver-side event queue: the run loop polls. Short local calls +//! (reset lines, the SVN floor, reports) still complete inside `execute`. //! //! Everything device-specific arrives through the seams in [`board`]: -//! image access ([`ImageSource`]), image judgment ([`Verifier`]), reset -//! actuation ([`orchestrator_capabilities::BootControl`]), boot +//! image access ([`ImageSource`]), image verification ([`Verifier`], start and +//! poll), reset actuation ([`orchestrator_capabilities::BootControl`]), boot //! supervision ([`orchestrator_capabilities::BootWatch`]) and the //! anti-rollback floor ([`orchestrator_capabilities::SvnFloor`]), bundled //! in one [`Board`] built by the board's composition crate. //! -//! Boot-walk verdicts are the one asynchronous read: the run loop calls -//! [`PlatformDriver::poll_boot_walks`] and dispatches the returned events -//! (`ComponentReady`/`Booted`/`BootFailed`) into the SM. +//! Verification verdicts and boot-walk verdicts are the asynchronous reads: +//! the run loop calls [`PlatformDriver::poll`], which covers both, and +//! dispatches the returned events +//! (`VerificationPassed`/`VerificationFailed`, `ComponentReady`/`Booted`/ +//! `BootFailed`) into the SM. //! //! [`Platform`]: openprot_orchestrator_sm::Platform @@ -37,5 +41,6 @@ mod tests; pub use board::{ Board, BoardCapabilities, ImageSource, Report, ReportSink, SvnFloorBinding, Verdict, Verifier, + VerifyStatus, }; -pub use driver::{BootWalkPoll, DriverError, PlatformDriver}; +pub use driver::{BootWalkPoll, DriverError, DriverPoll, PlatformDriver}; diff --git a/services/orchestrator/driver/src/tests.rs b/services/orchestrator/driver/src/tests.rs index 276593176..3d470f684 100644 --- a/services/orchestrator/driver/src/tests.rs +++ b/services/orchestrator/driver/src/tests.rs @@ -94,7 +94,7 @@ impl ImageSource for MemImage { } } -#[derive(Debug)] +#[derive(Debug, PartialEq)] struct VerifierError; impl core::fmt::Display for VerifierError { @@ -105,6 +105,56 @@ impl core::fmt::Display for VerifierError { impl core::error::Error for VerifierError {} +/// A check that runs to completion in one call, as the test fakes below do. +trait SyncCheck { + type Error: core::error::Error; + + fn verify( + &mut self, + id: ComponentId, + image: &mut impl ImageSource, + ) -> Result; +} + +/// Runs a [`SyncCheck`] as a [`Verifier`]: the check happens inside `start` +/// and the first `poll` returns the verdict. A real verifier that is fast and +/// local is written the same way. +struct Immediate { + inner: V, + done: Option, +} + +impl Immediate { + fn new(inner: V) -> Self { + Self { inner, done: None } + } +} + +impl Verifier for Immediate { + type Error = V::Error; + + fn start(&mut self, id: ComponentId, image: &mut impl ImageSource) -> Result<(), Self::Error> { + self.done = None; + let verdict = self.inner.verify(id, image)?; + self.done = Some(verdict); + Ok(()) + } + + fn poll(&mut self, _now_millis: u64) -> Result { + Ok(match self.done.take() { + Some(verdict) => VerifyStatus::Done(verdict), + None => VerifyStatus::Pending { + deadline_millis: None, + }, + }) + } + + fn cancel(&mut self) -> Result<(), Self::Error> { + self.done = None; + Ok(()) + } +} + /// The magic + XOR-zero check as a board-supplied verifier, reading in /// chunks. struct XorVerifier { @@ -115,7 +165,7 @@ struct XorVerifier { svn: u32, } -impl Verifier for XorVerifier { +impl SyncCheck for XorVerifier { type Error = VerifierError; fn verify( @@ -297,7 +347,7 @@ struct MockBoard; impl BoardCapabilities for MockBoard { type Image = MemImage; - type Verifier = XorVerifier; + type Verifier = Immediate; type BootControl = MockReset; type BootWatch = MockWalk; type SvnFloor = MockFloor; @@ -313,10 +363,10 @@ const MOCK_SVN: u32 = 5; fn mock_board() -> Board { Board { images: core::array::from_fn(|_| MemImage::holding(valid_image())), - verifier: XorVerifier { + verifier: Immediate::new(XorVerifier { fault: false, svn: MOCK_SVN, - }, + }), boot_controls: core::array::from_fn(|_| MockReset::new()), boot_watches: core::array::from_fn(|_| MockWalk::idle()), component_kinds: core::array::from_fn(|_| ComponentKind::Passive), @@ -340,15 +390,51 @@ fn orchestrator() -> Orchestrator<1, 4> { Orchestrator::new(chain.try_into().unwrap(), 3) } +/// Start the check and collect its verdict, for a verifier that answers on the +/// first poll (`Immediate`). +fn verify_now( + driver: &mut PlatformDriver, + id: ComponentId, +) -> Result { + driver.start_verify(id)?; + Ok(driver + .poll_verify(0)? + .expect("an immediate verifier answers on the first poll")) +} + +/// Dispatch `event`, then deliver verification verdicts as the run loop does +/// until none is left. A poll error is dispatched as `EffectFailed`. +fn dispatch_settled( + orch: &mut Orchestrator, + driver: &mut PlatformDriver, + event: Event, +) { + orch.dispatch(driver, event); + loop { + match driver.poll_verify(0) { + Ok(Some(ev)) => orch.dispatch(driver, ev), + Ok(None) => break, + Err(_) => { + orch.dispatch(driver, Event::EffectFailed); + break; + } + } + } +} + // PowerGood drives ReadFirmware + VerifyFirmware into the driver; the -// verdict returns through execute and the SM settles it in the same -// dispatch run, carrying a passive component all the way to Ready. +// verdict is polled back and dispatched, carrying a passive component all +// the way to Ready. #[test] fn boot_verifies_the_first_component() { let mut orch = orchestrator(); let mut driver = driver([MemImage::holding(valid_image())]); - orch.dispatch(&mut driver, Event::PowerGood(PowerOnResult::Provisioned)); + dispatch_settled( + &mut orch, + &mut driver, + Event::PowerGood(PowerOnResult::Provisioned), + ); assert_eq!(orch.state(), State::Ready); } @@ -362,7 +448,7 @@ fn corrupt_image_fails_verification() { driver.stage_firmware(C0).unwrap(); assert_eq!( - driver.verify_firmware(C0), + verify_now(&mut driver, C0), Ok(Event::VerificationFailed(C0)) ); } @@ -371,7 +457,7 @@ fn corrupt_image_fails_verification() { fn verify_without_read_is_refused() { let mut driver = driver([MemImage::holding(valid_image())]); - assert_eq!(driver.verify_firmware(C0), Err(DriverError::NotStaged)); + assert_eq!(verify_now(&mut driver, C0), Err(DriverError::NotStaged)); } // An unopenable source is a failed actuation, not a verdict: the SM @@ -383,7 +469,11 @@ fn unopenable_source_fails_closed() { image.fail_open = true; let mut driver = driver([image]); - orch.dispatch(&mut driver, Event::PowerGood(PowerOnResult::Provisioned)); + dispatch_settled( + &mut orch, + &mut driver, + Event::PowerGood(PowerOnResult::Provisioned), + ); assert_eq!(orch.state(), State::Locked); } @@ -397,7 +487,11 @@ fn unreadable_source_fails_closed() { image.fail_read = true; let mut driver = driver([image]); - orch.dispatch(&mut driver, Event::PowerGood(PowerOnResult::Provisioned)); + dispatch_settled( + &mut orch, + &mut driver, + Event::PowerGood(PowerOnResult::Provisioned), + ); assert_eq!(orch.state(), State::Locked); } @@ -407,14 +501,18 @@ fn unreadable_source_fails_closed() { fn verifier_fault_fails_closed() { let mut orch = orchestrator(); let mut driver = PlatformDriver::::new(Board { - verifier: XorVerifier { + verifier: Immediate::new(XorVerifier { fault: true, svn: MOCK_SVN, - }, + }), ..mock_board() }); - orch.dispatch(&mut driver, Event::PowerGood(PowerOnResult::Provisioned)); + dispatch_settled( + &mut orch, + &mut driver, + Event::PowerGood(PowerOnResult::Provisioned), + ); assert_eq!(orch.state(), State::Locked); } @@ -427,7 +525,7 @@ fn verify_for_a_different_component_is_refused() { driver.stage_firmware(C0).unwrap(); - assert_eq!(driver.verify_firmware(C1), Err(DriverError::NotStaged)); + assert_eq!(verify_now(&mut driver, C1), Err(DriverError::NotStaged)); } #[test] @@ -446,7 +544,7 @@ fn verify_of_unknown_component_is_refused() { let mut driver = driver([MemImage::holding(valid_image())]); assert_eq!( - driver.verify_firmware(ComponentId::new(9)), + verify_now(&mut driver, ComponentId::new(9)), Err(DriverError::UnknownComponent) ); } @@ -503,18 +601,22 @@ fn emit_is_refused() { ); } -// The verdict is the returned event of the VerifyFirmware effect. +// VerifyFirmware only starts the check: execute returns at once with no event, +// and the verdict is collected from poll_verify. #[test] -fn execute_returns_the_verdict_event() { +fn execute_starts_the_check_and_the_verdict_is_polled() { use openprot_orchestrator_sm::{Effect, Platform}; let mut driver = driver([MemImage::holding(valid_image())]); assert_eq!(driver.execute(Effect::ReadFirmware(C0)), Ok(None)); + assert_eq!(driver.execute(Effect::VerifyFirmware(C0)), Ok(None)); assert_eq!( - driver.execute(Effect::VerifyFirmware(C0)), + driver.poll_verify(0), Ok(Some(Event::VerificationPassed(C0))) ); + // Delivered once. + assert_eq!(driver.poll_verify(0), Ok(None)); } /// Wraps [`XorVerifier`] and snapshots the reset line as the check runs, @@ -525,7 +627,7 @@ struct LineWatchingVerifier { held_during_verify: std::rc::Rc>, } -impl Verifier for LineWatchingVerifier { +impl SyncCheck for LineWatchingVerifier { type Error = VerifierError; fn verify( @@ -542,7 +644,7 @@ struct WatchBoard; impl BoardCapabilities for WatchBoard { type Image = MemImage; - type Verifier = LineWatchingVerifier; + type Verifier = Immediate; type BootControl = MockReset; type BootWatch = MockWalk; type SvnFloor = MockFloor; @@ -559,14 +661,14 @@ fn release_follows_verification() { let held_during_verify = std::rc::Rc::new(core::cell::Cell::new(false)); let mut driver = PlatformDriver::::new(Board { images: [MemImage::holding(valid_image())], - verifier: LineWatchingVerifier { + verifier: Immediate::new(LineWatchingVerifier { inner: XorVerifier { fault: false, svn: MOCK_SVN, }, line: held.clone(), held_during_verify: held_during_verify.clone(), - }, + }), boot_controls: [control], boot_watches: [MockWalk::idle()], component_kinds: [ComponentKind::Passive], @@ -575,7 +677,11 @@ fn release_follows_verification() { }); let mut orch = orchestrator(); - orch.dispatch(&mut driver, Event::PowerGood(PowerOnResult::Provisioned)); + dispatch_settled( + &mut orch, + &mut driver, + Event::PowerGood(PowerOnResult::Provisioned), + ); assert_eq!(orch.state(), State::Ready); assert!( @@ -598,7 +704,11 @@ fn failed_release_fails_closed() { }); let mut orch = orchestrator(); - orch.dispatch(&mut driver, Event::PowerGood(PowerOnResult::Provisioned)); + dispatch_settled( + &mut orch, + &mut driver, + Event::PowerGood(PowerOnResult::Provisioned), + ); assert_eq!(orch.state(), State::Locked); assert!(held.get(), "never left reset"); @@ -823,7 +933,11 @@ fn booted_walk_settles_in_ready() { ..mock_board() }); - orch.dispatch(&mut driver, Event::PowerGood(PowerOnResult::Provisioned)); + dispatch_settled( + &mut orch, + &mut driver, + Event::PowerGood(PowerOnResult::Provisioned), + ); assert_eq!(orch.state(), State::Ready); let event = driver.poll_boot_walks(0).event.expect("walk completed"); @@ -847,7 +961,11 @@ fn boot_failure_fails_closed_without_recovery() { ..mock_board() }); - orch.dispatch(&mut driver, Event::PowerGood(PowerOnResult::Provisioned)); + dispatch_settled( + &mut orch, + &mut driver, + Event::PowerGood(PowerOnResult::Provisioned), + ); assert_eq!(orch.state(), State::Ready); let event = driver.poll_boot_walks(0).event.expect("walk failed"); @@ -935,6 +1053,7 @@ fn commit_advances_the_floor_to_the_verified_svn() { driver .execute(Effect::VerifyFirmware(C0)) .expect("verify failed"); + driver.poll_verify(0).expect("poll failed"); assert_eq!(driver.execute(Effect::CommitSvnFloor(C0)), Ok(None)); // Read back through the capability's own seam. @@ -984,7 +1103,7 @@ fn rejected_image_clears_the_verified_svn() { driver.stage_firmware(C0).expect("stage failed"); assert_eq!( - driver.verify_firmware(C0), + verify_now(&mut driver, C0), Ok(Event::VerificationPassed(C0)) ); @@ -992,7 +1111,7 @@ fn rejected_image_clears_the_verified_svn() { // the cached SVN with it. driver.stage_firmware(C0).expect("re-stage failed"); assert_eq!( - driver.verify_firmware(C0), + verify_now(&mut driver, C0), Ok(Event::VerificationFailed(C0)) ); @@ -1012,7 +1131,7 @@ fn floor_fault_is_reported() { }); driver.stage_firmware(C0).expect("stage failed"); - driver.verify_firmware(C0).expect("verify failed"); + verify_now(&mut driver, C0).expect("verify failed"); assert_eq!(driver.commit_svn_floor(C0), Err(DriverError::SvnFloorFault)); } @@ -1022,10 +1141,10 @@ fn floor_fault_is_reported() { #[test] fn reports_reach_the_board_sink() { let mut driver = PlatformDriver::::new(Board { - verifier: XorVerifier { + verifier: Immediate::new(XorVerifier { fault: false, svn: 0, - }, + }), ..mock_board() }); @@ -1052,10 +1171,10 @@ fn reports_reach_the_board_sink() { #[test] fn reporting_an_isolated_component_does_not_lock_the_platform() { let mut driver = PlatformDriver::::new(Board { - verifier: XorVerifier { + verifier: Immediate::new(XorVerifier { fault: false, svn: 0, - }, + }), ..mock_board() }); let mut chain = heapless::Vec::<_, 2>::new(); @@ -1067,7 +1186,11 @@ fn reporting_an_isolated_component_does_not_lock_the_platform() { .unwrap(); let mut orch = Orchestrator::<2, 6>::new(chain.try_into().unwrap(), 3); - orch.dispatch(&mut driver, Event::PowerGood(PowerOnResult::Provisioned)); + dispatch_settled( + &mut orch, + &mut driver, + Event::PowerGood(PowerOnResult::Provisioned), + ); assert_eq!(orch.state(), State::Ready, "both components verified"); orch.dispatch(&mut driver, Event::CorruptionDetected(C1)); @@ -1075,3 +1198,475 @@ fn reporting_an_isolated_component_does_not_lock_the_platform() { assert_eq!(orch.state(), State::Ready, "contained, not locked"); assert_eq!(driver.board().report_sink.seen, [Report::Isolated(C1)]); } + +// --------------------------------------------------------------------------- +// Asynchronous verification. +// --------------------------------------------------------------------------- + +/// What a [`ScriptedVerifier`] answers once its pending polls run out. +#[derive(Clone, Copy)] +enum Scripted { + Done(Verdict), + TimedOut, + Fault, +} + +/// An [`Verifier`] the test drives: `Pending` for a set number of polls, +/// then the scripted outcome. Records starts and cancels. +struct ScriptedVerifier { + pending: u32, + outcome: Scripted, + running: bool, + starts: u32, + cancels: u32, + /// When a check that is still pending gives up, in milliseconds. + deadline: Option, + /// Starts after this many have been made fail. + fail_after: Option, +} + +impl ScriptedVerifier { + fn new(pending: u32, outcome: Scripted) -> Self { + Self { + pending, + outcome, + running: false, + starts: 0, + cancels: 0, + deadline: None, + fail_after: None, + } + } +} + +impl Verifier for ScriptedVerifier { + type Error = VerifierError; + + fn start( + &mut self, + _id: ComponentId, + _image: &mut impl ImageSource, + ) -> Result<(), VerifierError> { + self.starts += 1; + if self.fail_after.is_some_and(|n| self.starts > n) { + return Err(VerifierError); + } + self.running = true; + Ok(()) + } + + fn poll(&mut self, now_millis: u64) -> Result { + let pending = VerifyStatus::Pending { + deadline_millis: self.deadline, + }; + if !self.running { + return Ok(pending); + } + if self.deadline.is_some_and(|at| now_millis >= at) { + self.running = false; + return Ok(VerifyStatus::TimedOut); + } + if self.pending > 0 { + self.pending -= 1; + return Ok(pending); + } + self.running = false; + match self.outcome { + Scripted::Done(verdict) => Ok(VerifyStatus::Done(verdict)), + Scripted::TimedOut => Ok(VerifyStatus::TimedOut), + Scripted::Fault => Err(VerifierError), + } + } + + fn cancel(&mut self) -> Result<(), VerifierError> { + self.cancels += 1; + self.running = false; + Ok(()) + } +} + +struct ScriptedBoard; + +impl BoardCapabilities for ScriptedBoard { + type Image = MemImage; + type Verifier = ScriptedVerifier; + type BootControl = MockReset; + type BootWatch = MockWalk; + type SvnFloor = MockFloor; + type ReportSink = RecordingSink; +} + +fn scripted_driver(pending: u32, outcome: Scripted) -> PlatformDriver { + scripted_driver_with_deadline(pending, outcome, None) +} + +fn scripted_driver_with_deadline( + pending: u32, + outcome: Scripted, + deadline: Option, +) -> PlatformDriver { + scripted_driver_with_walk(pending, outcome, deadline, MockWalk::idle()) +} + +fn scripted_driver_with_walk( + pending: u32, + outcome: Scripted, + deadline: Option, + walk: MockWalk, +) -> PlatformDriver { + let mut verifier = ScriptedVerifier::new(pending, outcome); + verifier.deadline = deadline; + PlatformDriver::new(Board { + images: [MemImage::holding(valid_image())], + verifier, + boot_controls: [MockReset::new()], + boot_watches: [walk], + component_kinds: [ComponentKind::Passive], + svn_floors: [SvnFloorBinding::Erot(MockFloor::new())], + report_sink: RecordingSink::new(), + }) +} + +const AUTHENTICATED: Verdict = Verdict::Authenticated { svn: Svn(MOCK_SVN) }; + +// A slow verifier holds the verdict back without holding the driver: starting +// returns at once, polling says nothing until the check answers, and the +// verdict is delivered once. +#[test] +fn a_pending_check_holds_back_the_verdict() { + let mut driver = scripted_driver(2, Scripted::Done(AUTHENTICATED)); + driver.stage_firmware(C0).unwrap(); + + assert_eq!(driver.start_verify(C0), Ok(())); + assert_eq!(driver.poll_verify(0), Ok(None)); + assert_eq!(driver.poll_verify(0), Ok(None)); + assert_eq!( + driver.poll_verify(0), + Ok(Some(Event::VerificationPassed(C0))) + ); + assert_eq!(driver.poll_verify(0), Ok(None)); + assert_eq!(driver.board().verifier.starts, 1); +} + +// A check that ran past its deadline is a failed verification, not a verdict +// and not a lock: the machine recovers the component. No verification completed, so +// no SVN is recorded for the commit. +#[test] +fn a_timed_out_check_reports_failure_and_records_no_svn() { + let mut driver = scripted_driver(0, Scripted::TimedOut); + driver.stage_firmware(C0).unwrap(); + driver.start_verify(C0).unwrap(); + + assert_eq!( + driver.poll_verify(0), + Ok(Some(Event::VerificationFailed(C0))) + ); + assert_eq!( + driver.commit_svn_floor(C0), + Err(DriverError::NoVerifiedImage) + ); +} + +// A verifier that cannot carry the check through is a fault, which ends the +// check; the run loop answers it with EffectFailed. +#[test] +fn a_failed_poll_ends_the_check_with_a_fault() { + let mut driver = scripted_driver(0, Scripted::Fault); + driver.stage_firmware(C0).unwrap(); + driver.start_verify(C0).unwrap(); + + assert_eq!(driver.poll_verify(0), Err(DriverError::VerifierFault)); + assert_eq!(driver.poll_verify(0), Ok(None), "nothing left outstanding"); +} + +// Re-staging replaces the image the outstanding check is verifying, so the check +// is cancelled and its answer never reaches the machine. +#[test] +fn restaging_cancels_the_outstanding_check() { + let mut driver = scripted_driver(5, Scripted::Done(AUTHENTICATED)); + driver.stage_firmware(C0).unwrap(); + driver.start_verify(C0).unwrap(); + + driver.stage_firmware(C0).unwrap(); + + assert_eq!(driver.board().verifier.cancels, 1); + assert_eq!(driver.poll_verify(0), Ok(None), "the old check is gone"); +} + +// Starting a second check cancels the first, so only one is ever outstanding. +#[test] +fn starting_again_cancels_the_first_check() { + let mut driver = scripted_driver(1, Scripted::Done(AUTHENTICATED)); + driver.stage_firmware(C0).unwrap(); + driver.start_verify(C0).unwrap(); + + driver.start_verify(C0).unwrap(); + + assert_eq!(driver.board().verifier.cancels, 1); + assert_eq!(driver.board().verifier.starts, 2); + assert_eq!(driver.poll_verify(0), Ok(None)); + assert_eq!( + driver.poll_verify(0), + Ok(Some(Event::VerificationPassed(C0))) + ); +} + +// Until a new check answers, the earlier authenticated reading must not reach +// the irreversible floor commit. +#[test] +fn starting_a_check_voids_the_earlier_svn() { + let mut driver = scripted_driver(0, Scripted::Done(AUTHENTICATED)); + driver.stage_firmware(C0).unwrap(); + driver.start_verify(C0).unwrap(); + assert_eq!( + driver.poll_verify(0), + Ok(Some(Event::VerificationPassed(C0))) + ); + assert_eq!(driver.commit_svn_floor(C0), Ok(())); + + driver.start_verify(C0).unwrap(); + + assert_eq!( + driver.commit_svn_floor(C0), + Err(DriverError::NoVerifiedImage) + ); +} + +// The full path through the machine with a slow verifier: PowerGood starts +// the check and the machine waits in PreSupervision; only the polled verdict +// carries it to Ready. +#[test] +fn the_machine_waits_for_a_slow_verdict() { + let mut orch = orchestrator(); + let mut driver = scripted_driver(2, Scripted::Done(AUTHENTICATED)); + + orch.dispatch(&mut driver, Event::PowerGood(PowerOnResult::Provisioned)); + assert_eq!(orch.state(), State::PreSupervision, "verdict not in yet"); + + assert_eq!(driver.poll_verify(0), Ok(None)); + assert_eq!(driver.poll_verify(0), Ok(None)); + let verdict = driver.poll_verify(0).unwrap().expect("verdict"); + orch.dispatch(&mut driver, verdict); + + assert_eq!(orch.state(), State::Ready); +} + +/// Delegates to the driver and records the effects the machine emitted. +struct Recording<'a, P: Platform> { + inner: &'a mut P, + effects: std::vec::Vec, +} + +impl Platform for Recording<'_, P> { + fn execute( + &mut self, + effect: Effect, + ) -> Result, openprot_orchestrator_sm::EffectError> { + self.effects.push(effect); + self.inner.execute(effect) + } +} + +// A timeout reaches the machine as a failed verification, so it asks for the +// component to be recovered. It does not report a fault, which would lock the +// platform. (The driver has no recovery executor yet, so the request itself +// still fails closed; that gap is separate from this one.) +#[test] +fn a_timeout_asks_the_machine_to_recover_the_component() { + let mut orch = orchestrator(); + let mut driver = scripted_driver(0, Scripted::TimedOut); + + orch.dispatch(&mut driver, Event::PowerGood(PowerOnResult::Provisioned)); + let verdict = driver.poll_verify(0).unwrap().expect("a timeout answers"); + assert_eq!(verdict, Event::VerificationFailed(C0)); + + let mut recording = Recording { + inner: &mut driver, + effects: std::vec::Vec::new(), + }; + orch.dispatch(&mut recording, verdict); + + assert!( + recording + .effects + .contains(&Effect::RecoverComponent { id: C0, attempt: 0 }), + "the machine asked for recovery: {:?}", + recording.effects + ); +} + +// The run loop sleeps until the verifier's deadline, because a verifier that +// has stopped answering sends no signal. The deadline arrives with the first +// poll after start, and is gone once the check ends. +#[test] +fn the_driver_reports_the_verifiers_deadline_only_while_a_check_is_outstanding() { + let mut driver = scripted_driver_with_deadline(1, Scripted::Done(AUTHENTICATED), Some(100)); + driver.stage_firmware(C0).unwrap(); + assert_eq!(driver.next_verify_deadline(), None, "nothing started yet"); + + driver.start_verify(C0).unwrap(); + assert_eq!( + driver.next_verify_deadline(), + None, + "not learnt until a poll" + ); + + assert_eq!(driver.poll_verify(10), Ok(None)); + assert_eq!(driver.next_verify_deadline(), Some(100)); + assert_eq!( + driver.poll_verify(20), + Ok(Some(Event::VerificationPassed(C0))) + ); + assert_eq!(driver.next_verify_deadline(), None, "the check ended"); +} + +// A verifier that never answers: still pending before its deadline, a failed +// verification at it, so the machine recovers the component. +#[test] +fn a_silent_verifier_times_out_when_polled_at_its_deadline() { + let mut driver = + scripted_driver_with_deadline(u32::MAX, Scripted::Done(AUTHENTICATED), Some(100)); + driver.stage_firmware(C0).unwrap(); + driver.start_verify(C0).unwrap(); + + assert_eq!(driver.poll_verify(99), Ok(None)); + assert_eq!(driver.next_verify_deadline(), Some(100)); + assert_eq!( + driver.poll_verify(100), + Ok(Some(Event::VerificationFailed(C0))) + ); + assert_eq!(driver.next_verify_deadline(), None); + assert_eq!( + driver.commit_svn_floor(C0), + Err(DriverError::NoVerifiedImage) + ); +} + +// A check that finishes inside start has no deadline for the loop to wake for. +#[test] +fn a_verifier_that_finishes_inside_start_has_no_deadline() { + let mut driver = driver([MemImage::holding(valid_image())]); + driver.stage_firmware(C0).unwrap(); + driver.start_verify(C0).unwrap(); + driver.poll_verify(0).unwrap(); + + assert_eq!(driver.next_verify_deadline(), None); +} + +// An earlier authenticated reading must not survive a new check, even one the +// verifier cannot start: the SVN is voided before the verifier is asked. +#[test] +fn a_check_that_cannot_start_still_voids_the_recorded_svn() { + let mut verifier = ScriptedVerifier::new(0, Scripted::Done(AUTHENTICATED)); + verifier.fail_after = Some(1); + let mut driver = PlatformDriver::::new(Board { + images: [MemImage::holding(valid_image())], + verifier, + boot_controls: [MockReset::new()], + boot_watches: [MockWalk::idle()], + component_kinds: [ComponentKind::Passive], + svn_floors: [SvnFloorBinding::Erot(MockFloor::new())], + report_sink: RecordingSink::new(), + }); + driver.stage_firmware(C0).unwrap(); + driver.start_verify(C0).unwrap(); + assert_eq!( + driver.poll_verify(0), + Ok(Some(Event::VerificationPassed(C0))) + ); + + assert_eq!(driver.start_verify(C0), Err(DriverError::VerifierFault)); + + assert_eq!( + driver.commit_svn_floor(C0), + Err(DriverError::NoVerifiedImage), + "the earlier reading must be gone" + ); +} + +// poll: the one call a run loop makes. It polls the verification and the boot +// walks and reports the earliest wake-up, so the loop cannot sleep without +// the deadline of a check it has just started. +#[test] +fn poll_learns_a_new_checks_deadline_in_one_call() { + let mut driver = + scripted_driver_with_deadline(u32::MAX, Scripted::Done(AUTHENTICATED), Some(100)); + driver.stage_firmware(C0).unwrap(); + driver.start_verify(C0).unwrap(); + + assert_eq!( + driver.poll(0), + Ok(DriverPoll::Idle { + next_wake_millis: Some(100) + }) + ); +} + +#[test] +fn poll_reports_the_earliest_of_the_verifier_and_the_walks() { + for (walk_at, verify_at, expected) in [(50, 100, 50), (500, 100, 100)] { + let walk = MockWalk::scripted(std::vec![WalkVerdict::Waiting { + deadline_millis: walk_at, + }]); + let mut driver = scripted_driver_with_walk( + u32::MAX, + Scripted::Done(AUTHENTICATED), + Some(verify_at), + walk, + ); + driver.stage_firmware(C0).unwrap(); + driver.start_verify(C0).unwrap(); + driver.release_reset(C0).unwrap(); + + assert_eq!( + driver.poll(0), + Ok(DriverPoll::Idle { + next_wake_millis: Some(expected) + }), + "walk at {walk_at}, verifier at {verify_at}" + ); + } +} + +#[test] +fn poll_returns_the_verification_before_the_walks() { + let walk = MockWalk::scripted(std::vec![WalkVerdict::Complete]); + let mut driver = scripted_driver_with_walk(0, Scripted::Done(AUTHENTICATED), None, walk); + driver.stage_firmware(C0).unwrap(); + driver.start_verify(C0).unwrap(); + driver.release_reset(C0).unwrap(); + + assert_eq!( + driver.poll(0), + Ok(DriverPoll::Event(Event::VerificationPassed(C0))) + ); + assert_eq!(driver.poll(0), Ok(DriverPoll::Event(Event::Booted(C0)))); + assert_eq!( + driver.poll(0), + Ok(DriverPoll::Idle { + next_wake_millis: None + }), + "each event is delivered once, then the loop is quiet" + ); +} + +#[test] +fn poll_with_nothing_outstanding_is_quiet() { + let mut driver = scripted_driver(0, Scripted::Done(AUTHENTICATED)); + + assert_eq!( + driver.poll(0), + Ok(DriverPoll::Idle { + next_wake_millis: None + }) + ); +} + +#[test] +fn poll_passes_a_verifier_fault_through() { + let mut driver = scripted_driver(0, Scripted::Fault); + driver.stage_firmware(C0).unwrap(); + driver.start_verify(C0).unwrap(); + + assert_eq!(driver.poll(0), Err(DriverError::VerifierFault)); +}