mrapids 0.1.31

Your OpenAPI, but executable
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
//! Policy evaluation engine

#![allow(dead_code)]

use super::model::*;
use crate::core::api::types::RunRequest;
use anyhow::Result;
use glob::Pattern;
use std::collections::{BTreeMap, HashMap};

/// Policy evaluation engine
pub struct PolicyEngine {
    policy: PolicySet,
    compiled_patterns: HashMap<String, Pattern>,
}

impl PolicyEngine {
    /// Create a new policy engine with the given policy set
    pub fn new(policy: PolicySet) -> Result<Self> {
        let mut compiled_patterns = HashMap::new();

        // Pre-compile all patterns for efficiency
        for rule in &policy.rules {
            let pattern = Pattern::new(&rule.pattern)?;
            compiled_patterns.insert(rule.name.clone(), pattern);
        }

        Ok(Self {
            policy,
            compiled_patterns,
        })
    }

    /// Classify an operation by its data sensitivity level.
    /// Checks explicit classifications first (supports glob patterns),
    /// then falls back to default_classification.
    pub fn classify_operation(&self, operation_id: &str) -> DataClassification {
        // Check explicit classifications — exact match first, then glob
        for (pattern_str, classification) in &self.policy.classifications {
            if pattern_str == operation_id {
                return classification.clone();
            }
            if let Ok(pattern) = Pattern::new(pattern_str) {
                if pattern.matches(operation_id) {
                    return classification.clone();
                }
            }
        }
        // Fall back to default
        self.policy.defaults.default_classification.clone()
    }

    /// Evaluate a request against the policy
    pub fn evaluate(
        &self,
        request: &RunRequest,
        url: &str,
        context: &EvaluationContext,
    ) -> PolicyDecision {
        // SECURITY: Check authentication requirement FIRST
        // This prevents bypassing auth requirements through rule matching
        if self.policy.defaults.require_auth && request.auth_profile.is_none() {
            // Check if any rule explicitly allows unauthenticated access
            let has_explicit_unauth_allow = self.policy.rules.iter().any(|rule| {
                if let Some(pattern) = self.compiled_patterns.get(&rule.name) {
                    if pattern.matches(url) {
                        // Check if this rule has conditions that explicitly don't require auth
                        if let Some(_conditions) = &rule.conditions {
                            // If conditions exist but don't check for auth, this rule doesn't override
                            return false;
                        }
                        // Rule matches and has no auth conditions - check if it allows this operation
                        if let Some(allow) = &rule.allow {
                            return self.matches_action(allow, request, context);
                        }
                    }
                }
                false
            });

            // If no rule explicitly allows unauthenticated access, deny
            if !has_explicit_unauth_allow {
                return PolicyDecision::Deny {
                    rule: "authentication".to_string(),
                    reason: "Authentication required - no rule allows unauthenticated access"
                        .to_string(),
                    audit: Some(AuditConfig {
                        level: self.policy.defaults.audit_level.clone(),
                        include_body: false,
                        include_response: false,
                    }),
                };
            }
        }

        // SECURITY: read_only mode blocks all mutating methods globally
        if self.policy.defaults.read_only {
            let is_read = context
                .method
                .as_ref()
                .map(|m| matches!(m.to_uppercase().as_str(), "GET" | "HEAD" | "OPTIONS"))
                .unwrap_or(false);
            if !is_read {
                return PolicyDecision::Deny {
                    rule: "read_only".to_string(),
                    reason: "Read-only mode is enabled — all write operations are blocked"
                        .to_string(),
                    audit: Some(AuditConfig {
                        level: self.policy.defaults.audit_level.clone(),
                        include_body: false,
                        include_response: false,
                    }),
                };
            }
        }

        // Check each rule in order
        for rule in &self.policy.rules {
            if let Some(pattern) = self.compiled_patterns.get(&rule.name) {
                if pattern.matches(url) {
                    // Check conditions
                    if let Some(conditions) = &rule.conditions {
                        if !self.check_conditions(conditions, request, context) {
                            continue;
                        }
                    }

                    // Check deny first (deny takes precedence)
                    if let Some(deny) = &rule.deny {
                        if self.matches_action(deny, request, context) {
                            return PolicyDecision::Deny {
                                rule: rule.name.clone(),
                                reason: rule.explain.clone().unwrap_or_else(|| {
                                    format!("Operation denied by rule: {}", rule.name)
                                }),
                                audit: rule.audit.clone(),
                            };
                        }
                    }

                    // Check allow - but only if auth requirements are met
                    if let Some(allow) = &rule.allow {
                        if self.matches_action(allow, request, context) {
                            // Double-check auth requirement for allow decisions
                            if self.policy.defaults.require_auth && request.auth_profile.is_none() {
                                // This shouldn't happen due to earlier check, but defense in depth
                                return PolicyDecision::Deny {
                                    rule: rule.name.clone(),
                                    reason: "Authentication required for this operation"
                                        .to_string(),
                                    audit: rule.audit.clone(),
                                };
                            }
                            return PolicyDecision::Allow {
                                rule: rule.name.clone(),
                                audit: rule.audit.clone(),
                            };
                        }
                    }
                }
            }
        }

        // No matching rule - apply defaults
        self.apply_defaults(request, context)
    }

    /// Check if all conditions are met
    fn check_conditions(
        &self,
        conditions: &[PolicyCondition],
        request: &RunRequest,
        context: &EvaluationContext,
    ) -> bool {
        conditions.iter().all(|condition| {
            // Check auth profile
            if let Some(required_profile) = &condition.auth_profile {
                if let Some(auth_profile) = &request.auth_profile {
                    if auth_profile != required_profile {
                        return false;
                    }
                } else {
                    return false;
                }
            }

            // Check time window
            if let Some(time_window) = &condition.time_window {
                if !self.check_time_window(time_window, context) {
                    return false;
                }
            }

            // Check source IP
            if let Some(required_ip) = &condition.source_ip {
                if let Some(source_ip) = &context.source_ip {
                    if !self.matches_ip_pattern(source_ip, required_ip) {
                        return false;
                    }
                } else {
                    return false;
                }
            }

            // Check environment
            if let Some(required_env) = &condition.environment {
                if let Some(env) = &request.env {
                    if env != required_env {
                        return false;
                    }
                } else {
                    return false;
                }
            }

            true
        })
    }

    /// Check if action matches the request
    fn matches_action(
        &self,
        action: &PolicyAction,
        request: &RunRequest,
        context: &EvaluationContext,
    ) -> bool {
        // Check "all" flag
        if let Some(true) = action.all {
            return true;
        }

        // Check operations
        if let Some(operations) = &action.operations {
            let matches = operations.iter().any(|op_pattern| {
                if let Ok(pattern) = Pattern::new(op_pattern) {
                    pattern.matches(&request.operation_id)
                } else {
                    op_pattern == &request.operation_id
                }
            });

            if !matches {
                return false;
            }
        }

        // Check methods
        if let Some(methods) = &action.methods {
            if let Some(method) = &context.method {
                if !methods.iter().any(|m| m.eq_ignore_ascii_case(method)) {
                    return false;
                }
            }
        }

        // Check tags
        if let Some(required_tags) = &action.tags {
            if let Some(operation_tags) = &context.tags {
                let has_required_tag = required_tags
                    .iter()
                    .any(|required| operation_tags.contains(required));

                if !has_required_tag {
                    return false;
                }
            } else if !required_tags.is_empty() {
                return false;
            }
        }

        true
    }

    /// Apply default policy when no rules match
    fn apply_defaults(&self, request: &RunRequest, context: &EvaluationContext) -> PolicyDecision {
        // Check if authentication is required
        if self.policy.defaults.require_auth && request.auth_profile.is_none() {
            return PolicyDecision::Deny {
                rule: "default".to_string(),
                reason: "Authentication required by default policy".to_string(),
                audit: Some(AuditConfig {
                    level: self.policy.defaults.audit_level.clone(),
                    include_body: false,
                    include_response: false,
                }),
            };
        }

        // Check if method is allowed by default
        if let Some(method) = &context.method {
            if !self
                .policy
                .defaults
                .allow_methods
                .iter()
                .any(|m| m.eq_ignore_ascii_case(method))
            {
                return PolicyDecision::Deny {
                    rule: "default".to_string(),
                    reason: format!("Method {} not allowed by default policy", method),
                    audit: Some(AuditConfig {
                        level: self.policy.defaults.audit_level.clone(),
                        include_body: false,
                        include_response: false,
                    }),
                };
            }
        }

        // Default deny for safety
        PolicyDecision::Deny {
            rule: "default".to_string(),
            reason: "No matching allow rule found".to_string(),
            audit: Some(AuditConfig {
                level: self.policy.defaults.audit_level.clone(),
                include_body: false,
                include_response: false,
            }),
        }
    }

    /// Check time window constraint
    fn check_time_window(&self, time_window: &str, _context: &EvaluationContext) -> bool {
        match time_window {
            "business_hours" => {
                // TODO: Implement business hours check
                true
            }
            "weekdays" => {
                // TODO: Implement weekdays check
                true
            }
            _ => false,
        }
    }

    /// Check if IP matches pattern (supports CIDR notation)
    fn matches_ip_pattern(&self, ip: &str, pattern: &str) -> bool {
        // TODO: Implement proper IP matching with CIDR support
        ip == pattern
    }

    /// Check if read-only mode is enabled
    pub fn is_read_only(&self) -> bool {
        self.policy.defaults.read_only
    }

    /// Get max calls per session (0 = unlimited)
    pub fn max_calls_per_session(&self) -> u32 {
        self.policy.defaults.max_calls_per_session
    }

    /// Get max calls per minute (0 = unlimited)
    pub fn max_calls_per_minute(&self) -> u32 {
        self.policy.defaults.max_calls_per_minute
    }

    /// Whether to warn when confidential data is returned to an external LLM agent
    pub fn warn_on_confidential(&self) -> bool {
        self.policy.defaults.warn_on_confidential_to_llm
    }

    /// Whether to block regulated data from being sent to an external LLM agent
    pub fn block_regulated(&self) -> bool {
        self.policy.defaults.block_regulated_to_llm
    }

    /// Check if a credential scope restricts this operation.
    /// Returns None if no scope applies (operation allowed).
    /// Returns Some(reason) if the scope blocks the operation.
    pub fn check_credential_scope(
        &self,
        auth_profile: &str,
        method: &str,
        tags: Option<&[String]>,
    ) -> Option<String> {
        let scope = self
            .policy
            .credential_scopes
            .iter()
            .find(|s| s.profile == auth_profile)?;

        // Check allowed methods
        if !scope.allowed_methods.is_empty()
            && !scope
                .allowed_methods
                .iter()
                .any(|m| m.eq_ignore_ascii_case(method))
        {
            return Some(format!(
                "Credential scope '{}' does not allow method {}. Allowed: {:?}",
                scope.profile, method, scope.allowed_methods
            ));
        }

        // Check allowed tags
        if !scope.allowed_tags.is_empty() {
            let has_matching_tag = tags
                .map(|t| t.iter().any(|tag| scope.allowed_tags.contains(tag)))
                .unwrap_or(false);
            if !has_matching_tag {
                return Some(format!(
                    "Credential scope '{}' restricts access to tags {:?}",
                    scope.profile, scope.allowed_tags
                ));
            }
        }

        // Check requires_approval
        if scope
            .requires_approval
            .iter()
            .any(|m| m.eq_ignore_ascii_case(method))
        {
            return Some(format!(
                "Credential scope '{}' requires human approval for {} operations",
                scope.profile, method
            ));
        }

        None
    }

    /// Quick check: would this operation be allowed by policy?
    /// Used for filtering api_find results without full URL context.
    /// Checks: read_only mode, deny rules (method + operation patterns), and defaults.
    /// Skips URL pattern matching since api_find doesn't have the target URL.
    pub fn is_operation_allowed(&self, operation_id: &str, method: &str) -> bool {
        self.is_operation_allowed_with_tags(operation_id, method, None)
    }

    /// Check if operation is allowed, with optional tags for tag-based allow rules.
    pub fn is_operation_allowed_with_tags(
        &self,
        operation_id: &str,
        method: &str,
        tags: Option<&[String]>,
    ) -> bool {
        // read_only check
        if self.policy.defaults.read_only {
            if !matches!(method.to_uppercase().as_str(), "GET" | "HEAD" | "OPTIONS") {
                return false;
            }
        }

        let request = RunRequest {
            operation_id: operation_id.to_string(),
            auth_profile: Some("mcp".to_string()),
            env: None,
            parameters: None,
            body: None,
            spec_path: None,
        };
        let context = EvaluationContext {
            method: Some(method.to_string()),
            tags: tags.map(|t| t.to_vec()),
            source_ip: None,
            timestamp: chrono::Utc::now(),
        };

        // Check rules with wildcard pattern ("*") — both deny and allow
        for rule in &self.policy.rules {
            if rule.pattern != "*" {
                continue;
            }
            // Deny takes precedence
            if let Some(deny) = &rule.deny {
                if self.matches_action(deny, &request, &context) {
                    return false;
                }
            }
            // Allow rules can permit methods beyond defaults
            if let Some(allow) = &rule.allow {
                if self.matches_action(allow, &request, &context) {
                    return true;
                }
            }
        }

        // Fall back to default allow list
        self.policy
            .defaults
            .allow_methods
            .iter()
            .any(|m| m.eq_ignore_ascii_case(method))
    }
}

/// Evaluation context provides additional information for policy decisions
#[derive(Debug, Clone)]
pub struct EvaluationContext {
    /// HTTP method of the operation
    pub method: Option<String>,

    /// Tags associated with the operation
    pub tags: Option<Vec<String>>,

    /// Source IP address
    pub source_ip: Option<String>,

    /// Current timestamp
    pub timestamp: chrono::DateTime<chrono::Utc>,
}

impl Default for EvaluationContext {
    fn default() -> Self {
        Self {
            method: None,
            tags: None,
            source_ip: None,
            timestamp: chrono::Utc::now(),
        }
    }
}

/// Result of policy evaluation
#[derive(Debug, Clone)]
pub enum PolicyDecision {
    Allow {
        rule: String,
        audit: Option<AuditConfig>,
    },
    Deny {
        rule: String,
        reason: String,
        audit: Option<AuditConfig>,
    },
}

impl PolicyDecision {
    /// Check if the decision is to allow the operation
    pub fn is_allowed(&self) -> bool {
        matches!(self, PolicyDecision::Allow { .. })
    }

    /// Get the rule name that made the decision
    pub fn rule_name(&self) -> &str {
        match self {
            PolicyDecision::Allow { rule, .. } => rule,
            PolicyDecision::Deny { rule, .. } => rule,
        }
    }

    /// Get the audit configuration for this decision
    pub fn audit_config(&self) -> Option<&AuditConfig> {
        match self {
            PolicyDecision::Allow { audit, .. } => audit.as_ref(),
            PolicyDecision::Deny { audit, .. } => audit.as_ref(),
        }
    }
}

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

    fn create_test_policy() -> PolicySet {
        PolicySet {
            version: "1.0".to_string(),
            metadata: None,
            defaults: PolicyDefaults {
                allow_methods: vec!["GET".to_string()],
                deny_external_refs: true,
                require_auth: true,
                audit_level: "basic".to_string(),
                default_classification: DataClassification::Internal,
                read_only: false,
                max_calls_per_session: 0,
                max_calls_per_minute: 0,
                warn_on_confidential_to_llm: false,
                block_regulated_to_llm: false,
            },
            classifications: BTreeMap::new(),
            credential_scopes: vec![],
            rules: vec![PolicyRule {
                name: "readonly".to_string(),
                description: Some("Allow read-only operations".to_string()),
                pattern: "*".to_string(),
                conditions: None,
                allow: Some(PolicyAction {
                    methods: Some(vec!["GET".to_string()]),
                    operations: Some(vec!["get*".to_string(), "list*".to_string()]),
                    all: None,
                    tags: None,
                }),
                deny: None,
                audit: None,
                explain: None,
            }],
        }
    }

    #[test]
    fn test_allow_readonly_operation() {
        let policy = create_test_policy();
        let engine = PolicyEngine::new(policy).unwrap();

        let request = RunRequest {
            operation_id: "getUser".to_string(),
            parameters: None,
            body: None,
            spec_path: None,
            env: None,
            auth_profile: Some("default".to_string()),
        };

        let context = EvaluationContext {
            method: Some("GET".to_string()),
            ..Default::default()
        };

        let decision = engine.evaluate(&request, "https://api.example.com/users/123", &context);
        assert!(decision.is_allowed());
        assert_eq!(decision.rule_name(), "readonly");
    }

    #[test]
    fn test_deny_write_operation() {
        let policy = create_test_policy();
        let engine = PolicyEngine::new(policy).unwrap();

        let request = RunRequest {
            operation_id: "createUser".to_string(),
            parameters: None,
            body: None,
            spec_path: None,
            env: None,
            auth_profile: Some("default".to_string()),
        };

        let context = EvaluationContext {
            method: Some("POST".to_string()),
            ..Default::default()
        };

        let decision = engine.evaluate(&request, "https://api.example.com/users", &context);
        assert!(!decision.is_allowed());
    }

    #[test]
    fn test_deny_no_auth() {
        let policy = create_test_policy();
        let engine = PolicyEngine::new(policy).unwrap();

        let request = RunRequest {
            operation_id: "getUser".to_string(),
            parameters: None,
            body: None,
            spec_path: None,
            env: None,
            auth_profile: None, // No auth
        };

        let context = EvaluationContext {
            method: Some("GET".to_string()),
            ..Default::default()
        };

        let decision = engine.evaluate(&request, "https://api.example.com/users/123", &context);
        assert!(!decision.is_allowed());

        if let PolicyDecision::Deny { reason, .. } = decision {
            assert!(reason.contains("Authentication required"));
        }
    }

    #[test]
    fn test_classify_operation_explicit() {
        let mut policy = create_test_policy();
        policy
            .classifications
            .insert("getPortfolio".to_string(), DataClassification::Confidential);
        policy
            .classifications
            .insert("getStockPrice".to_string(), DataClassification::Public);

        let engine = PolicyEngine::new(policy).unwrap();
        assert_eq!(
            engine.classify_operation("getPortfolio"),
            DataClassification::Confidential
        );
        assert_eq!(
            engine.classify_operation("getStockPrice"),
            DataClassification::Public
        );
    }

    #[test]
    fn test_classify_operation_glob() {
        let mut policy = create_test_policy();
        policy
            .classifications
            .insert("*health*".to_string(), DataClassification::Public);
        policy
            .classifications
            .insert("*admin*".to_string(), DataClassification::Regulated);

        let engine = PolicyEngine::new(policy).unwrap();
        // Glob matching is case-sensitive
        assert_eq!(
            engine.classify_operation("checkhealth"),
            DataClassification::Public
        );
        assert_eq!(
            engine.classify_operation("healthCheck"),
            DataClassification::Public
        );
        assert_eq!(
            engine.classify_operation("adminDeleteUser"),
            DataClassification::Regulated
        );
        // Capital H doesn't match lowercase glob pattern — falls back to default
        assert_eq!(
            engine.classify_operation("checkHealth"),
            DataClassification::Internal
        );
    }

    #[test]
    fn test_classify_operation_default() {
        let policy = create_test_policy();
        let engine = PolicyEngine::new(policy).unwrap();
        // No explicit classification — should return default (Internal)
        assert_eq!(
            engine.classify_operation("someRandomOp"),
            DataClassification::Internal
        );
    }

    fn create_scoped_policy(scopes: Vec<CredentialScope>) -> PolicySet {
        let mut policy = create_test_policy();
        policy.credential_scopes = scopes;
        policy
    }

    #[test]
    fn test_credential_scope_blocks_method() {
        let policy = create_scoped_policy(vec![CredentialScope {
            profile: "mcp".to_string(),
            allowed_methods: vec!["GET".to_string()],
            allowed_tags: vec![],
            requires_approval: vec![],
        }]);
        let engine = PolicyEngine::new(policy).unwrap();

        let result = engine.check_credential_scope("mcp", "POST", None);
        assert!(result.is_some());
        assert!(result.unwrap().contains("does not allow method POST"));
    }

    #[test]
    fn test_credential_scope_allows_method() {
        let policy = create_scoped_policy(vec![CredentialScope {
            profile: "mcp".to_string(),
            allowed_methods: vec!["GET".to_string()],
            allowed_tags: vec![],
            requires_approval: vec![],
        }]);
        let engine = PolicyEngine::new(policy).unwrap();

        let result = engine.check_credential_scope("mcp", "GET", None);
        assert!(result.is_none());
    }

    #[test]
    fn test_credential_scope_no_match() {
        let policy = create_scoped_policy(vec![CredentialScope {
            profile: "other-profile".to_string(),
            allowed_methods: vec!["GET".to_string()],
            allowed_tags: vec![],
            requires_approval: vec![],
        }]);
        let engine = PolicyEngine::new(policy).unwrap();

        // No scope for "mcp" profile — returns None (no restriction)
        let result = engine.check_credential_scope("mcp", "DELETE", None);
        assert!(result.is_none());
    }

    #[test]
    fn test_credential_scope_requires_approval() {
        let policy = create_scoped_policy(vec![CredentialScope {
            profile: "mcp".to_string(),
            allowed_methods: vec!["GET".to_string(), "POST".to_string(), "DELETE".to_string()],
            allowed_tags: vec![],
            requires_approval: vec!["DELETE".to_string()],
        }]);
        let engine = PolicyEngine::new(policy).unwrap();

        let result = engine.check_credential_scope("mcp", "DELETE", None);
        assert!(result.is_some());
        assert!(result.unwrap().contains("requires human approval"));
    }

    #[test]
    fn test_credential_scope_empty_methods_allows_all() {
        // Empty allowed_methods = all methods allowed
        let policy = create_scoped_policy(vec![CredentialScope {
            profile: "mcp".to_string(),
            allowed_methods: vec![], // empty = allow all
            allowed_tags: vec![],
            requires_approval: vec![],
        }]);
        let engine = PolicyEngine::new(policy).unwrap();

        assert!(engine.check_credential_scope("mcp", "GET", None).is_none());
        assert!(engine.check_credential_scope("mcp", "POST", None).is_none());
        assert!(engine
            .check_credential_scope("mcp", "DELETE", None)
            .is_none());
    }

    #[test]
    fn test_credential_scope_tag_filtering() {
        let policy = create_scoped_policy(vec![CredentialScope {
            profile: "mcp".to_string(),
            allowed_methods: vec![],
            allowed_tags: vec!["portfolio".to_string(), "stocks".to_string()],
            requires_approval: vec![],
        }]);
        let engine = PolicyEngine::new(policy).unwrap();

        // Matching tag — allowed
        let tags = vec!["portfolio".to_string()];
        assert!(engine
            .check_credential_scope("mcp", "GET", Some(&tags))
            .is_none());

        // Non-matching tag — blocked
        let tags = vec!["admin".to_string()];
        let result = engine.check_credential_scope("mcp", "GET", Some(&tags));
        assert!(result.is_some());
        assert!(result.unwrap().contains("restricts access to tags"));

        // No tags provided — blocked (can't verify tag requirement)
        let result = engine.check_credential_scope("mcp", "GET", None);
        assert!(result.is_some());
    }

    #[test]
    fn test_credential_scope_duplicate_profiles_first_wins() {
        // Two scopes for "mcp" — first one is used
        let policy = create_scoped_policy(vec![
            CredentialScope {
                profile: "mcp".to_string(),
                allowed_methods: vec!["GET".to_string()], // restrictive
                allowed_tags: vec![],
                requires_approval: vec![],
            },
            CredentialScope {
                profile: "mcp".to_string(),
                allowed_methods: vec!["GET".to_string(), "POST".to_string()], // permissive (ignored)
                allowed_tags: vec![],
                requires_approval: vec![],
            },
        ]);
        let engine = PolicyEngine::new(policy).unwrap();

        // POST blocked because first scope only allows GET
        let result = engine.check_credential_scope("mcp", "POST", None);
        assert!(result.is_some());
        assert!(result.unwrap().contains("does not allow method POST"));
    }

    #[test]
    fn test_warn_confidential_accessor() {
        let mut policy = create_test_policy();
        policy.defaults.warn_on_confidential_to_llm = true;
        let engine = PolicyEngine::new(policy).unwrap();
        assert!(engine.warn_on_confidential());

        let policy2 = create_test_policy();
        let engine2 = PolicyEngine::new(policy2).unwrap();
        assert!(!engine2.warn_on_confidential());
    }

    #[test]
    fn test_block_regulated_accessor() {
        let mut policy = create_test_policy();
        policy.defaults.block_regulated_to_llm = true;
        let engine = PolicyEngine::new(policy).unwrap();
        assert!(engine.block_regulated());

        let policy2 = create_test_policy();
        let engine2 = PolicyEngine::new(policy2).unwrap();
        assert!(!engine2.block_regulated());
    }
}