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
206
207
208
209
210
211
212
213
214
use crate::wildcard;
use crate::{Effect, Policy, AuthRequest, Result};
use uuid::Uuid;

/// Manage creation, storage/retrieval, and deletion of policies.
pub trait PolicyManager {
    /// Create and store a new policy. The policy ID is returned
    fn create(&mut self, policy: Policy) -> Result<Uuid>;

    /// Update an existing policy
    fn update(&mut self, policy: &Policy) -> Result<()>;

    /// Delete a policy
    ///
    /// Note: This will detach the policy from all principals it is currently used by
    fn delete(&mut self, id: &Uuid) -> Result<()>;

    /// Get a policy by id
    fn get(&self, id: &Uuid) -> Result<&Policy>;

    /// List all policies
    fn list(&self) -> Result<Vec<Policy>>;

    /// Attach a policy to a principal
    fn attach(&mut self, principal: &str, id: &Uuid) -> Result<()>;

    /// Detach a policy from a principal
    fn detach(&mut self, principal: &str, id: &Uuid) -> Result<()>;

    /// Get all policies for a given principal
    fn get_policies_for_principal(&self, principal: &str) -> Result<Option<Vec<Policy>>>;
}


/// Engine implements the logic to check if a specific request (action)
/// by a principal is allowed or not on a particular resource.
///
/// An action is allowed if and only if there is an explicit "allow" statement that can be applied. Any explicit "deny" statements will override an "allow".
/// If no statement matches then a request is implicitly denied by default.
///
pub struct Engine<T: PolicyManager> {
    /// The underlying policy manager/storage mechanism
    pub manager: T,
}

impl<T: PolicyManager> Engine<T> {
    /// Create a new engine with the given policy manager
    pub fn new(manager: T) -> Self {
        Engine { manager: manager }
    }

    /// Check if an action is allowed or not
    pub fn is_allowed(&mut self, req: &AuthRequest) -> Result<bool> {
        let policies = self.manager.get_policies_for_principal(&req.principal)?;

        if policies.is_none() {
            // no policies for the given principal
            return Ok(false);
        }
        let policies = policies.unwrap();

        let mut allowed = false;

        // we have to iterate over all the policies since policy statements may be contradictory
        // (e.g. one allows, another explicitly denies). Explicit denies take precedence over 
        // the 
        for p in policies.iter() {
            // check the policy statements
            for stmt in p.statements.iter() {
                // check if any of the actions match
                if !stmt
                    .actions
                    .iter()
                    .any(|action| wildcard::matches(action, &req.action))
                {
                    continue;
                }

                // check if any of the resources match
                if !stmt
                    .resources
                    .iter()
                    .any(|resource| wildcard::matches(resource, &req.resource))
                {
                    continue;
                }

                // the current statement is a candidate, check the intended effect
                match stmt.effect {
                    Effect::Allow => {
                        allowed = true;
                    }
                    Effect::Deny => {
                        // explicit deny 
                        return Ok(false);
                    }
                }
            }
        }

        Ok(allowed)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::managers::MemoryManager;
    use test::Bencher;

    #[test]
    fn test_engine_is_allowed() {
        let mut engine = Engine::new(MemoryManager::new());

        let jsp = r#"
        {
            "name": "Account policy",
            "statements": [
                {
                    "sid": "Grant account list access",
                    "effect": "allow",
                    "actions": ["account:list"],
                    "resources": ["resource:account:*"]
                },
                {
                    "sid": "Deny root account access",
                    "effect": "deny",
                    "actions": ["account:list"],
                    "resources": ["resource:account:123"]
                },
                {
                    "sid": "Grant all read access on specific account",
                    "effect": "allow",
                    "actions": ["account:describe:*"],
                    "resources": ["resource:account:789"]
                }
            ]
        }
        "#;

        let policy: Policy = serde_json::from_str(jsp).unwrap();
        let id = engine.manager.create(policy).unwrap();
        let principal = "user:test-user";
        engine.manager.attach(principal, &id).unwrap();

        #[rustfmt::skip] 
        let cases = vec![
            // principal, action, resource, expected
            ( "user:test-user", "account:list", "resource:account:567", true,), // statement 1
            ( "user:test-user", "account:list", "resource:account:789", true,), // statement 1
            ( "user:test-user-2", "account:list", "resource:account:789", false,), // non-existent principal
            ( "user:test-user", "account:list", "resource:account:123", false,), // statement 2 (explicit deny w/allowed match on other statements)
            ( "user:test-user", "account:describe:limits", "resource:account:123", false,), // no matching statements
            ( "user:test-user", "account:describe:limits", "resource:account:789", true,), // statement 3
        ];
        for x in cases {
            let (principal, action, resource, expected) = x;
            let req = AuthRequest {
                principal: principal.to_string(),
                action: action.to_string(),
                resource: resource.to_string(),
            };

            let actual = engine.is_allowed(&req).unwrap();
            assert_eq!(expected, actual, "req: {:?}", req);
        }
    }

    #[bench]
    fn bench_is_allowed(b: &mut Bencher) {
        let mut engine = Engine::new(MemoryManager::new());
        let jsp = r#"
        {
            "name": "Account policy",
            "statements": [
                {
                    "sid": "Grant account list access",
                    "effect": "allow",
                    "actions": ["account:list"],
                    "resources": ["resource:account:*"]
                },
                {
                    "sid": "Deny root account access",
                    "effect": "deny",
                    "actions": ["account:list"],
                    "resources": ["resource:account:123"]
                },
                {
                    "sid": "Grant all read access on specific account",
                    "effect": "allow",
                    "actions": ["account:describe:*"],
                    "resources": ["resource:account:789"]
                }
            ]
        }
        "#;

        let policy: Policy = serde_json::from_str(jsp).unwrap();
        let id = engine.manager.create(policy).unwrap();
        let principal = "user:test-user";
        engine.manager.attach(principal, &id).unwrap();

        let (principal, action, resource) = ( "user:test-user", "account:describe:limits", "resource:account:789",); // Statement 3
        let req = AuthRequest {
            principal: principal.to_string(),
            action: action.to_string(),
            resource: resource.to_string(),
        };

            
        b.iter(|| engine.is_allowed(&req));
    }

}