Coverage for /Users/les/Projects/crackerjack/crackerjack/services/security_logger.py: 0%

163 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-09-03 15:39 -0700

1import json 

2import logging 

3import time 

4import typing as t 

5from enum import Enum 

6from pathlib import Path 

7 

8from pydantic import BaseModel 

9 

10 

11class SecurityEventType(str, Enum): 

12 PATH_TRAVERSAL_ATTEMPT = "path_traversal_attempt" 

13 FILE_SIZE_EXCEEDED = "file_size_exceeded" 

14 DANGEROUS_PATH_DETECTED = "dangerous_path_detected" 

15 BACKUP_CREATED = "backup_created" 

16 BACKUP_RESTORED = "backup_restored" 

17 BACKUP_DELETED = "backup_deleted" 

18 FILE_CLEANED = "file_cleaned" 

19 ATOMIC_OPERATION = "atomic_operation" 

20 VALIDATION_FAILED = "validation_failed" 

21 TEMP_FILE_CREATED = "temp_file_created" 

22 COMMAND_INJECTION_ATTEMPT = "command_injection_attempt" 

23 SQL_INJECTION_ATTEMPT = "sql_injection_attempt" 

24 CODE_INJECTION_ATTEMPT = "code_injection_attempt" 

25 INPUT_SIZE_EXCEEDED = "input_size_exceeded" 

26 INVALID_JSON_PAYLOAD = "invalid_json_payload" 

27 RATE_LIMIT_EXCEEDED = "rate_limit_exceeded" 

28 UNAUTHORIZED_ACCESS_ATTEMPT = "unauthorized_access_attempt" 

29 SUBPROCESS_EXECUTION = "subprocess_execution" 

30 SUBPROCESS_ENVIRONMENT_SANITIZED = "subprocess_environment_sanitized" 

31 SUBPROCESS_COMMAND_VALIDATION = "subprocess_command_validation" 

32 SUBPROCESS_TIMEOUT = "subprocess_timeout" 

33 SUBPROCESS_FAILURE = "subprocess_failure" 

34 DANGEROUS_COMMAND_BLOCKED = "dangerous_command_blocked" 

35 ENVIRONMENT_VARIABLE_FILTERED = "environment_variable_filtered" 

36 STATUS_ACCESS_ATTEMPT = "status_access_attempt" 

37 SENSITIVE_DATA_SANITIZED = "sensitive_data_sanitized" 

38 STATUS_INFORMATION_DISCLOSURE = "status_information_disclosure" 

39 # Authentication and authorization events 

40 ACCESS_DENIED = "access_denied" 

41 API_KEY_CREATED = "api_key_created" 

42 API_KEY_REVOKED = "api_key_revoked" 

43 AUTH_EXPIRED = "auth_expired" 

44 AUTH_FAILURE = "auth_failure" 

45 AUTH_SUCCESS = "auth_success" 

46 LOCAL_ACCESS_GRANTED = "local_access_granted" 

47 INSUFFICIENT_PRIVILEGES = "insufficient_privileges" 

48 # Circuit breaker and resilience events 

49 CIRCUIT_BREAKER_CLOSED = "circuit_breaker_closed" 

50 CIRCUIT_BREAKER_HALF_OPEN = "circuit_breaker_half_open" 

51 CIRCUIT_BREAKER_OPEN = "circuit_breaker_open" 

52 CIRCUIT_BREAKER_RESET = "circuit_breaker_reset" 

53 # Collection and data processing events 

54 COLLECTION_END = "collection_end" 

55 COLLECTION_ERROR = "collection_error" 

56 COLLECTION_START = "collection_start" 

57 STATUS_COLLECTED = "status_collected" 

58 FILE_READ_ERROR = "file_read_error" 

59 # Connection and network events 

60 CONNECTION_CLOSED = "connection_closed" 

61 CONNECTION_ESTABLISHED = "connection_established" 

62 CONNECTION_IDLE = "connection_idle" 

63 CONNECTION_TIMEOUT = "connection_timeout" 

64 # Request lifecycle events 

65 REQUEST_END = "request_end" 

66 REQUEST_START = "request_start" 

67 REQUEST_TIMEOUT = "request_timeout" 

68 # Resource and operation management events 

69 RESOURCE_CLEANUP = "resource_cleanup" 

70 RESOURCE_EXHAUSTED = "resource_exhausted" 

71 RESOURCE_LIMIT_EXCEEDED = "resource_limit_exceeded" 

72 SERVICE_CLEANUP = "service_cleanup" 

73 SERVICE_START = "service_start" 

74 SERVICE_STOP = "service_stop" 

75 # Operation monitoring events 

76 MONITORING_ERROR = "monitoring_error" 

77 OPERATION_DURATION_EXCEEDED = "operation_duration_exceeded" 

78 OPERATION_FAILURE = "operation_failure" 

79 OPERATION_SUCCESS = "operation_success" 

80 OPERATION_TIMEOUT = "operation_timeout" 

81 # Input validation events 

82 INVALID_INPUT = "invalid_input" 

83 

84 

85class SecurityEventLevel(str, Enum): 

86 LOW = "low" 

87 MEDIUM = "medium" 

88 HIGH = "high" 

89 CRITICAL = "critical" 

90 

91 

92class SecurityEvent(BaseModel): 

93 timestamp: float 

94 event_type: SecurityEventType 

95 level: SecurityEventLevel 

96 message: str 

97 file_path: str | None = None 

98 user_id: str | None = None 

99 session_id: str | None = None 

100 additional_data: dict[str, t.Any] = {} 

101 

102 def to_dict(self) -> dict[str, t.Any]: 

103 return { 

104 "timestamp": self.timestamp, 

105 "event_type": self.event_type.value, 

106 "level": self.level.value, 

107 "message": self.message, 

108 "file_path": self.file_path, 

109 "user_id": self.user_id, 

110 "session_id": self.session_id, 

111 "additional_data": self.additional_data, 

112 } 

113 

114 

115class SecurityLogger: 

116 def __init__(self, logger_name: str = "crackerjack.security"): 

117 self.logger = logging.getLogger(logger_name) 

118 self._setup_security_logger() 

119 

120 def _setup_security_logger(self) -> None: 

121 self.logger.setLevel(logging.DEBUG) 

122 

123 if not self.logger.handlers: 

124 console_handler = logging.StreamHandler() 

125 console_handler.setLevel(logging.WARNING) 

126 

127 formatter = logging.Formatter( 

128 "%(asctime)s - SECURITY - %(levelname)s-%(message)s" 

129 ) 

130 console_handler.setFormatter(formatter) 

131 self.logger.addHandler(console_handler) 

132 

133 def log_security_event( 

134 self, 

135 event_type: SecurityEventType, 

136 level: SecurityEventLevel, 

137 message: str, 

138 file_path: Path | str | None = None, 

139 user_id: str | None = None, 

140 session_id: str | None = None, 

141 **additional_data: t.Any, 

142 ) -> None: 

143 event = SecurityEvent( 

144 timestamp=time.time(), 

145 event_type=event_type, 

146 level=level, 

147 message=message, 

148 file_path=str(file_path) if file_path else None, 

149 user_id=user_id, 

150 session_id=session_id, 

151 additional_data=additional_data, 

152 ) 

153 

154 log_level = self._get_logging_level(level) 

155 self.logger.log( 

156 log_level, json.dumps(event.to_dict()), extra={"security_event": True} 

157 ) 

158 

159 def _get_logging_level(self, level: SecurityEventLevel) -> int: 

160 level_mapping = { 

161 SecurityEventLevel.LOW: logging.DEBUG, 

162 SecurityEventLevel.MEDIUM: logging.INFO, 

163 SecurityEventLevel.HIGH: logging.WARNING, 

164 SecurityEventLevel.CRITICAL: logging.CRITICAL, 

165 } 

166 return level_mapping[level] 

167 

168 def log_path_traversal_attempt( 

169 self, 

170 attempted_path: Path | str, 

171 base_directory: Path | str | None = None, 

172 **kwargs: t.Any, 

173 ) -> None: 

174 self.log_security_event( 

175 SecurityEventType.PATH_TRAVERSAL_ATTEMPT, 

176 SecurityEventLevel.CRITICAL, 

177 f"Path traversal attempt detected: {attempted_path}", 

178 file_path=attempted_path, 

179 base_directory=str(base_directory) if base_directory else None, 

180 **kwargs, 

181 ) 

182 

183 def log_file_size_exceeded( 

184 self, file_path: Path | str, file_size: int, max_size: int, **kwargs: t.Any 

185 ) -> None: 

186 self.log_security_event( 

187 SecurityEventType.FILE_SIZE_EXCEEDED, 

188 SecurityEventLevel.HIGH, 

189 f"File size limit exceeded: {file_size} > {max_size}", 

190 file_path=file_path, 

191 file_size=file_size, 

192 max_size=max_size, 

193 **kwargs, 

194 ) 

195 

196 def log_dangerous_path_detected( 

197 self, path: Path | str, dangerous_component: str, **kwargs: t.Any 

198 ) -> None: 

199 self.log_security_event( 

200 SecurityEventType.DANGEROUS_PATH_DETECTED, 

201 SecurityEventLevel.HIGH, 

202 f"Dangerous path component detected: {dangerous_component} in {path}", 

203 file_path=path, 

204 dangerous_component=dangerous_component, 

205 **kwargs, 

206 ) 

207 

208 def log_backup_created( 

209 self, original_path: Path | str, backup_path: Path | str, **kwargs: t.Any 

210 ) -> None: 

211 self.log_security_event( 

212 SecurityEventType.BACKUP_CREATED, 

213 SecurityEventLevel.LOW, 

214 f"Backup created: {original_path} -> {backup_path}", 

215 file_path=original_path, 

216 backup_path=str(backup_path), 

217 **kwargs, 

218 ) 

219 

220 def log_file_cleaned( 

221 self, file_path: Path | str, steps_completed: list[str], **kwargs: t.Any 

222 ) -> None: 

223 self.log_security_event( 

224 SecurityEventType.FILE_CLEANED, 

225 SecurityEventLevel.LOW, 

226 f"File cleaned successfully: {file_path}", 

227 file_path=file_path, 

228 steps_completed=steps_completed, 

229 **kwargs, 

230 ) 

231 

232 def log_atomic_operation( 

233 self, operation: str, file_path: Path | str, success: bool, **kwargs: t.Any 

234 ) -> None: 

235 level = SecurityEventLevel.LOW if success else SecurityEventLevel.MEDIUM 

236 status = "successful" if success else "failed" 

237 

238 self.log_security_event( 

239 SecurityEventType.ATOMIC_OPERATION, 

240 level, 

241 f"Atomic {operation} {status}: {file_path}", 

242 file_path=file_path, 

243 operation=operation, 

244 success=success, 

245 **kwargs, 

246 ) 

247 

248 def log_validation_failed( 

249 self, validation_type: str, file_path: Path | str, reason: str, **kwargs: t.Any 

250 ) -> None: 

251 self.log_security_event( 

252 SecurityEventType.VALIDATION_FAILED, 

253 SecurityEventLevel.MEDIUM, 

254 f"Validation failed ({validation_type}): {reason} for {file_path}", 

255 file_path=file_path, 

256 validation_type=validation_type, 

257 reason=reason, 

258 **kwargs, 

259 ) 

260 

261 def log_temp_file_created( 

262 self, temp_path: Path | str, purpose: str, **kwargs: t.Any 

263 ) -> None: 

264 self.log_security_event( 

265 SecurityEventType.TEMP_FILE_CREATED, 

266 SecurityEventLevel.LOW, 

267 f"Secure temp file created for {purpose}: {temp_path}", 

268 file_path=temp_path, 

269 purpose=purpose, 

270 **kwargs, 

271 ) 

272 

273 def log_command_injection_attempt( 

274 self, command: str, detected_chars: list[str], **kwargs: t.Any 

275 ) -> None: 

276 self.log_security_event( 

277 SecurityEventType.COMMAND_INJECTION_ATTEMPT, 

278 SecurityEventLevel.CRITICAL, 

279 f"Command injection attempt detected: {detected_chars} in {command[:100]}", 

280 detected_chars=detected_chars, 

281 command_preview=command[:100], 

282 **kwargs, 

283 ) 

284 

285 def log_sql_injection_attempt( 

286 self, input_value: str, detected_pattern: str, **kwargs: t.Any 

287 ) -> None: 

288 self.log_security_event( 

289 SecurityEventType.SQL_INJECTION_ATTEMPT, 

290 SecurityEventLevel.CRITICAL, 

291 f"SQL injection pattern detected: {detected_pattern}", 

292 input_preview=input_value[:100], 

293 detected_pattern=detected_pattern, 

294 **kwargs, 

295 ) 

296 

297 def log_code_injection_attempt( 

298 self, input_value: str, detected_pattern: str, **kwargs: t.Any 

299 ) -> None: 

300 self.log_security_event( 

301 SecurityEventType.CODE_INJECTION_ATTEMPT, 

302 SecurityEventLevel.CRITICAL, 

303 f"Code injection pattern detected: {detected_pattern}", 

304 input_preview=input_value[:100], 

305 detected_pattern=detected_pattern, 

306 **kwargs, 

307 ) 

308 

309 def log_input_size_exceeded( 

310 self, input_type: str, actual_size: int, max_size: int, **kwargs: t.Any 

311 ) -> None: 

312 self.log_security_event( 

313 SecurityEventType.INPUT_SIZE_EXCEEDED, 

314 SecurityEventLevel.HIGH, 

315 f"Input size limit exceeded for {input_type}: {actual_size} > {max_size}", 

316 input_type=input_type, 

317 actual_size=actual_size, 

318 max_size=max_size, 

319 **kwargs, 

320 ) 

321 

322 def log_invalid_json_payload( 

323 self, error_message: str, payload_preview: str, **kwargs: t.Any 

324 ) -> None: 

325 self.log_security_event( 

326 SecurityEventType.INVALID_JSON_PAYLOAD, 

327 SecurityEventLevel.MEDIUM, 

328 f"Invalid JSON payload: {error_message}", 

329 error_message=error_message, 

330 payload_preview=payload_preview, 

331 **kwargs, 

332 ) 

333 

334 def log_rate_limit_exceeded( 

335 self, limit_type: str, current_count: int, max_allowed: int, **kwargs: t.Any 

336 ) -> None: 

337 self.log_security_event( 

338 SecurityEventType.RATE_LIMIT_EXCEEDED, 

339 SecurityEventLevel.HIGH, 

340 f"Rate limit exceeded for {limit_type}: {current_count} > {max_allowed}", 

341 limit_type=limit_type, 

342 current_count=current_count, 

343 max_allowed=max_allowed, 

344 **kwargs, 

345 ) 

346 

347 def log_subprocess_execution( 

348 self, 

349 command: list[str], 

350 cwd: str | None = None, 

351 env_vars_count: int = 0, 

352 **kwargs: t.Any, 

353 ) -> None: 

354 """Log secure subprocess execution.""" 

355 self.log_security_event( 

356 SecurityEventType.SUBPROCESS_EXECUTION, 

357 SecurityEventLevel.LOW, 

358 f"Subprocess executed: {' '.join(command[:3])}{'...' if len(command) > 3 else ''}", 

359 command=command[:10], # Log first 10 args only 

360 cwd=cwd, 

361 env_vars_count=env_vars_count, 

362 **kwargs, 

363 ) 

364 

365 def log_subprocess_environment_sanitized( 

366 self, 

367 original_count: int, 

368 sanitized_count: int, 

369 filtered_vars: list[str], 

370 **kwargs: t.Any, 

371 ) -> None: 

372 """Log environment sanitization for subprocess.""" 

373 self.log_security_event( 

374 SecurityEventType.SUBPROCESS_ENVIRONMENT_SANITIZED, 

375 SecurityEventLevel.LOW, 

376 f"Environment sanitized: {original_count} -> {sanitized_count} vars", 

377 original_count=original_count, 

378 sanitized_count=sanitized_count, 

379 filtered_vars=filtered_vars[:20], # Log first 20 filtered vars 

380 **kwargs, 

381 ) 

382 

383 def log_subprocess_command_validation( 

384 self, 

385 command: list[str], 

386 validation_result: bool, 

387 issues: list[str] = None, 

388 **kwargs: t.Any, 

389 ) -> None: 

390 """Log subprocess command validation results.""" 

391 level = SecurityEventLevel.LOW if validation_result else SecurityEventLevel.HIGH 

392 status = "passed" if validation_result else "failed" 

393 

394 self.log_security_event( 

395 SecurityEventType.SUBPROCESS_COMMAND_VALIDATION, 

396 level, 

397 f"Command validation {status}: {' '.join(command[:2])}{'...' if len(command) > 2 else ''}", 

398 command_preview=command[:5], 

399 validation_result=validation_result, 

400 issues=issues or [], 

401 **kwargs, 

402 ) 

403 

404 def log_subprocess_timeout( 

405 self, 

406 command: list[str], 

407 timeout_seconds: float, 

408 actual_duration: float, 

409 **kwargs: t.Any, 

410 ) -> None: 

411 """Log subprocess timeout events.""" 

412 self.log_security_event( 

413 SecurityEventType.SUBPROCESS_TIMEOUT, 

414 SecurityEventLevel.MEDIUM, 

415 f"Subprocess timed out after {timeout_seconds}s: {' '.join(command[:2])}{'...' if len(command) > 2 else ''}", 

416 command_preview=command[:3], 

417 timeout_seconds=timeout_seconds, 

418 actual_duration=actual_duration, 

419 **kwargs, 

420 ) 

421 

422 def log_subprocess_failure( 

423 self, command: list[str], exit_code: int, error_output: str, **kwargs: t.Any 

424 ) -> None: 

425 """Log subprocess execution failures.""" 

426 self.log_security_event( 

427 SecurityEventType.SUBPROCESS_FAILURE, 

428 SecurityEventLevel.MEDIUM, 

429 f"Subprocess failed (exit code {exit_code}): {' '.join(command[:2])}{'...' if len(command) > 2 else ''}", 

430 command_preview=command[:3], 

431 exit_code=exit_code, 

432 error_preview=error_output[:200], # Log first 200 chars of error 

433 **kwargs, 

434 ) 

435 

436 def log_dangerous_command_blocked( 

437 self, 

438 command: list[str], 

439 reason: str, 

440 dangerous_patterns: list[str], 

441 **kwargs: t.Any, 

442 ) -> None: 

443 """Log blocking of dangerous commands.""" 

444 self.log_security_event( 

445 SecurityEventType.DANGEROUS_COMMAND_BLOCKED, 

446 SecurityEventLevel.CRITICAL, 

447 f"Dangerous command blocked: {reason}", 

448 command_preview=command[:5], 

449 reason=reason, 

450 dangerous_patterns=dangerous_patterns, 

451 **kwargs, 

452 ) 

453 

454 def log_environment_variable_filtered( 

455 self, 

456 variable_name: str, 

457 reason: str, 

458 value_preview: str = None, 

459 **kwargs: t.Any, 

460 ) -> None: 

461 """Log filtering of environment variables.""" 

462 self.log_security_event( 

463 SecurityEventType.ENVIRONMENT_VARIABLE_FILTERED, 

464 SecurityEventLevel.LOW, 

465 f"Environment variable filtered: {variable_name} ({reason})", 

466 variable_name=variable_name, 

467 reason=reason, 

468 value_preview=value_preview[:50] if value_preview else None, 

469 **kwargs, 

470 ) 

471 

472 def log_status_access_attempt( 

473 self, 

474 endpoint: str, 

475 verbosity_level: str, 

476 user_context: str | None = None, 

477 data_keys: list[str] | None = None, 

478 **kwargs: t.Any, 

479 ) -> None: 

480 """Log status endpoint access attempts.""" 

481 self.log_security_event( 

482 SecurityEventType.STATUS_ACCESS_ATTEMPT, 

483 SecurityEventLevel.LOW, 

484 f"Status access: {endpoint} (verbosity: {verbosity_level})", 

485 user_id=user_context, 

486 endpoint=endpoint, 

487 verbosity_level=verbosity_level, 

488 data_keys=data_keys or [], 

489 **kwargs, 

490 ) 

491 

492 def log_sensitive_data_sanitized( 

493 self, 

494 data_type: str, 

495 sanitization_count: int, 

496 verbosity_level: str, 

497 patterns_matched: list[str] | None = None, 

498 **kwargs: t.Any, 

499 ) -> None: 

500 """Log sensitive data sanitization events.""" 

501 self.log_security_event( 

502 SecurityEventType.SENSITIVE_DATA_SANITIZED, 

503 SecurityEventLevel.LOW, 

504 f"Sensitive data sanitized: {sanitization_count} {data_type} items", 

505 data_type=data_type, 

506 sanitization_count=sanitization_count, 

507 verbosity_level=verbosity_level, 

508 patterns_matched=patterns_matched or [], 

509 **kwargs, 

510 ) 

511 

512 def log_status_information_disclosure( 

513 self, 

514 disclosure_type: str, 

515 sensitive_info: str, 

516 endpoint: str, 

517 severity: str = "medium", 

518 **kwargs: t.Any, 

519 ) -> None: 

520 """Log potential information disclosure in status responses.""" 

521 level_map = { 

522 "low": SecurityEventLevel.LOW, 

523 "medium": SecurityEventLevel.MEDIUM, 

524 "high": SecurityEventLevel.HIGH, 

525 "critical": SecurityEventLevel.CRITICAL, 

526 } 

527 

528 self.log_security_event( 

529 SecurityEventType.STATUS_INFORMATION_DISCLOSURE, 

530 level_map.get(severity, SecurityEventLevel.MEDIUM), 

531 f"Potential information disclosure: {disclosure_type} in {endpoint}", 

532 disclosure_type=disclosure_type, 

533 sensitive_info_preview=sensitive_info[:100], 

534 endpoint=endpoint, 

535 severity=severity, 

536 **kwargs, 

537 ) 

538 

539 

540_security_logger: SecurityLogger | None = None 

541 

542 

543def get_security_logger() -> SecurityLogger: 

544 global _security_logger 

545 if _security_logger is None: 

546 _security_logger = SecurityLogger() 

547 return _security_logger