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

133 statements  

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

1""" 

2Secure status formatter to prevent information disclosure vulnerabilities. 

3 

4This module provides secure sanitization of status responses to prevent 

5leaking sensitive system information such as absolute paths, internal URLs, 

6configuration details, and other sensitive data. 

7""" 

8 

9import re 

10import typing as t 

11from enum import Enum 

12from pathlib import Path 

13 

14from .security_logger import get_security_logger 

15 

16 

17class StatusVerbosity(str, Enum): 

18 """Status output verbosity levels for security-aware responses.""" 

19 

20 MINIMAL = "minimal" # Only essential operational status 

21 STANDARD = "standard" # Standard operational information (default) 

22 DETAILED = "detailed" # More detailed information for debugging 

23 FULL = "full" # Complete information (for internal use only) 

24 

25 

26class SecureStatusFormatter: 

27 """ 

28 Secure status formatter with configurable verbosity levels. 

29 

30 Sanitizes sensitive information while preserving necessary operational data. 

31 """ 

32 

33 # Patterns for sensitive information that should be masked or removed 

34 SENSITIVE_PATTERNS = { 

35 # Absolute system paths (replace with relative paths) 

36 "absolute_paths": [ 

37 r"(/[^/\s]*){2,}", # Paths like /Users/username/... 

38 r"/tmp/[^\s]*", # Temp directory paths 

39 r"/var/[^\s]*", # Var directory paths 

40 r"/home/[^\s]*", # Home directory paths 

41 ], 

42 # URLs with localhost/internal IPs 

43 "internal_urls": [ 

44 r"https?://localhost:\d+", 

45 r"https?://127\.0\.0\.1:\d+", 

46 r"https?://0\.0\.0\.0:\d+", 

47 r"ws://localhost:\d+", 

48 r"ws://127\.0\.0\.1:\d+", 

49 ], 

50 # Tokens and API keys 

51 "secrets": [ 

52 r"[A-Za-z0-9]{20,}", # Long alphanumeric strings (potential tokens) 

53 r"[A-Za-z0-9+/]{32,}={0,2}", # Base64-like strings 

54 ], 

55 # Process IDs and system identifiers 

56 "system_ids": [ 

57 r"pid:\d+", 

58 r"process_id:\s*\d+", 

59 ], 

60 } 

61 

62 # Sensitive keys that should be masked or removed 

63 SENSITIVE_KEYS = { 

64 "remove_minimal": { 

65 "progress_dir", 

66 "temp_files_count", 

67 "rate_limiter", 

68 "config", 

69 "traceback", 

70 "processes", 

71 }, 

72 "remove_standard": {"progress_dir", "traceback"}, 

73 "mask": { 

74 "project_path", 

75 "websocket_url", 

76 "monitor_url", 

77 "api_key", 

78 "token", 

79 "secret", 

80 "password", 

81 "auth", 

82 }, 

83 } 

84 

85 def __init__(self, project_root: Path | None = None): 

86 """ 

87 Initialize secure status formatter. 

88 

89 Args: 

90 project_root: Project root path for relative path conversion 

91 """ 

92 self.project_root = project_root or Path.cwd() 

93 self.security_logger = get_security_logger() 

94 

95 def format_status( 

96 self, 

97 status_data: dict[str, t.Any], 

98 verbosity: StatusVerbosity = StatusVerbosity.STANDARD, 

99 user_context: str | None = None, 

100 ) -> dict[str, t.Any]: 

101 """ 

102 Format status data with security sanitization. 

103 

104 Args: 

105 status_data: Raw status data to sanitize 

106 verbosity: Output verbosity level 

107 user_context: Optional user context for logging 

108 

109 Returns: 

110 Sanitized status data appropriate for the verbosity level 

111 """ 

112 # Log status access attempt 

113 self.security_logger.log_status_access_attempt( 

114 endpoint="status_data", 

115 verbosity_level=verbosity.value, 

116 user_context=user_context, 

117 data_keys=list(status_data.keys()), 

118 ) 

119 

120 # Deep copy to avoid modifying original 

121 sanitized = self._deep_copy_dict(status_data) 

122 

123 # Apply verbosity-based filtering 

124 sanitized = self._apply_verbosity_filter(sanitized, verbosity) 

125 

126 # Sanitize sensitive information 

127 sanitized = self._sanitize_sensitive_data(sanitized, verbosity) 

128 

129 # Add security metadata 

130 sanitized["_security"] = { 

131 "sanitized": True, 

132 "verbosity": verbosity.value, 

133 "timestamp": self._get_timestamp(), 

134 } 

135 

136 return sanitized 

137 

138 def _apply_verbosity_filter( 

139 self, data: dict[str, t.Any], verbosity: StatusVerbosity 

140 ) -> dict[str, t.Any]: 

141 """Apply verbosity-based key filtering.""" 

142 

143 # Keys to remove based on verbosity level 

144 if verbosity == StatusVerbosity.MINIMAL: 

145 remove_keys = self.SENSITIVE_KEYS["remove_minimal"] 

146 elif verbosity == StatusVerbosity.STANDARD: 

147 remove_keys = self.SENSITIVE_KEYS["remove_standard"] 

148 else: 

149 remove_keys = set() # Keep all keys for DETAILED/FULL 

150 

151 # Remove sensitive keys 

152 for key in list(data.keys()): 

153 if key in remove_keys: 

154 del data[key] 

155 

156 # Recursively apply to nested dictionaries 

157 for key, value in data.items(): 

158 if isinstance(value, dict): 

159 data[key] = self._apply_verbosity_filter(value, verbosity) 

160 

161 return data 

162 

163 def _sanitize_sensitive_data( 

164 self, data: dict[str, t.Any], verbosity: StatusVerbosity 

165 ) -> dict[str, t.Any]: 

166 """Sanitize sensitive data based on patterns and keys.""" 

167 

168 return self._sanitize_recursive(data, verbosity) 

169 

170 def _sanitize_recursive(self, obj: t.Any, verbosity: StatusVerbosity) -> t.Any: 

171 """Recursively sanitize data structures.""" 

172 

173 if isinstance(obj, dict): 

174 sanitized = {} 

175 for key, value in obj.items(): 

176 # Sanitize the key 

177 sanitized_key = self._sanitize_string(key, verbosity) 

178 

179 # Sanitize the value 

180 if ( 

181 key in self.SENSITIVE_KEYS["mask"] 

182 and verbosity != StatusVerbosity.FULL 

183 ): 

184 sanitized[sanitized_key] = self._mask_sensitive_value(str(value)) 

185 else: 

186 sanitized[sanitized_key] = self._sanitize_recursive( 

187 value, verbosity 

188 ) 

189 

190 return sanitized 

191 

192 elif isinstance(obj, list): 

193 return [self._sanitize_recursive(item, verbosity) for item in obj] 

194 

195 elif isinstance(obj, str): 

196 return self._sanitize_string(obj, verbosity) 

197 

198 else: 

199 return obj 

200 

201 def _sanitize_string(self, text: str, verbosity: StatusVerbosity) -> str: 

202 """Sanitize string content based on verbosity level.""" 

203 

204 if verbosity == StatusVerbosity.FULL: 

205 return text # No sanitization for full verbosity 

206 

207 sanitized = text 

208 

209 # Sanitize internal URLs FIRST (before other processing) 

210 sanitized = self._sanitize_internal_urls(sanitized) 

211 

212 # Sanitize absolute paths (convert to relative) 

213 sanitized = self._sanitize_paths(sanitized) 

214 

215 # Mask potential secrets (after URLs are already replaced) 

216 if verbosity == StatusVerbosity.MINIMAL: 

217 sanitized = self._mask_potential_secrets(sanitized) 

218 

219 return sanitized 

220 

221 def _sanitize_paths(self, text: str) -> str: 

222 """Convert absolute paths to relative paths where possible.""" 

223 

224 # More comprehensive path pattern that catches absolute paths 

225 path_patterns = [ 

226 r"/[a-zA-Z0-9_\-\.\/]+", # Unix-style absolute paths 

227 r"[A-Z]:[\\\/][a-zA-Z0-9_\-\.\\\/]+", # Windows-style absolute paths 

228 ] 

229 

230 for pattern in path_patterns: 

231 matches = re.findall(pattern, text) 

232 for match in matches: 

233 if len(match) > 3: # Only process paths longer than 3 chars 

234 try: 

235 abs_path = Path(match) 

236 if abs_path.is_absolute(): 

237 # Try to make relative to project root 

238 try: 

239 rel_path = abs_path.relative_to(self.project_root) 

240 text = text.replace(match, f"./{rel_path}") 

241 except (ValueError, OSError): 

242 # If not within project, mask it 

243 text = text.replace(match, "[REDACTED_PATH]") 

244 except (ValueError, OSError): 

245 # If path operations fail, mask it 

246 text = text.replace(match, "[REDACTED_PATH]") 

247 

248 return text 

249 

250 def _sanitize_internal_urls(self, text: str) -> str: 

251 """Replace internal URLs with generic placeholders.""" 

252 

253 # More comprehensive URL patterns 

254 url_patterns = [ 

255 r"https?://localhost:\d+[^\s]*", 

256 r"https?://127\.0\.0\.1:\d+[^\s]*", 

257 r"https?://0\.0\.0\.0:\d+[^\s]*", 

258 r"ws://localhost:\d+[^\s]*", 

259 r"ws://127\.0\.0\.1:\d+[^\s]*", 

260 r"http://localhost[^\s]*", 

261 r"ws://localhost[^\s]*", 

262 ] 

263 

264 for pattern in url_patterns: 

265 text = re.sub(pattern, "[INTERNAL_URL]", text) 

266 

267 return text 

268 

269 def _mask_potential_secrets(self, text: str) -> str: 

270 """Mask strings that might be secrets.""" 

271 

272 # Don't mask if it contains already sanitized content 

273 if "[INTERNAL_URL]" in text or "[REDACTED_PATH]" in text: 

274 return text 

275 

276 for pattern in self.SENSITIVE_PATTERNS["secrets"]: 

277 # Only mask if the string looks like a token (long alphanumeric) 

278 matches = re.findall(pattern, text) 

279 for match in matches: 

280 if len(match) > 16: # Only mask long strings 

281 # Don't mask if it looks like a URL or path component 

282 if not any(x in match for x in ["://", "/", "\\", "."]): 

283 masked = match[:4] + "*" * (len(match) - 8) + match[-4:] 

284 text = text.replace(match, masked) 

285 

286 return text 

287 

288 def _mask_sensitive_value(self, value: str) -> str: 

289 """Mask a known sensitive value.""" 

290 

291 if len(value) <= 4: 

292 return "***" 

293 elif len(value) <= 8: 

294 return value[0] + "*" * (len(value) - 1) 

295 else: 

296 return value[:2] + "*" * (len(value) - 4) + value[-2:] 

297 

298 def _deep_copy_dict(self, obj: t.Any) -> t.Any: 

299 """Deep copy a dictionary-like object safely.""" 

300 

301 if isinstance(obj, dict): 

302 return {key: self._deep_copy_dict(value) for key, value in obj.items()} 

303 elif isinstance(obj, list): 

304 return [self._deep_copy_dict(item) for item in obj] 

305 else: 

306 return obj 

307 

308 def _get_timestamp(self) -> float: 

309 """Get current timestamp.""" 

310 import time 

311 

312 return time.time() 

313 

314 def format_error_response( 

315 self, 

316 error_message: str, 

317 verbosity: StatusVerbosity = StatusVerbosity.STANDARD, 

318 include_details: bool = False, 

319 ) -> dict[str, t.Any]: 

320 """ 

321 Format error responses without leaking system details. 

322 

323 Args: 

324 error_message: Original error message 

325 verbosity: Output verbosity level 

326 include_details: Whether to include error details 

327 

328 Returns: 

329 Sanitized error response 

330 """ 

331 

332 # Generic error messages for production use 

333 generic_messages = { 

334 "connection": "Service temporarily unavailable. Please try again later.", 

335 "validation": "Invalid request parameters.", 

336 "permission": "Access denied.", 

337 "resource": "Requested resource not found.", 

338 "internal": "An internal error occurred. Please contact support.", 

339 } 

340 

341 # Determine error type and use appropriate generic message 

342 error_type = self._classify_error(error_message) 

343 

344 if verbosity == StatusVerbosity.MINIMAL: 

345 return { 

346 "success": False, 

347 "error": generic_messages.get(error_type, generic_messages["internal"]), 

348 "timestamp": self._get_timestamp(), 

349 } 

350 

351 # For higher verbosity levels, include sanitized original message 

352 sanitized_message = self._sanitize_string(error_message, verbosity) 

353 

354 response = { 

355 "success": False, 

356 "error": sanitized_message, 

357 "error_type": error_type, 

358 "timestamp": self._get_timestamp(), 

359 } 

360 

361 if include_details and verbosity in ( 

362 StatusVerbosity.DETAILED, 

363 StatusVerbosity.FULL, 

364 ): 

365 response["details"] = { 

366 "verbosity": verbosity.value, 

367 "sanitized": verbosity != StatusVerbosity.FULL, 

368 } 

369 

370 return response 

371 

372 def _classify_error(self, error_message: str) -> str: 

373 """Classify error message type for appropriate handling.""" 

374 

375 error_patterns = { 

376 "connection": ["connection", "timeout", "refused", "unavailable"], 

377 "validation": ["invalid", "validation", "format", "parameter"], 

378 "permission": ["permission", "access", "denied", "unauthorized"], 

379 "resource": ["not found", "missing", "does not exist"], 

380 } 

381 

382 error_lower = error_message.lower() 

383 

384 for error_type, patterns in error_patterns.items(): 

385 if any(pattern in error_lower for pattern in patterns): 

386 return error_type 

387 

388 return "internal" 

389 

390 

391# Singleton instance for global use 

392_secure_formatter: SecureStatusFormatter | None = None 

393 

394 

395def get_secure_status_formatter( 

396 project_root: Path | None = None, 

397) -> SecureStatusFormatter: 

398 """Get the global secure status formatter instance.""" 

399 

400 global _secure_formatter 

401 if _secure_formatter is None: 

402 _secure_formatter = SecureStatusFormatter(project_root) 

403 return _secure_formatter 

404 

405 

406def format_secure_status( 

407 status_data: dict[str, t.Any], 

408 verbosity: StatusVerbosity = StatusVerbosity.STANDARD, 

409 project_root: Path | None = None, 

410 user_context: str | None = None, 

411) -> dict[str, t.Any]: 

412 """ 

413 Convenience function for secure status formatting. 

414 

415 Args: 

416 status_data: Raw status data to sanitize 

417 verbosity: Output verbosity level 

418 project_root: Project root for relative path conversion 

419 user_context: Optional user context for logging 

420 

421 Returns: 

422 Sanitized status data 

423 """ 

424 

425 formatter = get_secure_status_formatter(project_root) 

426 return formatter.format_status(status_data, verbosity, user_context)