OXYGENHUB
# 978470f76e66 oxygen / crates / oxy-core / src / policy.rs
11.8 KiB · Rust · last changed Trust policy: policy objects, init/grant/revoke, enforcement on push and fetch, propagation with downgrade protection (spec 0.6) 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
    /// A single-root policy letting `root` do everything on every reference.
215
    pub fn single_root(repo: [u8; 16], root: Identity, expires: u64) -> Policy {
216
        let key = root.hash();
217
        Policy {
218
            repo,
219
            serial: 1,
220
            roots: vec![key],
221
            root_threshold: 1,
222
            rules: vec![Rule { pattern: "*".into(), keys: vec![key], threshold: 1, require: Require::Any, allow_conflicts: true }],
223
            identities: vec![root],
224
            revoked: vec![],
225
            expires,
226
        }
227
    }
228
229
    /// Identities keyed by KeyId.
230
    pub fn identity_map(&self) -> BTreeMap<KeyId, &Identity> {
231
        self.identities.iter().map(|i| (i.hash(), i)).collect()
232
    }
233
}
234
235
#[cfg(test)]
236
mod tests {
237
    use super::*;
238
    use crate::identity::SecretKey;
239
240
    fn sk(n: u8) -> SecretKey {
241
        SecretKey { ed_seed: [n; 32], ml_seed: [n + 100; 32] }
242
    }
243
244
    #[test]
245
    fn globs() {
246
        assert!(glob_matches("*", "main"));
247
        assert!(glob_matches("release/*", "release/1.0"));
248
        assert!(!glob_matches("release/*", "main"));
249
        assert!(glob_matches("main", "main"));
250
        assert!(!glob_matches("main", "main2"));
251
        assert!(glob_matches("*-rc*", "1.0-rc2"));
252
        assert!(glob_matches("", ""));
253
    }
254
255
    #[test]
256
    fn round_trip_and_rules() {
257
        let root = sk(1).identity("Root", "r@x", 0);
258
        let dev = sk(2).identity("Dev", "d@x", 0);
259
        let mut p = Policy::single_root([9; 16], root.clone(), 10);
260
        p.rules.insert(0, Rule { pattern: "release/*".into(), keys: vec![root.hash()], threshold: 1, require: Require::Signed, allow_conflicts: false });
261
        p.rules[1].keys.push(dev.hash());
262
        p.identities.push(dev.clone());
263
        p.revoked.push(ObjectRef([7; 32]));
264
        let d = Policy::decode(&p.encode()).unwrap();
265
        assert_eq!(d.rules.len(), 2);
266
        assert_eq!(d.rules[0].require, Require::Signed);
267
        assert_eq!(d.identity(&dev.hash()), Some(&dev));
268
        assert!(d.authorizes(&dev.hash(), "main"));
269
        assert!(!d.authorizes(&dev.hash(), "release/1"));
270
        assert!(d.authorizes(&root.hash(), "release/1"));
271
        assert!(d.is_expired(11) && !d.is_expired(10));
272
        assert_eq!(d.hash(), p.hash());
273
274
        let mut bad = p.clone();
275
        bad.root_threshold = 5;
276
        assert!(Policy::decode(&bad.encode()).is_err());
277
    }
278
279
    #[test]
280
    fn signatures_need_root_threshold() {
281
        let r1 = sk(1);
282
        let r2 = sk(2);
283
        let i1 = r1.identity("a", "a", 0);
284
        let i2 = r2.identity("b", "b", 0);
285
        let mut p = Policy::single_root([1; 16], i1.clone(), 100);
286
        p.roots.push(i2.hash());
287
        p.roots.sort();
288
        p.root_threshold = 2;
289
        p.identities.push(i2.clone());
290
        let h = p.hash();
291
        let s1 = r1.sign(Domain::Policy, &i1.hash(), &h);
292
        let s2 = r2.sign(Domain::Policy, &i2.hash(), &h);
293
        assert!(p.verify_signatures(&[s1.clone()], &p).is_err());
294
        assert_eq!(p.verify_signatures(&[s1.clone(), s2.clone()], &p).unwrap().len(), 2);
295
        // Duplicates do not count twice; a non-root signer does not count.
296
        assert!(p.verify_signatures(&[s1.clone(), s1.clone()], &p).is_err());
297
        let stranger = sk(3);
298
        let si = stranger.identity("s", "s", 0);
299
        let s3 = stranger.sign(Domain::Policy, &si.hash(), &h);
300
        assert!(p.verify_signatures(&[s1.clone(), s3], &p).is_err());
301
        // A successor policy is verified against the previous roots.
302
        let mut next = p.clone();
303
        next.serial = 2;
304
        next.revoked.push(i2.hash());
305
        let nh = next.hash();
306
        let n1 = r1.sign(Domain::Policy, &i1.hash(), &nh);
307
        let n2 = r2.sign(Domain::Policy, &i2.hash(), &nh);
308
        assert_eq!(next.verify_signatures(&[n1, n2], &p).unwrap().len(), 2);
309
    }
310
}