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//! review 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. Read from `ask:` too, its name
33    /// before ADR-053.
34    #[serde(default, alias = "ask")]
35    pub review: Vec<RuleGroup>,
36}
37
38impl RepoPolicy {
39    /// Parse and lint a repository policy. Pure: takes the YAML text.
40    pub fn parse(yaml: &str) -> Result<Self, PolicyError> {
41        let repo: Self = crate::yaml::from_str(yaml).map_err(PolicyError::Parse)?;
42        // Every key it has is a policy key, so the policy lint checks the
43        // version, the ids and every pattern the same way.
44        Policy::parse(yaml)?;
45        Ok(repo)
46    }
47
48    /// `user` with this policy merged in; its allow rules only when `trusted`.
49    /// The user's deny rules still come first, so even a trusted repository
50    /// cannot allow what the user denies.
51    pub fn merge(&self, user: &Policy, trusted: bool) -> Result<Policy, PolicyError> {
52        let mut merged = user.clone();
53        merged.deny.extend(prefixed(&self.deny));
54        merged.repo_review.extend(prefixed(&self.review));
55        if trusted {
56            merged.allow.extend(prefixed(&self.allow));
57        }
58        self.lint_merged(&merged)?;
59        Ok(merged)
60    }
61
62    /// Lint `merged` as a whole for what a merge can break (a duplicate id),
63    /// and parse only this policy's patterns: the user's were parsed when the
64    /// user policy was, and parsing them all again on every hook call cost more
65    /// than the rest of the lint.
66    fn lint_merged(&self, merged: &Policy) -> Result<(), PolicyError> {
67        merged.lint_structure()?;
68        self.deny
69            .iter()
70            .chain(&self.review)
71            .chain(&self.allow)
72            .try_for_each(RuleGroup::check_patterns)
73    }
74
75    /// `user` with only this policy's deny rules added: what `openmoat run`'s
76    /// proxy decides hosts with. Its review rules are left out, since the proxy
77    /// cannot prompt and a team's "review before any network" would cut the run off,
78    /// and its allow rules too, trusted or not: they would widen the proxy.
79    pub fn merge_deny(&self, user: &Policy) -> Result<Policy, PolicyError> {
80        let mut merged = user.clone();
81        merged.deny.extend(prefixed(&self.deny));
82        self.lint_merged(&merged)?;
83        Ok(merged)
84    }
85}
86
87fn prefixed(groups: &[RuleGroup]) -> impl Iterator<Item = RuleGroup> + '_ {
88    groups.iter().map(|g| RuleGroup {
89        id: format!("{REPO_RULE_PREFIX}{}", g.id),
90        ..g.clone()
91    })
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97    use crate::{Action, CompiledPolicy, EvalContext, Verdict};
98
99    const USER: &str = "version: 1\ndefaults: { '*': review, net: deny }\n\
100        deny:\n  - id: secrets\n    fs.read: ['~/.ssh/**']\n\
101        allow:\n  - id: dev\n    shell: ['cargo *', 'git status']\n";
102
103    fn decide(merged: &Policy, command: &str) -> (Verdict, Vec<String>) {
104        let ctx = EvalContext {
105            home: "/h".into(),
106            project: Some("/p".into()),
107            real_home: None,
108            real_project: None,
109            moved_dirs: Vec::new(),
110            cwd: "/p".into(),
111            case_insensitive_paths: false,
112        };
113        let d = CompiledPolicy::compile(merged, &ctx)
114            .unwrap()
115            .decide(&Action::Shell {
116                command: command.into(),
117            });
118        (d.verdict, d.rules)
119    }
120
121    fn merged(repo: &str, trusted: bool) -> Policy {
122        let user = Policy::parse(USER).unwrap();
123        RepoPolicy::parse(repo)
124            .unwrap()
125            .merge(&user, trusted)
126            .unwrap()
127    }
128
129    #[test]
130    fn deny_and_review_tighten_what_the_user_allows() {
131        let repo = "version: 1\ndeny:\n  - id: no-status\n    shell: ['git status']\n\
132            review:\n  - id: publish\n    shell: ['cargo publish']\n";
133        let p = merged(repo, false);
134        assert_eq!(
135            decide(&p, "git status"),
136            (Verdict::Deny, vec!["repo:no-status".into()])
137        );
138        assert_eq!(
139            decide(&p, "cargo publish"),
140            (Verdict::Review, vec!["repo:publish".into()])
141        );
142        assert_eq!(decide(&p, "cargo test").0, Verdict::Allow);
143    }
144
145    #[test]
146    fn allow_rules_widen_only_when_trusted_and_never_past_a_deny() {
147        let repo = "version: 1\nallow:\n  - id: wide\n    shell: ['make *', 'cat *']\n    \
148            fs.read: ['~/.ssh/**']\n";
149        assert_eq!(
150            decide(&merged(repo, false), "make deploy").0,
151            Verdict::Review
152        );
153        let trusted = merged(repo, true);
154        assert_eq!(
155            decide(&trusted, "make deploy"),
156            (Verdict::Allow, vec!["repo:wide".into()])
157        );
158        assert_eq!(
159            decide(&trusted, "cat ~/.ssh/id_rsa"),
160            (Verdict::Deny, vec!["secrets".into()])
161        );
162    }
163
164    #[test]
165    fn merging_denies_only_adds_no_review_and_no_allow() {
166        let repo = "version: 1\ndeny:\n  - id: no-status\n    shell: ['git status']\n\
167            review:\n  - id: publish\n    shell: ['cargo publish']\n\
168            allow:\n  - id: wide\n    shell: ['make *']\n";
169        let user = Policy::parse(USER).unwrap();
170        let p = RepoPolicy::parse(repo).unwrap().merge_deny(&user).unwrap();
171        assert_eq!(
172            decide(&p, "git status"),
173            (Verdict::Deny, vec!["repo:no-status".into()])
174        );
175        assert_eq!(p.repo_review, Vec::<RuleGroup>::new());
176        assert_eq!(p.allow, user.allow);
177        assert_eq!(decide(&p, "make deploy").0, Verdict::Review);
178    }
179
180    #[test]
181    fn a_repo_review_still_loses_to_a_user_deny() {
182        let repo = "version: 1\nreview:\n  - id: keys\n    fs.read: ['~/.ssh/**']\n";
183        assert_eq!(
184            decide(&merged(repo, false), "cat ~/.ssh/id_rsa"),
185            (Verdict::Deny, vec!["secrets".into()])
186        );
187    }
188
189    #[test]
190    fn rule_ids_are_prefixed_so_they_cannot_pose_as_the_users() {
191        let repo = "version: 1\ndeny:\n  - id: secrets\n    shell: ['ls']\n";
192        let p = merged(repo, false);
193        let ids: Vec<&str> = p.deny.iter().map(|g| g.id.as_str()).collect();
194        assert_eq!(ids, ["secrets", "repo:secrets"]);
195    }
196
197    #[test]
198    fn rejects_everything_but_rules_and_bad_rules() {
199        for bad in [
200            "version: 1\ndefaults: allow\n",
201            "version: 1\ndefaults: { net: allow }\n",
202            "version: 1\nexecutables:\n  git: ['/tmp/git']\n",
203            "version: 1\nsandbox:\n  read_roots: ['/etc']\n",
204            "version: 1\nrepo_review: []\n",
205            "version: 2\n",
206            "version: 1\ndeny:\n  - id: a\n",
207            "version: 1\ndeny:\n  - id: a\n    shell: ['x']\nreview:\n  - id: a\n    shell: ['y']\n",
208            "deny: []\n",
209        ] {
210            assert!(RepoPolicy::parse(bad).is_err(), "{bad} must be rejected");
211        }
212    }
213}