mcp-security-framework 0.1.0__py3-none-any.whl → 1.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. mcp_security_framework/core/auth_manager.py +12 -2
  2. mcp_security_framework/core/cert_manager.py +247 -16
  3. mcp_security_framework/core/permission_manager.py +4 -0
  4. mcp_security_framework/core/rate_limiter.py +10 -0
  5. mcp_security_framework/core/security_manager.py +2 -0
  6. mcp_security_framework/examples/comprehensive_example.py +884 -0
  7. mcp_security_framework/examples/django_example.py +45 -12
  8. mcp_security_framework/examples/fastapi_example.py +826 -354
  9. mcp_security_framework/examples/flask_example.py +51 -11
  10. mcp_security_framework/examples/gateway_example.py +109 -17
  11. mcp_security_framework/examples/microservice_example.py +112 -16
  12. mcp_security_framework/examples/standalone_example.py +646 -430
  13. mcp_security_framework/examples/test_all_examples.py +556 -0
  14. mcp_security_framework/middleware/auth_middleware.py +1 -1
  15. mcp_security_framework/middleware/fastapi_auth_middleware.py +82 -14
  16. mcp_security_framework/middleware/flask_auth_middleware.py +154 -7
  17. mcp_security_framework/schemas/models.py +1 -0
  18. mcp_security_framework/utils/cert_utils.py +5 -5
  19. {mcp_security_framework-0.1.0.dist-info → mcp_security_framework-1.1.0.dist-info}/METADATA +1 -1
  20. {mcp_security_framework-0.1.0.dist-info → mcp_security_framework-1.1.0.dist-info}/RECORD +38 -32
  21. tests/conftest.py +306 -0
  22. tests/test_cli/test_cert_cli.py +13 -31
  23. tests/test_core/test_cert_manager.py +12 -12
  24. tests/test_examples/test_comprehensive_example.py +560 -0
  25. tests/test_examples/test_fastapi_example.py +214 -116
  26. tests/test_examples/test_flask_example.py +250 -131
  27. tests/test_examples/test_standalone_example.py +44 -99
  28. tests/test_integration/test_auth_flow.py +4 -4
  29. tests/test_integration/test_certificate_flow.py +1 -1
  30. tests/test_integration/test_fastapi_integration.py +39 -45
  31. tests/test_integration/test_flask_integration.py +4 -2
  32. tests/test_integration/test_standalone_integration.py +48 -48
  33. tests/test_middleware/test_fastapi_auth_middleware.py +724 -0
  34. tests/test_middleware/test_flask_auth_middleware.py +638 -0
  35. tests/test_middleware/test_security_middleware.py +9 -3
  36. {mcp_security_framework-0.1.0.dist-info → mcp_security_framework-1.1.0.dist-info}/WHEEL +0 -0
  37. {mcp_security_framework-0.1.0.dist-info → mcp_security_framework-1.1.0.dist-info}/entry_points.txt +0 -0
  38. {mcp_security_framework-0.1.0.dist-info → mcp_security_framework-1.1.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,560 @@
1
+ """
2
+ Tests for Comprehensive Security Example
3
+
4
+ This module tests the comprehensive security example that demonstrates
5
+ all capabilities of the MCP Security Framework.
6
+ """
7
+
8
+ import pytest
9
+ import tempfile
10
+ import os
11
+ import shutil
12
+ from unittest.mock import Mock, patch, MagicMock, mock_open
13
+ from datetime import datetime, timezone
14
+
15
+ from mcp_security_framework.examples.comprehensive_example import ComprehensiveSecurityExample
16
+ from mcp_security_framework.schemas.models import AuthResult, AuthStatus, AuthMethod, ValidationResult, ValidationStatus
17
+ from mcp_security_framework.schemas.config import SecurityConfig
18
+
19
+
20
+ class TestComprehensiveSecurityExample:
21
+ """Test suite for ComprehensiveSecurityExample class."""
22
+
23
+ def setup_method(self):
24
+ """Set up test fixtures before each test method."""
25
+ self.temp_dir = tempfile.mkdtemp(prefix="test_comprehensive_")
26
+ self.example = ComprehensiveSecurityExample(work_dir=self.temp_dir)
27
+
28
+ def teardown_method(self):
29
+ """Clean up after each test method."""
30
+ if hasattr(self, 'temp_dir') and os.path.exists(self.temp_dir):
31
+ shutil.rmtree(self.temp_dir)
32
+
33
+ def test_comprehensive_security_example_initialization(self):
34
+ """Test ComprehensiveSecurityExample initialization."""
35
+ assert self.example.work_dir == self.temp_dir
36
+ assert os.path.exists(self.example.certs_dir)
37
+ assert os.path.exists(self.example.keys_dir)
38
+ assert os.path.exists(self.example.config_dir)
39
+ assert isinstance(self.example.config, SecurityConfig)
40
+ assert self.example.logger is not None
41
+ assert self.example.test_api_key == "admin_key_123"
42
+ assert self.example.test_jwt_token is not None
43
+
44
+ def test_create_comprehensive_config(self):
45
+ """Test comprehensive configuration creation."""
46
+ config = self.example._create_comprehensive_config()
47
+ assert isinstance(config, SecurityConfig)
48
+ assert config.auth.enabled is True
49
+ assert config.permissions.enabled is True
50
+ assert config.ssl.enabled is False # Initially disabled
51
+ assert config.certificates.enabled is False # Initially disabled
52
+ assert config.rate_limit.enabled is True
53
+ assert config.logging.enabled is True
54
+
55
+ def test_create_test_jwt_token(self):
56
+ """Test JWT token creation."""
57
+ token = self.example._create_test_jwt_token()
58
+ assert isinstance(token, str)
59
+ assert len(token) > 0
60
+
61
+ def test_create_roles_config(self):
62
+ """Test roles configuration creation."""
63
+ roles_file = os.path.join(self.example.config_dir, "roles.json")
64
+ assert os.path.exists(roles_file)
65
+
66
+ # Verify roles file content
67
+ import json
68
+ with open(roles_file, 'r') as f:
69
+ roles_config = json.load(f)
70
+
71
+ assert "roles" in roles_config
72
+ assert "admin" in roles_config["roles"]
73
+ assert "user" in roles_config["roles"]
74
+ assert "readonly" in roles_config["roles"]
75
+
76
+ @patch('mcp_security_framework.examples.comprehensive_example.CertificateManager')
77
+ def test_demonstrate_certificate_management_success(self, mock_cert_manager):
78
+ """Test successful certificate management demonstration."""
79
+ # Mock certificate manager methods
80
+ mock_manager = Mock()
81
+ mock_cert_manager.return_value = mock_manager
82
+
83
+ # Mock certificate creation results
84
+ mock_ca_pair = Mock()
85
+ mock_ca_pair.certificate_path = "/path/to/ca.crt"
86
+ mock_ca_pair.private_key_path = "/path/to/ca.key"
87
+ mock_ca_pair.serial_number = "123456789"
88
+
89
+ mock_intermediate_pair = Mock()
90
+ mock_intermediate_pair.certificate_path = "/path/to/intermediate.crt"
91
+ mock_intermediate_pair.private_key_path = "/path/to/intermediate.key"
92
+ mock_intermediate_pair.serial_number = "987654321"
93
+
94
+ mock_server_pair = Mock()
95
+ mock_server_pair.certificate_path = "/path/to/server.crt"
96
+ mock_server_pair.private_key_path = "/path/to/server.key"
97
+ mock_server_pair.serial_number = "111222333"
98
+
99
+ mock_client_pair = Mock()
100
+ mock_client_pair.certificate_path = "/path/to/client.crt"
101
+ mock_client_pair.private_key_path = "/path/to/client.key"
102
+ mock_client_pair.serial_number = "444555666"
103
+
104
+ mock_manager.create_root_ca.return_value = mock_ca_pair
105
+ mock_manager.create_intermediate_ca.return_value = mock_intermediate_pair
106
+ mock_manager.create_server_certificate.return_value = mock_server_pair
107
+ mock_manager.create_client_certificate.return_value = mock_client_pair
108
+ mock_manager.create_certificate_signing_request.return_value = ("/path/to/csr.pem", "/path/to/csr.key")
109
+ mock_manager.create_crl.return_value = "/path/to/crl.pem"
110
+
111
+ mock_cert_info = Mock()
112
+ mock_cert_info.subject = "CN=test.example.com"
113
+ mock_cert_info.issuer = "CN=Test CA"
114
+ mock_cert_info.serial_number = "123456789"
115
+ mock_cert_info.not_before = datetime.now(timezone.utc)
116
+ mock_cert_info.not_after = datetime.now(timezone.utc)
117
+ mock_cert_info.is_expired = False
118
+ mock_manager.get_certificate_info.return_value = mock_cert_info
119
+
120
+ # Run demonstration
121
+ results = self.example.demonstrate_certificate_management()
122
+
123
+ # Verify results
124
+ assert "root_ca_creation" in results
125
+ assert results["root_ca_creation"]["success"] is True
126
+ assert "intermediate_ca_creation" in results
127
+ assert results["intermediate_ca_creation"]["success"] is True
128
+ assert "server_cert_creation" in results
129
+ assert results["server_cert_creation"]["success"] is True
130
+ assert "client_cert_creation" in results
131
+ assert results["client_cert_creation"]["success"] is True
132
+ assert "csr_creation" in results
133
+ assert results["csr_creation"]["success"] is True
134
+ assert "crl_creation" in results
135
+ assert results["crl_creation"]["success"] is True
136
+ assert "certificate_validation" in results
137
+ assert results["certificate_validation"]["success"] is True
138
+
139
+ def test_demonstrate_certificate_management_exception(self):
140
+ """Test certificate management demonstration with exception."""
141
+ # Mock certificate manager to raise exception
142
+ with patch.object(self.example, 'cert_manager') as mock_cert_manager:
143
+ mock_cert_manager.create_root_ca.side_effect = Exception("Certificate creation failed")
144
+
145
+ results = self.example.demonstrate_certificate_management()
146
+
147
+ assert "error" in results
148
+ assert "Certificate creation failed" in results["error"]
149
+
150
+ def test_demonstrate_ssl_tls_management_success(self):
151
+ """Test successful SSL/TLS management demonstration."""
152
+ # Set certificate paths
153
+ self.example.server_cert_path = "/path/to/server.crt"
154
+ self.example.server_key_path = "/path/to/server.key"
155
+ self.example.ca_cert_path = "/path/to/ca.crt"
156
+ self.example.client_cert_path = "/path/to/client.crt"
157
+ self.example.client_key_path = "/path/to/client.key"
158
+
159
+ # Mock SSL manager methods
160
+ with patch.object(self.example, 'ssl_manager') as mock_ssl_manager:
161
+ # Mock SSL contexts
162
+ mock_server_context = Mock()
163
+ mock_server_context.verify_mode = "CERT_REQUIRED"
164
+ mock_server_context.minimum_version = "TLSv1.2"
165
+ mock_server_context.maximum_version = "TLSv1.3"
166
+
167
+ mock_client_context = Mock()
168
+ mock_client_context.verify_mode = "CERT_REQUIRED"
169
+ mock_client_context.minimum_version = "TLSv1.2"
170
+ mock_client_context.maximum_version = "TLSv1.3"
171
+
172
+ mock_ssl_manager.create_server_context.return_value = mock_server_context
173
+ mock_ssl_manager.create_client_context.return_value = mock_client_context
174
+
175
+ # Mock file existence
176
+ with patch('os.path.exists', return_value=True):
177
+ results = self.example.demonstrate_ssl_tls_management()
178
+
179
+ # Verify results
180
+ assert "server_context_creation" in results
181
+ assert results["server_context_creation"]["success"] is True
182
+ assert "client_context_creation" in results
183
+ assert results["client_context_creation"]["success"] is True
184
+ assert "mtls_context_creation" in results
185
+ assert results["mtls_context_creation"]["success"] is True
186
+ assert "ssl_validation" in results
187
+ assert results["ssl_validation"]["success"] is True
188
+
189
+ def test_demonstrate_ssl_tls_management_exception(self):
190
+ """Test SSL/TLS management demonstration with exception."""
191
+ # Mock SSL manager to raise exception
192
+ with patch.object(self.example, 'ssl_manager') as mock_ssl_manager:
193
+ mock_ssl_manager.create_server_context.side_effect = Exception("SSL context creation failed")
194
+
195
+ results = self.example.demonstrate_ssl_tls_management()
196
+
197
+ assert "error" in results
198
+ assert "SSL context creation failed" in results["error"]
199
+
200
+ def test_demonstrate_authentication_success(self):
201
+ """Test successful authentication demonstration."""
202
+ # Set client certificate path
203
+ self.example.client_cert_path = "/path/to/client.crt"
204
+
205
+ # Mock security manager methods
206
+ with patch.object(self.example, 'security_manager') as mock_security_manager:
207
+ # Mock authentication results
208
+ success_auth_result = AuthResult(
209
+ is_valid=True,
210
+ username="test_user",
211
+ roles=["user"],
212
+ auth_method=AuthMethod.API_KEY,
213
+ status=AuthStatus.SUCCESS
214
+ )
215
+
216
+ failed_auth_result = AuthResult(
217
+ is_valid=False,
218
+ username=None,
219
+ roles=[],
220
+ auth_method=AuthMethod.API_KEY,
221
+ status=AuthStatus.INVALID,
222
+ error_code=-32001,
223
+ error_message="Invalid API key"
224
+ )
225
+
226
+ mock_security_manager.authenticate_user.side_effect = [
227
+ success_auth_result, # API key auth
228
+ success_auth_result, # JWT auth
229
+ success_auth_result, # Certificate auth
230
+ failed_auth_result # Failed auth
231
+ ]
232
+
233
+ # Mock file reading
234
+ with patch('builtins.open', mock_open(read_data="test certificate")):
235
+ results = self.example.demonstrate_authentication()
236
+
237
+ # Verify results
238
+ assert "api_key_auth" in results
239
+ assert results["api_key_auth"]["success"] is True
240
+ assert "jwt_auth" in results
241
+ assert results["jwt_auth"]["success"] is True
242
+ assert "certificate_auth" in results
243
+ assert results["certificate_auth"]["success"] is True
244
+ assert "failed_auth" in results
245
+ assert results["failed_auth"]["success"] is False
246
+
247
+ def test_demonstrate_authentication_exception(self):
248
+ """Test authentication demonstration with exception."""
249
+ # Mock security manager to raise exception
250
+ with patch.object(self.example, 'security_manager') as mock_security_manager:
251
+ mock_security_manager.authenticate_user.side_effect = Exception("Authentication failed")
252
+
253
+ results = self.example.demonstrate_authentication()
254
+
255
+ assert "error" in results
256
+ assert "Authentication failed" in results["error"]
257
+
258
+ def test_demonstrate_authorization_success(self):
259
+ """Test successful authorization demonstration."""
260
+ # Mock security manager methods
261
+ with patch.object(self.example, 'security_manager') as mock_security_manager:
262
+ # Mock authorization results
263
+ success_result = ValidationResult(
264
+ is_valid=True,
265
+ status=ValidationStatus.VALID
266
+ )
267
+
268
+ failed_result = ValidationResult(
269
+ is_valid=False,
270
+ status=ValidationStatus.INVALID
271
+ )
272
+
273
+ mock_security_manager.check_permissions.side_effect = [
274
+ success_result, # Admin permissions
275
+ success_result, # User permissions
276
+ success_result, # Readonly permissions
277
+ failed_result # Denied permissions
278
+ ]
279
+
280
+ results = self.example.demonstrate_authorization()
281
+
282
+ # Verify results
283
+ assert "admin_permissions" in results
284
+ assert results["admin_permissions"]["success"] is True
285
+ assert "user_permissions" in results
286
+ assert results["user_permissions"]["success"] is True
287
+ assert "readonly_permissions" in results
288
+ assert results["readonly_permissions"]["success"] is True
289
+ assert "denied_permissions" in results
290
+ assert results["denied_permissions"]["success"] is False
291
+
292
+ def test_demonstrate_authorization_exception(self):
293
+ """Test authorization demonstration with exception."""
294
+ # Mock security manager to raise exception
295
+ with patch.object(self.example, 'security_manager') as mock_security_manager:
296
+ mock_security_manager.check_permissions.side_effect = Exception("Authorization failed")
297
+
298
+ results = self.example.demonstrate_authorization()
299
+
300
+ assert "error" in results
301
+ assert "Authorization failed" in results["error"]
302
+
303
+ def test_demonstrate_rate_limiting_success(self):
304
+ """Test successful rate limiting demonstration."""
305
+ # Mock security manager methods
306
+ with patch.object(self.example, 'security_manager') as mock_security_manager:
307
+ # Mock rate limiting results (first 4 allowed, 5th denied)
308
+ mock_security_manager.check_rate_limit.side_effect = [True, True, True, True, False]
309
+
310
+ results = self.example.demonstrate_rate_limiting()
311
+
312
+ # Verify results
313
+ assert "rate_limit_checks" in results
314
+ assert len(results["rate_limit_checks"]) == 5
315
+ assert results["rate_limit_exceeded"] is True
316
+
317
+ def test_demonstrate_rate_limiting_exception(self):
318
+ """Test rate limiting demonstration with exception."""
319
+ # Mock security manager to raise exception
320
+ with patch.object(self.example, 'security_manager') as mock_security_manager:
321
+ mock_security_manager.check_rate_limit.side_effect = Exception("Rate limiting failed")
322
+
323
+ results = self.example.demonstrate_rate_limiting()
324
+
325
+ assert "error" in results
326
+ assert "Rate limiting failed" in results["error"]
327
+
328
+ def test_demonstrate_security_validation_success(self):
329
+ """Test successful security validation demonstration."""
330
+ # Mock security manager methods
331
+ with patch.object(self.example, 'security_manager') as mock_security_manager:
332
+ # Mock validation results
333
+ success_result = ValidationResult(
334
+ is_valid=True,
335
+ status=ValidationStatus.VALID
336
+ )
337
+
338
+ mock_security_manager.validate_request.return_value = success_result
339
+ mock_security_manager.validate_configuration.return_value = success_result
340
+
341
+ results = self.example.demonstrate_security_validation()
342
+
343
+ # Verify results
344
+ assert "request_validation" in results
345
+ assert results["request_validation"]["success"] is True
346
+ assert "configuration_validation" in results
347
+ assert results["configuration_validation"]["success"] is True
348
+
349
+ def test_demonstrate_security_validation_exception(self):
350
+ """Test security validation demonstration with exception."""
351
+ # Mock security manager to raise exception
352
+ with patch.object(self.example, 'security_manager') as mock_security_manager:
353
+ mock_security_manager.validate_request.side_effect = Exception("Validation failed")
354
+
355
+ results = self.example.demonstrate_security_validation()
356
+
357
+ assert "error" in results
358
+ assert "Validation failed" in results["error"]
359
+
360
+ def test_demonstrate_security_monitoring_success(self):
361
+ """Test successful security monitoring demonstration."""
362
+ # Mock security manager methods
363
+ with patch.object(self.example, 'security_manager') as mock_security_manager:
364
+ # Mock monitoring results
365
+ mock_security_manager.get_security_status.return_value = {"status": "healthy"}
366
+ mock_security_manager.get_security_metrics.return_value = {"requests": 100}
367
+
368
+ results = self.example.demonstrate_security_monitoring()
369
+
370
+ # Verify results
371
+ assert "security_status" in results
372
+ assert results["security_status"]["status"] == "healthy"
373
+ assert "security_metrics" in results
374
+ assert results["security_metrics"]["requests"] == 100
375
+ assert "security_audit" in results
376
+
377
+ def test_demonstrate_security_monitoring_exception(self):
378
+ """Test security monitoring demonstration with exception."""
379
+ # Mock security manager to raise exception
380
+ with patch.object(self.example, 'security_manager') as mock_security_manager:
381
+ mock_security_manager.get_security_status.side_effect = Exception("Monitoring failed")
382
+
383
+ results = self.example.demonstrate_security_monitoring()
384
+
385
+ assert "error" in results
386
+ assert "Monitoring failed" in results["error"]
387
+
388
+ def test_update_config_after_certificates(self):
389
+ """Test configuration update after certificate creation."""
390
+ # Set certificate paths
391
+ self.example.ca_cert_path = "/path/to/ca.crt"
392
+ self.example.ca_key_path = "/path/to/ca.key"
393
+ self.example.server_cert_path = "/path/to/server.crt"
394
+ self.example.server_key_path = "/path/to/server.key"
395
+
396
+ # Mock file existence and SSL manager creation
397
+ with patch('os.path.exists', return_value=True), \
398
+ patch('mcp_security_framework.examples.comprehensive_example.SSLManager') as mock_ssl_manager_class, \
399
+ patch('mcp_security_framework.examples.comprehensive_example.CertificateManager') as mock_cert_manager_class:
400
+
401
+ mock_ssl_manager = Mock()
402
+ mock_cert_manager = Mock()
403
+ mock_ssl_manager_class.return_value = mock_ssl_manager
404
+ mock_cert_manager_class.return_value = mock_cert_manager
405
+
406
+ self.example._update_config_after_certificates()
407
+
408
+ # Verify configuration was updated
409
+ assert self.example.config.certificates.enabled is True
410
+ assert self.example.config.certificates.ca_cert_path == "/path/to/ca.crt"
411
+ assert self.example.config.certificates.ca_key_path == "/path/to/ca.key"
412
+ assert self.example.config.ssl.enabled is True
413
+ assert self.example.config.ssl.cert_file == "/path/to/server.crt"
414
+ assert self.example.config.ssl.key_file == "/path/to/server.key"
415
+ assert self.example.config.ssl.ca_cert_file == "/path/to/ca.crt"
416
+
417
+ @patch('mcp_security_framework.examples.comprehensive_example.ComprehensiveSecurityExample.demonstrate_certificate_management')
418
+ @patch('mcp_security_framework.examples.comprehensive_example.ComprehensiveSecurityExample.demonstrate_ssl_tls_management')
419
+ @patch('mcp_security_framework.examples.comprehensive_example.ComprehensiveSecurityExample.demonstrate_authentication')
420
+ @patch('mcp_security_framework.examples.comprehensive_example.ComprehensiveSecurityExample.demonstrate_authorization')
421
+ @patch('mcp_security_framework.examples.comprehensive_example.ComprehensiveSecurityExample.demonstrate_rate_limiting')
422
+ @patch('mcp_security_framework.examples.comprehensive_example.ComprehensiveSecurityExample.demonstrate_security_validation')
423
+ @patch('mcp_security_framework.examples.comprehensive_example.ComprehensiveSecurityExample.demonstrate_security_monitoring')
424
+ def test_run_comprehensive_demo_success(self, mock_monitoring, mock_validation, mock_rate_limit,
425
+ mock_authz, mock_auth, mock_ssl, mock_cert):
426
+ """Test successful comprehensive demonstration."""
427
+ # Mock all demonstration methods
428
+ mock_cert.return_value = {"root_ca_creation": {"success": True}}
429
+ mock_ssl.return_value = {"server_context_creation": {"success": True}}
430
+ mock_auth.return_value = {"api_key_auth": {"success": True}}
431
+ mock_authz.return_value = {"admin_permissions": {"success": True}}
432
+ mock_rate_limit.return_value = {"rate_limit_checks": []}
433
+ mock_validation.return_value = {"request_validation": {"success": True}}
434
+ mock_monitoring.return_value = {"security_status": {"status": "healthy"}}
435
+
436
+ results = self.example.run_comprehensive_demo()
437
+
438
+ # Verify results structure
439
+ assert "framework" in results
440
+ assert "version" in results
441
+ assert "timestamp" in results
442
+ assert "certificate_management" in results
443
+ assert "ssl_tls_management" in results
444
+ assert "authentication" in results
445
+ assert "authorization" in results
446
+ assert "rate_limiting" in results
447
+ assert "security_validation" in results
448
+ assert "security_monitoring" in results
449
+
450
+
451
+
452
+
453
+
454
+ def test_comprehensive_example_cleanup(self):
455
+ """Test that working directory is properly cleaned up."""
456
+ # Create a temporary example
457
+ temp_example = ComprehensiveSecurityExample()
458
+ work_dir = temp_example.work_dir
459
+
460
+ # Verify directory exists
461
+ assert os.path.exists(work_dir)
462
+
463
+ # Clean up
464
+ if os.path.exists(work_dir):
465
+ shutil.rmtree(work_dir)
466
+
467
+ # Verify directory is removed
468
+ assert not os.path.exists(work_dir)
469
+
470
+
471
+ def test_main_function():
472
+ """Test the main function."""
473
+ with patch('mcp_security_framework.examples.comprehensive_example.ComprehensiveSecurityExample') as mock_example_class:
474
+ mock_example = Mock()
475
+ mock_example_class.return_value = mock_example
476
+
477
+ # Mock the run_comprehensive_demo method
478
+ mock_example.run_comprehensive_demo.return_value = {
479
+ "framework": "MCP Security Framework",
480
+ "version": "1.0.0",
481
+ "timestamp": "2024-01-01T00:00:00Z",
482
+ "certificate_management": {
483
+ "root_ca_creation": {"success": True},
484
+ "intermediate_ca_creation": {"success": True},
485
+ "server_cert_creation": {"success": True},
486
+ "client_cert_creation": {"success": True},
487
+ "csr_creation": {"success": True},
488
+ "crl_creation": {"success": True},
489
+ "certificate_validation": {"success": True}
490
+ },
491
+ "ssl_tls_management": {
492
+ "server_context_creation": {"success": True},
493
+ "client_context_creation": {"success": True},
494
+ "mtls_context_creation": {"success": True},
495
+ "ssl_validation": {"success": True}
496
+ },
497
+ "authentication": {
498
+ "api_key_auth": {"success": True},
499
+ "jwt_auth": {"success": True},
500
+ "certificate_auth": {"success": True},
501
+ "failed_auth": {"success": False}
502
+ },
503
+ "authorization": {
504
+ "admin_permissions": {"success": True},
505
+ "user_permissions": {"success": True},
506
+ "readonly_permissions": {"success": True},
507
+ "denied_permissions": {"success": False}
508
+ },
509
+ "rate_limiting": {
510
+ "rate_limit_checks": [{"request": 1, "allowed": True}],
511
+ "rate_limit_exceeded": False
512
+ },
513
+ "security_validation": {
514
+ "request_validation": {"success": True},
515
+ "configuration_validation": {"success": True}
516
+ },
517
+ "security_monitoring": {
518
+ "security_status": {"status": "healthy"},
519
+ "security_metrics": {"requests": 100},
520
+ "security_audit": {"authentication": []}
521
+ }
522
+ }
523
+
524
+ # Mock cleanup
525
+ mock_example.work_dir = "/tmp/test"
526
+
527
+ # Import and run main function
528
+ from mcp_security_framework.examples.comprehensive_example import main
529
+
530
+ # Mock print to avoid output during tests
531
+ with patch('builtins.print'):
532
+ main()
533
+
534
+ # Verify example was created and demo was run
535
+ mock_example_class.assert_called_once()
536
+ mock_example.run_comprehensive_demo.assert_called_once()
537
+
538
+
539
+ def test_main_function_exception():
540
+ """Test main function with exception."""
541
+ with patch('mcp_security_framework.examples.comprehensive_example.ComprehensiveSecurityExample') as mock_example_class:
542
+ mock_example = Mock()
543
+ mock_example_class.return_value = mock_example
544
+
545
+ # Mock the run_comprehensive_demo method to raise exception
546
+ mock_example.run_comprehensive_demo.side_effect = Exception("Test exception")
547
+
548
+ # Import and run main function
549
+ from mcp_security_framework.examples.comprehensive_example import main
550
+
551
+ # Mock print to avoid output during tests
552
+ with patch('builtins.print'):
553
+ main()
554
+
555
+ # Verify example was created and demo was attempted
556
+ mock_example_class.assert_called_once()
557
+ mock_example.run_comprehensive_demo.assert_called_once()
558
+
559
+
560
+