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