OXYGENHUB

Coverage / crates/oxy-core/src/repo/policy.rs 80.2%

288 of 359 lines run, 44 of 82 functions · run #278 on main · run missed

1
//! Trust policy management and enforcement (spec §14.5).
2
//!
3
//! A repository with a policy verifies everything it receives: every change
4
//! must be authenticated by a key the policy authorizes for the bookmark,
5
//! every bookmark update must carry an attestation by such a key, and a new
6
//! policy must be signed by a threshold of the roots of the policy it replaces.
7
8
use super::*;
9
use crate::identity::SecretKey;
10
use crate::policy::{Policy, Require, Rule};
11
use crate::protocol::SignedPolicy;
12
13
/// One year, the default policy lifetime.
14
const POLICY_LIFETIME_MS: u64 = 365 * 24 * 60 * 60 * 1000;
15
16
/// A signed policy update: applied when it met the root threshold, else a
17
/// proposal carrying the signatures gathered so far (spec §14.5).
18
#[derive(Clone, Debug)]
19
pub struct PolicyUpdate {
20
    pub policy: Policy,
21
    pub sigs: Vec<Signature>,
22
    pub applied: bool,
23
}
24
25
impl PolicyUpdate {
263×
    pub fn signed(&self) -> SignedPolicy {
273×
        SignedPolicy {
283×
            policy: self.policy.clone(),
293×
            sigs: self.sigs.clone(),
303×
        }
313×
    }
32
}
33
34
impl Repo {
35
    /// The current policy and its signatures, if the repository has one.
363502×
    pub fn current_policy(&self) -> Result<Option<(ObjectRef, SignedPolicy)>> {
373502×
        let Some(r) = self.view()?.policy else {
383242×
            return Ok(None);
39
        };
40260×
        let policy = Policy::decode(&self.store.get_typed(&r, ObjectType::Policy)?)?;
41
        Ok(Some((
42260×
            r,
43
            SignedPolicy {
44260×
                policy,
45260×
                sigs: self.store.signatures(&r)?,
46
            },
47
        )))
483502×
    }
49
50
    /// Store a policy with its signatures and point the `policy` reference at it.
5151×
    pub(crate) fn set_policy(&self, sp: &SignedPolicy, command: &str) -> Result<ObjectRef> {
5251×
        let r = self.store.put(ObjectType::Policy, &sp.policy.encode())?;
5370×
        for sig in &sp.sigs {
5470×
            self.store.put_signature(&r, sig)?;
55
        }
56127×
        for id in &sp.policy.identities {
57127×
            self.store.put_identity(id)?;
58
        }
5951×
        let dir = self.oxy.join("policies");
6051×
        fs::create_dir_all(&dir)?;
6151×
        write_atomic(
6251×
            &dir.join(format!("{:020}", sp.policy.serial)),
6351×
            r.to_hex().as_bytes(),
640×
        )?;
6551×
        let (op_ref, op) = self.head_op()?;
6651×
        if op.view.policy != Some(r) {
6751×
            let mut view = op.view.clone();
6851×
            view.policy = Some(r);
6951×
            self.record_op(&[op_ref], command, view)?;
700×
        }
7151×
        Ok(r)
7251×
    }
73
74
    /// Every policy this repository has applied, ascending by serial, with
75
    /// its signatures. Policies applied before this index existed are
76
    /// missing from it, except the current one.
771006×
    pub fn policy_history(&self) -> Result<Vec<SignedPolicy>> {
781006×
        let mut out: BTreeMap<u64, SignedPolicy> = BTreeMap::new();
791006×
        if let Ok(rd) = fs::read_dir(self.oxy.join("policies")) {
80105×
            for e in rd.flatten() {
81105×
                let Ok(hex) = fs::read_to_string(e.path()) else {
820×
                    continue;
83
                };
84105×
                let Some(r) = ObjectRef::from_hex(hex.trim()) else {
850×
                    continue;
86
                };
87105×
                let Ok(bytes) = self.store.get_typed(&r, ObjectType::Policy) else {
880×
                    continue;
89
                };
90105×
                let policy = Policy::decode(&bytes)?;
91105×
                out.insert(
92105×
                    policy.serial,
93
                    SignedPolicy {
94105×
                        policy,
95105×
                        sigs: self.store.signatures(&r)?,
96
                    },
97
                );
98
            }
99963×
        }
1001006×
        if let Some((_, sp)) = self.current_policy()? {
10143×
            out.insert(sp.policy.serial, sp);
102963×
        }
1031006×
        Ok(out.into_values().collect())
1041006×
    }
105
106
    /// Verify and apply a chain of policies ending in `newest`, each
107
    /// against the one before it (spec §14.5). `chain` holds earlier
108
    /// policies in any order; only those after the current serial are used.
10925×
    pub(crate) fn adopt_policy_chain(
11025×
        &self,
11125×
        chain: &[SignedPolicy],
11225×
        newest: &SignedPolicy,
11325×
        command: &str,
11425×
    ) -> std::result::Result<(), String> {
11525×
        let mut current = self
11625×
            .current_policy()
11725×
            .map_err(|e| e.to_string())?
11825×
            .map(|(_, sp)| sp.policy);
11925×
        let mut steps: Vec<&SignedPolicy> = chain
12025×
            .iter()
12125×
            .filter(|sp| {
12219×
                current.as_ref().is_none_or(|c| sp.policy.serial > c.serial)
1238×
                    && sp.policy.serial < newest.policy.serial
12419×
            })
12525×
            .collect();
12625×
        steps.sort_by_key(|sp| sp.policy.serial);
12725×
        steps.push(newest);
12833×
        for sp in steps {
12933×
            self.check_policy(sp, current.as_ref())?;
13031×
            self.set_policy(
13131×
                sp,
13231×
                &format!("{command} (policy serial {})", sp.policy.serial),
133
            )
13431×
            .map_err(|e| e.to_string())?;
13531×
            current = Some(sp.policy.clone());
136
        }
13723×
        Ok(())
13825×
    }
139
140
    /// Validate an incoming policy against the one we trust (`None` when
141
    /// bootstrapping: the policy then vouches for itself).
14233×
    pub fn check_policy(
14333×
        &self,
14433×
        sp: &SignedPolicy,
14533×
        trusted: Option<&Policy>,
14633×
    ) -> std::result::Result<(), String> {
14733×
        if sp.policy.repo != self.id().map_err(|e| e.to_string())? {
1480×
            return Err("policy is for a different repository".into());
14933×
        }
15033×
        if let Some(t) = trusted {
15123×
            if sp.policy.serial <= t.serial {
1521×
                return Err(format!(
1531×
                    "policy serial {} is not greater than the current {}",
1541×
                    sp.policy.serial, t.serial
1551×
                ));
15622×
            }
15710×
        }
15832×
        match trusted {
15922×
            Some(t) => sp.policy.verify_signatures(&sp.sigs, t)?,
16010×
            None => vec![sp.policy.verify_bootstrap(&sp.sigs)?],
161
        };
16231×
        Ok(())
16333×
    }
164
165
    /// Sign `policy` with the configured key and apply it if the current
166
    /// policy's root threshold is met; otherwise return it as a proposal.
16714×
    fn sign_policy(&self, policy: Policy, command: &str) -> Result<PolicyUpdate> {
16814×
        let Some((key, sk)) = self.secret_key()? else {
1690×
            return fail("no secret key: run `oxy identity create` first");
170
        };
17114×
        self.sign_policy_with(policy, &[(key, &sk)], command)
17214×
    }
173
174
    /// Sign with every listed key; the first must be a root of the current
175
    /// policy (the others may be roots of the new policy only, so that a
176
    /// fresh clone can bootstrap from it).
17720×
    pub(crate) fn sign_policy_with(
17820×
        &self,
17920×
        policy: Policy,
18020×
        signers: &[(KeyId, &SecretKey)],
18120×
        command: &str,
18220×
    ) -> Result<PolicyUpdate> {
18320×
        let trusted = self
18420×
            .current_policy()?
18520×
            .map(|(_, sp)| sp.policy)
18620×
            .unwrap_or_else(|| policy.clone());
18720×
        if !signers
18820×
            .first()
18920×
            .is_some_and(|(k, _)| trusted.roots.contains(k))
190
        {
1910×
            return fail("your key is not a root key of the current policy");
19220×
        }
19320×
        let target = policy.hash();
19420×
        let sigs = signers
19520×
            .iter()
19626×
            .map(|(k, sk)| sk.sign(Domain::Policy, k, &target))
19720×
            .collect();
19820×
        self.gather(SignedPolicy { policy, sigs }, &trusted, command)
19920×
    }
200
201
    /// Apply `sp` when its signatures meet `trusted`'s threshold.
20222×
    fn gather(&self, sp: SignedPolicy, trusted: &Policy, command: &str) -> Result<PolicyUpdate> {
20322×
        let applied = sp.policy.verify_signatures(&sp.sigs, trusted).is_ok();
20422×
        if applied {
20520×
            self.set_policy(&sp, command)?;
2062×
        }
20722×
        Ok(PolicyUpdate {
20822×
            policy: sp.policy,
20922×
            sigs: sp.sigs,
21022×
            applied,
21122×
        })
21222×
    }
213
214
    /// Add your signature to a proposal made by another root holder; the
215
    /// policy is applied once the current root threshold is met.
2163×
    pub fn policy_sign(&self, proposal: SignedPolicy) -> Result<PolicyUpdate> {
2173×
        let Some((key, sk)) = self.secret_key()? else {
2180×
            return fail("no secret key: run `oxy identity create` first");
219
        };
2203×
        let Some((_, current)) = self.current_policy()? else {
2210×
            return fail("this repository has no policy; run `oxy policy init` or fetch one");
222
        };
2233×
        if proposal.policy.repo != self.id()? {
2240×
            return fail("the proposal is for a different repository");
2253×
        }
2263×
        if proposal.policy.serial <= current.policy.serial {
2271×
            return fail(format!(
228
                "the proposal's serial {} is not greater than the current {}",
229
                proposal.policy.serial, current.policy.serial
230
            ));
2312×
        }
2322×
        if !current.policy.roots.contains(&key) {
2330×
            return fail("your key is not a root key of the current policy");
2342×
        }
2352×
        let mut sigs: Vec<Signature> = proposal.sigs.into_iter().filter(|s| s.key != key).collect();
2362×
        sigs.push(sk.sign(Domain::Policy, &key, &proposal.policy.hash()));
2372×
        self.gather(
2382×
            SignedPolicy {
2392×
                policy: proposal.policy,
2402×
                sigs,
2412×
            },
2422×
            &current.policy,
2432×
            "oxy policy sign",
244
        )
2453×
    }
246
247
    /// Create the initial policy with the configured identity as sole root.
2488×
    pub fn policy_init(&self) -> Result<PolicyUpdate> {
2498×
        if self.current_policy()?.is_some() {
2500×
            return fail("this repository already has a policy");
2518×
        }
2528×
        let Some((key, _)) = self.secret_key()? else {
2530×
            return fail("no secret key: run `oxy identity create` first");
254
        };
2558×
        let identity = self.identity(&key)?;
2568×
        let policy = Policy::single_root(
2578×
            self.id()?,
2588×
            identity,
2598×
            Hlc::now().wall_ms + POLICY_LIFETIME_MS,
260
        );
2618×
        self.sign_policy(policy, "oxy policy init")
2628×
    }
263
264
    /// Make `identity` a root key.
2652×
    pub fn policy_root_add(&self, identity: Identity) -> Result<PolicyUpdate> {
2662×
        let mut p = self.next_policy()?;
2672×
        let key = identity.hash();
2682×
        if p.roots.contains(&key) {
2691×
            return fail(format!("{} is already a root", key.short(12)));
2701×
        }
2711×
        p.roots.push(key);
2721×
        p.roots.sort();
2731×
        p.revoked.retain(|k| k != &key);
2741×
        if p.identity(&key).is_none() {
2751×
            p.identities.push(identity);
2761×
        }
2771×
        self.sign_policy(p, &format!("oxy policy root add {}", key.short(12)))
2782×
    }
279
280
    /// Drop a root key; the remaining roots must still meet the threshold.
2810×
    pub fn policy_root_remove(&self, key: &KeyId) -> Result<PolicyUpdate> {
2820×
        let mut p = self.next_policy()?;
2830×
        if !p.roots.contains(key) {
2840×
            return fail(format!("{} is not a root", key.short(12)));
2850×
        }
2860×
        p.roots.retain(|k| k != key);
2870×
        if (p.roots.len() as u32) < p.root_threshold {
2880×
            return fail(format!(
289
                "removing it would leave {} root(s) for a threshold of {}",
2900×
                p.roots.len(),
291
                p.root_threshold
292
            ));
2930×
        }
2940×
        self.sign_policy(p, &format!("oxy policy root remove {}", key.short(12)))
2950×
    }
296
297
    /// Require `n` root signatures on future policy updates.
2982×
    pub fn policy_set_threshold(&self, n: u32) -> Result<PolicyUpdate> {
2992×
        let mut p = self.next_policy()?;
3002×
        if n == 0 || n as usize > p.roots.len() {
3011×
            return fail(format!(
302
                "the threshold must be between 1 and the number of roots ({})",
3031×
                p.roots.len()
304
            ));
3051×
        }
3061×
        p.root_threshold = n;
3071×
        self.sign_policy(p, &format!("oxy policy root threshold {n}"))
3082×
    }
309
31016×
    pub(crate) fn next_policy(&self) -> Result<Policy> {
31116×
        let Some((_, sp)) = self.current_policy()? else {
3120×
            return fail("this repository has no policy; run `oxy policy init`");
313
        };
31416×
        let mut p = sp.policy;
31516×
        p.serial += 1;
31616×
        p.expires = Hlc::now().wall_ms + POLICY_LIFETIME_MS;
31716×
        Ok(p)
31816×
    }
319
320
    /// Let `identity` update references matching `pattern` (default every reference).
3212×
    pub fn policy_grant(&self, identity: Identity, pattern: Option<&str>) -> Result<PolicyUpdate> {
3222×
        let mut p = self.next_policy()?;
3232×
        let key = identity.hash();
3242×
        let pattern = pattern.unwrap_or("*");
3252×
        p.revoked.retain(|k| k != &key);
3262×
        match p.rules.iter_mut().find(|r| r.pattern == pattern) {
3272×
            Some(rule) => {
3282×
                if !rule.keys.contains(&key) {
3292×
                    rule.keys.push(key);
3302×
                    rule.keys.sort();
3312×
                }
332
            }
3330×
            None => p.rules.push(Rule {
3340×
                pattern: pattern.into(),
3350×
                keys: vec![key],
3360×
                threshold: 1,
3370×
                require: Require::Any,
3380×
                allow_conflicts: true,
3390×
            }),
340
        }
3412×
        if p.identity(&key).is_none() {
3422×
            p.identities.push(identity);
3432×
        }
3442×
        self.sign_policy(p, &format!("oxy policy grant {}", key.short(12)))
3452×
    }
346
347
    /// Revoke `key`: it may no longer update anything, and existing rules
348
    /// drop it. A root key can be revoked by another root as long as the
349
    /// remaining roots still meet the threshold.
3504×
    pub fn policy_revoke(&self, key: &KeyId) -> Result<PolicyUpdate> {
3514×
        let mut p = self.next_policy()?;
3524×
        if p.roots.contains(key) {
3532×
            let own = self.secret_key()?.map(|(k, _)| k);
3542×
            if own == Some(*key) {
3551×
                return fail("a root cannot revoke itself; have another root revoke it, or remove it with `oxy policy root remove` first");
3561×
            }
3572×
            p.roots.retain(|k| k != key);
3581×
            if (p.roots.len() as u32) < p.root_threshold {
3591×
                return fail(format!(
360
                    "revoking it would leave {} root(s) for a threshold of {}",
3611×
                    p.roots.len(),
362
                    p.root_threshold
363
                ));
3640×
            }
3652×
        }
3662×
        for r in &mut p.rules {
3674×
            r.keys.retain(|k| k != key);
368
        }
3692×
        p.rules.retain(|r| !r.keys.is_empty());
3702×
        if !p.revoked.contains(key) {
3712×
            p.revoked.push(*key);
3722×
            p.revoked.sort();
3732×
        }
3742×
        self.sign_policy(p, &format!("oxy policy revoke {}", key.short(12)))
3754×
    }
376
377
    /// Whether `change` may be part of `reference` under `policy`: it must be
378
    /// authenticated (by its author or a delegate) with a key the matching
379
    /// rule lists, using the authenticator kind the rule requires. A rule key
380
    /// covers its rotation predecessors, and a delegate's signature counts
381
    /// for the author it acts for.
38215×
    pub fn change_allowed(
38315×
        &self,
38415×
        hash: &ChangeHash,
38515×
        policy: &Policy,
38615×
        reference: &str,
38715×
    ) -> std::result::Result<(), String> {
38815×
        let rule = policy
38915×
            .rule_for(reference)
39015×
            .ok_or_else(|| format!("no policy rule matches {reference:?}"))?;
39115×
        match self.authenticate_change(hash).map_err(|e| e.to_string())? {
39215×
            SignatureStatus::Valid { key, sealed, .. } => {
39315×
                if policy.is_revoked(&key) {
3940×
                    return Err(format!(
3950×
                        "change {} is signed by revoked key {}",
3960×
                        hash.short(12),
3970×
                        key.short(12)
3980×
                    ));
39915×
                }
40015×
                let author = self
40115×
                    .store
40215×
                    .get_change(hash)
40315×
                    .map(|c| c.author)
40415×
                    .map_err(|e| e.to_string())?;
40515×
                let principal = if author.is_zero() { key } else { author };
40615×
                let covered = rule
40715×
                    .keys
40815×
                    .iter()
40915×
                    .any(|k| policy.succeeds(k, &key) || policy.succeeds(k, &principal));
41015×
                if !covered {
4110×
                    return Err(format!(
4120×
                        "change {} is signed by {}, which may not update {reference:?}",
4130×
                        hash.short(12),
4140×
                        key.short(12)
4150×
                    ));
41615×
                }
41715×
                match (rule.require, sealed) {
4180×
                    (Require::Signed, true) => Err(format!(
4190×
                        "{reference:?} requires individually signed changes; {} is only sealed",
4200×
                        hash.short(12)
4210×
                    )),
4220×
                    (Require::Sealed, false) => Err(format!(
4230×
                        "{reference:?} requires sealed changes; {} is individually signed",
4240×
                        hash.short(12)
4250×
                    )),
42615×
                    _ => Ok(()),
427
                }
428
            }
429
            SignatureStatus::Unsigned => {
4300×
                Err(format!("change {} is not signed or sealed", hash.short(12)))
431
            }
4320×
            SignatureStatus::Invalid(e) => Err(format!("change {}: {e}", hash.short(12))),
433
        }
43415×
    }
435
436
    /// Check every change that `new` adds over `old` for `reference`.
43720×
    pub(crate) fn state_allowed(
43820×
        &self,
43920×
        old_heads: &[ChangeHash],
44020×
        new_heads: &[ChangeHash],
44120×
        policy: &Policy,
44220×
        reference: &str,
44320×
    ) -> std::result::Result<(), String> {
44420×
        let added = self
44520×
            .negotiate(old_heads, new_heads)
44620×
            .map_err(|e| e.to_string())?;
44720×
        for h in &added {
44814×
            self.change_allowed(h, policy, reference)?;
449
        }
45020×
        if let Some(rule) = policy.rule_for(reference) {
45120×
            if !rule.allow_conflicts && !added.is_empty() {
4520×
                let st = self.load_state(new_heads).map_err(|e| e.to_string())?;
4530×
                if st.materialize().is_conflicted() {
4540×
                    return Err(format!("{reference:?} does not allow conflicted states"));
4550×
                }
45620×
            }
4570×
        }
45820×
        Ok(())
45920×
    }
460
}