OXYGENHUB

Coverage / crates/oxy-core/src/policy.rs 92.7%

307 of 331 lines run, 65 of 80 functions · run #285 on main · run missed

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 {
25153×
    fn tag(self) -> u64 {
26153×
        match self {
274×
            Require::Signed => 0,
280×
            Require::Sealed => 1,
29149×
            Require::Any => 2,
30
        }
31153×
    }
32377×
    fn from_tag(t: u64) -> Result<Require, ObjectError> {
33377×
        Ok(match t {
342×
            0 => Require::Signed,
350×
            1 => Require::Sealed,
36375×
            2 => Require::Any,
370×
            _ => return Err(ObjectError::Schema(format!("unknown require {t}"))),
38
        })
39377×
    }
401×
    pub fn name(self) -> &'static str {
411×
        match self {
420×
            Require::Signed => "signed",
430×
            Require::Sealed => "sealed",
441×
            Require::Any => "any",
45
        }
461×
    }
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.
7386×
pub fn glob_matches(pattern: &str, name: &str) -> bool {
74523×
    fn rec(p: &[u8], n: &[u8]) -> bool {
75523×
        match p.first() {
76401×
            None => n.is_empty(),
77402×
            Some(b'*') => (0..=n.len()).any(|i| rec(&p[1..], &n[i..])),
7840×
            Some(c) => n.first() == Some(c) && rec(&p[1..], &n[1..]),
79
        }
80523×
    }
8186×
    rec(pattern.as_bytes(), name.as_bytes())
8286×
}
83
84
impl Policy {
85451×
    fn keys_value(keys: &[KeyId]) -> Value {
86451×
        Value::Array(keys.iter().map(|k| Value::Bytes(k.0.to_vec())).collect())
87451×
    }
881127×
    fn keys_from(v: &Value, what: &str) -> Result<Vec<KeyId>, ObjectError> {
891127×
        let mut ks = array(v, what)?
901127×
            .iter()
911127×
            .map(|k| oref(k, what))
921127×
            .collect::<Result<Vec<_>, _>>()?;
931127×
        ks.sort();
941127×
        ks.dedup();
951127×
        Ok(ks)
961127×
    }
97
98149×
    pub fn to_value(&self) -> Value {
99149×
        Value::map([
100149×
            (0, Value::Uint(FORMAT_VERSION)),
101149×
            (1, Value::Bytes(self.repo.to_vec())),
102149×
            (2, Value::Uint(self.serial)),
103149×
            (
104149×
                3,
105149×
                Value::map([
106149×
                    (0, Self::keys_value(&self.roots)),
107149×
                    (1, Value::Uint(self.root_threshold as u64)),
108149×
                ]),
109149×
            ),
110
            (
111
                4,
112
                Value::Array(
113149×
                    self.rules
114149×
                        .iter()
115153×
                        .map(|r| {
116153×
                            Value::map([
117153×
                                (0, Value::Text(r.pattern.clone())),
118153×
                                (1, Self::keys_value(&r.keys)),
119153×
                                (2, Value::Uint(r.threshold as u64)),
120153×
                                (3, Value::Uint(r.require.tag())),
121153×
                                (4, Value::Bool(r.allow_conflicts)),
122153×
                            ])
123153×
                        })
124149×
                        .collect(),
125
                ),
126
            ),
127
            (
128
                5,
129
                Value::Array(
130149×
                    self.identities
131149×
                        .iter()
132370×
                        .map(|i| Value::Bytes(i.encode()))
133149×
                        .collect(),
134
                ),
135
            ),
136149×
            (6, Self::keys_value(&self.revoked)),
137149×
            (7, Value::Uint(self.expires)),
138
        ])
139149×
    }
140
141149×
    pub fn encode(&self) -> Vec<u8> {
142149×
        cbor::encode(&self.to_value())
143149×
    }
144
14589×
    pub fn hash(&self) -> ObjectRef {
14689×
        hash_object(ObjectType::Policy, &self.encode())
14789×
    }
148
149375×
    pub fn decode(b: &[u8]) -> Result<Policy, ObjectError> {
150375×
        let v = cbor::decode(b)?;
151375×
        let m = map(&v, "policy")?;
152375×
        check_version(m)?;
153375×
        let roots = map(field(m, 3, "roots")?, "roots")?;
154375×
        let mut rules = Vec::new();
155377×
        for r in array(field(m, 4, "rules")?, "rules")? {
156377×
            let rm = map(r, "rule")?;
157377×
            rules.push(Rule {
158377×
                pattern: text(field(rm, 0, "pattern")?, "pattern")?.to_owned(),
159377×
                keys: Self::keys_from(field(rm, 1, "rule keys")?, "rule keys")?,
160377×
                threshold: uint(field(rm, 2, "threshold")?, "threshold")? as u32,
161377×
                require: Require::from_tag(uint(field(rm, 3, "require")?, "require")?)?,
162377×
                allow_conflicts: field(rm, 4, "allow_conflicts")?
163377×
                    .as_bool()
164377×
                    .ok_or_else(|| ObjectError::Schema("allow_conflicts: expected bool".into()))?,
165
            });
166
        }
167375×
        let identities = array(field(m, 5, "identities")?, "identities")?
168375×
            .iter()
169846×
            .map(|i| Identity::decode(bytes(i, "identity")?))
170375×
            .collect::<Result<Vec<_>, _>>()?;
171375×
        let p = Policy {
172375×
            repo: bytes(field(m, 1, "repo")?, "repo")?
173375×
                .try_into()
174375×
                .map_err(|_| ObjectError::Schema("repo: expected 16 bytes".into()))?,
175375×
            serial: uint(field(m, 2, "serial")?, "serial")?,
176375×
            roots: Self::keys_from(field(roots, 0, "root keys")?, "root keys")?,
177375×
            root_threshold: uint(field(roots, 1, "root threshold")?, "root threshold")? as u32,
178375×
            rules,
179375×
            identities,
180375×
            revoked: Self::keys_from(field(m, 6, "revoked")?, "revoked")?,
181375×
            expires: uint(field(m, 7, "expires")?, "expires")?,
182
        };
183375×
        if p.root_threshold == 0 || p.root_threshold as usize > p.roots.len() {
1841×
            return Err(ObjectError::Schema(
1851×
                "root threshold must be between 1 and the number of root keys".into(),
1861×
            ));
187374×
        }
188375×
        for r in &p.rules {
189375×
            if r.threshold == 0 || r.threshold as usize > r.keys.len() {
1900×
                return Err(ObjectError::Schema(format!(
1910×
                    "rule {:?}: threshold must be between 1 and the number of keys",
1920×
                    r.pattern
1930×
                )));
194375×
            }
195
        }
196374×
        Ok(p)
197375×
    }
198
19997×
    pub fn identity(&self, key: &KeyId) -> Option<&Identity> {
200198×
        self.identities.iter().find(|i| i.hash() == *key)
20197×
    }
202
203206×
    pub fn is_revoked(&self, key: &KeyId) -> bool {
204206×
        self.revoked.contains(key)
205206×
    }
206
2073×
    pub fn is_expired(&self, now_ms: u64) -> bool {
2083×
        now_ms > self.expires
2093×
    }
210
211
    /// The first rule whose pattern matches `reference`.
21278×
    pub fn rule_for(&self, reference: &str) -> Option<&Rule> {
21378×
        self.rules
21478×
            .iter()
21579×
            .find(|r| glob_matches(&r.pattern, reference))
21678×
    }
217
218
    /// Whether `key` may update `reference`: listed in the matching rule and not revoked.
21939×
    pub fn authorizes(&self, key: &KeyId, reference: &str) -> bool {
22039×
        !self.is_revoked(key)
22138×
            && self
22238×
                .rule_for(reference)
22338×
                .is_some_and(|r| r.keys.contains(key))
22439×
    }
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.
22949×
    pub fn verify_signatures(
23049×
        &self,
23149×
        sigs: &[Signature],
23249×
        trusted: &Policy,
23349×
    ) -> Result<Vec<KeyId>, String> {
23449×
        let target = self.hash();
23549×
        let mut signers = Vec::new();
23672×
        for sig in sigs {
23772×
            if !trusted.roots.contains(&sig.key) || trusted.is_revoked(&sig.key) {
23817×
                continue;
23955×
            }
24055×
            let Some(id) = trusted
24155×
                .identity(&sig.key)
24255×
                .or_else(|| self.identity(&sig.key))
243
            else {
2440×
                continue;
245
            };
24655×
            if identity::verify(id, sig, Domain::Policy, &target).is_ok()
24755×
                && !signers.contains(&sig.key)
24854×
            {
24954×
                signers.push(sig.key);
25054×
            }
251
        }
25249×
        if (signers.len() as u32) < trusted.root_threshold {
2536×
            return Err(format!(
2546×
                "policy needs {} root signature(s), has {}",
2556×
                trusted.root_threshold,
2566×
                signers.len()
2576×
            ));
25843×
        }
25943×
        Ok(signers)
26049×
    }
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.
26610×
    pub fn verify_bootstrap(&self, sigs: &[Signature]) -> Result<KeyId, String> {
26710×
        let target = self.hash();
26810×
        for sig in sigs {
26910×
            if !self.roots.contains(&sig.key) || self.is_revoked(&sig.key) {
2700×
                continue;
27110×
            }
27210×
            if let Some(id) = self.identity(&sig.key) {
27310×
                if identity::verify(id, sig, Domain::Policy, &target).is_ok() {
27410×
                    return Ok(sig.key);
2750×
                }
2760×
            }
277
        }
2780×
        Err("policy carries no valid signature by one of its own root keys".into())
27910×
    }
280
281
    /// A single-root policy letting `root` do everything on every reference.
28211×
    pub fn single_root(repo: [u8; 16], root: Identity, expires: u64) -> Policy {
28311×
        let key = root.hash();
28411×
        Policy {
28511×
            repo,
28611×
            serial: 1,
28711×
            roots: vec![key],
28811×
            root_threshold: 1,
28911×
            rules: vec![Rule {
29011×
                pattern: "*".into(),
29111×
                keys: vec![key],
29211×
                threshold: 1,
29311×
                require: Require::Any,
29411×
                allow_conflicts: true,
29511×
            }],
29611×
            identities: vec![root],
29711×
            revoked: vec![],
29811×
            expires,
29911×
        }
30011×
    }
301
302
    /// Whether `key` appears anywhere in the policy (roots, rules, identities).
3037×
    pub fn mentions(&self, key: &KeyId) -> bool {
3047×
        self.roots.contains(key)
3051×
            || self.rules.iter().any(|r| r.keys.contains(key))
3060×
            || self.identity(key).is_some()
3077×
    }
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.
31221×
    pub fn succeeds(&self, rule_key: &KeyId, key: &KeyId) -> bool {
31321×
        if self.is_revoked(key) {
3140×
            return false;
31521×
        }
31621×
        let mut cur = Some(*rule_key);
31721×
        for _ in 0..32 {
31830×
            match cur {
31930×
                Some(k) if k == *key => return true,
32014×
                Some(k) => cur = self.identity(&k).and_then(|i| i.previous),
3215×
                None => return false,
322
            }
323
        }
3240×
        false
32521×
    }
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.
3316×
    pub fn substitute_key(&mut self, old: &KeyId, new: Identity) {
3326×
        let nk = new.hash();
33312×
        for k in self
3346×
            .roots
3356×
            .iter_mut()
3366×
            .chain(self.rules.iter_mut().flat_map(|r| r.keys.iter_mut()))
337
        {
33812×
            if k == old {
33912×
                *k = nk;
34012×
            }
341
        }
3426×
        for r in &mut self.rules {
3436×
            r.keys.sort();
3446×
            r.keys.dedup();
3456×
        }
3466×
        self.roots.sort();
3476×
        self.roots.dedup();
3486×
        if self.identity(&nk).is_none() {
3496×
            self.identities.push(new);
3506×
        }
3516×
    }
352
353
    /// Identities keyed by KeyId.
3540×
    pub fn identity_map(&self) -> BTreeMap<KeyId, &Identity> {
3550×
        self.identities.iter().map(|i| (i.hash(), i)).collect()
3560×
    }
357
}
358
359
#[cfg(test)]
360
mod tests {
361
    use super::*;
362
    use crate::identity::SecretKey;
363
3645×
    fn sk(n: u8) -> SecretKey {
3655×
        SecretKey {
3665×
            ed_seed: [n; 32],
3675×
            ml_seed: [n + 100; 32],
3685×
        }
3695×
    }
370
371
    #[test]
3721×
    fn globs() {
3731×
        assert!(glob_matches("*", "main"));
3741×
        assert!(glob_matches("release/*", "release/1.0"));
3751×
        assert!(!glob_matches("release/*", "main"));
3761×
        assert!(glob_matches("main", "main"));
3771×
        assert!(!glob_matches("main", "main2"));
3781×
        assert!(glob_matches("*-rc*", "1.0-rc2"));
3791×
        assert!(glob_matches("", ""));
3801×
    }
381
382
    #[test]
3831×
    fn round_trip_and_rules() {
3841×
        let root = sk(1).identity("Root", "r@x", 0);
3851×
        let dev = sk(2).identity("Dev", "d@x", 0);
3861×
        let mut p = Policy::single_root([9; 16], root.clone(), 10);
3871×
        p.rules.insert(
388
            0,
3891×
            Rule {
3901×
                pattern: "release/*".into(),
3911×
                keys: vec![root.hash()],
3921×
                threshold: 1,
3931×
                require: Require::Signed,
3941×
                allow_conflicts: false,
3951×
            },
396
        );
3971×
        p.rules[1].keys.push(dev.hash());
3981×
        p.identities.push(dev.clone());
3991×
        p.revoked.push(ObjectRef([7; 32]));
4001×
        let d = Policy::decode(&p.encode()).unwrap();
4011×
        assert_eq!(d.rules.len(), 2);
4021×
        assert_eq!(d.rules[0].require, Require::Signed);
4031×
        assert_eq!(d.identity(&dev.hash()), Some(&dev));
4041×
        assert!(d.authorizes(&dev.hash(), "main"));
4051×
        assert!(!d.authorizes(&dev.hash(), "release/1"));
4061×
        assert!(d.authorizes(&root.hash(), "release/1"));
4071×
        assert!(d.is_expired(11) && !d.is_expired(10));
4081×
        assert_eq!(d.hash(), p.hash());
409
4101×
        let mut bad = p.clone();
4111×
        bad.root_threshold = 5;
4121×
        assert!(Policy::decode(&bad.encode()).is_err());
4131×
    }
414
415
    #[test]
4161×
    fn signatures_need_root_threshold() {
4171×
        let r1 = sk(1);
4181×
        let r2 = sk(2);
4191×
        let i1 = r1.identity("a", "a", 0);
4201×
        let i2 = r2.identity("b", "b", 0);
4211×
        let mut p = Policy::single_root([1; 16], i1.clone(), 100);
4221×
        p.roots.push(i2.hash());
4231×
        p.roots.sort();
4241×
        p.root_threshold = 2;
4251×
        p.identities.push(i2.clone());
4261×
        let h = p.hash();
4271×
        let s1 = r1.sign(Domain::Policy, &i1.hash(), &h);
4281×
        let s2 = r2.sign(Domain::Policy, &i2.hash(), &h);
4291×
        assert!(p.verify_signatures(std::slice::from_ref(&s1), &p).is_err());
4301×
        assert_eq!(
4311×
            p.verify_signatures(&[s1.clone(), s2.clone()], &p)
4321×
                .unwrap()
4331×
                .len(),
434
            2
435
        );
436
        // Duplicates do not count twice; a non-root signer does not count.
4371×
        assert!(p.verify_signatures(&[s1.clone(), s1.clone()], &p).is_err());
4381×
        let stranger = sk(3);
4391×
        let si = stranger.identity("s", "s", 0);
4401×
        let s3 = stranger.sign(Domain::Policy, &si.hash(), &h);
4411×
        assert!(p.verify_signatures(&[s1.clone(), s3], &p).is_err());
442
        // A successor policy is verified against the previous roots.
4431×
        let mut next = p.clone();
4441×
        next.serial = 2;
4451×
        next.revoked.push(i2.hash());
4461×
        let nh = next.hash();
4471×
        let n1 = r1.sign(Domain::Policy, &i1.hash(), &nh);
4481×
        let n2 = r2.sign(Domain::Policy, &i2.hash(), &nh);
4491×
        assert_eq!(next.verify_signatures(&[n1, n2], &p).unwrap().len(), 2);
4501×
    }
451
}