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