Skip to main content

openmoat_core/
repo.rs

1//! Repository policy: `<project>/.moat/policy.yaml`, committed by a team
2//! (docs/POLICY.md ยง9, ADR-022).
3//!
4//! A repository is input the person did not write, so by itself its policy
5//! only makes the user policy stricter: its deny rules join the user's, and its
6//! ask rules are tried before the user's allow rules. Its allow rules widen the
7//! user policy only once a person has trusted that exact file (`moat trust`);
8//! the caller decides that and passes it to [`RepoPolicy::merge`].
9
10use serde::Deserialize;
11
12use crate::policy::{Policy, PolicyError, RuleGroup};
13
14/// Prefix of every rule id a repository policy contributes, so decisions and
15/// the audit log say where a rule came from, and a repository rule can never
16/// pass for one of the user's (`kernel-self`) or collide with it.
17pub const REPO_RULE_PREFIX: &str = "repo:";
18
19/// A repository policy. Only rules: `defaults`, `executables` and `sandbox`
20/// stay the user's, so any other key is a parse error.
21#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
22#[serde(deny_unknown_fields)]
23pub struct RepoPolicy {
24    /// Schema version; only 1 is supported.
25    pub version: u32,
26    /// Added to the user's deny rules.
27    #[serde(default)]
28    pub deny: Vec<RuleGroup>,
29    /// Added to the user's allow rules, only when the file is trusted.
30    #[serde(default)]
31    pub allow: Vec<RuleGroup>,
32    /// Tried before the user's allow rules.
33    #[serde(default)]
34    pub ask: Vec<RuleGroup>,
35}
36
37impl RepoPolicy {
38    /// Parse and lint a repository policy. Pure: takes the YAML text.
39    pub fn parse(yaml: &str) -> Result<Self, PolicyError> {
40        let repo: Self = crate::yaml::from_str(yaml).map_err(PolicyError::Parse)?;
41        // Every key it has is a policy key, so the policy lint checks the
42        // version, the ids and every pattern the same way.
43        Policy::parse(yaml)?;
44        Ok(repo)
45    }
46
47    /// `user` with this policy merged in; its allow rules only when `trusted`.
48    /// The user's deny rules still come first, so even a trusted repository
49    /// cannot allow what the user denies.
50    pub fn merge(&self, user: &Policy, trusted: bool) -> Result<Policy, PolicyError> {
51        let mut merged = user.clone();
52        merged.deny.extend(prefixed(&self.deny));
53        merged.repo_ask.extend(prefixed(&self.ask));
54        if trusted {
55            merged.allow.extend(prefixed(&self.allow));
56        }
57        merged.lint()?;
58        Ok(merged)
59    }
60}
61
62fn prefixed(groups: &[RuleGroup]) -> impl Iterator<Item = RuleGroup> + '_ {
63    groups.iter().map(|g| RuleGroup {
64        id: format!("{REPO_RULE_PREFIX}{}", g.id),
65        ..g.clone()
66    })
67}
68
69#[cfg(test)]
70mod tests {
71    use super::*;
72    use crate::{Action, CompiledPolicy, EvalContext, Verdict};
73
74    const USER: &str = "version: 1\ndefaults: { '*': ask, net: deny }\n\
75        deny:\n  - id: secrets\n    fs.read: ['~/.ssh/**']\n\
76        allow:\n  - id: dev\n    shell: ['cargo *', 'git status']\n";
77
78    fn decide(merged: &Policy, command: &str) -> (Verdict, Vec<String>) {
79        let ctx = EvalContext {
80            home: "/h".into(),
81            project: Some("/p".into()),
82            real_home: None,
83            real_project: None,
84            moved_dirs: Vec::new(),
85            cwd: "/p".into(),
86            case_insensitive_paths: false,
87        };
88        let d = CompiledPolicy::compile(merged, &ctx)
89            .unwrap()
90            .decide(&Action::Shell {
91                command: command.into(),
92            });
93        (d.verdict, d.rules)
94    }
95
96    fn merged(repo: &str, trusted: bool) -> Policy {
97        let user = Policy::parse(USER).unwrap();
98        RepoPolicy::parse(repo)
99            .unwrap()
100            .merge(&user, trusted)
101            .unwrap()
102    }
103
104    #[test]
105    fn deny_and_ask_tighten_what_the_user_allows() {
106        let repo = "version: 1\ndeny:\n  - id: no-status\n    shell: ['git status']\n\
107            ask:\n  - id: publish\n    shell: ['cargo publish']\n";
108        let p = merged(repo, false);
109        assert_eq!(
110            decide(&p, "git status"),
111            (Verdict::Deny, vec!["repo:no-status".into()])
112        );
113        assert_eq!(
114            decide(&p, "cargo publish"),
115            (Verdict::Ask, vec!["repo:publish".into()])
116        );
117        assert_eq!(decide(&p, "cargo test").0, Verdict::Allow);
118    }
119
120    #[test]
121    fn allow_rules_widen_only_when_trusted_and_never_past_a_deny() {
122        let repo = "version: 1\nallow:\n  - id: wide\n    shell: ['make *', 'cat *']\n    \
123            fs.read: ['~/.ssh/**']\n";
124        assert_eq!(decide(&merged(repo, false), "make deploy").0, Verdict::Ask);
125        let trusted = merged(repo, true);
126        assert_eq!(
127            decide(&trusted, "make deploy"),
128            (Verdict::Allow, vec!["repo:wide".into()])
129        );
130        assert_eq!(
131            decide(&trusted, "cat ~/.ssh/id_rsa"),
132            (Verdict::Deny, vec!["secrets".into()])
133        );
134    }
135
136    #[test]
137    fn a_repo_ask_still_loses_to_a_user_deny() {
138        let repo = "version: 1\nask:\n  - id: keys\n    fs.read: ['~/.ssh/**']\n";
139        assert_eq!(
140            decide(&merged(repo, false), "cat ~/.ssh/id_rsa"),
141            (Verdict::Deny, vec!["secrets".into()])
142        );
143    }
144
145    #[test]
146    fn rule_ids_are_prefixed_so_they_cannot_pose_as_the_users() {
147        let repo = "version: 1\ndeny:\n  - id: secrets\n    shell: ['ls']\n";
148        let p = merged(repo, false);
149        let ids: Vec<&str> = p.deny.iter().map(|g| g.id.as_str()).collect();
150        assert_eq!(ids, ["secrets", "repo:secrets"]);
151    }
152
153    #[test]
154    fn rejects_everything_but_rules_and_bad_rules() {
155        for bad in [
156            "version: 1\ndefaults: allow\n",
157            "version: 1\ndefaults: { net: allow }\n",
158            "version: 1\nexecutables:\n  git: ['/tmp/git']\n",
159            "version: 1\nsandbox:\n  read_roots: ['/etc']\n",
160            "version: 1\nrepo_ask: []\n",
161            "version: 2\n",
162            "version: 1\ndeny:\n  - id: a\n",
163            "version: 1\ndeny:\n  - id: a\n    shell: ['x']\nask:\n  - id: a\n    shell: ['y']\n",
164            "deny: []\n",
165        ] {
166            assert!(RepoPolicy::parse(bad).is_err(), "{bad} must be rejected");
167        }
168    }
169}