Coverage for src/taipanstack/security/decorators.py: 100%

151 statements  

« prev     ^ index     » next       coverage.py v7.15.1, created at 2026-11-23 17:43 +0000

1""" 

2Security decorators for robust Python applications. 

3 

4Provides decorators for input validation, exception handling, 

5timeout control, and other security patterns. Compatible with 

6any Python framework (Flask, FastAPI, Django, etc.). 

7""" 

8 

9import functools 

10import inspect 

11import math 

12import signal 

13import sys 

14import threading 

15from collections.abc import Callable 

16from types import FrameType 

17from typing import ParamSpec, TypeVar 

18 

19from taipanstack.security.guards import SecurityError 

20 

21P = ParamSpec("P") 

22R = TypeVar("R") 

23T = TypeVar("T") 

24 

25 

26def _apply_single_validator( 

27 param_name: str, 

28 value: object, 

29 validator: Callable[[object], object], 

30) -> object | None: 

31 try: 

32 return validator(value) 

33 except (ValueError, TypeError) as e: 

34 raise ValidationError( 

35 str(e), 

36 param_name=param_name, 

37 value=repr(value)[:100], 

38 ) from e 

39 

40 

41def _process_single_bound_argument( 

42 bound: inspect.BoundArguments, 

43 param_name: str, 

44 validator: Callable[[object], object], 

45) -> None: 

46 if param_name not in bound.arguments: # type: ignore[misc] 

47 return 

48 value = bound.arguments[param_name] # type: ignore[misc] 

49 validated = _apply_single_validator(param_name, value, validator) # type: ignore[misc] 

50 if validated is not None: 

51 bound.arguments[param_name] = validated # type: ignore[misc] 

52 

53 

54def _validate_bound_arguments( 

55 bound: inspect.BoundArguments, 

56 validators: dict[str, Callable[[object], object]], 

57) -> None: 

58 for param_name, validator in validators.items(): 

59 _process_single_bound_argument(bound, param_name, validator) 

60 

61 

62def _log_guarded_exception(e: Exception, func_name: str) -> None: 

63 import logging 

64 

65 logging.getLogger("taipanstack.security").warning( 

66 "Exception caught in %s: %s", 

67 func_name, 

68 str(e), 

69 ) 

70 

71 

72def _reraise_guarded_exception(e: Exception, reraise_as: type[Exception]) -> None: 

73 if reraise_as == SecurityError: 

74 raise SecurityError( 

75 str(e), 

76 guard_name="guard_exceptions", 

77 ) from e 

78 raise reraise_as(str(e)) from e 

79 

80 

81def _handle_guarded_exception( 

82 e: Exception, 

83 func_name: str, 

84 reraise_as: type[Exception] | None, 

85 log_errors: bool, 

86) -> None: 

87 if log_errors: 

88 _log_guarded_exception(e, func_name) 

89 

90 if reraise_as is not None: 

91 _reraise_guarded_exception(e, reraise_as) 

92 

93 

94def _check_bound_types( 

95 bound: inspect.BoundArguments, 

96 type_hints: dict[str, type], 

97) -> None: 

98 for param_name, expected_type in type_hints.items(): 

99 if param_name in bound.arguments: # type: ignore[misc] 

100 value = bound.arguments[param_name] # type: ignore[misc] 

101 if not isinstance(value, expected_type): # type: ignore[misc] 

102 raise TypeError( 

103 f"Parameter '{param_name}' expected " 

104 f"{expected_type.__name__}, got {type(value).__name__}", # type: ignore[misc] 

105 ) 

106 

107 

108class OperationTimeoutError(Exception): 

109 """Raised when a function exceeds its timeout limit.""" 

110 

111 def __init__(self, seconds: float, func_name: str = "function") -> None: 

112 """Initialize OperationTimeoutError. 

113 

114 Args: 

115 seconds: The timeout that was exceeded. 

116 func_name: Name of the function that timed out. 

117 

118 """ 

119 self.seconds = seconds 

120 self.func_name = func_name 

121 super().__init__(f"{func_name} timed out after {seconds} seconds") 

122 

123 

124class ValidationError(Exception): 

125 """Raised when input validation fails.""" 

126 

127 def __init__( 

128 self, 

129 message: str, 

130 param_name: str | None = None, 

131 value: object = None, 

132 ) -> None: 

133 """Initialize ValidationError. 

134 

135 Args: 

136 message: Description of the validation failure. 

137 param_name: Name of the parameter that failed. 

138 value: The invalid value (sanitized). 

139 

140 """ 

141 self.param_name = param_name 

142 self.value = value 

143 super().__init__(message) 

144 

145 

146def validate_inputs( 

147 **validators: Callable[[object], object], 

148) -> Callable[[Callable[P, R]], Callable[P, R]]: 

149 """Decorator to validate function inputs. 

150 

151 Validates function arguments using provided validator functions. 

152 Validators should raise ValueError or ValidationError on invalid input. 

153 

154 Args: 

155 **validators: Mapping of parameter names to validator functions. 

156 

157 Returns: 

158 Decorated function with input validation. 

159 

160 Example: 

161 >>> from taipanstack.security.validators import validate_email, validate_port 

162 >>> @validate_inputs(email=validate_email, port=validate_port) 

163 ... def connect(email: str, port: int) -> None: 

164 ... pass 

165 >>> connect(email="invalid", port=8080) 

166 ValidationError: Invalid email format: invalid 

167 

168 """ 

169 

170 def decorator(func: Callable[P, R]) -> Callable[P, R]: 

171 sig = inspect.signature(func) 

172 

173 @functools.wraps(func) 

174 def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: 

175 # Bind and apply defaults on each call 

176 bound = sig.bind(*args, **kwargs) 

177 bound.apply_defaults() 

178 

179 # Validate each parameter that has a validator 

180 _validate_bound_arguments(bound, validators) 

181 

182 # Call original function with validated arguments 

183 return func(*bound.args, **bound.kwargs) # type: ignore[misc] 

184 

185 return wrapper 

186 

187 return decorator 

188 

189 

190def guard_exceptions( 

191 *, 

192 catch: tuple[type[Exception], ...] = (Exception,), 

193 reraise_as: type[Exception] | None = None, 

194 default: T | None = None, 

195 log_errors: bool = True, 

196) -> Callable[[Callable[P, R]], Callable[P, R | T | None]]: 

197 """Decorator to safely handle exceptions. 

198 

199 Catches exceptions and optionally re-raises as a different type 

200 or returns a default value. 

201 

202 Args: 

203 catch: Exception types to catch. 

204 reraise_as: Exception type to re-raise as (None = don't reraise). 

205 default: Default value to return if exception caught and not reraised. 

206 log_errors: Whether to log caught exceptions. 

207 

208 Returns: 

209 Decorated function with exception handling. 

210 

211 Example: 

212 >>> @guard_exceptions(catch=(IOError,), reraise_as=SecurityError) 

213 ... def read_file(path: str) -> str: 

214 ... return open(path).read() 

215 >>> read_file("/nonexistent") 

216 SecurityError: [guard_exceptions] ... 

217 

218 """ 

219 

220 def decorator(func: Callable[P, R]) -> Callable[P, R | T | None]: 

221 @functools.wraps(func) 

222 def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | T | None: 

223 try: 

224 return func(*args, **kwargs) 

225 except catch as e: 

226 _handle_guarded_exception(e, func.__name__, reraise_as, log_errors) 

227 return default 

228 

229 return wrapper 

230 

231 return decorator 

232 

233 

234def _validate_timeout_seconds(seconds: float) -> None: 

235 """Validate timeout duration.""" 

236 if ( 

237 not isinstance(seconds, (int, float)) 

238 or not math.isfinite(seconds) 

239 or seconds < 0 

240 ): 

241 raise ValueError("timeout must be a finite non-negative number") 

242 

243 

244def _is_signal_supported(use_signal: bool) -> bool: 

245 """Check if signal-based timeout can be used.""" 

246 return ( 

247 use_signal 

248 and sys.platform != "win32" 

249 and threading.current_thread() is threading.main_thread() 

250 ) 

251 

252 

253def timeout( 

254 seconds: float, 

255 *, 

256 use_signal: bool = True, 

257) -> Callable[[Callable[P, R]], Callable[P, R]]: 

258 """Decorator to limit function execution time. 

259 

260 Uses signal-based timeout on Unix or thread-based on Windows. 

261 Signal-based is more reliable but only works in main thread. 

262 

263 Args: 

264 seconds: Maximum execution time in seconds. 

265 use_signal: Use signal-based timeout (Unix only, main thread only). 

266 

267 Returns: 

268 Decorated function with timeout. 

269 

270 Example: 

271 >>> @timeout(5.0) 

272 ... def slow_operation() -> str: 

273 ... import time 

274 ... time.sleep(10) 

275 ... return "done" 

276 >>> slow_operation() 

277 TimeoutError: slow_operation timed out after 5.0 seconds 

278 

279 """ 

280 # Security Enhancement: explicitly validate bounds using math.isfinite() 

281 # and check for non-negative limits to prevent silent NaN propagation, 

282 # unhandled ValueError exceptions from threading/asyncio primitives, 

283 # or unexpected infinite blocking behaviors. 

284 _validate_timeout_seconds(seconds) 

285 

286 def decorator(func: Callable[P, R]) -> Callable[P, R]: 

287 @functools.wraps(func) 

288 def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: 

289 if _is_signal_supported(use_signal): 

290 return _timeout_with_signal( 

291 func, 

292 seconds, 

293 args, 

294 dict(kwargs), 

295 ) 

296 return _timeout_with_thread( 

297 func, 

298 seconds, 

299 args, 

300 dict(kwargs), 

301 ) 

302 

303 return wrapper 

304 

305 return decorator 

306 

307 

308def _timeout_with_signal( 

309 func: Callable[..., R], 

310 seconds: float, 

311 args: tuple[object, ...], 

312 kwargs: dict[str, object], 

313) -> R: 

314 """Implement timeout using Unix signals.""" 

315 

316 def handler(_signum: int, _frame: FrameType | None) -> None: 

317 raise OperationTimeoutError(seconds, func.__name__) # type: ignore[misc] 

318 

319 # Set up signal handler 

320 old_handler = signal.signal(signal.SIGALRM, handler) 

321 signal.setitimer(signal.ITIMER_REAL, seconds) 

322 

323 try: 

324 return func(*args, **kwargs) 

325 finally: 

326 # Restore old handler and cancel alarm 

327 signal.setitimer(signal.ITIMER_REAL, 0) 

328 signal.signal(signal.SIGALRM, old_handler) 

329 

330 

331def _check_thread_timeout( 

332 thread: threading.Thread, seconds: float, func_name: str 

333) -> None: 

334 """Raise OperationTimeoutError if the thread is still running.""" 

335 if thread.is_alive(): 

336 raise OperationTimeoutError(seconds, func_name) 

337 

338 

339def _check_thread_exception(exception: list[BaseException]) -> None: 

340 """Raise the first exception if the thread encountered any.""" 

341 if exception: 

342 raise exception[0] 

343 

344 

345def _timeout_with_thread( 

346 func: Callable[..., R], 

347 seconds: float, 

348 args: tuple[object, ...], 

349 kwargs: dict[str, object], 

350) -> R: 

351 """Implement timeout using a separate thread.""" 

352 result: list[R] = [] 

353 exception: list[BaseException] = [] 

354 

355 def target() -> None: 

356 try: 

357 result.append(func(*args, **kwargs)) 

358 except BaseException as e: 

359 exception.append(e) 

360 

361 thread = threading.Thread(target=target) 

362 thread.daemon = True 

363 thread.start() 

364 thread.join(timeout=seconds) 

365 

366 _check_thread_timeout(thread, seconds, func.__name__) # type: ignore[misc] 

367 _check_thread_exception(exception) 

368 

369 return result[0] 

370 

371 

372def _build_deprecation_message( 

373 func_name: str, message: str, removal_version: str | None 

374) -> str: 

375 """Build the deprecation warning message.""" 

376 msg = f"{func_name} is deprecated." 

377 if removal_version: 

378 msg += f" Will be removed in version {removal_version}." 

379 if message: 

380 msg += f" {message}" 

381 return msg 

382 

383 

384def deprecated( 

385 message: str = "", 

386 *, 

387 removal_version: str | None = None, 

388) -> Callable[[Callable[P, R]], Callable[P, R]]: 

389 """Mark a function as deprecated. 

390 

391 Emits a warning when the decorated function is called. 

392 

393 Args: 

394 message: Additional deprecation message. 

395 removal_version: Version when function will be removed. 

396 

397 Returns: 

398 Decorated function that warns on use. 

399 

400 Example: 

401 >>> @deprecated("Use new_function instead", removal_version="2.0") 

402 ... def old_function() -> None: 

403 ... pass 

404 

405 """ 

406 

407 def decorator(func: Callable[P, R]) -> Callable[P, R]: 

408 @functools.wraps(func) 

409 def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: 

410 import warnings 

411 

412 msg = _build_deprecation_message(func.__name__, message, removal_version) 

413 

414 warnings.warn(msg, DeprecationWarning, stacklevel=2) 

415 return func(*args, **kwargs) 

416 

417 return wrapper 

418 

419 return decorator 

420 

421 

422def require_type( 

423 **type_hints: type, 

424) -> Callable[[Callable[P, R]], Callable[P, R]]: 

425 """Decorator to enforce runtime type checking. 

426 

427 Validates that arguments match specified types at runtime. 

428 

429 Args: 

430 **type_hints: Mapping of parameter names to expected types. 

431 

432 Returns: 

433 Decorated function with type checking. 

434 

435 Example: 

436 >>> @require_type(name=str, count=int) 

437 ... def greet(name: str, count: int) -> None: 

438 ... print(f"Hello {name}" * count) 

439 >>> greet(name=123, count=2) 

440 TypeError: Parameter 'name' expected str, got int 

441 

442 """ 

443 

444 def decorator(func: Callable[P, R]) -> Callable[P, R]: 

445 sig = inspect.signature(func) 

446 

447 @functools.wraps(func) 

448 def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: 

449 bound = sig.bind(*args, **kwargs) 

450 bound.apply_defaults() 

451 

452 _check_bound_types(bound, type_hints) 

453 

454 return func(*bound.args, **bound.kwargs) # type: ignore[misc] 

455 

456 return wrapper 

457 

458 return decorator