File size: 7,214 Bytes
e5034c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
use super::operation::PermissionOperation;
use super::policy::Policy;
use crate::PolicyConfig;
use crate::policies::Permission;

/// High-level policy engine that provides convenient methods for checking
/// policies
///
/// This wrapper around Workflow provides easy-to-use methods for services to
/// check if operations are allowed without having to construct Operation enums
/// manually.
pub struct PolicyEngine<'a> {
    policies: &'a PolicyConfig,
}

impl<'a> PolicyEngine<'a> {
    /// Create a new PolicyEngine from a workflow
    pub fn new(policies: &'a PolicyConfig) -> Self {
        Self { policies }
    }

    /// Check if an operation is allowed
    /// Returns permission result
    pub fn can_perform(&self, operation: &PermissionOperation) -> Permission {
        self.evaluate_policies(operation)
    }

    /// Internal helper function to evaluate policies for a given operation
    /// Returns permission result, defaults to Confirm if no policies match
    fn evaluate_policies(&self, operation: &PermissionOperation) -> Permission {
        let has_policies = !self.policies.policies.is_empty();

        if !has_policies {
            return Permission::Confirm;
        }

        let mut last_allow: Option<Permission> = None;

        // Evaluate all policies in order: workflow policies first, then extended
        // policies

        if let Some(permission) = self.evaluate_policy_set(self.policies.policies.iter(), operation)
        {
            match permission {
                Permission::Deny | Permission::Confirm => {
                    // Return immediately for denials or confirmations
                    return permission;
                }
                Permission::Allow => {
                    // Keep track of the last allow
                    last_allow = Some(permission);
                }
            }
        }

        // Return last allow if found, otherwise default to Confirm
        last_allow.unwrap_or(Permission::Confirm)
    }

    /// Helper function to evaluate a set of policies
    /// Returns the first non-Allow result, or the last Allow result if all are
    /// Allow
    fn evaluate_policy_set<'p, I: IntoIterator<Item = &'p Policy>>(
        &self,
        policies: I,
        operation: &PermissionOperation,
    ) -> Option<Permission> {
        let mut last_allow: Option<Permission> = None;

        for policy in policies {
            if let Some(permission) = policy.eval(operation) {
                match permission {
                    Permission::Deny | Permission::Confirm => {
                        // Return immediately for denials or confirmations
                        return Some(permission);
                    }
                    Permission::Allow => {
                        // Keep track of the last allow
                        last_allow = Some(permission);
                    }
                }
            }
        }

        last_allow
    }
}

#[cfg(test)]
mod tests {
    use pretty_assertions::assert_eq;

    use super::*;
    use crate::{ExecuteRule, Fetch, Permission, Policy, PolicyConfig, ReadRule, Rule, WriteRule};

    fn fixture_workflow_with_read_policy() -> PolicyConfig {
        PolicyConfig::new().add_policy(Policy::Simple {
            permission: Permission::Allow,
            rule: Rule::Read(ReadRule { read: "src/**/*.rs".to_string(), dir: None }),
        })
    }

    fn fixture_workflow_with_write_policy() -> PolicyConfig {
        PolicyConfig::new().add_policy(Policy::Simple {
            permission: Permission::Deny,
            rule: Rule::Write(WriteRule { write: "**/*.rs".to_string(), dir: None }),
        })
    }

    fn fixture_workflow_with_execute_policy() -> PolicyConfig {
        PolicyConfig::new().add_policy(Policy::Simple {
            permission: Permission::Allow,
            rule: Rule::Execute(ExecuteRule { command: "cargo *".to_string(), dir: None }),
        })
    }

    fn fixture_workflow_with_write_policy_confirm() -> PolicyConfig {
        PolicyConfig::new().add_policy(Policy::Simple {
            permission: Permission::Confirm,
            rule: Rule::Write(WriteRule { write: "src/**/*.rs".to_string(), dir: None }),
        })
    }

    fn fixture_workflow_with_net_fetch_policy() -> PolicyConfig {
        PolicyConfig::new().add_policy(Policy::Simple {
            permission: Permission::Allow,
            rule: Rule::Fetch(Fetch { url: "https://api.example.com/*".to_string(), dir: None }),
        })
    }

    #[test]
    fn test_policy_engine_can_perform_read() {
        let fixture_workflow = fixture_workflow_with_read_policy();
        let fixture = PolicyEngine::new(&fixture_workflow);
        let operation = PermissionOperation::Read {
            path: std::path::PathBuf::from("src/main.rs"),
            cwd: std::path::PathBuf::from("/test/cwd"),
            message: "Read file: src/main.rs".to_string(),
        };

        let actual = fixture.can_perform(&operation);

        assert_eq!(actual, Permission::Allow);
    }

    #[test]
    fn test_policy_engine_can_perform_write() {
        let fixture_workflow = fixture_workflow_with_write_policy();
        let fixture = PolicyEngine::new(&fixture_workflow);
        let operation = PermissionOperation::Write {
            path: std::path::PathBuf::from("src/main.rs"),
            cwd: std::path::PathBuf::from("/test/cwd"),
            message: "Create/overwrite file: src/main.rs".to_string(),
        };

        let actual = fixture.can_perform(&operation);

        assert_eq!(actual, Permission::Deny);
    }

    #[test]
    fn test_policy_engine_can_perform_write_with_confirm() {
        let fixture_workflow = fixture_workflow_with_write_policy_confirm();
        let fixture = PolicyEngine::new(&fixture_workflow);
        let operation = PermissionOperation::Write {
            path: std::path::PathBuf::from("src/main.rs"),
            cwd: std::path::PathBuf::from("/test/cwd"),
            message: "Create/overwrite file: src/main.rs".to_string(),
        };

        let actual = fixture.can_perform(&operation);

        assert_eq!(actual, Permission::Confirm);
    }

    #[test]
    fn test_policy_engine_can_perform_execute() {
        let fixture_workflow = fixture_workflow_with_execute_policy();
        let fixture = PolicyEngine::new(&fixture_workflow);
        let operation = PermissionOperation::Execute {
            command: "cargo build".to_string(),
            cwd: std::path::PathBuf::from("/test/cwd"),
        };

        let actual = fixture.can_perform(&operation);

        assert_eq!(actual, Permission::Allow);
    }

    #[test]
    fn test_policy_engine_can_perform_net_fetch() {
        let fixture_workflow = fixture_workflow_with_net_fetch_policy();
        let fixture = PolicyEngine::new(&fixture_workflow);
        let operation = PermissionOperation::Fetch {
            url: "https://api.example.com/data".to_string(),
            cwd: std::path::PathBuf::from("/test/cwd"),
            message: "Fetch content from URL: https://api.example.com/data".to_string(),
        };

        let actual = fixture.can_perform(&operation);

        assert_eq!(actual, Permission::Allow);
    }
}