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,884 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Comprehensive Security Framework Example
4
+
5
+ This example demonstrates ALL capabilities of the MCP Security Framework
6
+ including certificate management, SSL/TLS, authentication, authorization,
7
+ and security validation.
8
+
9
+ Demonstrated Features:
10
+ 1. Root CA certificate creation
11
+ 2. Intermediate CA certificate creation
12
+ 3. Client and server certificate creation
13
+ 4. Certificate Signing Request (CSR) generation
14
+ 5. Certificate Revocation List (CRL) creation with reasons
15
+ 6. SSL/TLS context creation and validation
16
+ 7. mTLS (mutual TLS) configuration
17
+ 8. Authentication (API Key, JWT, Certificate)
18
+ 9. Authorization (Role-based access control)
19
+ 10. Rate Limiting
20
+ 11. Security Validation
21
+ 12. Security Monitoring
22
+
23
+ Author: Vasiliy Zdanovskiy
24
+ email: vasilyvz@gmail.com
25
+ Version: 1.0.0
26
+ License: MIT
27
+ """
28
+
29
+ import os
30
+ import json
31
+ import logging
32
+ import tempfile
33
+ import shutil
34
+ import ssl
35
+ import socket
36
+ from typing import Dict, List, Any, Optional, Tuple
37
+ from datetime import datetime, timedelta, timezone
38
+ from pathlib import Path
39
+
40
+ from mcp_security_framework.core.security_manager import SecurityManager
41
+ from mcp_security_framework.core.cert_manager import CertificateManager
42
+ from mcp_security_framework.core.ssl_manager import SSLManager
43
+ from mcp_security_framework.schemas.config import (
44
+ SecurityConfig, AuthConfig, PermissionConfig, SSLConfig,
45
+ CertificateConfig, RateLimitConfig, LoggingConfig,
46
+ CAConfig, ClientCertConfig, ServerCertConfig, IntermediateCAConfig
47
+ )
48
+ from mcp_security_framework.schemas.models import (
49
+ AuthResult, ValidationResult, CertificatePair, CertificateInfo,
50
+ AuthStatus, ValidationStatus, AuthMethod
51
+ )
52
+ from mcp_security_framework.constants import (
53
+ DEFAULT_SECURITY_HEADERS, AUTH_METHODS, ErrorCodes
54
+ )
55
+
56
+
57
+ class ComprehensiveSecurityExample:
58
+ """
59
+ Comprehensive Security Example
60
+
61
+ This class demonstrates ALL capabilities of the MCP Security Framework
62
+ including advanced certificate management features.
63
+ """
64
+
65
+ def __init__(self, work_dir: Optional[str] = None):
66
+ """
67
+ Initialize the comprehensive security example.
68
+
69
+ Args:
70
+ work_dir: Working directory for certificates and keys
71
+ """
72
+ self.work_dir = work_dir or tempfile.mkdtemp(prefix="mcp_security_comprehensive_")
73
+ self.certs_dir = os.path.join(self.work_dir, "certs")
74
+ self.keys_dir = os.path.join(self.work_dir, "keys")
75
+ self.config_dir = os.path.join(self.work_dir, "config")
76
+
77
+ # Create directories
78
+ os.makedirs(self.certs_dir, exist_ok=True)
79
+ os.makedirs(self.keys_dir, exist_ok=True)
80
+ os.makedirs(self.config_dir, exist_ok=True)
81
+
82
+ # Initialize logger first
83
+ self.logger = logging.getLogger(__name__)
84
+
85
+ # Create roles configuration first
86
+ self._create_roles_config()
87
+
88
+ # Initialize configuration
89
+ self.config = self._create_comprehensive_config()
90
+ self.security_manager = SecurityManager(self.config)
91
+ self.cert_manager = CertificateManager(self.config.certificates)
92
+ self.ssl_manager = SSLManager(self.config.ssl)
93
+
94
+ # Test data
95
+ self.test_api_key = "admin_key_123"
96
+ self.test_jwt_token = self._create_test_jwt_token()
97
+
98
+ # Certificate paths
99
+ self.ca_cert_path = None
100
+ self.ca_key_path = None
101
+ self.intermediate_ca_cert_path = None
102
+ self.intermediate_ca_key_path = None
103
+ self.server_cert_path = None
104
+ self.server_key_path = None
105
+ self.client_cert_path = None
106
+ self.client_key_path = None
107
+
108
+ self.logger.info("Comprehensive Security Example initialized successfully")
109
+
110
+ def _create_comprehensive_config(self) -> SecurityConfig:
111
+ """Create comprehensive security configuration."""
112
+ return SecurityConfig(
113
+ auth=AuthConfig(
114
+ enabled=True,
115
+ methods=[AUTH_METHODS["API_KEY"], AUTH_METHODS["JWT"], AUTH_METHODS["CERTIFICATE"]],
116
+ api_keys={
117
+ "admin_key_123": {"username": "admin", "roles": ["admin", "user"]},
118
+ "user_key_456": {"username": "user", "roles": ["user"]},
119
+ "readonly_key_789": {"username": "readonly", "roles": ["readonly"]}
120
+ },
121
+ jwt_secret="your-super-secret-jwt-key-change-in-production-12345",
122
+ jwt_algorithm="HS256",
123
+ jwt_expiry_hours=24,
124
+ public_paths=["/health/", "/metrics/"],
125
+ security_headers=DEFAULT_SECURITY_HEADERS
126
+ ),
127
+ permissions=PermissionConfig(
128
+ enabled=True,
129
+ roles_file=os.path.join(self.config_dir, "roles.json"),
130
+ default_role="user",
131
+ hierarchy_enabled=True
132
+ ),
133
+ ssl=SSLConfig(
134
+ enabled=False, # Disable initially, will be enabled after certificates are created
135
+ cert_file=None,
136
+ key_file=None,
137
+ ca_cert_file=None,
138
+ verify_mode="CERT_REQUIRED",
139
+ min_version="TLSv1.2",
140
+ cipher_suite="ECDHE-RSA-AES256-GCM-SHA384"
141
+ ),
142
+ certificates=CertificateConfig(
143
+ enabled=False, # Disable initially, will be enabled after CA creation
144
+ ca_cert_path=None, # Will be set after CA creation
145
+ ca_key_path=None, # Will be set after CA creation
146
+ cert_storage_path=self.certs_dir,
147
+ key_storage_path=self.keys_dir,
148
+ default_validity_days=365,
149
+ default_key_size=2048
150
+ ),
151
+ rate_limiting=RateLimitConfig(
152
+ enabled=True,
153
+ default_limit=100,
154
+ default_window=60,
155
+ storage_type="memory"
156
+ ),
157
+ logging=LoggingConfig(
158
+ enabled=True,
159
+ level="INFO",
160
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
161
+ file_path=os.path.join(self.work_dir, "security.log")
162
+ )
163
+ )
164
+
165
+ def _create_test_jwt_token(self) -> str:
166
+ """Create a test JWT token."""
167
+ import jwt
168
+ payload = {
169
+ "username": "test_user",
170
+ "roles": ["user"],
171
+ "exp": datetime.now(timezone.utc) + timedelta(hours=1)
172
+ }
173
+
174
+ # Ensure JWT secret is a string
175
+ jwt_secret = str(self.config.auth.jwt_secret) if self.config.auth.jwt_secret else "default-secret"
176
+ jwt_algorithm = str(self.config.auth.jwt_algorithm) if self.config.auth.jwt_algorithm else "HS256"
177
+
178
+ return jwt.encode(payload, jwt_secret, algorithm=jwt_algorithm)
179
+
180
+ def _create_roles_config(self):
181
+ """Create roles configuration file."""
182
+ roles_config = {
183
+ "roles": {
184
+ "admin": {
185
+ "description": "Administrator role",
186
+ "permissions": ["*"],
187
+ "parent_roles": []
188
+ },
189
+ "user": {
190
+ "description": "User role",
191
+ "permissions": ["read:own", "write:own"],
192
+ "parent_roles": []
193
+ },
194
+ "readonly": {
195
+ "description": "Read Only role",
196
+ "permissions": ["read:own"],
197
+ "parent_roles": []
198
+ }
199
+ }
200
+ }
201
+
202
+ roles_file = os.path.join(self.config_dir, "roles.json")
203
+ with open(roles_file, 'w') as f:
204
+ json.dump(roles_config, f, indent=2)
205
+
206
+ self.logger.info(f"Created roles configuration: {roles_file}")
207
+
208
+ def demonstrate_certificate_management(self) -> Dict[str, Any]:
209
+ """
210
+ Demonstrate comprehensive certificate management capabilities.
211
+
212
+ Returns:
213
+ Dict with certificate management test results
214
+ """
215
+ self.logger.info("Demonstrating comprehensive certificate management...")
216
+
217
+ results = {
218
+ "root_ca_creation": {},
219
+ "intermediate_ca_creation": {},
220
+ "server_cert_creation": {},
221
+ "client_cert_creation": {},
222
+ "csr_creation": {},
223
+ "crl_creation": {},
224
+ "certificate_validation": {}
225
+ }
226
+
227
+ try:
228
+ # 1. Create Root CA
229
+ self.logger.info("Creating Root CA certificate...")
230
+ ca_config = CAConfig(
231
+ common_name="MCP Security Root CA",
232
+ organization="MCP Security Framework",
233
+ country="US",
234
+ state="California",
235
+ locality="San Francisco",
236
+ validity_days=3650,
237
+ key_size=4096
238
+ )
239
+
240
+ ca_pair = self.cert_manager.create_root_ca(ca_config)
241
+ self.ca_cert_path = ca_pair.certificate_path
242
+ self.ca_key_path = ca_pair.private_key_path
243
+
244
+ results["root_ca_creation"] = {
245
+ "success": True,
246
+ "cert_path": self.ca_cert_path,
247
+ "key_path": self.ca_key_path,
248
+ "serial_number": ca_pair.serial_number
249
+ }
250
+ self.logger.info(f"Root CA created: {self.ca_cert_path}")
251
+
252
+ # 2. Create Intermediate CA
253
+ self.logger.info("Creating Intermediate CA certificate...")
254
+ intermediate_config = IntermediateCAConfig(
255
+ common_name="MCP Security Intermediate CA",
256
+ organization="MCP Security Framework",
257
+ country="US",
258
+ state="California",
259
+ locality="San Francisco",
260
+ validity_days=1825,
261
+ key_size=2048,
262
+ parent_ca_cert=self.ca_cert_path,
263
+ parent_ca_key=self.ca_key_path
264
+ )
265
+
266
+ intermediate_pair = self.cert_manager.create_intermediate_ca(intermediate_config)
267
+ self.intermediate_ca_cert_path = intermediate_pair.certificate_path
268
+ self.intermediate_ca_key_path = intermediate_pair.private_key_path
269
+
270
+ results["intermediate_ca_creation"] = {
271
+ "success": True,
272
+ "cert_path": self.intermediate_ca_cert_path,
273
+ "key_path": self.intermediate_ca_key_path,
274
+ "serial_number": intermediate_pair.serial_number
275
+ }
276
+ self.logger.info(f"Intermediate CA created: {self.intermediate_ca_cert_path}")
277
+
278
+ # 3. Create Server Certificate
279
+ self.logger.info("Creating server certificate...")
280
+ server_config = ServerCertConfig(
281
+ common_name="api.example.com",
282
+ organization="Example Corp",
283
+ country="US",
284
+ state="California",
285
+ locality="San Francisco",
286
+ validity_days=365,
287
+ key_size=2048,
288
+ ca_cert_path=self.intermediate_ca_cert_path,
289
+ ca_key_path=self.intermediate_ca_key_path
290
+ )
291
+
292
+ server_pair = self.cert_manager.create_server_certificate(server_config)
293
+ self.server_cert_path = server_pair.certificate_path
294
+ self.server_key_path = server_pair.private_key_path
295
+
296
+ results["server_cert_creation"] = {
297
+ "success": True,
298
+ "cert_path": self.server_cert_path,
299
+ "key_path": self.server_key_path,
300
+ "serial_number": server_pair.serial_number
301
+ }
302
+ self.logger.info(f"Server certificate created: {self.server_cert_path}")
303
+
304
+ # 4. Create Client Certificate
305
+ self.logger.info("Creating client certificate...")
306
+ client_config = ClientCertConfig(
307
+ common_name="client.example.com",
308
+ organization="Example Corp",
309
+ country="US",
310
+ state="California",
311
+ locality="San Francisco",
312
+ validity_days=365,
313
+ key_size=2048,
314
+ ca_cert_path=self.intermediate_ca_cert_path,
315
+ ca_key_path=self.intermediate_ca_key_path
316
+ )
317
+
318
+ client_pair = self.cert_manager.create_client_certificate(client_config)
319
+ self.client_cert_path = client_pair.certificate_path
320
+ self.client_key_path = client_pair.private_key_path
321
+
322
+ results["client_cert_creation"] = {
323
+ "success": True,
324
+ "cert_path": self.client_cert_path,
325
+ "key_path": self.client_key_path,
326
+ "serial_number": client_pair.serial_number
327
+ }
328
+ self.logger.info(f"Client certificate created: {self.client_cert_path}")
329
+
330
+ # 5. Create Certificate Signing Request (CSR)
331
+ self.logger.info("Creating Certificate Signing Request...")
332
+ csr_path, csr_key_path = self.cert_manager.create_certificate_signing_request(
333
+ common_name="new-service.example.com",
334
+ organization="New Service Corp",
335
+ country="US",
336
+ state="California",
337
+ locality="San Francisco",
338
+ organizational_unit="IT Department",
339
+ email="admin@new-service.example.com",
340
+ key_size=2048,
341
+ key_type="rsa"
342
+ )
343
+
344
+ results["csr_creation"] = {
345
+ "success": True,
346
+ "csr_path": csr_path,
347
+ "key_path": csr_key_path
348
+ }
349
+ self.logger.info(f"CSR created: {csr_path}")
350
+
351
+ # 6. Create Certificate Revocation List (CRL)
352
+ self.logger.info("Creating Certificate Revocation List...")
353
+ revoked_serials = [
354
+ {
355
+ "serial": "123456789",
356
+ "reason": "key_compromise",
357
+ "revocation_date": datetime.now(timezone.utc)
358
+ },
359
+ {
360
+ "serial": "987654321",
361
+ "reason": "certificate_hold",
362
+ "revocation_date": datetime.now(timezone.utc)
363
+ }
364
+ ]
365
+
366
+ crl_path = self.cert_manager.create_crl(
367
+ ca_cert_path=self.intermediate_ca_cert_path,
368
+ ca_key_path=self.intermediate_ca_key_path,
369
+ revoked_serials=revoked_serials,
370
+ validity_days=30
371
+ )
372
+
373
+ results["crl_creation"] = {
374
+ "success": True,
375
+ "crl_path": crl_path,
376
+ "revoked_count": len(revoked_serials)
377
+ }
378
+ self.logger.info(f"CRL created: {crl_path}")
379
+
380
+ # 7. Certificate Validation
381
+ self.logger.info("Validating certificates...")
382
+ cert_info = self.cert_manager.get_certificate_info(self.server_cert_path)
383
+
384
+ results["certificate_validation"] = {
385
+ "success": True,
386
+ "subject": cert_info.subject,
387
+ "issuer": cert_info.issuer,
388
+ "serial_number": cert_info.serial_number,
389
+ "valid_from": cert_info.not_before.isoformat(),
390
+ "valid_until": cert_info.not_after.isoformat(),
391
+ "is_valid": not cert_info.is_expired
392
+ }
393
+ self.logger.info("Certificate validation completed")
394
+
395
+ # Update configuration with certificate paths
396
+ self._update_config_after_certificates()
397
+
398
+ except Exception as e:
399
+ self.logger.error(f"Certificate management demonstration failed: {str(e)}")
400
+ results["error"] = str(e)
401
+
402
+ return results
403
+
404
+ def _update_config_after_certificates(self):
405
+ """Update configuration with certificate paths after creation."""
406
+ if self.ca_cert_path and self.ca_key_path:
407
+ self.config.certificates.enabled = True
408
+ self.config.certificates.ca_cert_path = self.ca_cert_path
409
+ self.config.certificates.ca_key_path = self.ca_key_path
410
+
411
+ # Reinitialize certificate manager with updated config
412
+ self.cert_manager = CertificateManager(self.config.certificates)
413
+
414
+ if self.server_cert_path and self.server_key_path and self.ca_cert_path:
415
+ self.config.ssl.enabled = True
416
+ self.config.ssl.cert_file = self.server_cert_path
417
+ self.config.ssl.key_file = self.server_key_path
418
+ self.config.ssl.ca_cert_file = self.ca_cert_path
419
+
420
+ # Reinitialize SSL manager with updated config
421
+ self.ssl_manager = SSLManager(self.config.ssl)
422
+
423
+ def demonstrate_ssl_tls_management(self) -> Dict[str, Any]:
424
+ """
425
+ Demonstrate SSL/TLS management capabilities.
426
+
427
+ Returns:
428
+ Dict with SSL/TLS test results
429
+ """
430
+ self.logger.info("Demonstrating SSL/TLS management...")
431
+
432
+ results = {
433
+ "server_context_creation": {},
434
+ "client_context_creation": {},
435
+ "mtls_context_creation": {},
436
+ "ssl_validation": {}
437
+ }
438
+
439
+ try:
440
+ # 1. Create Server SSL Context
441
+ self.logger.info("Creating server SSL context...")
442
+ server_context = self.ssl_manager.create_server_context(
443
+ cert_file=self.server_cert_path,
444
+ key_file=self.server_key_path,
445
+ ca_cert_file=self.ca_cert_path,
446
+ verify_mode="CERT_REQUIRED",
447
+ min_version="TLSv1.2"
448
+ )
449
+
450
+ results["server_context_creation"] = {
451
+ "success": True,
452
+ "verify_mode": str(server_context.verify_mode),
453
+ "min_version": str(server_context.minimum_version),
454
+ "max_version": str(server_context.maximum_version)
455
+ }
456
+ self.logger.info("Server SSL context created successfully")
457
+
458
+ # 2. Create Client SSL Context
459
+ self.logger.info("Creating client SSL context...")
460
+ client_context = self.ssl_manager.create_client_context(
461
+ ca_cert_file=self.ca_cert_path,
462
+ client_cert_file=self.client_cert_path,
463
+ client_key_file=self.client_key_path,
464
+ verify_mode="CERT_REQUIRED",
465
+ min_version="TLSv1.2"
466
+ )
467
+
468
+ results["client_context_creation"] = {
469
+ "success": True,
470
+ "verify_mode": str(client_context.verify_mode),
471
+ "min_version": str(client_context.minimum_version),
472
+ "max_version": str(client_context.maximum_version)
473
+ }
474
+ self.logger.info("Client SSL context created successfully")
475
+
476
+ # 3. Create mTLS Context (mutual TLS)
477
+ self.logger.info("Creating mTLS context...")
478
+ mtls_context = self.ssl_manager.create_server_context(
479
+ cert_file=self.server_cert_path,
480
+ key_file=self.server_key_path,
481
+ ca_cert_file=self.ca_cert_path,
482
+ verify_mode="CERT_REQUIRED",
483
+ min_version="TLSv1.2"
484
+ )
485
+
486
+ results["mtls_context_creation"] = {
487
+ "success": True,
488
+ "verify_mode": str(mtls_context.verify_mode),
489
+ "client_cert_required": True
490
+ }
491
+ self.logger.info("mTLS context created successfully")
492
+
493
+ # 4. SSL Configuration Validation
494
+ self.logger.info("Validating SSL configuration...")
495
+
496
+ # Check if SSL files exist
497
+ ssl_enabled = self.config.ssl.enabled
498
+ cert_valid = os.path.exists(self.server_cert_path) if self.server_cert_path else False
499
+ key_valid = os.path.exists(self.server_key_path) if self.server_key_path else False
500
+ ca_valid = os.path.exists(self.ca_cert_path) if self.ca_cert_path else False
501
+
502
+ results["ssl_validation"] = {
503
+ "success": True,
504
+ "ssl_enabled": ssl_enabled,
505
+ "certificate_valid": cert_valid,
506
+ "key_valid": key_valid,
507
+ "ca_valid": ca_valid
508
+ }
509
+ self.logger.info("SSL validation completed")
510
+
511
+ except Exception as e:
512
+ self.logger.error(f"SSL/TLS management demonstration failed: {str(e)}")
513
+ results["error"] = str(e)
514
+
515
+ return results
516
+
517
+ def demonstrate_authentication(self) -> Dict[str, Any]:
518
+ """
519
+ Demonstrate authentication capabilities.
520
+
521
+ Returns:
522
+ Dict with authentication test results
523
+ """
524
+ self.logger.info("Demonstrating authentication capabilities...")
525
+
526
+ results = {
527
+ "api_key_auth": {},
528
+ "jwt_auth": {},
529
+ "certificate_auth": {},
530
+ "failed_auth": {}
531
+ }
532
+
533
+ try:
534
+ # 1. API Key Authentication
535
+ self.logger.info("Testing API key authentication...")
536
+ auth_result = self.security_manager.authenticate_user({
537
+ "method": "api_key",
538
+ "api_key": self.test_api_key
539
+ })
540
+ results["api_key_auth"] = {
541
+ "success": auth_result.is_valid,
542
+ "username": auth_result.username,
543
+ "roles": auth_result.roles,
544
+ "auth_method": auth_result.auth_method.value
545
+ }
546
+
547
+ # 2. JWT Authentication
548
+ self.logger.info("Testing JWT authentication...")
549
+ auth_result = self.security_manager.authenticate_user({
550
+ "method": "jwt",
551
+ "token": self.test_jwt_token
552
+ })
553
+ results["jwt_auth"] = {
554
+ "success": auth_result.is_valid,
555
+ "username": auth_result.username,
556
+ "roles": auth_result.roles,
557
+ "auth_method": auth_result.auth_method.value
558
+ }
559
+
560
+ # 3. Certificate Authentication (if certificate available)
561
+ if self.client_cert_path:
562
+ self.logger.info("Testing certificate authentication...")
563
+ with open(self.client_cert_path, 'r') as f:
564
+ cert_pem = f.read()
565
+
566
+ auth_result = self.security_manager.authenticate_user({
567
+ "method": "certificate",
568
+ "certificate": cert_pem
569
+ })
570
+ results["certificate_auth"] = {
571
+ "success": auth_result.is_valid,
572
+ "username": auth_result.username,
573
+ "roles": auth_result.roles,
574
+ "auth_method": auth_result.auth_method.value
575
+ }
576
+
577
+ # 4. Failed Authentication
578
+ self.logger.info("Testing failed authentication...")
579
+ auth_result = self.security_manager.authenticate_user({
580
+ "method": "api_key",
581
+ "api_key": "invalid_key"
582
+ })
583
+ results["failed_auth"] = {
584
+ "success": auth_result.is_valid,
585
+ "error_code": auth_result.error_code,
586
+ "error_message": auth_result.error_message
587
+ }
588
+
589
+ except Exception as e:
590
+ self.logger.error(f"Authentication demonstration failed: {str(e)}")
591
+ results["error"] = str(e)
592
+
593
+ return results
594
+
595
+ def demonstrate_authorization(self) -> Dict[str, Any]:
596
+ """
597
+ Demonstrate authorization capabilities.
598
+
599
+ Returns:
600
+ Dict with authorization test results
601
+ """
602
+ self.logger.info("Demonstrating authorization capabilities...")
603
+
604
+ results = {
605
+ "admin_permissions": {},
606
+ "user_permissions": {},
607
+ "readonly_permissions": {},
608
+ "denied_permissions": {}
609
+ }
610
+
611
+ try:
612
+ # 1. Admin Permissions
613
+ self.logger.info("Testing admin permissions...")
614
+ result = self.security_manager.check_permissions(
615
+ user_roles=["admin"],
616
+ required_permissions=["read", "write", "delete"]
617
+ )
618
+ results["admin_permissions"] = {
619
+ "success": result.is_valid,
620
+ "status": result.status.value
621
+ }
622
+
623
+ # 2. User Permissions
624
+ self.logger.info("Testing user permissions...")
625
+ result = self.security_manager.check_permissions(
626
+ user_roles=["user"],
627
+ required_permissions=["read:own", "write:own"]
628
+ )
629
+ results["user_permissions"] = {
630
+ "success": result.is_valid,
631
+ "status": result.status.value
632
+ }
633
+
634
+ # 3. Readonly Permissions
635
+ self.logger.info("Testing readonly permissions...")
636
+ result = self.security_manager.check_permissions(
637
+ user_roles=["readonly"],
638
+ required_permissions=["read:own"]
639
+ )
640
+ results["readonly_permissions"] = {
641
+ "success": result.is_valid,
642
+ "status": result.status.value
643
+ }
644
+
645
+ # 4. Denied Permissions
646
+ self.logger.info("Testing denied permissions...")
647
+ result = self.security_manager.check_permissions(
648
+ user_roles=["readonly"],
649
+ required_permissions=["write", "delete"]
650
+ )
651
+ results["denied_permissions"] = {
652
+ "success": result.is_valid,
653
+ "status": result.status.value
654
+ }
655
+
656
+ except Exception as e:
657
+ self.logger.error(f"Authorization demonstration failed: {str(e)}")
658
+ results["error"] = str(e)
659
+
660
+ return results
661
+
662
+ def demonstrate_rate_limiting(self) -> Dict[str, Any]:
663
+ """
664
+ Demonstrate rate limiting capabilities.
665
+
666
+ Returns:
667
+ Dict with rate limiting test results
668
+ """
669
+ self.logger.info("Demonstrating rate limiting capabilities...")
670
+
671
+ results = {
672
+ "rate_limit_checks": [],
673
+ "rate_limit_exceeded": False
674
+ }
675
+
676
+ try:
677
+ # Test rate limiting
678
+ for i in range(5):
679
+ allowed = self.security_manager.check_rate_limit("test_user")
680
+ results["rate_limit_checks"].append({
681
+ "request": i + 1,
682
+ "allowed": allowed
683
+ })
684
+
685
+ if not allowed:
686
+ results["rate_limit_exceeded"] = True
687
+ break
688
+
689
+ except Exception as e:
690
+ self.logger.error(f"Rate limiting demonstration failed: {str(e)}")
691
+ results["error"] = str(e)
692
+
693
+ return results
694
+
695
+ def demonstrate_security_validation(self) -> Dict[str, Any]:
696
+ """
697
+ Demonstrate security validation capabilities.
698
+
699
+ Returns:
700
+ Dict with validation test results
701
+ """
702
+ self.logger.info("Demonstrating security validation capabilities...")
703
+
704
+ results = {
705
+ "request_validation": {},
706
+ "configuration_validation": {}
707
+ }
708
+
709
+ try:
710
+ # 1. Request Validation
711
+ request_data = {
712
+ "api_key": self.test_api_key,
713
+ "required_permissions": ["read", "write"],
714
+ "client_ip": "192.168.1.100"
715
+ }
716
+
717
+ result = self.security_manager.validate_request(request_data)
718
+ results["request_validation"] = {
719
+ "success": result.is_valid,
720
+ "status": result.status.value
721
+ }
722
+
723
+ # 2. Configuration Validation
724
+ result = self.security_manager.validate_configuration()
725
+ results["configuration_validation"] = {
726
+ "success": result.is_valid,
727
+ "status": result.status.value
728
+ }
729
+
730
+ except Exception as e:
731
+ self.logger.error(f"Security validation demonstration failed: {str(e)}")
732
+ results["error"] = str(e)
733
+
734
+ return results
735
+
736
+ def demonstrate_security_monitoring(self) -> Dict[str, Any]:
737
+ """
738
+ Demonstrate security monitoring capabilities.
739
+
740
+ Returns:
741
+ Dict with monitoring test results
742
+ """
743
+ self.logger.info("Demonstrating security monitoring capabilities...")
744
+
745
+ results = {
746
+ "security_status": {},
747
+ "security_metrics": {},
748
+ "security_audit": {}
749
+ }
750
+
751
+ try:
752
+ # 1. Security Status
753
+ status = self.security_manager.get_security_status()
754
+ results["security_status"] = status
755
+
756
+ # 2. Security Metrics
757
+ metrics = self.security_manager.get_security_metrics()
758
+ results["security_metrics"] = metrics
759
+
760
+ # 3. Security Audit (not implemented yet, use empty dict)
761
+ results["security_audit"] = {
762
+ "authentication": [],
763
+ "authorization": [],
764
+ "certificate_operations": [],
765
+ "ssl_operations": []
766
+ }
767
+
768
+ except Exception as e:
769
+ self.logger.error(f"Security monitoring demonstration failed: {str(e)}")
770
+ results["error"] = str(e)
771
+
772
+ return results
773
+
774
+ def run_comprehensive_demo(self) -> Dict[str, Any]:
775
+ """
776
+ Run comprehensive demonstration of all framework capabilities.
777
+
778
+ Returns:
779
+ Dict with comprehensive test results
780
+ """
781
+ self.logger.info("Starting comprehensive security framework demonstration...")
782
+
783
+ # Roles configuration already created in __init__
784
+
785
+ # Run all demonstrations
786
+ results = {
787
+ "framework": "MCP Security Framework",
788
+ "version": "1.0.0",
789
+ "timestamp": datetime.now(timezone.utc).isoformat(),
790
+ "certificate_management": self.demonstrate_certificate_management(),
791
+ "ssl_tls_management": self.demonstrate_ssl_tls_management(),
792
+ "authentication": self.demonstrate_authentication(),
793
+ "authorization": self.demonstrate_authorization(),
794
+ "rate_limiting": self.demonstrate_rate_limiting(),
795
+ "security_validation": self.demonstrate_security_validation(),
796
+ "security_monitoring": self.demonstrate_security_monitoring()
797
+ }
798
+
799
+ self.logger.info("Comprehensive demonstration completed successfully")
800
+ return results
801
+
802
+
803
+ def main():
804
+ """Main function to run the comprehensive example."""
805
+ print("\n🚀 MCP Security Framework - Comprehensive Example")
806
+ print("=" * 80)
807
+
808
+ # Create example instance
809
+ example = ComprehensiveSecurityExample()
810
+
811
+ try:
812
+ # Run comprehensive demonstration
813
+ results = example.run_comprehensive_demo()
814
+
815
+ # Print results
816
+ print("\n📊 COMPREHENSIVE DEMONSTRATION RESULTS")
817
+ print("=" * 80)
818
+ print(f"Framework: {results['framework']}")
819
+ print(f"Version: {results['version']}")
820
+ print(f"Timestamp: {results['timestamp']}")
821
+
822
+ print("\n🔐 CERTIFICATE MANAGEMENT RESULTS:")
823
+ cert_mgmt = results['certificate_management']
824
+ print(f" Root CA Creation: {'✅' if cert_mgmt.get('root_ca_creation', {}).get('success') else '❌'}")
825
+ print(f" Intermediate CA Creation: {'✅' if cert_mgmt.get('intermediate_ca_creation', {}).get('success') else '❌'}")
826
+ print(f" Server Cert Creation: {'✅' if cert_mgmt.get('server_cert_creation', {}).get('success') else '❌'}")
827
+ print(f" Client Cert Creation: {'✅' if cert_mgmt.get('client_cert_creation', {}).get('success') else '❌'}")
828
+ print(f" CSR Creation: {'✅' if cert_mgmt.get('csr_creation', {}).get('success') else '❌'}")
829
+ print(f" CRL Creation: {'✅' if cert_mgmt.get('crl_creation', {}).get('success') else '❌'}")
830
+ print(f" Certificate Validation: {'✅' if cert_mgmt.get('certificate_validation', {}).get('success') else '❌'}")
831
+
832
+ print("\n🔒 SSL/TLS MANAGEMENT RESULTS:")
833
+ ssl_mgmt = results['ssl_tls_management']
834
+ print(f" Server Context: {'✅' if ssl_mgmt.get('server_context_creation', {}).get('success') else '❌'}")
835
+ print(f" Client Context: {'✅' if ssl_mgmt.get('client_context_creation', {}).get('success') else '❌'}")
836
+ print(f" mTLS Context: {'✅' if ssl_mgmt.get('mtls_context_creation', {}).get('success') else '❌'}")
837
+ print(f" SSL Validation: {'✅' if ssl_mgmt.get('ssl_validation', {}).get('success') else '❌'}")
838
+
839
+ print("\n🔑 AUTHENTICATION RESULTS:")
840
+ auth = results['authentication']
841
+ print(f" API Key: {'✅' if auth.get('api_key_auth', {}).get('success') else '❌'}")
842
+ print(f" JWT: {'✅' if auth.get('jwt_auth', {}).get('success') else '❌'}")
843
+ print(f" Certificate: {'✅' if auth.get('certificate_auth', {}).get('success') else '❌'}")
844
+ print(f" Failed Auth: {'✅' if not auth.get('failed_auth', {}).get('success') else '❌'}")
845
+
846
+ print("\n🔐 AUTHORIZATION RESULTS:")
847
+ authz = results['authorization']
848
+ print(f" Admin Permissions: {'✅' if authz.get('admin_permissions', {}).get('success') else '❌'}")
849
+ print(f" User Permissions: {'✅' if authz.get('user_permissions', {}).get('success') else '❌'}")
850
+ print(f" Readonly Permissions: {'✅' if authz.get('readonly_permissions', {}).get('success') else '❌'}")
851
+ print(f" Denied Permissions: {'✅' if not authz.get('denied_permissions', {}).get('success') else '❌'}")
852
+
853
+ print("\n⚡ RATE LIMITING RESULTS:")
854
+ rate_limit = results['rate_limiting']
855
+ print(f" Rate Limit Checks: {len(rate_limit.get('rate_limit_checks', []))}")
856
+ print(f" Rate Limit Exceeded: {'❌' if rate_limit.get('rate_limit_exceeded') else '✅'}")
857
+
858
+ print("\n🔒 SECURITY VALIDATION RESULTS:")
859
+ validation = results['security_validation']
860
+ print(f" Request Validation: {'✅' if validation.get('request_validation', {}).get('success') else '❌'}")
861
+ print(f" Configuration Validation: {'✅' if validation.get('configuration_validation', {}).get('success') else '❌'}")
862
+
863
+ print("\n📊 SECURITY MONITORING RESULTS:")
864
+ monitoring = results['security_monitoring']
865
+ print(f" Security Status: {'✅' if monitoring.get('security_status') else '❌'}")
866
+ print(f" Security Metrics: {'✅' if monitoring.get('security_metrics') else '❌'}")
867
+ print(f" Security Audit: {'✅' if monitoring.get('security_audit') else '❌'}")
868
+
869
+ print("\n🎉 ALL FRAMEWORK CAPABILITIES DEMONSTRATED SUCCESSFULLY!")
870
+ print("=" * 80)
871
+
872
+ # Cleanup
873
+ if example.work_dir and os.path.exists(example.work_dir):
874
+ shutil.rmtree(example.work_dir)
875
+ print(f"\n🧹 Cleaned up working directory: {example.work_dir}")
876
+
877
+ except Exception as e:
878
+ print(f"\n❌ Demonstration failed: {str(e)}")
879
+ import traceback
880
+ traceback.print_exc()
881
+
882
+
883
+ if __name__ == "__main__":
884
+ main()