File size: 12,690 Bytes
d817b84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Tests for the policy engine."""

import pytest
from pathlib import Path
from unittest.mock import Mock, patch

from fastmcp.policy import PolicyEngine, PolicyRegistry, Decision
from fastmcp.policy.policies import MinimumNecessaryAccessPolicy, RBACPolicy


class TestPolicyEngine:
    """Test the policy engine functionality."""
    
    @pytest.fixture
    def policy_engine(self):
        """Create a policy engine for testing."""
        return PolicyEngine()
    
    @pytest.fixture
    def sample_context(self):
        """Create a sample context for testing."""
        return {
            "user": {
                "id": "user123",
                "roles": ["user"],
                "permissions": ["read", "write"]
            },
            "action": "read",
            "resource": {
                "type": "document",
                "id": "doc123",
                "owner": "user123",
                "visibility": "private"
            }
        }
    
    def test_policy_engine_initialization(self, policy_engine):
        """Test policy engine initialization."""
        assert policy_engine.registry is not None
        assert isinstance(policy_engine.registry, PolicyRegistry)
        assert policy_engine._evaluation_order == []
    
    def test_set_evaluation_order(self, policy_engine):
        """Test setting evaluation order."""
        order = ["policy1", "policy2", "policy3"]
        policy_engine.set_evaluation_order(order)
        assert policy_engine._evaluation_order == order
    
    @pytest.mark.asyncio
    async def test_evaluate_no_policies(self, policy_engine, sample_context):
        """Test evaluation when no policies are registered."""
        decision = await policy_engine.evaluate(sample_context)
        assert decision.allow is True
        assert "All policies evaluated successfully" in decision.reason
    
    @pytest.mark.asyncio
    async def test_evaluate_single_policy(self, policy_engine, sample_context):
        """Test evaluation of a single policy."""
        # Register a policy
        policy = MinimumNecessaryAccessPolicy()
        policy_engine.register_policy(policy)
        
        # Evaluate
        decision = await policy_engine.evaluate(sample_context)
        assert decision.allow is True
        # The policy engine returns its own response, not the individual policy response
        assert "All policies evaluated successfully" in decision.reason
    
    @pytest.mark.asyncio
    async def test_evaluate_specific_policies(self, policy_engine, sample_context):
        """Test evaluation of specific policies."""
        # Register multiple policies
        policy1 = MinimumNecessaryAccessPolicy(name="policy1")
        policy2 = RBACPolicy(name="policy2")
        policy_engine.register_policy(policy1)
        policy_engine.register_policy(policy2)
        
        # Evaluate only policy1
        decision = await policy_engine.evaluate(sample_context, ["policy1"])
        assert decision.allow is True
    
    @pytest.mark.asyncio
    async def test_evaluate_policy_denial(self, policy_engine):
        """Test evaluation when a policy denies access."""
        # Create context with sensitive action
        context = {
            "user": {"roles": ["user"]},
            "action": "delete",
            "resource": {"type": "user_data"}
        }
        
        # Register minimum necessary policy
        policy = MinimumNecessaryAccessPolicy()
        policy_engine.register_policy(policy)
        
        # Evaluate
        decision = await policy_engine.evaluate(context)
        assert decision.allow is False
        assert "requires justification" in decision.reason
    
    @pytest.mark.asyncio
    async def test_evaluate_single_policy_method(self, policy_engine, sample_context):
        """Test evaluate_single_policy method."""
        # Register a policy
        policy = MinimumNecessaryAccessPolicy(name="test_policy")
        policy_engine.register_policy(policy)
        
        # Evaluate single policy
        decision = await policy_engine.evaluate_single_policy("test_policy", sample_context)
        assert decision is not None
        assert decision.allow is True
    
    @pytest.mark.asyncio
    async def test_evaluate_single_policy_not_found(self, policy_engine, sample_context):
        """Test evaluate_single_policy with non-existent policy."""
        decision = await policy_engine.evaluate_single_policy("non_existent", sample_context)
        assert decision is None
    
    def test_get_policy_metadata(self, policy_engine):
        """Test getting policy metadata."""
        # Register policies
        policy1 = MinimumNecessaryAccessPolicy(name="policy1")
        policy2 = RBACPolicy(name="policy2")
        policy_engine.register_policy(policy1)
        policy_engine.register_policy(policy2)
        
        metadata = policy_engine.get_policy_metadata()
        assert len(metadata) == 2
        assert any(p["name"] == "policy1" for p in metadata)
        assert any(p["name"] == "policy2" for p in metadata)
    
    def test_register_unregister_policy(self, policy_engine):
        """Test policy registration and unregistration."""
        policy = MinimumNecessaryAccessPolicy(name="test_policy")
        
        # Register
        policy_engine.register_policy(policy)
        assert policy_engine.registry.get_policy("test_policy") is not None
        
        # Unregister
        unregistered = policy_engine.unregister_policy("test_policy")
        assert unregistered is not None
        assert unregistered.name == "test_policy"
        assert policy_engine.registry.get_policy("test_policy") is None


class TestPolicyRegistry:
    """Test the policy registry functionality."""
    
    @pytest.fixture
    def registry(self):
        """Create a policy registry for testing."""
        return PolicyRegistry()
    
    def test_registry_initialization(self, registry):
        """Test registry initialization."""
        assert registry._policies == {}
        assert registry._policy_classes == {}
    
    def test_register_policy(self, registry):
        """Test policy registration."""
        policy = MinimumNecessaryAccessPolicy()
        registry.register_policy(policy)
        assert "minimum_necessary_access" in registry._policies
    
    def test_unregister_policy(self, registry):
        """Test policy unregistration."""
        policy = MinimumNecessaryAccessPolicy()
        registry.register_policy(policy)
        
        unregistered = registry.unregister_policy("minimum_necessary_access")
        assert unregistered is not None
        assert "minimum_necessary_access" not in registry._policies
    
    def test_get_policy(self, registry):
        """Test getting a policy."""
        policy = MinimumNecessaryAccessPolicy()
        registry.register_policy(policy)
        
        retrieved = registry.get_policy("minimum_necessary_access")
        assert retrieved is not None
        assert retrieved.name == "minimum_necessary_access"
    
    def test_list_policies(self, registry):
        """Test listing policies."""
        policy1 = MinimumNecessaryAccessPolicy(name="policy1")
        policy2 = RBACPolicy(name="policy2")
        registry.register_policy(policy1)
        registry.register_policy(policy2)
        
        policies = registry.list_policies()
        assert len(policies) == 2
        assert any(p["name"] == "policy1" for p in policies)
        assert any(p["name"] == "policy2" for p in policies)
    
    def test_register_policy_class(self, registry):
        """Test registering a policy class."""
        registry.register_policy_class("test_policy", MinimumNecessaryAccessPolicy)
        assert "test_policy" in registry._policy_classes
        assert registry._policy_classes["test_policy"] == MinimumNecessaryAccessPolicy
    
    def test_register_invalid_policy_class(self, registry):
        """Test registering an invalid policy class."""
        with pytest.raises(ValueError):
            registry.register_policy_class("invalid", str)
    
    def test_create_policy_from_config(self, registry):
        """Test creating policy from configuration."""
        registry.register_policy_class("test_policy", MinimumNecessaryAccessPolicy)
        
        config = {
            "type": "test_policy",
            "parameters": {
                "name": "config_policy",
                "required_justification": False
            }
        }
        
        policy = registry.create_policy_from_config(config)
        assert policy is not None
        assert policy.name == "config_policy"
        assert isinstance(policy, MinimumNecessaryAccessPolicy)
    
    def test_create_policy_from_invalid_config(self, registry):
        """Test creating policy from invalid configuration."""
        config = {"type": "non_existent"}
        policy = registry.create_policy_from_config(config)
        assert policy is None


class TestPolicyLoadAndReload:
    """Test policy loading and hot-reload functionality."""
    
    @pytest.fixture
    def registry(self):
        """Create a policy registry for testing."""
        return PolicyRegistry()
    
    @pytest.fixture
    def yaml_config_file(self, tmp_path):
        """Create a temporary YAML config file."""
        config_content = """
policies:
  - name: yaml_policy1
    type: minimum_necessary
    parameters:
      required_justification: false
  - name: yaml_policy2
    type: rbac
    parameters:
      version: "1.0.0"
"""
        config_file = tmp_path / "policies.yaml"
        config_file.write_text(config_content)
        return config_file
    
    def test_load_policies_from_yaml(self, registry, yaml_config_file):
        """Test loading policies from YAML file."""
        # Register policy classes
        registry.register_policy_class("minimum_necessary", MinimumNecessaryAccessPolicy)
        registry.register_policy_class("rbac", RBACPolicy)
        
        # Load from YAML
        registry.load_policies_from_yaml(yaml_config_file)
        
        # Check that policies were loaded
        assert registry.get_policy("yaml_policy1") is not None
        assert registry.get_policy("yaml_policy2") is not None
    
    def test_hot_reload_policies(self, registry, yaml_config_file):
        """Test hot reloading policies."""
        # Register policy classes
        registry.register_policy_class("minimum_necessary", MinimumNecessaryAccessPolicy)
        registry.register_policy_class("rbac", RBACPolicy)
        
        # Initial load
        registry.load_policies_from_yaml(yaml_config_file)
        initial_count = len(registry._policies)
        
        # Hot reload
        registry.hot_reload_policies(yaml_config_file)
        
        # Check that policies were reloaded
        assert len(registry._policies) == initial_count
        assert registry.get_policy("yaml_policy1") is not None
        assert registry.get_policy("yaml_policy2") is not None
    
    @patch('importlib.metadata.entry_points')
    def test_load_policy_from_entry_point(self, mock_entry_points, registry):
        """Test loading policies from entry points."""
        # Mock entry points
        mock_entry_point = Mock()
        mock_entry_point.name = "test_policy"
        mock_entry_point.load.return_value = MinimumNecessaryAccessPolicy
        
        mock_entry_points.return_value.select.return_value = [mock_entry_point]
        
        # Load from entry points
        registry.load_policy_from_entry_point("fastmcp.policies")
        
        # Check that policy was loaded
        assert registry.get_policy("test_policy") is not None


class TestPolicyIntegration:
    """Test policy integration with FastMCP server."""
    
    @pytest.mark.asyncio
    async def test_policy_engine_with_server(self):
        """Test policy engine integration with FastMCP server."""
        from fastmcp import FastMCP
        
        # Create server with policy engine
        server = FastMCP("Test Server")
        policy_engine = server.enable_policy_engine()
        
        # Register policies
        policy_engine.register_policy(MinimumNecessaryAccessPolicy())
        policy_engine.register_policy(RBACPolicy())
        
        # Test that policy engine is accessible
        assert server.get_policy_engine() is not None
        assert server.get_policy_engine() == policy_engine
        
        # Test policy evaluation
        context = {
            "user": {"roles": ["user"]},
            "action": "read",
            "resource": {"type": "document"}
        }
        
        decision = await policy_engine.evaluate(context)
        assert decision.allow is True