Skip to main content

weirdnet_update/
root.rs

1//! Org roots: the client's root of trust.
2//!
3//! A [`Root`] lists the org's k-of-n root keys, the release keys it delegates (optionally
4//! scoped to apps and channels, with an expiry) and the timestamp keys the org chose to trust:
5//! none, the WeirdBrains timestamp key, the org's own, or several. The app pins a
6//! [`RootPin`] (a fingerprint of the first root's keys and threshold) at build time.
7//!
8//! Rotation follows TUF: root version N+1 must be signed by a threshold of version N's keys
9//! *and* a threshold of its own keys.
10
11use crate::envelope::{Domain, Signed};
12use crate::ids::{check_id, check_unique};
13use crate::keys::PublicKey;
14use crate::{Error, Hash32, Result, Timestamp};
15use serde::{Deserialize, Serialize};
16use std::fmt;
17
18/// Most keys in any one role.
19pub const MAX_KEYS: usize = 32;
20/// Most app or channel names in one delegation scope.
21pub const MAX_SCOPE: usize = 256;
22
23/// A release key delegated by the root.
24#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
25pub struct Delegation {
26    /// The release key.
27    pub key: PublicKey,
28    /// Apps it may sign for; empty means every app of the org.
29    #[serde(default)]
30    pub apps: Vec<String>,
31    /// Channels it may sign for; empty means every channel.
32    #[serde(default)]
33    pub channels: Vec<String>,
34    /// After this time the delegation no longer counts.
35    #[serde(default)]
36    pub expires: Option<Timestamp>,
37}
38
39impl Delegation {
40    /// An unscoped delegation with no expiry.
41    pub fn any(key: PublicKey) -> Self {
42        Self { key, apps: Vec::new(), channels: Vec::new(), expires: None }
43    }
44
45    /// Whether this delegation covers `app`/`channel` at `now`.
46    pub fn covers(&self, app: &str, channel: &str, now: Timestamp) -> bool {
47        (self.apps.is_empty() || self.apps.iter().any(|a| a == app))
48            && (self.channels.is_empty() || self.channels.iter().any(|c| c == channel))
49            && self.expires.is_none_or(|e| now < e)
50    }
51}
52
53/// An org root record.
54#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
55pub struct Root {
56    /// Starts at 1 and goes up by exactly 1 per rotation.
57    pub version: u32,
58    /// The org's id on the service.
59    pub org: String,
60    /// Root keys (held offline by the org, never by the service).
61    pub keys: Vec<PublicKey>,
62    /// Root signatures needed.
63    pub threshold: u8,
64    /// Delegated release keys.
65    pub release: Vec<Delegation>,
66    /// Release signatures needed on a manifest.
67    pub release_threshold: u8,
68    /// Trusted timestamp keys; empty means the app trusts none (freshness falls back to the
69    /// manifest's own expiry and seq order).
70    #[serde(default)]
71    pub timestamp: Vec<PublicKey>,
72    /// Timestamp signatures needed; 0 exactly when `timestamp` is empty.
73    #[serde(default)]
74    pub timestamp_threshold: u8,
75    /// Optional expiry of this root version.
76    #[serde(default)]
77    pub expires: Option<Timestamp>,
78}
79
80impl Root {
81    /// Structural checks: ids, no duplicate keys, thresholds within range, limits.
82    pub fn validate(&self) -> Result<()> {
83        if self.version == 0 {
84            return Err(Error::invalid("root", "version starts at 1"));
85        }
86        check_id("org", &self.org)?;
87        check_role("root keys", &self.keys, self.threshold, false)?;
88        let release_keys: Vec<PublicKey> = self.release.iter().map(|d| d.key).collect();
89        check_role("release keys", &release_keys, self.release_threshold, false)?;
90        check_role("timestamp keys", &self.timestamp, self.timestamp_threshold, true)?;
91        for d in &self.release {
92            if d.apps.len() > MAX_SCOPE || d.channels.len() > MAX_SCOPE {
93                return Err(Error::invalid("delegation", format!("more than {MAX_SCOPE} scope entries")));
94            }
95            for a in &d.apps {
96                check_id("app", a)?;
97            }
98            for c in &d.channels {
99                check_id("channel", c)?;
100            }
101        }
102        Ok(())
103    }
104
105    /// The fingerprint of this root's keys and threshold.
106    pub fn pin(&self) -> RootPin {
107        RootPin::for_keys(&self.keys, self.threshold)
108    }
109
110    /// Whether the app trusts any timestamp key.
111    pub fn trusts_timestamps(&self) -> bool {
112        !self.timestamp.is_empty()
113    }
114
115    /// Release keys that may sign for `app`/`channel` at `now`.
116    pub fn release_keys_for(&self, app: &str, channel: &str, now: Timestamp) -> Vec<PublicKey> {
117        self.release.iter().filter(|d| d.covers(app, channel, now)).map(|d| d.key).collect()
118    }
119
120    pub(crate) fn check_live(&self, now: Timestamp) -> Result<()> {
121        if self.expires.is_some_and(|e| now >= e) {
122            return Err(Error::Expired(Domain::Root));
123        }
124        Ok(())
125    }
126
127    /// Verifies the first root against the pin compiled into the app: its keys must hash to
128    /// the pin and a threshold of them must have signed it.
129    pub fn verify_initial(pin: &RootPin, env: &Signed, now: Timestamp) -> Result<Self> {
130        if env.domain != Domain::Root {
131            return Err(Error::WrongDomain { expected: Domain::Root, found: env.domain });
132        }
133        let root: Root = env.decode()?;
134        root.validate()?;
135        if root.pin() != *pin {
136            return Err(Error::PinMismatch);
137        }
138        env.verify_threshold(Domain::Root, &root.keys, root.threshold.into())?;
139        root.check_live(now)?;
140        Ok(root)
141    }
142
143    /// Verifies a rotation from `self` to the next version.
144    pub fn verify_next(&self, env: &Signed, now: Timestamp) -> Result<Self> {
145        // Old keys first: nothing in the payload is trusted until the current root vouches for it.
146        env.verify_threshold(Domain::Root, &self.keys, self.threshold.into())?;
147        let next: Root = env.decode()?;
148        next.validate()?;
149        if next.version != self.version.saturating_add(1) || self.version == u32::MAX {
150            return Err(Error::RootVersion { current: self.version, found: next.version });
151        }
152        if next.org != self.org {
153            return Err(Error::RootOrg);
154        }
155        env.verify_threshold(Domain::Root, &next.keys, next.threshold.into())?;
156        next.check_live(now)?;
157        Ok(next)
158    }
159}
160
161fn check_role(what: &'static str, keys: &[PublicKey], threshold: u8, may_be_empty: bool) -> Result<()> {
162    if keys.len() > MAX_KEYS {
163        return Err(Error::invalid(what, format!("more than {MAX_KEYS} keys")));
164    }
165    check_unique(what, keys)?;
166    if keys.is_empty() {
167        return if may_be_empty && threshold == 0 {
168            Ok(())
169        } else if may_be_empty {
170            Err(Error::invalid(what, "threshold must be 0 when no keys are listed"))
171        } else {
172            Err(Error::invalid(what, "at least one key is required"))
173        };
174    }
175    if threshold == 0 || usize::from(threshold) > keys.len() {
176        return Err(Error::invalid(what, format!("threshold must be 1..={}", keys.len())));
177    }
178    Ok(())
179}
180
181/// The trust anchor compiled into an app: BLAKE3 (derive-key mode) over the threshold and the
182/// sorted root keys. It names a key set, not a document, so it survives re-signing.
183#[derive(Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
184pub struct RootPin(pub Hash32);
185
186impl RootPin {
187    /// The pin for a root key set.
188    pub fn for_keys(keys: &[PublicKey], threshold: u8) -> Self {
189        let mut sorted: Vec<&PublicKey> = keys.iter().collect();
190        sorted.sort();
191        let mut h = blake3::Hasher::new_derive_key("weirdnet-update v1 root pin");
192        h.update(&[threshold]);
193        h.update(&(sorted.len() as u32).to_le_bytes());
194        for k in sorted {
195            h.update(k.as_bytes());
196        }
197        Self(h.finalize().into())
198    }
199
200    /// Parses the hex form (as written in `salty.toml`).
201    pub fn from_hex(s: &str) -> Result<Self> {
202        Ok(Self(Hash32::from_hex(s)?))
203    }
204}
205
206impl fmt::Display for RootPin {
207    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208        f.write_str(&self.0.to_hex())
209    }
210}
211
212impl fmt::Debug for RootPin {
213    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214        write!(f, "RootPin({})", self.0.to_hex())
215    }
216}