Coverage for src/taipanstack/utils/subprocess.py: 100%

98 statements  

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

1""" 

2Safe subprocess execution with security guards. 

3 

4Provides secure wrappers around subprocess execution with 

5command validation, timeout handling, and retry logic. 

6""" 

7 

8import math 

9import os 

10import shutil 

11import subprocess # nosec B404 

12import time 

13from collections.abc import Sequence 

14from dataclasses import dataclass 

15from pathlib import Path 

16 

17from taipanstack.security.guards import ( 

18 SecurityError, 

19 guard_command_injection, 

20) 

21 

22 

23@dataclass(frozen=True) 

24class SafeCommandResult: 

25 """Result of a safe command execution. 

26 

27 Attributes: 

28 command: The executed command. 

29 returncode: Exit code of the command. 

30 stdout: Standard output. 

31 stderr: Standard error. 

32 success: Whether the command succeeded (returncode == 0). 

33 duration_seconds: How long the command took. 

34 

35 """ 

36 

37 command: list[str] 

38 returncode: int 

39 stdout: str = "" 

40 stderr: str = "" 

41 duration_seconds: float = 0.0 

42 

43 @property 

44 def success(self) -> bool: 

45 """Check if command succeeded.""" 

46 return self.returncode == 0 

47 

48 def raise_on_error(self) -> "SafeCommandResult": 

49 """Raise an exception if command failed. 

50 

51 Returns: 

52 Self if successful. 

53 

54 Raises: 

55 subprocess.CalledProcessError: If command failed. 

56 

57 """ 

58 if not self.success: 

59 raise subprocess.CalledProcessError( 

60 self.returncode, 

61 self.command, 

62 self.stdout, 

63 self.stderr, 

64 ) 

65 return self 

66 

67 

68# Default allowed commands whitelist 

69DEFAULT_ALLOWED_COMMANDS: frozenset[str] = frozenset( 

70 { 

71 # Python/Poetry 

72 "python", 

73 "python3", 

74 "pip", 

75 "pip3", 

76 "poetry", 

77 "pipx", 

78 # Version control 

79 "git", 

80 # Build tools 

81 "make", 

82 # Testing 

83 "pytest", 

84 "mypy", 

85 "ruff", 

86 "bandit", 

87 "safety", 

88 "semgrep", 

89 "pre-commit", 

90 # System 

91 "echo", 

92 "cat", 

93 "ls", 

94 "pwd", 

95 "mkdir", 

96 "rm", 

97 "cp", 

98 "mv", 

99 "touch", 

100 "chmod", 

101 "which", 

102 }, 

103) 

104 

105 

106def _get_command_whitelist(allowed_commands: Sequence[str] | None) -> list[str]: 

107 if allowed_commands is not None: 

108 return list(allowed_commands) 

109 return list(DEFAULT_ALLOWED_COMMANDS) 

110 

111 

112def _validate_and_resolve_command( 

113 command: Sequence[str], 

114 allowed_commands: Sequence[str] | None, 

115) -> list[str]: 

116 """Validate and resolve a command. 

117 

118 Args: 

119 command: Command and arguments as a sequence. 

120 allowed_commands: Whitelist of allowed commands. 

121 

122 Returns: 

123 The validated command as a list. 

124 

125 Raises: 

126 SecurityError: If validation fails. 

127 

128 """ 

129 cmd_list = list(command) 

130 

131 if not cmd_list: 

132 raise SecurityError( 

133 "Empty command is not allowed", 

134 guard_name="safe_command", 

135 ) 

136 

137 whitelist = _get_command_whitelist(allowed_commands) 

138 

139 validated_cmd = guard_command_injection(cmd_list, allowed_commands=whitelist) 

140 

141 base_command = validated_cmd[0] 

142 if not shutil.which(base_command): 

143 raise SecurityError( 

144 f"Command not found: {base_command}", 

145 guard_name="safe_command", 

146 value=base_command, 

147 ) 

148 

149 return validated_cmd 

150 

151 

152def _get_allowed_keys(allowed_env_vars: Sequence[str] | None) -> set[str]: 

153 """Get the allowed environment variable keys. 

154 

155 Args: 

156 allowed_env_vars: Whitelist of allowed environment variable names. 

157 

158 Returns: 

159 Set of allowed keys in uppercase. 

160 

161 """ 

162 if allowed_env_vars is None: 

163 return {"PATH"} 

164 return {k.upper() for k in allowed_env_vars} 

165 

166 

167def _get_env_to_filter(env: dict[str, str] | None) -> dict[str, str]: 

168 """Get the environment to filter.""" 

169 return env if env is not None else dict(os.environ) 

170 

171 

172def _build_filtered_env( 

173 env_to_filter: dict[str, str], allowed_keys: set[str] 

174) -> dict[str, str]: 

175 """Build the filtered environment dictionary.""" 

176 if not allowed_keys: 

177 return {} 

178 return {k: str(v) for k, v in env_to_filter.items() if k.upper() in allowed_keys} 

179 

180 

181def _filter_environment( 

182 env: dict[str, str] | None, 

183 allowed_env_vars: Sequence[str] | None = None, 

184) -> dict[str, str]: 

185 """Filter environment variables for safe execution using a whitelist approach. 

186 

187 Args: 

188 env: Environment variables to filter. If None, uses os.environ. 

189 allowed_env_vars: Whitelist of allowed environment variable names. 

190 If None, only minimal necessary variables (e.g. PATH) are inherited. 

191 Pass an empty list for a completely empty environment. 

192 

193 Returns: 

194 Filtered environment variables containing only allowed keys. 

195 

196 """ 

197 env_to_filter = _get_env_to_filter(env) 

198 allowed_keys = _get_allowed_keys(allowed_env_vars) 

199 return _build_filtered_env(env_to_filter, allowed_keys) 

200 

201 

202def _extract_timeout_stdout(e: subprocess.TimeoutExpired) -> str: 

203 """Extract stdout from a TimeoutExpired exception safely. 

204 

205 Args: 

206 e: The TimeoutExpired exception. 

207 

208 Returns: 

209 The extracted stdout string. 

210 

211 """ 

212 if not hasattr(e, "stdout") or e.stdout is None: 

213 return "" 

214 if isinstance(e.stdout, str): # type: ignore[unreachable] 

215 return e.stdout # type: ignore[unreachable] 

216 return e.stdout.decode("utf-8", errors="replace") 

217 

218 

219def _execute_command( 

220 validated_cmd: list[str], 

221 cwd: Path | None, 

222 timeout: float, 

223 capture_output: bool, 

224 safe_env: dict[str, str], 

225) -> SafeCommandResult: 

226 """Execute the command and handle TimeoutExpired. 

227 

228 Args: 

229 validated_cmd: Validated command list. 

230 cwd: Resolved working directory. 

231 timeout: Execution timeout. 

232 capture_output: Capture stdout/stderr. 

233 safe_env: Filtered environment variables. 

234 

235 Returns: 

236 The execution result. 

237 

238 """ 

239 start_time = time.time() 

240 

241 try: 

242 result = subprocess.run( # nosec B603 

243 validated_cmd, 

244 cwd=cwd, 

245 timeout=timeout, 

246 capture_output=capture_output, 

247 text=True, 

248 encoding="utf-8", 

249 env=safe_env, 

250 check=False, 

251 ) 

252 except subprocess.TimeoutExpired as e: 

253 duration = time.time() - start_time 

254 return SafeCommandResult( 

255 command=validated_cmd, 

256 returncode=-1, 

257 stdout=_extract_timeout_stdout(e), 

258 stderr=f"Command timed out after {timeout}s", 

259 duration_seconds=duration, 

260 ) 

261 

262 duration = time.time() - start_time 

263 

264 return SafeCommandResult( 

265 command=validated_cmd, 

266 returncode=result.returncode, 

267 stdout=result.stdout or "", 

268 stderr=result.stderr or "", 

269 duration_seconds=duration, 

270 ) 

271 

272 

273def _validate_cwd(cwd: Path | str | None) -> Path | None: 

274 """Resolve and validate the working directory.""" 

275 if cwd is None: 

276 return None 

277 resolved_cwd = Path(cwd).resolve() 

278 if not resolved_cwd.exists(): 

279 raise SecurityError( 

280 f"Working directory does not exist: {cwd}", 

281 guard_name="safe_command", 

282 ) 

283 return resolved_cwd 

284 

285 

286def _handle_dry_run(validated_cmd: list[str]) -> SafeCommandResult: 

287 """Return a SafeCommandResult for a dry run execution.""" 

288 return SafeCommandResult( 

289 command=validated_cmd, 

290 returncode=0, 

291 stdout=f"[DRY-RUN] Would execute: {' '.join(validated_cmd)}", 

292 stderr="", 

293 duration_seconds=0.0, 

294 ) 

295 

296 

297def _check_timeout_type(timeout: float) -> None: 

298 """Check if timeout is a number.""" 

299 if not isinstance(timeout, (int, float)): 

300 raise TypeError("timeout must be a finite non-negative number") 

301 

302 

303def _check_timeout_value(timeout: float) -> None: 

304 """Check if timeout is finite and non-negative.""" 

305 if not math.isfinite(timeout) or timeout < 0: 

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

307 

308 

309def _validate_timeout(timeout: float) -> None: 

310 """Validate that the timeout is a finite, non-negative number. 

311 

312 Args: 

313 timeout: The timeout value to validate. 

314 

315 Raises: 

316 ValueError: If timeout is invalid. 

317 

318 """ 

319 if timeout is None: 

320 return # type: ignore[unreachable] 

321 

322 _check_timeout_type(timeout) 

323 _check_timeout_value(timeout) 

324 

325 

326def run_safe_command( 

327 command: Sequence[str], 

328 *, 

329 cwd: Path | str | None = None, 

330 timeout: float = 300.0, 

331 capture_output: bool = True, 

332 check: bool = False, 

333 allowed_commands: Sequence[str] | None = None, 

334 env: dict[str, str] | None = None, 

335 allowed_env_vars: Sequence[str] | None = None, 

336 dry_run: bool = False, 

337) -> SafeCommandResult: 

338 """Execute a command safely with security guards. 

339 

340 This function provides a secure wrapper around subprocess.run 

341 with command injection protection, timeout handling, and 

342 optional command whitelisting. 

343 

344 Args: 

345 command: Command and arguments as a sequence. 

346 cwd: Working directory for the command. 

347 timeout: Maximum execution time in seconds. 

348 capture_output: Whether to capture stdout/stderr. 

349 check: Whether to raise on non-zero exit. 

350 allowed_commands: Whitelist of allowed commands. 

351 env: Environment variables to set. 

352 allowed_env_vars: Whitelist of allowed environment variables. 

353 dry_run: If True, don't actually execute the command. 

354 

355 Returns: 

356 SafeCommandResult with execution details. 

357 

358 Raises: 

359 SecurityError: If command validation fails. 

360 subprocess.TimeoutExpired: If command times out. 

361 subprocess.CalledProcessError: If check=True and command fails. 

362 

363 Example: 

364 >>> result = run_safe_command(["poetry", "install"]) 

365 >>> if result.success: 

366 ... print("Installation complete!") 

367 

368 """ 

369 # Security Enhancement: Prevent DoS via infinite blocking behaviors or 

370 # unhandled exceptions from threading/asyncio primitives by explicitly 

371 # validating that timeout is a finite, non-negative number. 

372 _validate_timeout(timeout) 

373 

374 validated_cmd = _validate_and_resolve_command(command, allowed_commands) 

375 safe_env = _filter_environment(env, allowed_env_vars) 

376 

377 if dry_run: 

378 return _handle_dry_run(validated_cmd) 

379 

380 resolved_cwd = _validate_cwd(cwd) 

381 

382 safe_result = _execute_command( 

383 validated_cmd, 

384 resolved_cwd, 

385 timeout, 

386 capture_output, 

387 safe_env, 

388 ) 

389 

390 if check: 

391 safe_result.raise_on_error() 

392 

393 return safe_result