1use 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#[derive(Clone, Debug)]
26pub struct VerifyOptions {
27 pub now: Timestamp,
29 pub client_version: Version,
31 pub base_release: Option<String>,
33 pub dart_patches: bool,
35 pub wasm_host_abi: Option<u32>,
37 pub max_freshness_secs: u64,
39 pub clock_skew_secs: u64,
41}
42
43impl VerifyOptions {
44 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#[derive(Clone, Debug, Default)]
60pub struct UpdateBundle {
61 pub roots: Vec<Signed>,
63 pub manifest: Option<Signed>,
65 pub freshness: Option<Signed>,
67}
68
69#[derive(Clone, Debug, PartialEq, Eq)]
71pub struct VerifiedUpdate {
72 pub manifest: UpdateManifest,
74 pub manifest_hash: Hash32,
76 pub freshness: Option<Freshness>,
78}
79
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
82pub enum Applicability {
83 Applies,
85 NotTargeted,
87 NotInRolloutYet,
89}
90
91impl VerifiedUpdate {
92 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#[derive(Debug)]
110pub struct Client {
111 pin: RootPin,
112 root: Root,
113 state: ClientState,
114}
115
116impl Client {
117 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 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 pub fn pin(&self) -> RootPin {
136 self.pin
137 }
138
139 pub fn root(&self) -> &Root {
141 &self.root
142 }
143
144 pub fn state(&self) -> &ClientState {
146 &self.state
147 }
148
149 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 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 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 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 pub fn mark_bad(&mut self, update_id: &str) {
286 self.state.bad.insert(update_id.to_owned());
287 }
288}