mcp-security-framework 0.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 (76) hide show
  1. mcp_security_framework/__init__.py +96 -0
  2. mcp_security_framework/cli/__init__.py +18 -0
  3. mcp_security_framework/cli/cert_cli.py +511 -0
  4. mcp_security_framework/cli/security_cli.py +791 -0
  5. mcp_security_framework/constants.py +209 -0
  6. mcp_security_framework/core/__init__.py +61 -0
  7. mcp_security_framework/core/auth_manager.py +1011 -0
  8. mcp_security_framework/core/cert_manager.py +1663 -0
  9. mcp_security_framework/core/permission_manager.py +735 -0
  10. mcp_security_framework/core/rate_limiter.py +602 -0
  11. mcp_security_framework/core/security_manager.py +943 -0
  12. mcp_security_framework/core/ssl_manager.py +735 -0
  13. mcp_security_framework/examples/__init__.py +75 -0
  14. mcp_security_framework/examples/django_example.py +615 -0
  15. mcp_security_framework/examples/fastapi_example.py +472 -0
  16. mcp_security_framework/examples/flask_example.py +506 -0
  17. mcp_security_framework/examples/gateway_example.py +803 -0
  18. mcp_security_framework/examples/microservice_example.py +690 -0
  19. mcp_security_framework/examples/standalone_example.py +576 -0
  20. mcp_security_framework/middleware/__init__.py +250 -0
  21. mcp_security_framework/middleware/auth_middleware.py +292 -0
  22. mcp_security_framework/middleware/fastapi_auth_middleware.py +447 -0
  23. mcp_security_framework/middleware/fastapi_middleware.py +757 -0
  24. mcp_security_framework/middleware/flask_auth_middleware.py +465 -0
  25. mcp_security_framework/middleware/flask_middleware.py +591 -0
  26. mcp_security_framework/middleware/mtls_middleware.py +439 -0
  27. mcp_security_framework/middleware/rate_limit_middleware.py +403 -0
  28. mcp_security_framework/middleware/security_middleware.py +507 -0
  29. mcp_security_framework/schemas/__init__.py +109 -0
  30. mcp_security_framework/schemas/config.py +694 -0
  31. mcp_security_framework/schemas/models.py +709 -0
  32. mcp_security_framework/schemas/responses.py +686 -0
  33. mcp_security_framework/tests/__init__.py +0 -0
  34. mcp_security_framework/utils/__init__.py +121 -0
  35. mcp_security_framework/utils/cert_utils.py +525 -0
  36. mcp_security_framework/utils/crypto_utils.py +475 -0
  37. mcp_security_framework/utils/validation_utils.py +571 -0
  38. mcp_security_framework-0.1.0.dist-info/METADATA +411 -0
  39. mcp_security_framework-0.1.0.dist-info/RECORD +76 -0
  40. mcp_security_framework-0.1.0.dist-info/WHEEL +5 -0
  41. mcp_security_framework-0.1.0.dist-info/entry_points.txt +3 -0
  42. mcp_security_framework-0.1.0.dist-info/top_level.txt +2 -0
  43. tests/__init__.py +0 -0
  44. tests/test_cli/__init__.py +0 -0
  45. tests/test_cli/test_cert_cli.py +379 -0
  46. tests/test_cli/test_security_cli.py +657 -0
  47. tests/test_core/__init__.py +0 -0
  48. tests/test_core/test_auth_manager.py +582 -0
  49. tests/test_core/test_cert_manager.py +795 -0
  50. tests/test_core/test_permission_manager.py +395 -0
  51. tests/test_core/test_rate_limiter.py +626 -0
  52. tests/test_core/test_security_manager.py +841 -0
  53. tests/test_core/test_ssl_manager.py +532 -0
  54. tests/test_examples/__init__.py +8 -0
  55. tests/test_examples/test_fastapi_example.py +264 -0
  56. tests/test_examples/test_flask_example.py +238 -0
  57. tests/test_examples/test_standalone_example.py +292 -0
  58. tests/test_integration/__init__.py +0 -0
  59. tests/test_integration/test_auth_flow.py +502 -0
  60. tests/test_integration/test_certificate_flow.py +527 -0
  61. tests/test_integration/test_fastapi_integration.py +341 -0
  62. tests/test_integration/test_flask_integration.py +398 -0
  63. tests/test_integration/test_standalone_integration.py +493 -0
  64. tests/test_middleware/__init__.py +0 -0
  65. tests/test_middleware/test_fastapi_middleware.py +523 -0
  66. tests/test_middleware/test_flask_middleware.py +582 -0
  67. tests/test_middleware/test_security_middleware.py +493 -0
  68. tests/test_schemas/__init__.py +0 -0
  69. tests/test_schemas/test_config.py +811 -0
  70. tests/test_schemas/test_models.py +879 -0
  71. tests/test_schemas/test_responses.py +1054 -0
  72. tests/test_schemas/test_serialization.py +493 -0
  73. tests/test_utils/__init__.py +0 -0
  74. tests/test_utils/test_cert_utils.py +510 -0
  75. tests/test_utils/test_crypto_utils.py +603 -0
  76. tests/test_utils/test_validation_utils.py +477 -0
@@ -0,0 +1,694 @@
1
+ """
2
+ Configuration Models Module
3
+
4
+ This module provides comprehensive configuration models for all components
5
+ of the MCP Security Framework. It includes Pydantic models for validation
6
+ and type safety across the entire framework.
7
+
8
+ Key Features:
9
+ - Type-safe configuration validation
10
+ - Default values for common use cases
11
+ - Comprehensive field validation
12
+ - Nested configuration support
13
+ - Environment variable support
14
+
15
+ Classes:
16
+ SecurityConfig: Main security configuration
17
+ SSLConfig: SSL/TLS configuration
18
+ AuthConfig: Authentication configuration
19
+ CertificateConfig: Certificate management configuration
20
+ PermissionConfig: Role and permission configuration
21
+ RateLimitConfig: Rate limiting configuration
22
+ LoggingConfig: Logging configuration
23
+ CAConfig: Certificate Authority configuration
24
+ ClientCertConfig: Client certificate configuration
25
+ ServerCertConfig: Server certificate configuration
26
+ IntermediateCAConfig: Intermediate CA configuration
27
+
28
+ Author: MCP Security Team
29
+ Version: 1.0.0
30
+ License: MIT
31
+ """
32
+
33
+ from enum import Enum
34
+ from pathlib import Path
35
+ from typing import Any, Dict, List, Optional, Union
36
+
37
+ from pydantic import BaseModel, Field, field_validator, model_validator
38
+ from pydantic.types import SecretStr
39
+
40
+
41
+ class TLSVersion(str, Enum):
42
+ """TLS version enumeration."""
43
+
44
+ TLS_1_0 = "TLSv1.0"
45
+ TLS_1_1 = "TLSv1.1"
46
+ TLS_1_2 = "TLSv1.2"
47
+ TLS_1_3 = "TLSv1.3"
48
+
49
+
50
+ class AuthMethod(str, Enum):
51
+ """Authentication method enumeration."""
52
+
53
+ API_KEY = "api_key"
54
+ JWT = "jwt"
55
+ CERTIFICATE = "certificate"
56
+ BASIC = "basic"
57
+ OAUTH2 = "oauth2"
58
+
59
+
60
+ class LogLevel(str, Enum):
61
+ """Logging level enumeration."""
62
+
63
+ DEBUG = "DEBUG"
64
+ INFO = "INFO"
65
+ WARNING = "WARNING"
66
+ ERROR = "ERROR"
67
+ CRITICAL = "CRITICAL"
68
+
69
+
70
+ class SSLConfig(BaseModel):
71
+ """
72
+ SSL/TLS Configuration Model
73
+
74
+ This model defines SSL/TLS configuration settings for secure
75
+ communication including certificate paths, TLS versions, and
76
+ verification settings.
77
+
78
+ Attributes:
79
+ enabled: Whether SSL/TLS is enabled
80
+ cert_file: Path to server certificate file
81
+ key_file: Path to server private key file
82
+ ca_cert_file: Path to CA certificate file
83
+ verify_mode: SSL verification mode
84
+ min_tls_version: Minimum TLS version to support
85
+ max_tls_version: Maximum TLS version to support
86
+ cipher_suite: Custom cipher suite configuration
87
+ check_hostname: Whether to check hostname in certificates
88
+ check_expiry: Whether to check certificate expiry
89
+ expiry_warning_days: Days before expiry to warn
90
+ """
91
+
92
+ enabled: bool = Field(default=False, description="Whether SSL/TLS is enabled")
93
+ cert_file: Optional[str] = Field(
94
+ default=None, description="Path to server certificate file"
95
+ )
96
+ key_file: Optional[str] = Field(
97
+ default=None, description="Path to server private key file"
98
+ )
99
+ ca_cert_file: Optional[str] = Field(
100
+ default=None, description="Path to CA certificate file"
101
+ )
102
+ client_cert_file: Optional[str] = Field(
103
+ default=None, description="Path to client certificate file"
104
+ )
105
+ client_key_file: Optional[str] = Field(
106
+ default=None, description="Path to client private key file"
107
+ )
108
+ verify_mode: str = Field(
109
+ default="CERT_REQUIRED", description="SSL verification mode"
110
+ )
111
+ min_tls_version: TLSVersion = Field(
112
+ default=TLSVersion.TLS_1_2, description="Minimum TLS version"
113
+ )
114
+ max_tls_version: Optional[TLSVersion] = Field(
115
+ default=None, description="Maximum TLS version"
116
+ )
117
+ cipher_suite: Optional[str] = Field(
118
+ default=None, description="Custom cipher suite configuration"
119
+ )
120
+ check_hostname: bool = Field(
121
+ default=True, description="Whether to check hostname in certificates"
122
+ )
123
+ check_expiry: bool = Field(
124
+ default=True, description="Whether to check certificate expiry"
125
+ )
126
+ expiry_warning_days: int = Field(
127
+ default=30, ge=1, le=365, description="Days before expiry to warn"
128
+ )
129
+
130
+ @field_validator(
131
+ "cert_file", "key_file", "ca_cert_file", "client_cert_file", "client_key_file"
132
+ )
133
+ @classmethod
134
+ def validate_file_paths(cls, v):
135
+ """Validate that file paths exist when SSL is enabled."""
136
+ if v is not None and not Path(v).exists():
137
+ raise ValueError(f"File does not exist: {v}")
138
+ return v
139
+
140
+ @field_validator("verify_mode")
141
+ @classmethod
142
+ def validate_verify_mode(cls, v):
143
+ """Validate SSL verification mode."""
144
+ valid_modes = ["CERT_NONE", "CERT_OPTIONAL", "CERT_REQUIRED"]
145
+ if v not in valid_modes:
146
+ raise ValueError(f"Invalid verify_mode. Must be one of: {valid_modes}")
147
+ return v
148
+
149
+ @model_validator(mode="after")
150
+ def validate_ssl_configuration(self):
151
+ """Validate SSL configuration consistency."""
152
+ if self.enabled:
153
+ if not self.cert_file or not self.key_file:
154
+ raise ValueError(
155
+ "SSL enabled but certificate and key files are required"
156
+ )
157
+ return self
158
+
159
+
160
+ class AuthConfig(BaseModel):
161
+ """
162
+ Authentication Configuration Model
163
+
164
+ This model defines authentication configuration settings including
165
+ API keys, JWT settings, and certificate-based authentication.
166
+
167
+ Attributes:
168
+ enabled: Whether authentication is enabled
169
+ methods: List of enabled authentication methods
170
+ api_keys: Dictionary of API keys and associated users/roles
171
+ jwt_secret: JWT secret key for token signing
172
+ jwt_algorithm: JWT signing algorithm
173
+ jwt_expiry_hours: JWT token expiry time in hours
174
+ certificate_auth: Whether certificate-based auth is enabled
175
+ certificate_roles_oid: OID for extracting roles from certificates
176
+ certificate_permissions_oid: OID for extracting permissions from certificates
177
+ basic_auth: Whether basic authentication is enabled
178
+ oauth2_config: OAuth2 configuration settings
179
+ """
180
+
181
+ enabled: bool = Field(default=True, description="Whether authentication is enabled")
182
+ methods: List[AuthMethod] = Field(
183
+ default=[AuthMethod.API_KEY], description="Enabled auth methods"
184
+ )
185
+ api_keys: Dict[str, Union[str, Dict[str, Any]]] = Field(
186
+ default_factory=dict, description="API keys and associated users/roles"
187
+ )
188
+ user_roles: Dict[str, List[str]] = Field(
189
+ default_factory=dict, description="User roles mapping"
190
+ )
191
+ jwt_secret: Optional[SecretStr] = Field(default=None, description="JWT secret key")
192
+ jwt_algorithm: str = Field(default="HS256", description="JWT signing algorithm")
193
+ jwt_expiry_hours: int = Field(
194
+ default=24, ge=1, le=8760, description="JWT token expiry time in hours"
195
+ )
196
+ certificate_auth: bool = Field(
197
+ default=False, description="Whether certificate-based auth is enabled"
198
+ )
199
+ certificate_roles_oid: str = Field(
200
+ default="1.3.6.1.4.1.99999.1.1", description="OID for extracting roles"
201
+ )
202
+ certificate_permissions_oid: str = Field(
203
+ default="1.3.6.1.4.1.99999.1.2", description="OID for extracting permissions"
204
+ )
205
+ basic_auth: bool = Field(
206
+ default=False, description="Whether basic authentication is enabled"
207
+ )
208
+ oauth2_config: Optional[Dict[str, Any]] = Field(
209
+ default=None, description="OAuth2 configuration"
210
+ )
211
+ public_paths: List[str] = Field(
212
+ default_factory=list, description="List of public paths that bypass authentication"
213
+ )
214
+ security_headers: Optional[Dict[str, str]] = Field(
215
+ default=None, description="Custom security headers to add to responses"
216
+ )
217
+
218
+ @field_validator("jwt_algorithm")
219
+ @classmethod
220
+ def validate_jwt_algorithm(cls, v):
221
+ """Validate JWT algorithm."""
222
+ valid_algorithms = ["HS256", "HS384", "HS512", "RS256", "RS384", "RS512"]
223
+ if v not in valid_algorithms:
224
+ raise ValueError(
225
+ f"Invalid JWT algorithm. Must be one of: {valid_algorithms}"
226
+ )
227
+ return v
228
+
229
+ @model_validator(mode="after")
230
+ def validate_auth_configuration(self):
231
+ """Validate authentication configuration consistency."""
232
+ if self.enabled and not self.methods:
233
+ raise ValueError("Authentication enabled but no methods specified")
234
+
235
+ if AuthMethod.JWT in self.methods and not self.jwt_secret:
236
+ raise ValueError("JWT authentication enabled but no JWT secret provided")
237
+
238
+ return self
239
+
240
+
241
+ class CertificateConfig(BaseModel):
242
+ """
243
+ Certificate Management Configuration Model
244
+
245
+ This model defines certificate management configuration settings
246
+ including CA settings, certificate storage, and validation options.
247
+
248
+ Attributes:
249
+ enabled: Whether certificate management is enabled
250
+ ca_cert_path: Path to CA certificate
251
+ ca_key_path: Path to CA private key
252
+ cert_storage_path: Path for certificate storage
253
+ key_storage_path: Path for private key storage
254
+ default_validity_days: Default certificate validity in days
255
+ key_size: RSA key size for generated certificates
256
+ hash_algorithm: Hash algorithm for certificate signing
257
+ crl_enabled: Whether CRL is enabled
258
+ crl_path: Path for CRL storage
259
+ crl_validity_days: CRL validity period in days
260
+ auto_renewal: Whether automatic certificate renewal is enabled
261
+ renewal_threshold_days: Days before expiry to renew
262
+ """
263
+
264
+ enabled: bool = Field(
265
+ default=False, description="Whether certificate management is enabled"
266
+ )
267
+ ca_cert_path: Optional[str] = Field(
268
+ default=None, description="Path to CA certificate"
269
+ )
270
+ ca_key_path: Optional[str] = Field(
271
+ default=None, description="Path to CA private key"
272
+ )
273
+ cert_storage_path: str = Field(
274
+ default="./certs", description="Path for certificate storage"
275
+ )
276
+ key_storage_path: str = Field(
277
+ default="./keys", description="Path for private key storage"
278
+ )
279
+ default_validity_days: int = Field(
280
+ default=365, ge=1, le=3650, description="Default certificate validity in days"
281
+ )
282
+ key_size: int = Field(
283
+ default=2048,
284
+ ge=1024,
285
+ le=4096,
286
+ description="RSA key size for generated certificates",
287
+ )
288
+ hash_algorithm: str = Field(
289
+ default="sha256", description="Hash algorithm for certificate signing"
290
+ )
291
+ crl_enabled: bool = Field(default=False, description="Whether CRL is enabled")
292
+ crl_path: Optional[str] = Field(default=None, description="Path for CRL storage")
293
+ crl_validity_days: int = Field(
294
+ default=30, ge=1, le=365, description="CRL validity period in days"
295
+ )
296
+ auto_renewal: bool = Field(
297
+ default=False, description="Whether automatic certificate renewal is enabled"
298
+ )
299
+ renewal_threshold_days: int = Field(
300
+ default=30, ge=1, le=90, description="Days before expiry to renew"
301
+ )
302
+
303
+ @field_validator("hash_algorithm")
304
+ @classmethod
305
+ def validate_hash_algorithm(cls, v):
306
+ """Validate hash algorithm."""
307
+ valid_algorithms = ["sha1", "sha256", "sha384", "sha512"]
308
+ if v not in valid_algorithms:
309
+ raise ValueError(
310
+ f"Invalid hash algorithm. Must be one of: {valid_algorithms}"
311
+ )
312
+ return v
313
+
314
+ @model_validator(mode="after")
315
+ def validate_certificate_configuration(self):
316
+ """Validate certificate configuration consistency."""
317
+ if self.enabled:
318
+ if not self.ca_cert_path or not self.ca_key_path:
319
+ raise ValueError(
320
+ "Certificate management enabled but CA certificate and key paths are required"
321
+ )
322
+
323
+ if self.crl_enabled and not self.crl_path:
324
+ raise ValueError("CRL enabled but CRL path is required")
325
+
326
+ return self
327
+
328
+
329
+ class PermissionConfig(BaseModel):
330
+ """
331
+ Permission and Role Configuration Model
332
+
333
+ This model defines role and permission configuration settings
334
+ including role definitions, permission mappings, and hierarchy.
335
+
336
+ Attributes:
337
+ enabled: Whether permission management is enabled
338
+ roles_file: Path to roles configuration file
339
+ default_role: Default role for unauthenticated users
340
+ admin_role: Administrator role name
341
+ role_hierarchy: Role hierarchy configuration
342
+ permission_cache_enabled: Whether permission caching is enabled
343
+ permission_cache_ttl: Permission cache TTL in seconds
344
+ wildcard_permissions: Whether wildcard permissions are enabled
345
+ strict_mode: Whether strict permission checking is enabled
346
+ """
347
+
348
+ enabled: bool = Field(
349
+ default=True, description="Whether permission management is enabled"
350
+ )
351
+ roles_file: Optional[str] = Field(
352
+ default=None, description="Path to roles configuration file"
353
+ )
354
+ default_role: str = Field(
355
+ default="guest", description="Default role for unauthenticated users"
356
+ )
357
+ admin_role: str = Field(default="admin", description="Administrator role name")
358
+ role_hierarchy: Dict[str, List[str]] = Field(
359
+ default_factory=dict, description="Role hierarchy configuration"
360
+ )
361
+ permission_cache_enabled: bool = Field(
362
+ default=True, description="Whether permission caching is enabled"
363
+ )
364
+ permission_cache_ttl: int = Field(
365
+ default=300, ge=1, le=3600, description="Permission cache TTL in seconds"
366
+ )
367
+ wildcard_permissions: bool = Field(
368
+ default=False, description="Whether wildcard permissions are enabled"
369
+ )
370
+ strict_mode: bool = Field(
371
+ default=True, description="Whether strict permission checking is enabled"
372
+ )
373
+ roles: Optional[Dict[str, List[str]]] = Field(
374
+ default=None, description="Role definitions and their permissions"
375
+ )
376
+
377
+ @field_validator("roles_file")
378
+ @classmethod
379
+ def validate_roles_file(cls, v):
380
+ """Validate roles file path."""
381
+ if v is not None and not Path(v).exists():
382
+ raise ValueError(f"Roles file does not exist: {v}")
383
+ return v
384
+
385
+
386
+ class RateLimitConfig(BaseModel):
387
+ """
388
+ Rate Limiting Configuration Model
389
+
390
+ This model defines rate limiting configuration settings including
391
+ limits, windows, and storage backends.
392
+
393
+ Attributes:
394
+ enabled: Whether rate limiting is enabled
395
+ default_requests_per_minute: Default requests per minute limit
396
+ default_requests_per_hour: Default requests per hour limit
397
+ burst_limit: Burst limit multiplier
398
+ window_size_seconds: Rate limiting window size in seconds
399
+ storage_backend: Rate limiting storage backend
400
+ redis_config: Redis configuration for rate limiting
401
+ cleanup_interval: Cleanup interval for expired entries
402
+ exempt_paths: Paths exempt from rate limiting
403
+ exempt_roles: Roles exempt from rate limiting
404
+ """
405
+
406
+ enabled: bool = Field(default=True, description="Whether rate limiting is enabled")
407
+ default_requests_per_minute: int = Field(
408
+ default=60, ge=1, le=10000, description="Default requests per minute limit"
409
+ )
410
+ default_requests_per_hour: int = Field(
411
+ default=1000, ge=1, le=100000, description="Default requests per hour limit"
412
+ )
413
+ burst_limit: int = Field(
414
+ default=2, ge=1, le=10, description="Burst limit multiplier"
415
+ )
416
+ window_size_seconds: int = Field(
417
+ default=60, ge=1, le=3600, description="Rate limiting window size in seconds"
418
+ )
419
+ storage_backend: str = Field(
420
+ default="memory", description="Rate limiting storage backend"
421
+ )
422
+ redis_config: Optional[Dict[str, Any]] = Field(
423
+ default=None, description="Redis configuration for rate limiting"
424
+ )
425
+ cleanup_interval: int = Field(
426
+ default=300, ge=1, le=3600, description="Cleanup interval for expired entries"
427
+ )
428
+ exempt_paths: List[str] = Field(
429
+ default_factory=list, description="Paths exempt from rate limiting"
430
+ )
431
+ exempt_roles: List[str] = Field(
432
+ default_factory=list, description="Roles exempt from rate limiting"
433
+ )
434
+
435
+ @field_validator("storage_backend")
436
+ @classmethod
437
+ def validate_storage_backend(cls, v):
438
+ """Validate storage backend."""
439
+ valid_backends = ["memory", "redis", "database"]
440
+ if v not in valid_backends:
441
+ raise ValueError(
442
+ f"Invalid storage backend. Must be one of: {valid_backends}"
443
+ )
444
+ return v
445
+
446
+
447
+ class LoggingConfig(BaseModel):
448
+ """
449
+ Logging Configuration Model
450
+
451
+ This model defines logging configuration settings including
452
+ log levels, formats, and output destinations.
453
+
454
+ Attributes:
455
+ enabled: Whether logging is enabled
456
+ level: Logging level
457
+ format: Log message format
458
+ date_format: Date format for log messages
459
+ file_path: Path to log file
460
+ max_file_size: Maximum log file size in MB
461
+ backup_count: Number of backup log files
462
+ console_output: Whether to output to console
463
+ json_format: Whether to use JSON format
464
+ include_timestamp: Whether to include timestamps
465
+ include_level: Whether to include log level
466
+ include_module: Whether to include module name
467
+ """
468
+
469
+ enabled: bool = Field(default=True, description="Whether logging is enabled")
470
+ level: LogLevel = Field(default=LogLevel.INFO, description="Logging level")
471
+ format: str = Field(
472
+ default="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
473
+ description="Log message format",
474
+ )
475
+ date_format: str = Field(
476
+ default="%Y-%m-%d %H:%M:%S", description="Date format for log messages"
477
+ )
478
+ file_path: Optional[str] = Field(default=None, description="Path to log file")
479
+ max_file_size: int = Field(
480
+ default=10, ge=1, le=1000, description="Maximum log file size in MB"
481
+ )
482
+ backup_count: int = Field(
483
+ default=5, ge=0, le=100, description="Number of backup log files"
484
+ )
485
+ console_output: bool = Field(
486
+ default=True, description="Whether to output to console"
487
+ )
488
+ json_format: bool = Field(default=False, description="Whether to use JSON format")
489
+ include_timestamp: bool = Field(
490
+ default=True, description="Whether to include timestamps"
491
+ )
492
+ include_level: bool = Field(
493
+ default=True, description="Whether to include log level"
494
+ )
495
+ include_module: bool = Field(
496
+ default=True, description="Whether to include module name"
497
+ )
498
+
499
+
500
+ class SecurityConfig(BaseModel):
501
+ """
502
+ Main Security Configuration Model
503
+
504
+ This is the main configuration model that combines all security
505
+ component configurations into a single, comprehensive configuration.
506
+
507
+ Attributes:
508
+ ssl: SSL/TLS configuration
509
+ auth: Authentication configuration
510
+ certificates: Certificate management configuration
511
+ permissions: Permission and role configuration
512
+ rate_limit: Rate limiting configuration
513
+ logging: Logging configuration
514
+ debug: Whether debug mode is enabled
515
+ environment: Environment name (dev, staging, prod)
516
+ version: Configuration version
517
+ """
518
+
519
+ ssl: SSLConfig = Field(
520
+ default_factory=SSLConfig, description="SSL/TLS configuration"
521
+ )
522
+ auth: AuthConfig = Field(
523
+ default_factory=AuthConfig, description="Authentication configuration"
524
+ )
525
+ certificates: CertificateConfig = Field(
526
+ default_factory=CertificateConfig,
527
+ description="Certificate management configuration",
528
+ )
529
+ permissions: PermissionConfig = Field(
530
+ default_factory=PermissionConfig,
531
+ description="Permission and role configuration",
532
+ )
533
+ rate_limit: RateLimitConfig = Field(
534
+ default_factory=RateLimitConfig, description="Rate limiting configuration"
535
+ )
536
+ logging: LoggingConfig = Field(
537
+ default_factory=LoggingConfig, description="Logging configuration"
538
+ )
539
+ debug: bool = Field(default=False, description="Whether debug mode is enabled")
540
+ environment: str = Field(default="dev", description="Environment name")
541
+ version: str = Field(default="1.0.0", description="Configuration version")
542
+
543
+ @field_validator("environment")
544
+ @classmethod
545
+ def validate_environment(cls, v):
546
+ """Validate environment name."""
547
+ valid_environments = [
548
+ "dev",
549
+ "development",
550
+ "staging",
551
+ "prod",
552
+ "production",
553
+ "test",
554
+ ]
555
+ if v not in valid_environments:
556
+ raise ValueError(
557
+ f"Invalid environment. Must be one of: {valid_environments}"
558
+ )
559
+ return v
560
+
561
+
562
+ # Certificate-specific configuration models
563
+ class CAConfig(BaseModel):
564
+ """
565
+ Certificate Authority Configuration Model
566
+
567
+ This model defines configuration for creating and managing
568
+ Certificate Authority (CA) certificates.
569
+
570
+ Attributes:
571
+ common_name: CA common name
572
+ organization: Organization name
573
+ organizational_unit: Organizational unit
574
+ country: Country code
575
+ state: State or province
576
+ locality: City or locality
577
+ email: Contact email
578
+ validity_years: CA certificate validity in years
579
+ key_size: RSA key size
580
+ hash_algorithm: Hash algorithm for signing
581
+ """
582
+
583
+ common_name: str = Field(..., description="CA common name")
584
+ organization: str = Field(..., description="Organization name")
585
+ organizational_unit: Optional[str] = Field(
586
+ default=None, description="Organizational unit"
587
+ )
588
+ country: str = Field(
589
+ default="US", min_length=2, max_length=2, description="Country code"
590
+ )
591
+ state: Optional[str] = Field(default=None, description="State or province")
592
+ locality: Optional[str] = Field(default=None, description="City or locality")
593
+ email: Optional[str] = Field(default=None, description="Contact email")
594
+ validity_years: int = Field(
595
+ default=10, ge=1, le=50, description="CA certificate validity in years"
596
+ )
597
+ key_size: int = Field(default=4096, ge=2048, le=8192, description="RSA key size")
598
+ hash_algorithm: str = Field(
599
+ default="sha256", description="Hash algorithm for signing"
600
+ )
601
+
602
+
603
+ class IntermediateCAConfig(CAConfig):
604
+ """
605
+ Intermediate Certificate Authority Configuration Model
606
+
607
+ This model extends CAConfig for intermediate CA certificates
608
+ with additional settings specific to intermediate CAs.
609
+
610
+ Attributes:
611
+ parent_ca_cert: Path to parent CA certificate
612
+ parent_ca_key: Path to parent CA private key
613
+ path_length: Maximum path length constraint
614
+ """
615
+
616
+ parent_ca_cert: str = Field(..., description="Path to parent CA certificate")
617
+ parent_ca_key: str = Field(..., description="Path to parent CA private key")
618
+ path_length: int = Field(
619
+ default=0, ge=0, le=10, description="Maximum path length constraint"
620
+ )
621
+
622
+
623
+ class ClientCertConfig(BaseModel):
624
+ """
625
+ Client Certificate Configuration Model
626
+
627
+ This model defines configuration for creating client certificates
628
+ including subject information and certificate extensions.
629
+
630
+ Attributes:
631
+ common_name: Client certificate common name
632
+ organization: Organization name
633
+ organizational_unit: Organizational unit
634
+ country: Country code
635
+ state: State or province
636
+ locality: City or locality
637
+ email: Contact email
638
+ validity_days: Certificate validity in days
639
+ key_size: RSA key size
640
+ roles: List of roles to include in certificate
641
+ permissions: List of permissions to include in certificate
642
+ ca_cert_path: Path to signing CA certificate
643
+ ca_key_path: Path to signing CA private key
644
+ """
645
+
646
+ common_name: str = Field(..., description="Client certificate common name")
647
+ organization: str = Field(..., description="Organization name")
648
+ organizational_unit: Optional[str] = Field(
649
+ default=None, description="Organizational unit"
650
+ )
651
+ country: str = Field(
652
+ default="US", min_length=2, max_length=2, description="Country code"
653
+ )
654
+ state: Optional[str] = Field(default=None, description="State or province")
655
+ locality: Optional[str] = Field(default=None, description="City or locality")
656
+ email: Optional[str] = Field(default=None, description="Contact email")
657
+ validity_days: int = Field(
658
+ default=365, ge=1, le=3650, description="Certificate validity in days"
659
+ )
660
+ key_size: int = Field(default=2048, ge=1024, le=4096, description="RSA key size")
661
+ roles: List[str] = Field(
662
+ default_factory=list, description="List of roles to include in certificate"
663
+ )
664
+ permissions: List[str] = Field(
665
+ default_factory=list,
666
+ description="List of permissions to include in certificate",
667
+ )
668
+ ca_cert_path: str = Field(..., description="Path to signing CA certificate")
669
+ ca_key_path: str = Field(..., description="Path to signing CA private key")
670
+
671
+
672
+ class ServerCertConfig(ClientCertConfig):
673
+ """
674
+ Server Certificate Configuration Model
675
+
676
+ This model extends ClientCertConfig for server certificates
677
+ with additional settings specific to server certificates.
678
+
679
+ Attributes:
680
+ subject_alt_names: List of subject alternative names
681
+ key_usage: Key usage extensions
682
+ extended_key_usage: Extended key usage extensions
683
+ """
684
+
685
+ subject_alt_names: List[str] = Field(
686
+ default_factory=list, description="List of subject alternative names"
687
+ )
688
+ key_usage: List[str] = Field(
689
+ default=["digitalSignature", "keyEncipherment"],
690
+ description="Key usage extensions",
691
+ )
692
+ extended_key_usage: List[str] = Field(
693
+ default=["serverAuth"], description="Extended key usage extensions"
694
+ )