Skip to main content

weirdnet_update/
verify.rs

1//! The client acceptance rule.
2//!
3//! An update is accepted only when all of these hold:
4//! 1. the root chains to the pinned fingerprint (rotations signed by old and new thresholds);
5//! 2. the manifest carries a threshold of signatures from release keys the root delegates for
6//!    this app and channel, and is inside its validity window;
7//! 3. when the root trusts timestamp keys, a valid, unexpired, short-lived freshness record
8//!    names this exact manifest and doesn't revoke it;
9//! 4. its seq is above the last seen for the channel (the same manifest again is fine);
10//! 5. its kind, client-version range, base release and version (no silent downgrade) fit
11//!    this client.
12//!
13//! Targeting and rollout ([`VerifiedUpdate::applies`]) and consent ([`crate::policy`]) come after.
14
15use crate::envelope::{Domain, Signed};
16use crate::freshness::Freshness;
17use crate::manifest::{UpdateKind, UpdateManifest};
18use crate::root::{Root, RootPin};
19use crate::state::{ClientState, Seen, channel_key, installed_key};
20use crate::target::Device;
21use crate::{Error, Hash32, Result, Timestamp};
22use semver::Version;
23
24/// Per-check settings.
25#[derive(Clone, Debug)]
26pub struct VerifyOptions {
27    /// Current time.
28    pub now: Timestamp,
29    /// The running app version.
30    pub client_version: Version,
31    /// The installed base release id, if the app knows it.
32    pub base_release: Option<String>,
33    /// Accept Dart patches (placeholder; leave `false`).
34    pub dart_patches: bool,
35    /// The Wasm host ABI this build provides; `None` refuses Wasm updates.
36    pub wasm_host_abi: Option<u32>,
37    /// Longest freshness lifetime accepted (default 24 hours).
38    pub max_freshness_secs: u64,
39    /// Allowed clock skew for "not yet valid" checks (default 5 minutes).
40    pub clock_skew_secs: u64,
41}
42
43impl VerifyOptions {
44    /// Defaults for a client at `client_version`.
45    pub fn new(now: Timestamp, client_version: Version) -> Self {
46        Self {
47            now,
48            client_version,
49            base_release: None,
50            dart_patches: false,
51            wasm_host_abi: None,
52            max_freshness_secs: 24 * 3600,
53            clock_skew_secs: 300,
54        }
55    }
56}
57
58/// What arrives from a relay, a peer or HTTPS.
59#[derive(Clone, Debug, Default)]
60pub struct UpdateBundle {
61    /// Root rotations newer than the client may have, oldest first.
62    pub roots: Vec<Signed>,
63    /// The manifest.
64    pub manifest: Option<Signed>,
65    /// The freshness record, when the root trusts timestamp keys.
66    pub freshness: Option<Signed>,
67}
68
69/// A manifest that passed the acceptance rule.
70#[derive(Clone, Debug, PartialEq, Eq)]
71pub struct VerifiedUpdate {
72    /// The manifest.
73    pub manifest: UpdateManifest,
74    /// Its payload hash.
75    pub manifest_hash: Hash32,
76    /// The freshness record that vouched for it, if the root trusts timestamp keys.
77    pub freshness: Option<Freshness>,
78}
79
80/// Whether a verified update is meant for this device right now.
81#[derive(Clone, Copy, Debug, PartialEq, Eq)]
82pub enum Applicability {
83    /// Targeted, and inside the rollout.
84    Applies,
85    /// The targeting rule doesn't match.
86    NotTargeted,
87    /// Targeted, but this device's bucket isn't in the rollout yet (or it is paused).
88    NotInRolloutYet,
89}
90
91impl VerifiedUpdate {
92    /// Evaluates targeting and rollout on the device.
93    pub fn applies(&self, device: &Device) -> Applicability {
94        if let Some(rule) = &self.manifest.targeting
95            && !rule.evaluate(device)
96        {
97            return Applicability::NotTargeted;
98        }
99        let cap = self.freshness.as_ref().and_then(|f| f.rollout_cap_bp);
100        let included = match &self.manifest.rollout {
101            Some(plan) => plan.includes(device.bucket(&self.manifest.update_id), device.now, cap),
102            None => cap.is_none_or(|c| device.bucket(&self.manifest.update_id) < c),
103        };
104        if included { Applicability::Applies } else { Applicability::NotInRolloutYet }
105    }
106}
107
108/// An app's update verifier: the pinned root, the trusted root chain and anti-rollback state.
109#[derive(Debug)]
110pub struct Client {
111    pin: RootPin,
112    root: Root,
113    state: ClientState,
114}
115
116impl Client {
117    /// Starts from the first root, checked against the pin compiled into the app.
118    pub fn new(pin: RootPin, initial_root: &Signed, now: Timestamp) -> Result<Self> {
119        let root = Root::verify_initial(&pin, initial_root, now)?;
120        let state = ClientState { roots: vec![initial_root.clone()], ..ClientState::default() };
121        Ok(Self { pin, root, state })
122    }
123
124    /// Restores saved state, re-verifying the whole root chain from the pin.
125    pub fn from_state(pin: RootPin, state: ClientState, now: Timestamp) -> Result<Self> {
126        let (first, rest) = state.roots.split_first().ok_or_else(|| Error::invalid("client state", "no root"))?;
127        let mut root = Root::verify_initial(&pin, first, now)?;
128        for env in rest {
129            root = root.verify_next(env, now)?;
130        }
131        Ok(Self { pin, root, state })
132    }
133
134    /// The pin.
135    pub fn pin(&self) -> RootPin {
136        self.pin
137    }
138
139    /// The trusted root.
140    pub fn root(&self) -> &Root {
141        &self.root
142    }
143
144    /// State to persist after each change.
145    pub fn state(&self) -> &ClientState {
146        &self.state
147    }
148
149    /// Applies a root rotation. Versions at or below the trusted one are ignored if they are the
150    /// same document, and refused otherwise.
151    pub fn update_root(&mut self, env: &Signed, now: Timestamp) -> Result<()> {
152        if self.state.roots.iter().any(|r| r == env) {
153            return Ok(());
154        }
155        let next = self.root.verify_next(env, now)?;
156        self.root = next;
157        self.state.roots.push(env.clone());
158        Ok(())
159    }
160
161    /// Runs the acceptance rule for `app`/`channel` and records the seq on success.
162    pub fn verify(&mut self, app: &str, channel: &str, bundle: &UpdateBundle, opts: &VerifyOptions) -> Result<VerifiedUpdate> {
163        for env in &bundle.roots {
164            self.update_root(env, opts.now)?;
165        }
166        self.root.check_live(opts.now)?;
167        let target = channel_key(app, channel);
168        let env = bundle.manifest.as_ref().ok_or_else(|| Error::invalid("bundle", "no manifest"))?;
169
170        let keys = self.root.release_keys_for(app, channel, opts.now);
171        if keys.is_empty() {
172            return Err(Error::NotDelegated(target));
173        }
174        env.verify_threshold(Domain::Manifest, &keys, self.root.release_threshold.into())?;
175        let manifest: UpdateManifest = env.decode()?;
176        manifest.validate()?;
177        if manifest.app != app || manifest.channel != channel {
178            return Err(Error::WrongTarget { expected: target, found: manifest.target() });
179        }
180        if opts.now.plus(opts.clock_skew_secs) < manifest.created || opts.now >= manifest.expires {
181            return Err(Error::Expired(Domain::Manifest));
182        }
183        self.check_kind(&manifest, opts)?;
184        if self.state.bad.contains(&manifest.update_id) {
185            return Err(Error::KnownBad(manifest.update_id));
186        }
187
188        let manifest_hash = env.payload_hash();
189        if let Some(seen) = self.state.seen.get(&target) {
190            if manifest.seq < seen.seq {
191                return Err(Error::Replay { last: seen.seq, found: manifest.seq });
192            }
193            if manifest.seq == seen.seq && manifest_hash != seen.manifest_hash {
194                return Err(Error::Equivocation(manifest.seq));
195            }
196        }
197
198        let freshness = self.check_freshness(app, channel, &manifest, manifest_hash, bundle, opts)?;
199        Self::check_applicable(&manifest, opts)?;
200        self.check_downgrade(&manifest, opts)?;
201
202        self.state.seen.insert(target, Seen { seq: manifest.seq, manifest_hash });
203        Ok(VerifiedUpdate { manifest, manifest_hash, freshness })
204    }
205
206    fn check_kind(&self, m: &UpdateManifest, opts: &VerifyOptions) -> Result<()> {
207        match &m.kind {
208            UpdateKind::DartPatch(_) if !opts.dart_patches => Err(Error::UnsupportedKind("dart-patch")),
209            UpdateKind::Wasm { host_abi } if opts.wasm_host_abi != Some(*host_abi) => Err(Error::UnsupportedKind("wasm (host ABI)")),
210            _ => Ok(()),
211        }
212    }
213
214    fn check_freshness(
215        &self,
216        app: &str,
217        channel: &str,
218        m: &UpdateManifest,
219        manifest_hash: Hash32,
220        bundle: &UpdateBundle,
221        opts: &VerifyOptions,
222    ) -> Result<Option<Freshness>> {
223        if !self.root.trusts_timestamps() {
224            // The org trusts no timestamp key: manifest expiry and seq order are the only
225            // freshness checks, and any record that came along carries no weight.
226            return Ok(None);
227        }
228        let env = bundle.freshness.as_ref().ok_or(Error::FreshnessRequired)?;
229        env.verify_threshold(Domain::Freshness, &self.root.timestamp, self.root.timestamp_threshold.into())?;
230        let f: Freshness = env.decode()?;
231        f.validate()?;
232        if f.app != app || f.channel != channel {
233            return Err(Error::WrongTarget { expected: channel_key(app, channel), found: channel_key(&f.app, &f.channel) });
234        }
235        let lifetime = f.expires.0 - f.issued.0;
236        if opts.now.plus(opts.clock_skew_secs) < f.issued || opts.now >= f.expires || lifetime > opts.max_freshness_secs {
237            return Err(Error::Expired(Domain::Freshness));
238        }
239        if f.revoked.iter().any(|id| id == &m.update_id) {
240            return Err(Error::Revoked(m.update_id.clone()));
241        }
242        if f.latest_seq != m.seq || f.manifest_hash != manifest_hash {
243            return Err(Error::FreshnessMismatch);
244        }
245        Ok(Some(f))
246    }
247
248    fn check_applicable(m: &UpdateManifest, opts: &VerifyOptions) -> Result<()> {
249        let v = &opts.client_version;
250        if m.min_client.as_ref().is_some_and(|lo| v < lo) || m.max_client.as_ref().is_some_and(|hi| v > hi) {
251            return Err(Error::ClientVersion(v.to_string()));
252        }
253        if !m.base_releases.is_empty() {
254            let base = opts.base_release.as_deref().unwrap_or("");
255            if !m.base_releases.iter().any(|b| b == base) {
256                return Err(Error::BaseMismatch(base.to_owned()));
257            }
258        }
259        Ok(())
260    }
261
262    fn check_downgrade(&self, m: &UpdateManifest, opts: &VerifyOptions) -> Result<()> {
263        if m.rollback_of.is_some() {
264            return Ok(());
265        }
266        let installed = match &m.kind {
267            UpdateKind::Full(_) | UpdateKind::StoreNotice { .. } => Some(&opts.client_version),
268            _ => self.state.installed.get(&installed_key(&m.app, &m.channel, m.kind.name())),
269        };
270        if let Some(cur) = installed
271            && m.version < *cur
272        {
273            return Err(Error::Downgrade { installed: cur.to_string(), offered: m.version.to_string() });
274        }
275        Ok(())
276    }
277
278    /// Records that an update was installed and committed (after its boot check).
279    pub fn mark_installed(&mut self, update: &VerifiedUpdate) {
280        let m = &update.manifest;
281        self.state.installed.insert(installed_key(&m.app, &m.channel, m.kind.name()), m.version.clone());
282    }
283
284    /// Records that an update failed its boot check; it is refused from now on.
285    pub fn mark_bad(&mut self, update_id: &str) {
286        self.state.bad.insert(update_id.to_owned());
287    }
288}