1use 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
18pub const MAX_KEYS: usize = 32;
20pub const MAX_SCOPE: usize = 256;
22
23#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
25pub struct Delegation {
26 pub key: PublicKey,
28 #[serde(default)]
30 pub apps: Vec<String>,
31 #[serde(default)]
33 pub channels: Vec<String>,
34 #[serde(default)]
36 pub expires: Option<Timestamp>,
37}
38
39impl Delegation {
40 pub fn any(key: PublicKey) -> Self {
42 Self { key, apps: Vec::new(), channels: Vec::new(), expires: None }
43 }
44
45 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
55pub struct Root {
56 pub version: u32,
58 pub org: String,
60 pub keys: Vec<PublicKey>,
62 pub threshold: u8,
64 pub release: Vec<Delegation>,
66 pub release_threshold: u8,
68 #[serde(default)]
71 pub timestamp: Vec<PublicKey>,
72 #[serde(default)]
74 pub timestamp_threshold: u8,
75 #[serde(default)]
77 pub expires: Option<Timestamp>,
78}
79
80impl Root {
81 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 pub fn pin(&self) -> RootPin {
107 RootPin::for_keys(&self.keys, self.threshold)
108 }
109
110 pub fn trusts_timestamps(&self) -> bool {
112 !self.timestamp.is_empty()
113 }
114
115 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 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 pub fn verify_next(&self, env: &Signed, now: Timestamp) -> Result<Self> {
145 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#[derive(Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
184pub struct RootPin(pub Hash32);
185
186impl RootPin {
187 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 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}