Skip to main content

auth_framework/protocols/
opa.rs

1//! Open Policy Agent (OPA) integration for externalized authorization.
2//!
3//! Delegates fine-grained policy evaluation to an OPA server using its
4//! REST API, enabling dynamic, data-driven authorization decisions
5//! expressed in Rego.
6//!
7//! # Architecture
8//!
9//! ```text
10//! Application ──► OpaClient ──► POST /v1/data/{path} ──► OPA Server
11//!                                                         │
12//!                                                     Rego policies
13//!                                                         │
14//!                                                  ◄── Decision ──►
15//! ```
16//!
17//! # References
18//!
19//! - [OPA REST API](https://www.openpolicyagent.org/docs/latest/rest-api/)
20//! - [Rego Policy Language](https://www.openpolicyagent.org/docs/latest/policy-language/)
21
22use crate::errors::{AuthError, Result};
23use serde::{Deserialize, Serialize};
24use std::collections::HashMap;
25use std::sync::Arc;
26use std::time::Duration;
27use tokio::sync::RwLock;
28use url::Url;
29
30// ── Configuration ───────────────────────────────────────────────────
31
32/// OPA client configuration.
33#[derive(Clone, Serialize, Deserialize)]
34pub struct OpaConfig {
35    /// Base URL of the OPA server (e.g., `http://localhost:8181`).
36    pub base_url: String,
37    /// Default policy path for queries (e.g., `authz/allow`).
38    pub default_policy_path: String,
39    /// HTTP request timeout in seconds.
40    pub timeout_secs: u64,
41    /// Optional bearer token for authenticating with OPA.
42    pub auth_token: Option<String>,
43    /// Whether to cache policy decisions.
44    pub enable_cache: bool,
45    /// Cache TTL in seconds (0 = no expiry).
46    pub cache_ttl_secs: u64,
47}
48
49impl std::fmt::Debug for OpaConfig {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        let mut d = f.debug_struct("OpaConfig");
52        d.field("base_url", &self.base_url);
53        d.field("default_policy_path", &self.default_policy_path);
54        d.field("timeout_secs", &self.timeout_secs);
55        d.field(
56            "auth_token",
57            &crate::utils::redact::redacted(&self.auth_token),
58        );
59        d.field("enable_cache", &self.enable_cache);
60        d.field("cache_ttl_secs", &self.cache_ttl_secs);
61        d.finish()
62    }
63}
64
65impl Default for OpaConfig {
66    fn default() -> Self {
67        Self {
68            base_url: "http://localhost:8181".to_string(),
69            default_policy_path: "authz/allow".to_string(),
70            timeout_secs: 5,
71            auth_token: None,
72            enable_cache: false,
73            cache_ttl_secs: 60,
74        }
75    }
76}
77
78// ── OPA request / response ──────────────────────────────────────────
79
80/// Input payload sent to OPA for policy evaluation.
81#[derive(Clone, Serialize, Deserialize)]
82pub struct OpaInput {
83    /// The input object passed to the Rego policy.
84    pub input: serde_json::Value,
85}
86
87impl std::fmt::Debug for OpaInput {
88    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89        let mut d = f.debug_struct("OpaInput");
90        d.field("input", &crate::utils::redact::redacted(&self.input));
91        d.finish()
92    }
93}
94
95/// Response from an OPA policy query.
96#[derive(Debug, Clone, Serialize, Deserialize)]
97pub struct OpaResponse {
98    /// The policy decision result.
99    #[serde(default)]
100    pub result: serde_json::Value,
101    /// Decision ID for audit logging.
102    #[serde(default)]
103    pub decision_id: Option<String>,
104}
105
106impl OpaResponse {
107    /// Check if the result is a simple boolean `true`.
108    pub fn is_allowed(&self) -> bool {
109        self.result.as_bool().unwrap_or(false)
110    }
111
112    /// Extract a boolean from a nested path in the result.
113    pub fn get_bool(&self, path: &str) -> Option<bool> {
114        let mut current = &self.result;
115        for segment in path.split('.') {
116            current = current.get(segment)?;
117        }
118        current.as_bool()
119    }
120
121    /// Extract a string from a nested path in the result.
122    pub fn get_str(&self, path: &str) -> Option<&str> {
123        let mut current = &self.result;
124        for segment in path.split('.') {
125            current = current.get(segment)?;
126        }
127        current.as_str()
128    }
129}
130
131// ── Cache entry ─────────────────────────────────────────────────────
132
133struct CacheEntry {
134    response: OpaResponse,
135    expires_at: u64,
136}
137
138// ── OPA Client ──────────────────────────────────────────────────────
139
140/// Client for evaluating authorization decisions against an OPA server.
141pub struct OpaClient {
142    config: OpaConfig,
143    base_url: Url,
144    http: reqwest::Client,
145    cache: Arc<RwLock<HashMap<String, CacheEntry>>>,
146}
147
148impl OpaClient {
149    /// Create a new OPA client.
150    pub fn new(config: OpaConfig) -> Result<Self> {
151        let base_url = normalize_opa_base_url(&config.base_url)?;
152
153        let http = reqwest::Client::builder()
154            .timeout(Duration::from_secs(config.timeout_secs))
155            .build()
156            .map_err(|e| AuthError::internal(format!("HTTP client init failed: {e}")))?;
157
158        Ok(Self {
159            config,
160            base_url,
161            http,
162            cache: Arc::new(RwLock::new(HashMap::new())),
163        })
164    }
165
166    /// Evaluate a policy at the given path with the provided input.
167    ///
168    /// # Arguments
169    ///
170    /// * `policy_path` — The Rego package/rule path (e.g., `authz/allow`)
171    /// * `input` — Arbitrary JSON input for the policy
172    ///
173    /// # Example
174    ///
175    /// ```rust,no_run
176    /// # use auth_framework::protocols::opa::*;
177    /// # async fn example() -> auth_framework::errors::Result<()> {
178    /// let client = OpaClient::new(OpaConfig::default())?;
179    /// let input = serde_json::json!({
180    ///     "user": "alice",
181    ///     "action": "read",
182    ///     "resource": "/documents/secret"
183    /// });
184    /// let response = client.query("authz/allow", input).await?;
185    /// if response.is_allowed() {
186    ///     println!("Access granted");
187    /// }
188    /// # Ok(())
189    /// # }
190    /// ```
191    pub async fn query(&self, policy_path: &str, input: serde_json::Value) -> Result<OpaResponse> {
192        // Check cache first
193        if self.config.enable_cache {
194            let cache_key = format!("{}:{}", policy_path, input);
195            let cache = self.cache.read().await;
196            if let Some(entry) = cache.get(&cache_key) {
197                let now = now_secs();
198                if self.config.cache_ttl_secs == 0 || entry.expires_at > now {
199                    return Ok(entry.response.clone());
200                }
201            }
202            drop(cache);
203        }
204
205        let url = self.build_api_url("v1/data", policy_path)?;
206        let payload = OpaInput {
207            input: input.clone(),
208        };
209
210        let mut request = self.http.post(url).json(&payload);
211        if let Some(ref token) = self.config.auth_token {
212            request = request.bearer_auth(token);
213        }
214
215        let resp = request
216            .send()
217            .await
218            .map_err(|e| AuthError::internal(format!("OPA request failed: {e}")))?;
219
220        if !resp.status().is_success() {
221            let status = resp.status();
222            let body = read_error_body(resp).await;
223            return Err(AuthError::internal(format!(
224                "OPA returned HTTP {status}: {body}"
225            )));
226        }
227
228        let opa_response: OpaResponse = resp
229            .json()
230            .await
231            .map_err(|e| AuthError::internal(format!("Invalid OPA response: {e}")))?;
232
233        // Update cache
234        if self.config.enable_cache {
235            let cache_key = format!("{}:{}", policy_path, input);
236            let entry = CacheEntry {
237                response: opa_response.clone(),
238                expires_at: now_secs() + self.config.cache_ttl_secs,
239            };
240            self.cache.write().await.insert(cache_key, entry);
241        }
242
243        Ok(opa_response)
244    }
245
246    /// Evaluate the default policy path.
247    pub async fn evaluate(&self, input: serde_json::Value) -> Result<OpaResponse> {
248        self.query(&self.config.default_policy_path, input).await
249    }
250
251    /// Convenience: check if the default policy allows the given input.
252    pub async fn is_allowed(&self, input: serde_json::Value) -> Result<bool> {
253        let resp = self.evaluate(input).await?;
254        Ok(resp.is_allowed())
255    }
256
257    /// Check OPA server health.
258    pub async fn health_check(&self) -> Result<bool> {
259        let url = self.build_static_url("health")?;
260        let mut request = self.http.get(url);
261        if let Some(ref token) = self.config.auth_token {
262            request = request.bearer_auth(token);
263        }
264        let resp = request
265            .send()
266            .await
267            .map_err(|e| AuthError::internal(format!("OPA health check failed: {e}")))?;
268        Ok(resp.status().is_success())
269    }
270
271    /// Upload a Rego policy to OPA.
272    pub async fn put_policy(&self, policy_id: &str, rego: &str) -> Result<()> {
273        let url = self.build_api_url("v1/policies", policy_id)?;
274        let mut request = self
275            .http
276            .put(url)
277            .header("Content-Type", "text/plain")
278            .body(rego.to_string());
279        if let Some(ref token) = self.config.auth_token {
280            request = request.bearer_auth(token);
281        }
282
283        let resp = request
284            .send()
285            .await
286            .map_err(|e| AuthError::internal(format!("OPA policy upload failed: {e}")))?;
287
288        if !resp.status().is_success() {
289            let body = read_error_body(resp).await;
290            return Err(AuthError::internal(format!(
291                "OPA policy upload returned error: {body}"
292            )));
293        }
294        Ok(())
295    }
296
297    /// Delete a policy from OPA.
298    pub async fn delete_policy(&self, policy_id: &str) -> Result<()> {
299        let url = self.build_api_url("v1/policies", policy_id)?;
300        let mut request = self.http.delete(url);
301        if let Some(ref token) = self.config.auth_token {
302            request = request.bearer_auth(token);
303        }
304
305        let resp = request
306            .send()
307            .await
308            .map_err(|e| AuthError::internal(format!("OPA policy delete failed: {e}")))?;
309
310        if !resp.status().is_success() {
311            let body = read_error_body(resp).await;
312            return Err(AuthError::internal(format!(
313                "OPA policy delete returned error: {body}"
314            )));
315        }
316        Ok(())
317    }
318
319    /// Upload data to OPA's data store.
320    pub async fn put_data(&self, data_path: &str, data: serde_json::Value) -> Result<()> {
321        let url = self.build_api_url("v1/data", data_path)?;
322        let mut request = self.http.put(url).json(&data);
323        if let Some(ref token) = self.config.auth_token {
324            request = request.bearer_auth(token);
325        }
326
327        let resp = request
328            .send()
329            .await
330            .map_err(|e| AuthError::internal(format!("OPA data upload failed: {e}")))?;
331
332        if !resp.status().is_success() {
333            let body = read_error_body(resp).await;
334            return Err(AuthError::internal(format!(
335                "OPA data upload error: {body}"
336            )));
337        }
338        Ok(())
339    }
340
341    fn build_static_url(&self, path: &str) -> Result<Url> {
342        self.base_url
343            .join(path)
344            .map_err(|e| AuthError::internal(format!("Failed to build OPA URL: {e}")))
345    }
346
347    fn build_api_url(&self, prefix: &str, path: &str) -> Result<Url> {
348        let sanitized_path = sanitize_opa_path(path)?;
349        let joined = if sanitized_path.is_empty() {
350            prefix.to_string()
351        } else {
352            format!("{}/{}", prefix.trim_end_matches('/'), sanitized_path)
353        };
354        self.build_static_url(&joined)
355    }
356
357    /// Clear the response cache.
358    pub async fn clear_cache(&self) {
359        self.cache.write().await.clear();
360    }
361
362    /// Get the number of cached entries.
363    pub async fn cache_size(&self) -> usize {
364        self.cache.read().await.len()
365    }
366}
367
368fn now_secs() -> u64 {
369    std::time::SystemTime::now()
370        .duration_since(std::time::UNIX_EPOCH)
371        .unwrap_or_default()
372        .as_secs()
373}
374
375fn normalize_opa_base_url(base_url: &str) -> Result<Url> {
376    if base_url.is_empty() {
377        return Err(AuthError::validation("OPA base URL cannot be empty"));
378    }
379
380    let mut parsed = Url::parse(base_url)
381        .map_err(|e| AuthError::validation(format!("Invalid OPA base URL: {e}")))?;
382
383    if !matches!(parsed.scheme(), "http" | "https") {
384        return Err(AuthError::validation("OPA base URL must use http or https"));
385    }
386
387    if parsed.host_str().is_none() {
388        return Err(AuthError::validation("OPA base URL must include a host"));
389    }
390
391    if !parsed.username().is_empty() || parsed.password().is_some() {
392        return Err(AuthError::validation(
393            "OPA base URL must not embed credentials",
394        ));
395    }
396
397    if parsed.query().is_some() || parsed.fragment().is_some() {
398        return Err(AuthError::validation(
399            "OPA base URL must not include query parameters or fragments",
400        ));
401    }
402
403    if !parsed.path().ends_with('/') {
404        let new_path = format!("{}/", parsed.path().trim_end_matches('/'));
405        parsed.set_path(&new_path);
406    }
407
408    Ok(parsed)
409}
410
411fn sanitize_opa_path(path: &str) -> Result<String> {
412    let segments: Vec<&str> = path
413        .split('/')
414        .filter(|segment| !segment.is_empty())
415        .collect();
416
417    if segments.is_empty() {
418        return Err(AuthError::validation("OPA path cannot be empty"));
419    }
420
421    for segment in &segments {
422        if matches!(*segment, "." | "..")
423            || segment.contains('\\')
424            || segment.contains('?')
425            || segment.contains('#')
426        {
427            return Err(AuthError::validation("OPA path contains invalid segments"));
428        }
429    }
430
431    Ok(segments.join("/"))
432}
433
434async fn read_error_body(response: reqwest::Response) -> String {
435    match response.text().await {
436        Ok(body) if !body.is_empty() => body,
437        Ok(_) => "<empty response body>".to_string(),
438        Err(error) => format!("<failed to read response body: {error}>"),
439    }
440}
441
442// ── Rego-style local evaluator (for embedded policies) ──────────────
443
444/// A lightweight local policy evaluator for simple attribute-based checks.
445///
446/// Useful when a full OPA server is not deployed. Supports rule evaluation
447/// against a set of named attributes.
448pub struct LocalPolicyEvaluator {
449    rules: Vec<PolicyRule>,
450}
451
452/// A policy rule consisting of conditions that must all be true.
453#[derive(Debug, Clone, Serialize, Deserialize)]
454pub struct PolicyRule {
455    /// Human-readable rule name.
456    pub name: String,
457    /// Conditions that must ALL be satisfied.
458    pub conditions: Vec<PolicyCondition>,
459    /// Effect when all conditions are met.
460    pub effect: PolicyEffect,
461}
462
463/// A single condition in a policy rule.
464#[derive(Debug, Clone, Serialize, Deserialize)]
465pub struct PolicyCondition {
466    /// Attribute path (dot-separated, e.g. "user.role").
467    pub attribute: String,
468    /// Comparison operator.
469    pub operator: ConditionOperator,
470    /// Expected value.
471    pub value: serde_json::Value,
472}
473
474/// Comparison operators for policy conditions.
475#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
476#[serde(rename_all = "snake_case")]
477pub enum ConditionOperator {
478    Equals,
479    NotEquals,
480    Contains,
481    In,
482    Exists,
483}
484
485/// Policy decision effect.
486#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
487#[serde(rename_all = "lowercase")]
488pub enum PolicyEffect {
489    Allow,
490    Deny,
491}
492
493impl LocalPolicyEvaluator {
494    /// Create a new evaluator with no rules (default-deny).
495    pub fn new() -> Self {
496        Self { rules: Vec::new() }
497    }
498
499    /// Add a policy rule.
500    pub fn add_rule(&mut self, rule: PolicyRule) {
501        self.rules.push(rule);
502    }
503
504    /// Evaluate an input against all rules.
505    ///
506    /// Returns `Allow` if at least one Allow rule matches and no Deny rule matches.
507    /// Returns `Deny` if no rules match or a Deny rule fires.
508    pub fn evaluate(&self, input: &serde_json::Value) -> PolicyEffect {
509        let mut any_allow = false;
510
511        for rule in &self.rules {
512            if self.evaluate_rule(rule, input) {
513                match rule.effect {
514                    PolicyEffect::Deny => return PolicyEffect::Deny,
515                    PolicyEffect::Allow => any_allow = true,
516                }
517            }
518        }
519
520        if any_allow {
521            PolicyEffect::Allow
522        } else {
523            PolicyEffect::Deny
524        }
525    }
526
527    fn evaluate_rule(&self, rule: &PolicyRule, input: &serde_json::Value) -> bool {
528        rule.conditions
529            .iter()
530            .all(|cond| self.evaluate_condition(cond, input))
531    }
532
533    fn evaluate_condition(&self, cond: &PolicyCondition, input: &serde_json::Value) -> bool {
534        let actual = resolve_path(input, &cond.attribute);
535
536        match cond.operator {
537            ConditionOperator::Equals => match actual {
538                Some(v) => *v == cond.value,
539                None => false,
540            },
541            ConditionOperator::NotEquals => match actual {
542                Some(v) => *v != cond.value,
543                None => true,
544            },
545            ConditionOperator::Contains => match actual {
546                Some(v) => {
547                    if let (Some(arr), Some(needle)) = (v.as_array(), cond.value.as_str()) {
548                        arr.iter().any(|e| e.as_str() == Some(needle))
549                    } else if let (Some(s), Some(needle)) = (v.as_str(), cond.value.as_str()) {
550                        s.contains(needle)
551                    } else {
552                        false
553                    }
554                }
555                None => false,
556            },
557            ConditionOperator::In => match actual {
558                Some(v) => {
559                    if let Some(arr) = cond.value.as_array() {
560                        arr.contains(v)
561                    } else {
562                        false
563                    }
564                }
565                None => false,
566            },
567            ConditionOperator::Exists => actual.is_some(),
568        }
569    }
570}
571
572impl Default for LocalPolicyEvaluator {
573    fn default() -> Self {
574        Self::new()
575    }
576}
577
578/// Resolve a dot-separated path in a JSON value.
579fn resolve_path<'a>(value: &'a serde_json::Value, path: &str) -> Option<&'a serde_json::Value> {
580    let mut current = value;
581    for segment in path.split('.') {
582        current = current.get(segment)?;
583    }
584    Some(current)
585}
586
587#[cfg(test)]
588mod tests {
589    use super::*;
590
591    // ── OPA config ──────────────────────────────────────────────
592
593    #[test]
594    fn test_config_defaults() {
595        let cfg = OpaConfig::default();
596        assert_eq!(cfg.base_url, "http://localhost:8181");
597        assert_eq!(cfg.default_policy_path, "authz/allow");
598        assert_eq!(cfg.timeout_secs, 5);
599        assert!(cfg.auth_token.is_none());
600        assert!(!cfg.enable_cache);
601    }
602
603    // ── OpaResponse ─────────────────────────────────────────────
604
605    #[test]
606    fn test_response_is_allowed_true() {
607        let resp = OpaResponse {
608            result: serde_json::json!(true),
609            decision_id: None,
610        };
611        assert!(resp.is_allowed());
612    }
613
614    #[test]
615    fn test_response_is_allowed_false() {
616        let resp = OpaResponse {
617            result: serde_json::json!(false),
618            decision_id: None,
619        };
620        assert!(!resp.is_allowed());
621    }
622
623    #[test]
624    fn test_response_is_allowed_non_bool() {
625        let resp = OpaResponse {
626            result: serde_json::json!({"allow": true}),
627            decision_id: None,
628        };
629        assert!(!resp.is_allowed());
630    }
631
632    #[test]
633    fn test_response_get_bool() {
634        let resp = OpaResponse {
635            result: serde_json::json!({"authz": {"allow": true, "admin": false}}),
636            decision_id: Some("dec-1".to_string()),
637        };
638        assert_eq!(resp.get_bool("authz.allow"), Some(true));
639        assert_eq!(resp.get_bool("authz.admin"), Some(false));
640        assert_eq!(resp.get_bool("authz.missing"), None);
641    }
642
643    #[test]
644    fn test_response_get_str() {
645        let resp = OpaResponse {
646            result: serde_json::json!({"reason": "policy XYZ"}),
647            decision_id: None,
648        };
649        assert_eq!(resp.get_str("reason"), Some("policy XYZ"));
650    }
651
652    // ── OPA Client creation ─────────────────────────────────────
653
654    #[test]
655    fn test_client_creation_valid() {
656        let client = OpaClient::new(OpaConfig::default());
657        assert!(client.is_ok());
658    }
659
660    #[test]
661    fn test_client_creation_empty_url() {
662        let cfg = OpaConfig {
663            base_url: String::new(),
664            ..Default::default()
665        };
666        assert!(OpaClient::new(cfg).is_err());
667    }
668
669    #[test]
670    fn test_client_creation_rejects_embedded_credentials() {
671        let cfg = OpaConfig {
672            base_url: "https://user:pass@opa.example.com".to_string(),
673            ..Default::default()
674        };
675        assert!(OpaClient::new(cfg).is_err());
676    }
677
678    #[test]
679    fn test_client_creation_rejects_query_string_base_url() {
680        let cfg = OpaConfig {
681            base_url: "https://opa.example.com?target=internal".to_string(),
682            ..Default::default()
683        };
684        assert!(OpaClient::new(cfg).is_err());
685    }
686
687    #[test]
688    fn test_sanitize_opa_path_rejects_traversal() {
689        assert!(sanitize_opa_path("../system/main").is_err());
690        assert!(sanitize_opa_path("authz/../../admin").is_err());
691    }
692
693    // ── Local Policy Evaluator ──────────────────────────────────
694
695    #[test]
696    fn test_local_evaluator_default_deny() {
697        let eval = LocalPolicyEvaluator::new();
698        let input = serde_json::json!({"user": "alice"});
699        assert_eq!(eval.evaluate(&input), PolicyEffect::Deny);
700    }
701
702    #[test]
703    fn test_local_evaluator_allow_rule() {
704        let mut eval = LocalPolicyEvaluator::new();
705        eval.add_rule(PolicyRule {
706            name: "allow admins".to_string(),
707            conditions: vec![PolicyCondition {
708                attribute: "user.role".to_string(),
709                operator: ConditionOperator::Equals,
710                value: serde_json::json!("admin"),
711            }],
712            effect: PolicyEffect::Allow,
713        });
714
715        let input = serde_json::json!({"user": {"role": "admin"}});
716        assert_eq!(eval.evaluate(&input), PolicyEffect::Allow);
717
718        let input2 = serde_json::json!({"user": {"role": "viewer"}});
719        assert_eq!(eval.evaluate(&input2), PolicyEffect::Deny);
720    }
721
722    #[test]
723    fn test_local_evaluator_deny_overrides_allow() {
724        let mut eval = LocalPolicyEvaluator::new();
725        eval.add_rule(PolicyRule {
726            name: "allow all".to_string(),
727            conditions: vec![PolicyCondition {
728                attribute: "user.active".to_string(),
729                operator: ConditionOperator::Equals,
730                value: serde_json::json!(true),
731            }],
732            effect: PolicyEffect::Allow,
733        });
734        eval.add_rule(PolicyRule {
735            name: "deny blocked".to_string(),
736            conditions: vec![PolicyCondition {
737                attribute: "user.blocked".to_string(),
738                operator: ConditionOperator::Equals,
739                value: serde_json::json!(true),
740            }],
741            effect: PolicyEffect::Deny,
742        });
743
744        let input = serde_json::json!({"user": {"active": true, "blocked": true}});
745        assert_eq!(eval.evaluate(&input), PolicyEffect::Deny);
746    }
747
748    #[test]
749    fn test_local_evaluator_contains_operator() {
750        let mut eval = LocalPolicyEvaluator::new();
751        eval.add_rule(PolicyRule {
752            name: "role check".to_string(),
753            conditions: vec![PolicyCondition {
754                attribute: "user.roles".to_string(),
755                operator: ConditionOperator::Contains,
756                value: serde_json::json!("editor"),
757            }],
758            effect: PolicyEffect::Allow,
759        });
760
761        let input = serde_json::json!({"user": {"roles": ["viewer", "editor"]}});
762        assert_eq!(eval.evaluate(&input), PolicyEffect::Allow);
763
764        let input2 = serde_json::json!({"user": {"roles": ["viewer"]}});
765        assert_eq!(eval.evaluate(&input2), PolicyEffect::Deny);
766    }
767
768    #[test]
769    fn test_local_evaluator_in_operator() {
770        let mut eval = LocalPolicyEvaluator::new();
771        eval.add_rule(PolicyRule {
772            name: "allowed actions".to_string(),
773            conditions: vec![PolicyCondition {
774                attribute: "action".to_string(),
775                operator: ConditionOperator::In,
776                value: serde_json::json!(["read", "list"]),
777            }],
778            effect: PolicyEffect::Allow,
779        });
780
781        let input = serde_json::json!({"action": "read"});
782        assert_eq!(eval.evaluate(&input), PolicyEffect::Allow);
783
784        let input2 = serde_json::json!({"action": "delete"});
785        assert_eq!(eval.evaluate(&input2), PolicyEffect::Deny);
786    }
787
788    #[test]
789    fn test_local_evaluator_exists_operator() {
790        let mut eval = LocalPolicyEvaluator::new();
791        eval.add_rule(PolicyRule {
792            name: "has token".to_string(),
793            conditions: vec![PolicyCondition {
794                attribute: "auth.token".to_string(),
795                operator: ConditionOperator::Exists,
796                value: serde_json::json!(null),
797            }],
798            effect: PolicyEffect::Allow,
799        });
800
801        let input = serde_json::json!({"auth": {"token": "abc"}});
802        assert_eq!(eval.evaluate(&input), PolicyEffect::Allow);
803
804        let input2 = serde_json::json!({"auth": {}});
805        assert_eq!(eval.evaluate(&input2), PolicyEffect::Deny);
806    }
807
808    #[test]
809    fn test_local_evaluator_not_equals() {
810        let mut eval = LocalPolicyEvaluator::new();
811        eval.add_rule(PolicyRule {
812            name: "not guest".to_string(),
813            conditions: vec![PolicyCondition {
814                attribute: "user.role".to_string(),
815                operator: ConditionOperator::NotEquals,
816                value: serde_json::json!("guest"),
817            }],
818            effect: PolicyEffect::Allow,
819        });
820
821        let input = serde_json::json!({"user": {"role": "admin"}});
822        assert_eq!(eval.evaluate(&input), PolicyEffect::Allow);
823
824        let guest = serde_json::json!({"user": {"role": "guest"}});
825        assert_eq!(eval.evaluate(&guest), PolicyEffect::Deny);
826    }
827
828    #[test]
829    fn test_local_evaluator_multiple_conditions() {
830        let mut eval = LocalPolicyEvaluator::new();
831        eval.add_rule(PolicyRule {
832            name: "admin write".to_string(),
833            conditions: vec![
834                PolicyCondition {
835                    attribute: "user.role".to_string(),
836                    operator: ConditionOperator::Equals,
837                    value: serde_json::json!("admin"),
838                },
839                PolicyCondition {
840                    attribute: "action".to_string(),
841                    operator: ConditionOperator::Equals,
842                    value: serde_json::json!("write"),
843                },
844            ],
845            effect: PolicyEffect::Allow,
846        });
847
848        // Both conditions met
849        let input = serde_json::json!({"user": {"role": "admin"}, "action": "write"});
850        assert_eq!(eval.evaluate(&input), PolicyEffect::Allow);
851
852        // Only one condition met
853        let input2 = serde_json::json!({"user": {"role": "admin"}, "action": "read"});
854        assert_eq!(eval.evaluate(&input2), PolicyEffect::Deny);
855    }
856
857    #[test]
858    fn test_resolve_path() {
859        let v = serde_json::json!({"a": {"b": {"c": 42}}});
860        assert_eq!(resolve_path(&v, "a.b.c"), Some(&serde_json::json!(42)));
861        assert_eq!(resolve_path(&v, "a.b"), Some(&serde_json::json!({"c": 42})));
862        assert_eq!(resolve_path(&v, "x.y"), None);
863    }
864
865    #[test]
866    fn test_policy_rule_serialization() {
867        let rule = PolicyRule {
868            name: "test".to_string(),
869            conditions: vec![PolicyCondition {
870                attribute: "user.role".to_string(),
871                operator: ConditionOperator::Equals,
872                value: serde_json::json!("admin"),
873            }],
874            effect: PolicyEffect::Allow,
875        };
876        let json = serde_json::to_string(&rule).unwrap();
877        let parsed: PolicyRule = serde_json::from_str(&json).unwrap();
878        assert_eq!(parsed.name, "test");
879        assert_eq!(parsed.effect, PolicyEffect::Allow);
880    }
881
882    #[test]
883    fn test_opa_input_serialization() {
884        let input = OpaInput {
885            input: serde_json::json!({"user": "alice"}),
886        };
887        let json = serde_json::to_value(&input).unwrap();
888        assert_eq!(json["input"]["user"], "alice");
889    }
890}