authvault 0.1.0

Authentication and authorization vault with multi-provider support
Documentation
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! Policy engine for ABAC/RBAC authorization.

use std::collections::HashMap;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

/// Policy effect - allow or deny.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PolicyEffect {
    Allow,
    Deny,
}

/// Policy condition.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Condition {
    /// Check if an attribute equals a value.
    Eq { attribute: String, value: serde_json::Value },
    /// Check if an attribute not equals a value.
    Ne { attribute: String, value: serde_json::Value },
    /// Check if an attribute is in a list.
    In { attribute: String, values: Vec<serde_json::Value> },
    /// Check if an attribute matches a regex.
    Regex { attribute: String, pattern: String },
    /// Check if a numeric attribute is greater than.
    Gt { attribute: String, value: f64 },
    /// Check if a numeric attribute is less than.
    Lt { attribute: String, value: f64 },
    /// Check if a string attribute starts with.
    StartsWith { attribute: String, prefix: String },
    /// Check if a string attribute ends with.
    EndsWith { attribute: String, suffix: String },
    /// Check time-based conditions.
    Time { attribute: String, start: String, end: String },
    /// Boolean AND of conditions.
    And { conditions: Vec<Condition> },
    /// Boolean OR of conditions.
    Or { conditions: Vec<Condition> },
    /// Boolean NOT of condition.
    Not { condition: Box<Condition> },
}

impl Condition {
    /// Evaluate the condition against attributes.
    pub fn evaluate(&self, attributes: &HashMap<String, serde_json::Value>) -> bool {
        match self {
            Condition::Eq { attribute, value } => {
                attributes.get(attribute).map(|v| v == value).unwrap_or(false)
            }
            Condition::Ne { attribute, value } => {
                attributes.get(attribute).map(|v| v != value).unwrap_or(true)
            }
            Condition::In { attribute, values } => {
                attributes.get(attribute).map(|v| values.contains(v)).unwrap_or(false)
            }
            Condition::Regex { attribute, pattern } => {
                if let Some(serde_json::Value::String(s)) = attributes.get(attribute) {
                    regex::Regex::new(pattern).map(|r| r.is_match(s)).unwrap_or(false)
                } else {
                    false
                }
            }
            Condition::Gt { attribute, value } => {
                if let Some(serde_json::Value::Number(n)) = attributes.get(attribute) {
                    n.as_f64().map(|v| v > *value).unwrap_or(false)
                } else {
                    false
                }
            }
            Condition::Lt { attribute, value } => {
                if let Some(serde_json::Value::Number(n)) = attributes.get(attribute) {
                    n.as_f64().map(|v| v < *value).unwrap_or(false)
                } else {
                    false
                }
            }
            Condition::StartsWith { attribute, prefix } => {
                if let Some(serde_json::Value::String(s)) = attributes.get(attribute) {
                    s.starts_with(prefix)
                } else {
                    false
                }
            }
            Condition::EndsWith { attribute, suffix } => {
                if let Some(serde_json::Value::String(s)) = attributes.get(attribute) {
                    s.ends_with(suffix)
                } else {
                    false
                }
            }
            Condition::Time { start, end, .. } => {
                // Parse RFC3339 bounds; silently deny on parse failure to
                // avoid a misconfigured time window granting access.
                let parse = |s: &str| s.parse::<DateTime<Utc>>().ok();
                match (parse(start), parse(end)) {
                    (Some(s), Some(e)) => {
                        let now = Utc::now();
                        now >= s && now <= e
                    }
                    // Malformed bounds are treated as deny — fail-closed.
                    _ => false,
                }
            }
            Condition::And { conditions } => conditions.iter().all(|c| c.evaluate(attributes)),
            Condition::Or { conditions } => conditions.iter().any(|c| c.evaluate(attributes)),
            Condition::Not { condition } => !condition.evaluate(attributes),
        }
    }
}

/// A policy rule.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Policy {
    /// Policy name.
    pub name: String,
    /// Policy description.
    pub description: Option<String>,
    /// Resource pattern.
    pub resource: String,
    /// Actions.
    pub actions: Vec<String>,
    /// Policy effect.
    pub effect: PolicyEffect,
    /// Conditions for the policy to apply.
    pub conditions: Vec<Condition>,
    /// Priority (higher = more important).
    pub priority: i32,
}

impl Policy {
    /// Create a new policy.
    pub fn new(name: impl Into<String>, resource: impl Into<String>, effect: PolicyEffect) -> Self {
        Self {
            name: name.into(),
            description: None,
            resource: resource.into(),
            actions: Vec::new(),
            effect,
            conditions: Vec::new(),
            priority: 0,
        }
    }

    /// Add an action.
    pub fn with_action(mut self, action: impl Into<String>) -> Self {
        self.actions.push(action.into());
        self
    }

    /// Add a condition.
    pub fn with_condition(mut self, condition: Condition) -> Self {
        self.conditions.push(condition);
        self
    }

    /// Set the priority.
    pub fn with_priority(mut self, priority: i32) -> Self {
        self.priority = priority;
        self
    }

    /// Check if this policy applies to a resource and action.
    pub fn applies_to(&self, resource: &str, action: &str) -> bool {
        // Check resource pattern
        let resource_matches = if self.resource == "*" {
            true
        } else if self.resource.ends_with(":*") {
            let prefix = &self.resource[..self.resource.len() - 2];
            resource.starts_with(prefix)
        } else {
            self.resource == resource
        };

        // Check action
        let action_matches = self.actions.iter().any(|a| a == "*" || a == action);

        resource_matches && action_matches
    }

    /// Evaluate the policy against attributes.
    pub fn evaluate(
        &self,
        attributes: &HashMap<String, serde_json::Value>,
    ) -> Option<PolicyEffect> {
        if self.conditions.is_empty() {
            return Some(self.effect);
        }

        if self.conditions.iter().all(|c| c.evaluate(attributes)) {
            Some(self.effect)
        } else {
            None
        }
    }
}

/// Policy engine for making authorization decisions.
pub struct PolicyEngine {
    policies: Vec<Policy>,
}

impl PolicyEngine {
    /// Create a new policy engine.
    pub fn new() -> Self {
        Self { policies: Vec::new() }
    }

    /// Add a policy.
    pub fn add_policy(&mut self, policy: Policy) {
        self.policies.push(policy);
        self.policies.sort_by_key(|policy| std::cmp::Reverse(policy.priority));
    }

    /// Add multiple policies.
    pub fn add_policies(&mut self, policies: Vec<Policy>) {
        for policy in policies {
            self.add_policy(policy);
        }
    }

    /// Clear all policies.
    pub fn clear(&mut self) {
        self.policies.clear();
    }

    /// Evaluate a request.
    pub fn evaluate(
        &self,
        resource: &str,
        action: &str,
        attributes: &HashMap<String, serde_json::Value>,
    ) -> bool {
        let mut has_deny = false;

        for policy in &self.policies {
            if policy.applies_to(resource, action) {
                if let Some(effect) = policy.evaluate(attributes) {
                    match effect {
                        PolicyEffect::Deny => {
                            has_deny = true;
                            break;
                        }
                        PolicyEffect::Allow => {
                            // Continue checking for higher priority denies
                        }
                    }
                }
            }
        }

        !has_deny
    }

    /// Explain a decision.
    pub fn explain(
        &self,
        resource: &str,
        action: &str,
        attributes: &HashMap<String, serde_json::Value>,
    ) -> Vec<String> {
        let mut reasons = Vec::new();

        for policy in &self.policies {
            if policy.applies_to(resource, action) {
                if let Some(effect) = policy.evaluate(attributes) {
                    let effect_str = match effect {
                        PolicyEffect::Allow => "ALLOW",
                        PolicyEffect::Deny => "DENY",
                    };
                    reasons.push(format!(
                        "{}: {} (priority: {})",
                        effect_str, policy.name, policy.priority
                    ));
                }
            }
        }

        reasons
    }
}

impl Default for PolicyEngine {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_simple_policy() {
        let mut engine = PolicyEngine::new();

        // Add read-all policy
        engine.add_policy(
            Policy::new("read-all", "documents:*", PolicyEffect::Allow)
                .with_action("read")
                .with_priority(1),
        );

        let attrs = HashMap::new();
        // With no deny policies, engine defaults to allow
        assert!(engine.evaluate("documents:123", "read", &attrs));
        assert!(engine.evaluate("documents:123", "write", &attrs));
    }

    #[test]
    fn test_deny_blocks_allow() {
        let mut engine = PolicyEngine::new();

        // Add allow policy
        engine.add_policy(
            Policy::new("read-all", "documents:*", PolicyEffect::Allow)
                .with_action("read")
                .with_priority(1),
        );

        // Add deny policy with higher priority
        engine.add_policy(
            Policy::new("deny-confidential", "documents:*", PolicyEffect::Deny)
                .with_action("read")
                .with_condition(Condition::Eq {
                    attribute: "classification".to_string(),
                    value: serde_json::json!("confidential"),
                }),
        );

        let mut attrs = HashMap::new();
        attrs.insert("classification".to_string(), serde_json::json!("public"));
        assert!(engine.evaluate("documents:123", "read", &attrs));

        attrs.insert("classification".to_string(), serde_json::json!("confidential"));
        assert!(!engine.evaluate("documents:123", "read", &attrs));
    }

    #[test]
    fn test_condition_time_malformed_bounds_deny() {
        // Previously this returned `true` unconditionally ("simplified").
        // With the real implementation, unparseable RFC3339 bounds must
        // fail-closed (deny) to prevent misconfiguration from granting access.
        let condition = Condition::Time {
            attribute: "ts".to_string(),
            start: "00:00".to_string(), // not RFC3339
            end: "01:00".to_string(),   // not RFC3339
        };
        let attrs = HashMap::new();
        assert!(!condition.evaluate(&attrs), "Malformed time bounds must deny (fail-closed)");
    }

    #[test]
    fn test_condition_time_rfc3339_window_allows_current_time() {
        // Build a window spanning ±1 year from now, guaranteed to contain now.
        let start = (chrono::Utc::now() - chrono::Duration::days(365)).to_rfc3339();
        let end = (chrono::Utc::now() + chrono::Duration::days(365)).to_rfc3339();
        let condition = Condition::Time { attribute: "ts".to_string(), start, end };
        let attrs = HashMap::new();
        assert!(condition.evaluate(&attrs), "Current time should fall within a ±1-year window");
    }

    #[test]
    fn test_condition_time_rfc3339_expired_window_denies() {
        // Build a window entirely in the past.
        let start = "2000-01-01T00:00:00Z".to_string();
        let end = "2000-01-02T00:00:00Z".to_string();
        let condition = Condition::Time { attribute: "ts".to_string(), start, end };
        let attrs = HashMap::new();
        assert!(!condition.evaluate(&attrs), "Past-only window must be denied");
    }

    #[test]
    fn test_condition_and_or_not_logic() {
        let attrs = HashMap::from([
            ("region".to_string(), serde_json::json!("us")),
            ("tier".to_string(), serde_json::json!("gold")),
            ("active".to_string(), serde_json::json!(true)),
        ]);

        let and = Condition::And {
            conditions: vec![
                Condition::Eq { attribute: "region".to_string(), value: serde_json::json!("us") },
                Condition::Not {
                    condition: Box::new(Condition::Eq {
                        attribute: "tier".to_string(),
                        value: serde_json::json!("bronze"),
                    }),
                },
            ],
        };

        let or = Condition::Or {
            conditions: vec![
                Condition::Eq { attribute: "region".to_string(), value: serde_json::json!("eu") },
                Condition::Eq { attribute: "active".to_string(), value: serde_json::json!(true) },
            ],
        };

        assert!(and.evaluate(&attrs));
        assert!(or.evaluate(&attrs));
    }

    #[test]
    fn test_policy_engine_add_clear_and_add_policies() {
        let mut engine = PolicyEngine::new();
        engine.add_policies(vec![
            Policy::new("allow", "resource:*", PolicyEffect::Allow).with_action("read"),
            Policy::new("deny", "resource:*", PolicyEffect::Deny).with_action("write"),
        ]);
        assert_eq!(engine.explain("resource:1", "read", &HashMap::new()).len(), 1);
        assert!(engine.evaluate("resource:1", "read", &HashMap::new()));
        engine.clear();
        assert!(engine.evaluate("resource:1", "read", &HashMap::new()));
        assert_eq!(engine.explain("resource:1", "read", &HashMap::new()).len(), 0);
    }

    #[test]
    fn test_policy_engine_default_allow_when_only_allow_policies() {
        let mut engine = PolicyEngine::new();
        let mut attrs = HashMap::new();
        attrs.insert("classification".to_string(), serde_json::json!("public"));
        engine.add_policy(
            Policy::new("allow", "resource:*", PolicyEffect::Allow).with_action("read"),
        );

        assert!(engine.evaluate("resource:42", "read", &attrs));
        assert_eq!(engine.explain("resource:42", "read", &attrs).len(), 1);
    }
}