OXYGENHUB
# 728da0f92161 oxygen / crates / oxy-core / src / policy.rs
14.3 KiB · Rust · last changed Identity lifecycle: rotate, renew, delegates, revoke; expiry checks; policy roots, thresholds, proposals and oxy policy sign; policy chains served on refs and carried in push bundles (spec 0.6n) 1 month ago source blame history raw
1
//! The trust policy (spec §14.5): who may update which references, signed
2
//! by a threshold of root keys. A repository without a policy is unverified.
3
//!
4
//! Encoding: `{0: version, 1: repo, 2: serial, 3: {0: root keys, 1: threshold},
5
//! 4: [rule], 5: [identity bytes], 6: [revoked], 7: expires}`; a rule is
6
//! `{0: pattern, 1: keys, 2: threshold, 3: require, 4: allow_conflicts}` with
7
//! `require` 0 = signed, 1 = sealed, 2 = any.
8
9
use crate::cbor::{self, Value};
10
use crate::hash::{hash_object, KeyId, ObjectRef, ObjectType};
11
use crate::identity::{self, Domain, Identity, Signature};
12
use crate::objects::{array, bytes, check_version, field, map, oref, text, uint, ObjectError, FORMAT_VERSION};
13
use std::collections::BTreeMap;
14
15
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16
pub enum Require {
17
    Signed,
18
    Sealed,
19
    Any,
20
}
21
22
impl Require {
23
    fn tag(self) -> u64 {
24
        match self {
25
            Require::Signed => 0,
26
            Require::Sealed => 1,
27
            Require::Any => 2,
28
        }
29
    }
30
    fn from_tag(t: u64) -> Result<Require, ObjectError> {
31
        Ok(match t {
32
            0 => Require::Signed,
33
            1 => Require::Sealed,
34
            2 => Require::Any,
35
            _ => return Err(ObjectError::Schema(format!("unknown require {t}"))),
36
        })
37
    }
38
    pub fn name(self) -> &'static str {
39
        match self {
40
            Require::Signed => "signed",
41
            Require::Sealed => "sealed",
42
            Require::Any => "any",
43
        }
44
    }
45
}
46
47
#[derive(Clone, Debug, PartialEq, Eq)]
48
pub struct Rule {
49
    /// Glob over reference names; `*` matches any run of characters.
50
    pub pattern: String,
51
    pub keys: Vec<KeyId>,
52
    pub threshold: u32,
53
    pub require: Require,
54
    pub allow_conflicts: bool,
55
}
56
57
#[derive(Clone, Debug, PartialEq, Eq)]
58
pub struct Policy {
59
    pub repo: [u8; 16],
60
    pub serial: u64,
61
    pub roots: Vec<KeyId>,
62
    pub root_threshold: u32,
63
    pub rules: Vec<Rule>,
64
    /// Embedded so verification needs no fetch.
65
    pub identities: Vec<Identity>,
66
    pub revoked: Vec<KeyId>,
67
    pub expires: u64,
68
}
69
70
/// `*` matches any run of characters (including `/`); everything else is literal.
71
pub fn glob_matches(pattern: &str, name: &str) -> bool {
72
    fn rec(p: &[u8], n: &[u8]) -> bool {
73
        match p.first() {
74
            None => n.is_empty(),
75
            Some(b'*') => (0..=n.len()).any(|i| rec(&p[1..], &n[i..])),
76
            Some(c) => n.first() == Some(c) && rec(&p[1..], &n[1..]),
77
        }
78
    }
79
    rec(pattern.as_bytes(), name.as_bytes())
80
}
81
82
impl Policy {
83
    fn keys_value(keys: &[KeyId]) -> Value {
84
        Value::Array(keys.iter().map(|k| Value::Bytes(k.0.to_vec())).collect())
85
    }
86
    fn keys_from(v: &Value, what: &str) -> Result<Vec<KeyId>, ObjectError> {
87
        let mut ks = array(v, what)?.iter().map(|k| oref(k, what)).collect::<Result<Vec<_>, _>>()?;
88
        ks.sort();
89
        ks.dedup();
90
        Ok(ks)
91
    }
92
93
    pub fn to_value(&self) -> Value {
94
        Value::map([
95
            (0, Value::Uint(FORMAT_VERSION)),
96
            (1, Value::Bytes(self.repo.to_vec())),
97
            (2, Value::Uint(self.serial)),
98
            (3, Value::map([(0, Self::keys_value(&self.roots)), (1, Value::Uint(self.root_threshold as u64))])),
99
            (
100
                4,
101
                Value::Array(
102
                    self.rules
103
                        .iter()
104
                        .map(|r| {
105
                            Value::map([
106
                                (0, Value::Text(r.pattern.clone())),
107
                                (1, Self::keys_value(&r.keys)),
108
                                (2, Value::Uint(r.threshold as u64)),
109
                                (3, Value::Uint(r.require.tag())),
110
                                (4, Value::Bool(r.allow_conflicts)),
111
                            ])
112
                        })
113
                        .collect(),
114
                ),
115
            ),
116
            (5, Value::Array(self.identities.iter().map(|i| Value::Bytes(i.encode())).collect())),
117
            (6, Self::keys_value(&self.revoked)),
118
            (7, Value::Uint(self.expires)),
119
        ])
120
    }
121
122
    pub fn encode(&self) -> Vec<u8> {
123
        cbor::encode(&self.to_value())
124
    }
125
126
    pub fn hash(&self) -> ObjectRef {
127
        hash_object(ObjectType::Policy, &self.encode())
128
    }
129
130
    pub fn decode(b: &[u8]) -> Result<Policy, ObjectError> {
131
        let v = cbor::decode(b)?;
132
        let m = map(&v, "policy")?;
133
        check_version(m)?;
134
        let roots = map(field(m, 3, "roots")?, "roots")?;
135
        let mut rules = Vec::new();
136
        for r in array(field(m, 4, "rules")?, "rules")? {
137
            let rm = map(r, "rule")?;
138
            rules.push(Rule {
139
                pattern: text(field(rm, 0, "pattern")?, "pattern")?.to_owned(),
140
                keys: Self::keys_from(field(rm, 1, "rule keys")?, "rule keys")?,
141
                threshold: uint(field(rm, 2, "threshold")?, "threshold")? as u32,
142
                require: Require::from_tag(uint(field(rm, 3, "require")?, "require")?)?,
143
                allow_conflicts: field(rm, 4, "allow_conflicts")?.as_bool().ok_or_else(|| ObjectError::Schema("allow_conflicts: expected bool".into()))?,
144
            });
145
        }
146
        let identities = array(field(m, 5, "identities")?, "identities")?
147
            .iter()
148
            .map(|i| Identity::decode(bytes(i, "identity")?))
149
            .collect::<Result<Vec<_>, _>>()?;
150
        let p = Policy {
151
            repo: bytes(field(m, 1, "repo")?, "repo")?.try_into().map_err(|_| ObjectError::Schema("repo: expected 16 bytes".into()))?,
152
            serial: uint(field(m, 2, "serial")?, "serial")?,
153
            roots: Self::keys_from(field(roots, 0, "root keys")?, "root keys")?,
154
            root_threshold: uint(field(roots, 1, "root threshold")?, "root threshold")? as u32,
155
            rules,
156
            identities,
157
            revoked: Self::keys_from(field(m, 6, "revoked")?, "revoked")?,
158
            expires: uint(field(m, 7, "expires")?, "expires")?,
159
        };
160
        if p.root_threshold == 0 || p.root_threshold as usize > p.roots.len() {
161
            return Err(ObjectError::Schema("root threshold must be between 1 and the number of root keys".into()));
162
        }
163
        for r in &p.rules {
164
            if r.threshold == 0 || r.threshold as usize > r.keys.len() {
165
                return Err(ObjectError::Schema(format!("rule {:?}: threshold must be between 1 and the number of keys", r.pattern)));
166
            }
167
        }
168
        Ok(p)
169
    }
170
171
    pub fn identity(&self, key: &KeyId) -> Option<&Identity> {
172
        self.identities.iter().find(|i| i.hash() == *key)
173
    }
174
175
    pub fn is_revoked(&self, key: &KeyId) -> bool {
176
        self.revoked.contains(key)
177
    }
178
179
    pub fn is_expired(&self, now_ms: u64) -> bool {
180
        now_ms > self.expires
181
    }
182
183
    /// The first rule whose pattern matches `reference`.
184
    pub fn rule_for(&self, reference: &str) -> Option<&Rule> {
185
        self.rules.iter().find(|r| glob_matches(&r.pattern, reference))
186
    }
187
188
    /// Whether `key` may update `reference`: listed in the matching rule and not revoked.
189
    pub fn authorizes(&self, key: &KeyId, reference: &str) -> bool {
190
        !self.is_revoked(key) && self.rule_for(reference).is_some_and(|r| r.keys.contains(key))
191
    }
192
193
    /// Verify that `sigs` over this policy's hash meet `trusted`'s root
194
    /// threshold (`trusted` is the previous policy, or this one when
195
    /// bootstrapping). Returns the signing root keys.
196
    pub fn verify_signatures(&self, sigs: &[Signature], trusted: &Policy) -> Result<Vec<KeyId>, String> {
197
        let target = self.hash();
198
        let mut signers = Vec::new();
199
        for sig in sigs {
200
            if !trusted.roots.contains(&sig.key) || trusted.is_revoked(&sig.key) {
201
                continue;
202
            }
203
            let Some(id) = trusted.identity(&sig.key).or_else(|| self.identity(&sig.key)) else { continue };
204
            if identity::verify(id, sig, Domain::Policy, &target).is_ok() && !signers.contains(&sig.key) {
205
                signers.push(sig.key);
206
            }
207
        }
208
        if (signers.len() as u32) < trusted.root_threshold {
209
            return Err(format!("policy needs {} root signature(s), has {}", trusted.root_threshold, signers.len()));
210
        }
211
        Ok(signers)
212
    }
213
214
    /// Bootstrap check for the first policy a repository sees (trust on
215
    /// first use): at least one valid signature by one of its own roots.
216
    /// The full threshold applies only to updates from a trusted policy,
217
    /// whose signers are the previous roots and need not be the new ones.
218
    pub fn verify_bootstrap(&self, sigs: &[Signature]) -> Result<KeyId, String> {
219
        let target = self.hash();
220
        for sig in sigs {
221
            if !self.roots.contains(&sig.key) || self.is_revoked(&sig.key) {
222
                continue;
223
            }
224
            if let Some(id) = self.identity(&sig.key) {
225
                if identity::verify(id, sig, Domain::Policy, &target).is_ok() {
226
                    return Ok(sig.key);
227
                }
228
            }
229
        }
230
        Err("policy carries no valid signature by one of its own root keys".into())
231
    }
232
233
    /// A single-root policy letting `root` do everything on every reference.
234
    pub fn single_root(repo: [u8; 16], root: Identity, expires: u64) -> Policy {
235
        let key = root.hash();
236
        Policy {
237
            repo,
238
            serial: 1,
239
            roots: vec![key],
240
            root_threshold: 1,
241
            rules: vec![Rule { pattern: "*".into(), keys: vec![key], threshold: 1, require: Require::Any, allow_conflicts: true }],
242
            identities: vec![root],
243
            revoked: vec![],
244
            expires,
245
        }
246
    }
247
248
    /// Whether `key` appears anywhere in the policy (roots, rules, identities).
249
    pub fn mentions(&self, key: &KeyId) -> bool {
250
        self.roots.contains(key) || self.rules.iter().any(|r| r.keys.contains(key)) || self.identity(key).is_some()
251
    }
252
253
    /// Whether `key` is `rule_key` or one of its predecessors in the
254
    /// rotation chain (`previous` links, spec §14.2), so that changes signed
255
    /// before a rotation remain authorized. Revoked keys never qualify.
256
    pub fn succeeds(&self, rule_key: &KeyId, key: &KeyId) -> bool {
257
        if self.is_revoked(key) {
258
            return false;
259
        }
260
        let mut cur = Some(*rule_key);
261
        for _ in 0..32 {
262
            match cur {
263
                Some(k) if k == *key => return true,
264
                Some(k) => cur = self.identity(&k).and_then(|i| i.previous),
265
                None => return false,
266
            }
267
        }
268
        false
269
    }
270
271
    /// Replace `old` by `new` in the roots and every rule and embed `new`'s
272
    /// identity (a rotation, spec §14.2). The old identity stays embedded so
273
    /// signatures made before the rotation still verify; it is superseded,
274
    /// not revoked.
275
    pub fn substitute_key(&mut self, old: &KeyId, new: Identity) {
276
        let nk = new.hash();
277
        for k in self.roots.iter_mut().chain(self.rules.iter_mut().flat_map(|r| r.keys.iter_mut())) {
278
            if k == old {
279
                *k = nk;
280
            }
281
        }
282
        for r in &mut self.rules {
283
            r.keys.sort();
284
            r.keys.dedup();
285
        }
286
        self.roots.sort();
287
        self.roots.dedup();
288
        if self.identity(&nk).is_none() {
289
            self.identities.push(new);
290
        }
291
    }
292
293
    /// Identities keyed by KeyId.
294
    pub fn identity_map(&self) -> BTreeMap<KeyId, &Identity> {
295
        self.identities.iter().map(|i| (i.hash(), i)).collect()
296
    }
297
}
298
299
#[cfg(test)]
300
mod tests {
301
    use super::*;
302
    use crate::identity::SecretKey;
303
304
    fn sk(n: u8) -> SecretKey {
305
        SecretKey { ed_seed: [n; 32], ml_seed: [n + 100; 32] }
306
    }
307
308
    #[test]
309
    fn globs() {
310
        assert!(glob_matches("*", "main"));
311
        assert!(glob_matches("release/*", "release/1.0"));
312
        assert!(!glob_matches("release/*", "main"));
313
        assert!(glob_matches("main", "main"));
314
        assert!(!glob_matches("main", "main2"));
315
        assert!(glob_matches("*-rc*", "1.0-rc2"));
316
        assert!(glob_matches("", ""));
317
    }
318
319
    #[test]
320
    fn round_trip_and_rules() {
321
        let root = sk(1).identity("Root", "r@x", 0);
322
        let dev = sk(2).identity("Dev", "d@x", 0);
323
        let mut p = Policy::single_root([9; 16], root.clone(), 10);
324
        p.rules.insert(0, Rule { pattern: "release/*".into(), keys: vec![root.hash()], threshold: 1, require: Require::Signed, allow_conflicts: false });
325
        p.rules[1].keys.push(dev.hash());
326
        p.identities.push(dev.clone());
327
        p.revoked.push(ObjectRef([7; 32]));
328
        let d = Policy::decode(&p.encode()).unwrap();
329
        assert_eq!(d.rules.len(), 2);
330
        assert_eq!(d.rules[0].require, Require::Signed);
331
        assert_eq!(d.identity(&dev.hash()), Some(&dev));
332
        assert!(d.authorizes(&dev.hash(), "main"));
333
        assert!(!d.authorizes(&dev.hash(), "release/1"));
334
        assert!(d.authorizes(&root.hash(), "release/1"));
335
        assert!(d.is_expired(11) && !d.is_expired(10));
336
        assert_eq!(d.hash(), p.hash());
337
338
        let mut bad = p.clone();
339
        bad.root_threshold = 5;
340
        assert!(Policy::decode(&bad.encode()).is_err());
341
    }
342
343
    #[test]
344
    fn signatures_need_root_threshold() {
345
        let r1 = sk(1);
346
        let r2 = sk(2);
347
        let i1 = r1.identity("a", "a", 0);
348
        let i2 = r2.identity("b", "b", 0);
349
        let mut p = Policy::single_root([1; 16], i1.clone(), 100);
350
        p.roots.push(i2.hash());
351
        p.roots.sort();
352
        p.root_threshold = 2;
353
        p.identities.push(i2.clone());
354
        let h = p.hash();
355
        let s1 = r1.sign(Domain::Policy, &i1.hash(), &h);
356
        let s2 = r2.sign(Domain::Policy, &i2.hash(), &h);
357
        assert!(p.verify_signatures(&[s1.clone()], &p).is_err());
358
        assert_eq!(p.verify_signatures(&[s1.clone(), s2.clone()], &p).unwrap().len(), 2);
359
        // Duplicates do not count twice; a non-root signer does not count.
360
        assert!(p.verify_signatures(&[s1.clone(), s1.clone()], &p).is_err());
361
        let stranger = sk(3);
362
        let si = stranger.identity("s", "s", 0);
363
        let s3 = stranger.sign(Domain::Policy, &si.hash(), &h);
364
        assert!(p.verify_signatures(&[s1.clone(), s3], &p).is_err());
365
        // A successor policy is verified against the previous roots.
366
        let mut next = p.clone();
367
        next.serial = 2;
368
        next.revoked.push(i2.hash());
369
        let nh = next.hash();
370
        let n1 = r1.sign(Domain::Policy, &i1.hash(), &nh);
371
        let n2 = r2.sign(Domain::Policy, &i2.hash(), &nh);
372
        assert_eq!(next.verify_signatures(&[n1, n2], &p).unwrap().len(), 2);
373
    }
374
}