taipanstack 0.4.7__tar.gz → 0.4.8__tar.gz

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 (53) hide show
  1. {taipanstack-0.4.7 → taipanstack-0.4.8}/PKG-INFO +10 -10
  2. {taipanstack-0.4.7 → taipanstack-0.4.8}/README.md +9 -9
  3. {taipanstack-0.4.7 → taipanstack-0.4.8}/pyproject.toml +2 -2
  4. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/__init__.py +1 -1
  5. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/bridges/http_bridge.py +48 -22
  6. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/bridges/web_bridge.py +52 -24
  7. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/core/result.py +14 -4
  8. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/resilience/circuit_breaker.py +55 -15
  9. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/resilience/retry.py +38 -21
  10. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/resilience/watchdogs/health_pinger.py +22 -18
  11. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/resilience/watchdogs/resource_watcher.py +16 -18
  12. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/security/models.py +5 -7
  13. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/security/password.py +12 -16
  14. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/security/validators.py +29 -16
  15. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/utils/filesystem.py +4 -0
  16. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/utils/logging.py +34 -25
  17. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/utils/rate_limit.py +31 -33
  18. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/utils/serialization.py +7 -9
  19. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/utils/subprocess.py +50 -21
  20. {taipanstack-0.4.7 → taipanstack-0.4.8}/LICENSE +0 -0
  21. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/bridges/__init__.py +0 -0
  22. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/bridges/_imports.py +0 -0
  23. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/bridges/db_bridge.py +0 -0
  24. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/config/__init__.py +0 -0
  25. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/config/generators.py +0 -0
  26. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/config/models.py +0 -0
  27. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/config/version_config.py +0 -0
  28. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/core/__init__.py +0 -0
  29. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/core/compat.py +0 -0
  30. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/core/optimizations.py +0 -0
  31. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/resilience/__init__.py +0 -0
  32. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/resilience/adaptive/__init__.py +0 -0
  33. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/resilience/adaptive/adaptive_breaker.py +0 -0
  34. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/resilience/adaptive/adaptive_retry.py +0 -0
  35. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/resilience/adaptive/bulkhead.py +0 -0
  36. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/resilience/adaptive/orchestrator.py +0 -0
  37. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/resilience/resilience.py +0 -0
  38. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/resilience/watchdogs/__init__.py +0 -0
  39. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/resilience/watchdogs/_base.py +0 -0
  40. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/resilience/watchdogs/config_watcher.py +0 -0
  41. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/security/__init__.py +0 -0
  42. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/security/decorators.py +0 -0
  43. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/security/guards.py +0 -0
  44. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/security/jwt.py +0 -0
  45. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/security/sanitizers.py +0 -0
  46. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/security/types.py +0 -0
  47. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/utils/__init__.py +0 -0
  48. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/utils/cache.py +0 -0
  49. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/utils/circuit_breaker.py +0 -0
  50. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/utils/concurrency.py +0 -0
  51. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/utils/context.py +0 -0
  52. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/utils/resilience.py +0 -0
  53. {taipanstack-0.4.7 → taipanstack-0.4.8}/src/taipanstack/utils/retry.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: taipanstack
3
- Version: 0.4.7
3
+ Version: 0.4.8
4
4
  Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -87,12 +87,12 @@ Description-Content-Type: text/markdown
87
87
 
88
88
  Taipan Stack is a battle-tested foundation for production-grade Python projects that combines **security**, **performance**, and **developer experience** into a single, cohesive toolkit.
89
89
 
90
- ### ✨ What's New in v0.4.7
91
- - **Security Hardening**: Fixed TOCTOU, SSRF Unicode bypasses, and hardened Argon2 password verification (PR #663, #667, #661).
92
- - **Resource Resilience**: Handled system resource exhaustion in Bulkhead and hardened adaptive orchestrator (PR #662, #668).
93
- - **Complexity Reduction**: Significantly reduced cyclomatic complexity across core resilience and circuit breaker modules (PR #680, #676, #666).
94
- - **Test Suite Audit**: Comprehensive audit and refactor of the entire suite for strict compliance and isolation (PR #683, #671, #665).
95
- - **Total Stack Coverage**: Reached **1,299 passing tests** with 100% verified genuine coverage across all modules.
90
+ ### ✨ What's New in v0.4.8
91
+ - **Hardening Resilience**: Hardened `RateLimiter` and `CircuitBreaker` against state corruption and type mutations via chaos testing (PR #689, #684).
92
+ - **Complexity Reduction**: Major reduction of cyclomatic complexity across core modules, subprocess utilities, and web bridges (PR #706, #692).
93
+ - **Security Hardening**: Restored missing type guard for password verification and enhanced durability of atomic writes (Commit f83b6745, PR #688).
94
+ - **Performance**: Implemented concurrent execution for async health checks in `HealthPinger` (PR #694).
95
+ - **Total Stack Coverage**: Reached **1,315 passing tests** with 100% verified genuine coverage across all modules.
96
96
 
97
97
  <table>
98
98
  <tr>
@@ -130,7 +130,7 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
130
130
 
131
131
  ### 🔧 Developer Experience
132
132
  - Pre-configured quality tools
133
- - **100% code coverage** (1299 tests)
133
+ - **100% code coverage** (1315 tests)
134
134
  - Architecture enforcement
135
135
  - Hardened Docker template
136
136
 
@@ -172,7 +172,7 @@ make all
172
172
  ### Verify Installation
173
173
 
174
174
  ```bash
175
- # Run tests with 100% coverage (1299 tests)
175
+ # Run tests with 100% coverage (1315 tests)
176
176
  make test
177
177
 
178
178
  # Check architecture contracts
@@ -227,7 +227,7 @@ TaipanStack/
227
227
  │ ├── config/ # ⚙️ Configuration models & generators
228
228
  │ ├── security/ # 🛡️ Guards, sanitizers, validators
229
229
  │ └── utils/ # 🔧 Logging, metrics, retry, filesystem
230
- ├── tests/ # ✅ 1299 tests, 100% coverage
230
+ ├── tests/ # ✅ 1315 tests, 100% coverage
231
231
  ├── .semgrep/ # 🔍 Custom SAST rules
232
232
  ├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
233
233
  ├── Dockerfile # 🐳 Hardened multi-stage container
@@ -30,12 +30,12 @@
30
30
 
31
31
  Taipan Stack is a battle-tested foundation for production-grade Python projects that combines **security**, **performance**, and **developer experience** into a single, cohesive toolkit.
32
32
 
33
- ### ✨ What's New in v0.4.7
34
- - **Security Hardening**: Fixed TOCTOU, SSRF Unicode bypasses, and hardened Argon2 password verification (PR #663, #667, #661).
35
- - **Resource Resilience**: Handled system resource exhaustion in Bulkhead and hardened adaptive orchestrator (PR #662, #668).
36
- - **Complexity Reduction**: Significantly reduced cyclomatic complexity across core resilience and circuit breaker modules (PR #680, #676, #666).
37
- - **Test Suite Audit**: Comprehensive audit and refactor of the entire suite for strict compliance and isolation (PR #683, #671, #665).
38
- - **Total Stack Coverage**: Reached **1,299 passing tests** with 100% verified genuine coverage across all modules.
33
+ ### ✨ What's New in v0.4.8
34
+ - **Hardening Resilience**: Hardened `RateLimiter` and `CircuitBreaker` against state corruption and type mutations via chaos testing (PR #689, #684).
35
+ - **Complexity Reduction**: Major reduction of cyclomatic complexity across core modules, subprocess utilities, and web bridges (PR #706, #692).
36
+ - **Security Hardening**: Restored missing type guard for password verification and enhanced durability of atomic writes (Commit f83b6745, PR #688).
37
+ - **Performance**: Implemented concurrent execution for async health checks in `HealthPinger` (PR #694).
38
+ - **Total Stack Coverage**: Reached **1,315 passing tests** with 100% verified genuine coverage across all modules.
39
39
 
40
40
  <table>
41
41
  <tr>
@@ -73,7 +73,7 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
73
73
 
74
74
  ### 🔧 Developer Experience
75
75
  - Pre-configured quality tools
76
- - **100% code coverage** (1299 tests)
76
+ - **100% code coverage** (1315 tests)
77
77
  - Architecture enforcement
78
78
  - Hardened Docker template
79
79
 
@@ -115,7 +115,7 @@ make all
115
115
  ### Verify Installation
116
116
 
117
117
  ```bash
118
- # Run tests with 100% coverage (1299 tests)
118
+ # Run tests with 100% coverage (1315 tests)
119
119
  make test
120
120
 
121
121
  # Check architecture contracts
@@ -170,7 +170,7 @@ TaipanStack/
170
170
  │ ├── config/ # ⚙️ Configuration models & generators
171
171
  │ ├── security/ # 🛡️ Guards, sanitizers, validators
172
172
  │ └── utils/ # 🔧 Logging, metrics, retry, filesystem
173
- ├── tests/ # ✅ 1299 tests, 100% coverage
173
+ ├── tests/ # ✅ 1315 tests, 100% coverage
174
174
  ├── .semgrep/ # 🔍 Custom SAST rules
175
175
  ├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
176
176
  ├── Dockerfile # 🐳 Hardened multi-stage container
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "taipanstack"
3
- version = "0.4.7"
3
+ version = "0.4.8"
4
4
  description = "TaipanStack - Modular, secure, and scalable Python stack for robust development"
5
5
  authors = [
6
6
  {name = "gabrielima7", email = "gabrielima.alu.lmb@gmail.com"}
@@ -107,7 +107,7 @@ dev = [
107
107
  "pygments (>=2.19.2)",
108
108
  "hypothesis (>=6.151.12,<7.0.0)",
109
109
  "authlib (>=1.6.11,<2.0.0)",
110
- "cryptography (>=46.0.7,<48.0.0)",
110
+ "cryptography (>=46.0.7,<49.0.0)",
111
111
  "nltk (>=3.9.4,<4.0.0)",
112
112
  "mutmut (>=3.0.0,<4.0.0)",
113
113
  "pip (>=26.1,<27.0)",
@@ -5,7 +5,7 @@ A modular, secure, and scalable Python stack for robust development.
5
5
  Supports Python 3.11+ with version-aware optimizations for 3.13/3.14.
6
6
  """
7
7
 
8
- __version__ = "0.4.7"
8
+ __version__ = "0.4.8"
9
9
 
10
10
  from taipanstack.config.version_config import (
11
11
  VersionRecommendations,
@@ -165,6 +165,42 @@ async def _handle_http_exception(
165
165
  return False
166
166
 
167
167
 
168
+ async def _execute_single_attempt(
169
+ request_func: Callable[[], Awaitable[httpx.Response]],
170
+ retry_config: RetryConfig | None,
171
+ circuit_breaker: CircuitBreaker | None,
172
+ retryable_status_codes: frozenset[int],
173
+ attempt: int,
174
+ max_attempts: int,
175
+ ) -> Result[httpx.Response, Exception] | Exception | bool:
176
+ """Execute a single HTTP attempt.
177
+
178
+ Returns Result on success/final failure, Exception if it failed and we
179
+ should record it, or True if we should just retry because of status code.
180
+ """
181
+ try:
182
+ response = await request_func()
183
+ if _should_retry_status(
184
+ response,
185
+ retry_config,
186
+ retryable_status_codes,
187
+ attempt,
188
+ max_attempts,
189
+ ):
190
+ # Config is not None if we reach here
191
+ delay = calculate_delay(attempt, cast(RetryConfig, retry_config))
192
+ await asyncio.sleep(min(delay, 3600.0))
193
+ return True
194
+ return Ok(response)
195
+ except Exception as exc:
196
+ should_retry = await _handle_http_exception(
197
+ exc, attempt, max_attempts, retry_config, circuit_breaker
198
+ )
199
+ if should_retry:
200
+ return exc
201
+ return Err(exc)
202
+
203
+
168
204
  async def _execute_with_retries(
169
205
  request_func: Callable[[], Awaitable[httpx.Response]],
170
206
  retry_config: RetryConfig | None,
@@ -187,28 +223,18 @@ async def _execute_with_retries(
187
223
  last_error: Exception | None = None
188
224
 
189
225
  for attempt in range(1, max_attempts + 1):
190
- try:
191
- response = await request_func()
192
- if _should_retry_status(
193
- response,
194
- retry_config,
195
- retryable_status_codes,
196
- attempt,
197
- max_attempts,
198
- ):
199
- # Config is not None if we reach here
200
- delay = calculate_delay(attempt, cast(RetryConfig, retry_config))
201
- await asyncio.sleep(min(delay, 3600.0))
202
- continue
203
- return Ok(response)
204
- except Exception as exc:
205
- last_error = exc
206
- should_retry = await _handle_http_exception(
207
- exc, attempt, max_attempts, retry_config, circuit_breaker
208
- )
209
- if should_retry:
210
- continue
211
- break
226
+ outcome = await _execute_single_attempt(
227
+ request_func,
228
+ retry_config,
229
+ circuit_breaker,
230
+ retryable_status_codes,
231
+ attempt,
232
+ max_attempts,
233
+ )
234
+ if isinstance(outcome, (Ok, Err)):
235
+ return outcome
236
+ if isinstance(outcome, Exception):
237
+ last_error = outcome
212
238
 
213
239
  return Err(last_error or RuntimeError("Request failed"))
214
240
 
@@ -177,6 +177,56 @@ class TaipanMiddleware:
177
177
  self._security_headers = security_headers
178
178
  self._headers_config = headers_config or SecurityHeadersConfig()
179
179
 
180
+ def _wrap_send_with_security_headers(self, send: Send) -> Send:
181
+ """Wrap the send callable to inject security headers if enabled.
182
+
183
+ Args:
184
+ send: The original ASGI send callable.
185
+
186
+ Returns:
187
+ The wrapped ASGI send callable.
188
+
189
+ """
190
+ if not self._security_headers:
191
+ return send
192
+
193
+ extra_headers = self._headers_config.to_headers()
194
+
195
+ async def send_with_headers(message: MutableMapping[str, object]) -> None:
196
+ if message.get("type") == "http.response.start":
197
+ headers = message.get("headers")
198
+ existing = list(headers) if isinstance(headers, list) else []
199
+ existing.extend(extra_headers)
200
+ message["headers"] = existing
201
+ await send(message)
202
+
203
+ return send_with_headers
204
+
205
+ async def _handle_rate_limit(self, send: Send) -> bool:
206
+ """Apply rate limiting and send response if exceeded.
207
+
208
+ Args:
209
+ send: ASGI send callable.
210
+
211
+ Returns:
212
+ True if rate limit was exceeded, False otherwise.
213
+
214
+ """
215
+ if self._rate_limiter is None or self._rate_limiter.consume():
216
+ return False
217
+
218
+ logger.warning("Rate limit exceeded for request")
219
+ security_hdrs = (
220
+ self._headers_config.to_headers() if self._security_headers else None
221
+ )
222
+ await _send_json_response(
223
+ send,
224
+ status=429,
225
+ body={"error": "Rate limit exceeded", "retry_after": 1},
226
+ extra_headers=security_hdrs,
227
+ )
228
+ return True
229
+
180
230
  async def __call__(
181
231
  self,
182
232
  scope: Scope,
@@ -197,33 +247,11 @@ class TaipanMiddleware:
197
247
  return
198
248
 
199
249
  # Rate limiting
200
- if self._rate_limiter is not None and not self._rate_limiter.consume():
201
- logger.warning("Rate limit exceeded for request")
202
- security_hdrs = (
203
- self._headers_config.to_headers() if self._security_headers else None
204
- )
205
- await _send_json_response(
206
- send,
207
- status=429,
208
- body={"error": "Rate limit exceeded", "retry_after": 1},
209
- extra_headers=security_hdrs,
210
- )
250
+ if await self._handle_rate_limit(send):
211
251
  return
212
252
 
213
253
  # Wrap send to inject security headers
214
- if self._security_headers:
215
- original_send = send
216
- extra_headers = self._headers_config.to_headers()
217
-
218
- async def send_with_headers(message: MutableMapping[str, object]) -> None:
219
- if message.get("type") == "http.response.start":
220
- headers = message.get("headers")
221
- existing = list(headers) if isinstance(headers, list) else []
222
- existing.extend(extra_headers)
223
- message["headers"] = existing
224
- await original_send(message)
225
-
226
- send = send_with_headers
254
+ send = self._wrap_send_with_security_headers(send)
227
255
 
228
256
  # Call the actual application
229
257
  try:
@@ -182,6 +182,17 @@ def safe_from(
182
182
  return cast(SafeFromDecorator[E], decorator)
183
183
 
184
184
 
185
+ def _collect_list(
186
+ results: list[Result[T, E]] | tuple[Result[T, E], ...],
187
+ ) -> Result[list[T], E] | None:
188
+ try:
189
+ # We use a runtime # type: ignore to bypass mypy's strict check
190
+ # on the AttributeError strategy for extreme performance on the hot path
191
+ return Ok([r.ok_value for r in results]) # type: ignore[union-attr]
192
+ except AttributeError:
193
+ return None
194
+
195
+
185
196
  def collect_results(
186
197
  results: Iterable[Result[T, E]],
187
198
  ) -> Result[list[T], E]:
@@ -204,10 +215,9 @@ def collect_results(
204
215
 
205
216
  """
206
217
  if isinstance(results, (list, tuple)):
207
- try:
208
- return Ok([r.ok_value for r in results])
209
- except AttributeError:
210
- pass
218
+ optimized_res = _collect_list(results)
219
+ if optimized_res is not None:
220
+ return optimized_res
211
221
 
212
222
  ok_cls = Ok
213
223
  err_cls = Err
@@ -126,16 +126,24 @@ class CircuitBreaker:
126
126
 
127
127
  """
128
128
 
129
+ @staticmethod
130
+ def _check_finite_val(value: float, min_val: float, err_msg: str) -> None:
131
+ if not math.isfinite(value) or value < min_val:
132
+ raise ValueError(err_msg)
133
+
129
134
  @staticmethod
130
135
  def _validate_thresholds(
131
136
  timeout: float, failure_threshold: int, success_threshold: int
132
137
  ) -> None:
133
- if not math.isfinite(timeout) or timeout < 0:
134
- raise ValueError("timeout must be a finite non-negative number")
135
- if not math.isfinite(failure_threshold) or failure_threshold < 1:
136
- raise ValueError("failure_threshold must be a finite number >= 1")
137
- if not math.isfinite(success_threshold) or success_threshold < 1:
138
- raise ValueError("success_threshold must be a finite number >= 1")
138
+ CircuitBreaker._check_finite_val(
139
+ timeout, 0, "timeout must be a finite non-negative number"
140
+ )
141
+ CircuitBreaker._check_finite_val(
142
+ failure_threshold, 1, "failure_threshold must be a finite number >= 1"
143
+ )
144
+ CircuitBreaker._check_finite_val(
145
+ success_threshold, 1, "success_threshold must be a finite number >= 1"
146
+ )
139
147
 
140
148
  def __init__(
141
149
  self,
@@ -234,7 +242,12 @@ class CircuitBreaker:
234
242
  def _handle_open_state(self) -> bool:
235
243
  """Handle logic for OPEN state in _should_attempt."""
236
244
  now = time.monotonic()
237
- elapsed = now - self._state.last_failure_time
245
+ try:
246
+ elapsed = now - self._state.last_failure_time
247
+ except TypeError:
248
+ # Type corruption detected (e.g. last_failure_time is string)
249
+ return False
250
+
238
251
  # Safe check against NaN and Inf time corruption
239
252
  # If elapsed < 0, a backward clock jump occurred. We should
240
253
  # allow a transition to prevent permanent lockout.
@@ -265,8 +278,13 @@ class CircuitBreaker:
265
278
  return False
266
279
 
267
280
  def _handle_attempt_half_open(self) -> bool:
268
- if not math.isfinite(self._state.half_open_attempts):
281
+ try:
282
+ if not math.isfinite(self._state.half_open_attempts):
283
+ return False
284
+ except TypeError:
285
+ # Type corruption detected, deny attempt to be safe
269
286
  return False
287
+
270
288
  if self._state.half_open_attempts < self.config.success_threshold:
271
289
  self._state.half_open_attempts += 1
272
290
  return True
@@ -288,9 +306,13 @@ class CircuitBreaker:
288
306
  return False
289
307
 
290
308
  def _handle_success_half_open(self) -> None:
291
- if not math.isfinite(self._state.success_count):
292
- self._state.success_count = 0
293
- self._state.success_count += 1
309
+ try:
310
+ if not math.isfinite(self._state.success_count):
311
+ self._state.success_count = 0
312
+ self._state.success_count += 1
313
+ except TypeError:
314
+ # Type corruption detected, reset and increment
315
+ self._state.success_count = 1
294
316
 
295
317
  if self._state.success_count >= self.config.success_threshold:
296
318
  self._state.state = CircuitState.CLOSED
@@ -336,10 +358,22 @@ class CircuitBreaker:
336
358
  def _handle_failure_closed(self) -> None:
337
359
  """Handle failure when in CLOSED state."""
338
360
  # Check against corrupted NaN/Inf failure_count
339
- if not math.isfinite(self._state.failure_count):
361
+ try:
362
+ if not math.isfinite(self._state.failure_count):
363
+ self._state.state = CircuitState.OPEN
364
+ logger.warning(
365
+ "Circuit %s opened due to state corruption (NaN/Inf failures)",
366
+ self.name,
367
+ )
368
+ self._notify_state_change(
369
+ CircuitState.CLOSED,
370
+ CircuitState.OPEN,
371
+ )
372
+ return
373
+ except TypeError:
340
374
  self._state.state = CircuitState.OPEN
341
375
  logger.warning(
342
- "Circuit %s opened due to state corruption (NaN/Inf failures)",
376
+ "Circuit %s opened due to type corruption in failure_count",
343
377
  self.name,
344
378
  )
345
379
  self._notify_state_change(
@@ -362,8 +396,14 @@ class CircuitBreaker:
362
396
  )
363
397
 
364
398
  def _update_failure_metrics(self) -> None:
365
- if math.isfinite(self._state.failure_count):
366
- self._state.failure_count += 1
399
+ try:
400
+ if math.isfinite(self._state.failure_count):
401
+ self._state.failure_count += 1
402
+ except TypeError:
403
+ # Handle type mutation (e.g. failure_count became string)
404
+ # Safe degradation: reset to max so it opens immediately
405
+ self._state.failure_count = self.config.failure_threshold
406
+
367
407
  now = time.monotonic()
368
408
  if math.isfinite(now):
369
409
  self._state.last_failure_time = now
@@ -163,6 +163,41 @@ def calculate_delay(
163
163
  return delay
164
164
 
165
165
 
166
+ def _log_retry_callback_failure(func_name: str, e: Exception) -> None:
167
+ """Log a failure during the retry callback execution."""
168
+ if _HAS_STRUCTLOG and _structlog_logger is not None:
169
+ _structlog_logger.error(
170
+ "retry_callback_failed",
171
+ function=func_name,
172
+ error=str(e),
173
+ )
174
+ else:
175
+ logger.error(
176
+ "Retry callback failed for %s: %s",
177
+ func_name,
178
+ str(e),
179
+ )
180
+
181
+
182
+ def _log_retry_attempt_fallback(
183
+ func_name: str,
184
+ attempt: int,
185
+ exc: Exception,
186
+ delay: float,
187
+ config: RetryConfig,
188
+ ) -> None:
189
+ """Log the retry attempt if no callback is provided."""
190
+ if _HAS_STRUCTLOG and _structlog_logger is not None: # pragma: no branch
191
+ _structlog_logger.warning(
192
+ "retry_attempted",
193
+ function=func_name,
194
+ attempt=attempt,
195
+ max_attempts=config.max_attempts,
196
+ error=str(exc),
197
+ delay_seconds=round(delay, 3),
198
+ )
199
+
200
+
166
201
  def _invoke_retry_callback(
167
202
  func_name: str,
168
203
  attempt: int,
@@ -184,27 +219,9 @@ def _invoke_retry_callback(
184
219
  try:
185
220
  config.on_retry(attempt, config.max_attempts, exc, delay)
186
221
  except Exception as e:
187
- if _HAS_STRUCTLOG and _structlog_logger is not None:
188
- _structlog_logger.error(
189
- "retry_callback_failed",
190
- function=func_name,
191
- error=str(e),
192
- )
193
- else:
194
- logger.error(
195
- "Retry callback failed for %s: %s",
196
- func_name,
197
- str(e),
198
- )
199
- elif _HAS_STRUCTLOG and _structlog_logger is not None: # pragma: no branch
200
- _structlog_logger.warning(
201
- "retry_attempted",
202
- function=func_name,
203
- attempt=attempt,
204
- max_attempts=config.max_attempts,
205
- error=str(exc),
206
- delay_seconds=round(delay, 3),
207
- )
222
+ _log_retry_callback_failure(func_name, e)
223
+ else:
224
+ _log_retry_attempt_fallback(func_name, attempt, exc, delay, config)
208
225
 
209
226
 
210
227
  def _log_retry_attempt(
@@ -6,6 +6,7 @@ becomes unhealthy the associated ``CircuitBreaker`` is opened
6
6
  preventively.
7
7
  """
8
8
 
9
+ import asyncio
9
10
  import logging
10
11
  from collections.abc import Awaitable, Callable, Sequence
11
12
  from dataclasses import dataclass
@@ -55,7 +56,7 @@ async def check_target(target: HealthTarget) -> Result[bool, Exception]:
55
56
  async def check_all(
56
57
  targets: Sequence[HealthTarget],
57
58
  ) -> Result[dict[str, bool], Exception]:
58
- """Run health checks for all targets.
59
+ """Run health checks for all targets concurrently.
59
60
 
60
61
  Args:
61
62
  targets: Targets to check.
@@ -64,9 +65,11 @@ async def check_all(
64
65
  ``Ok(dict)`` mapping target names to health status.
65
66
 
66
67
  """
68
+ # Run all checks concurrently
69
+ check_results = await asyncio.gather(*(check_target(t) for t in targets))
70
+
67
71
  results: dict[str, bool] = {}
68
- for target in targets:
69
- result = await check_target(target)
72
+ for target, result in zip(targets, check_results, strict=True):
70
73
  match result:
71
74
  case Ok(healthy):
72
75
  results[target.name] = healthy
@@ -144,18 +147,7 @@ class HealthPinger(BaseWatcher):
144
147
  """Update target status and handle side-effects."""
145
148
  previous = self._last_status.get(target.name)
146
149
 
147
- if previous != is_healthy:
148
- self._last_status[target.name] = is_healthy
149
-
150
- if self._on_health_change is not None:
151
- self._on_health_change(target.name, is_healthy)
152
-
153
- if is_healthy:
154
- logger.info("Target '%s' is now healthy", target.name)
155
- else:
156
- logger.warning("Target '%s' is now unhealthy", target.name)
157
-
158
- # Open circuit breaker preventively on failure
150
+ # Open circuit breaker preventively on failure (always checked)
159
151
  if (
160
152
  not is_healthy
161
153
  and target.circuit_breaker is not None
@@ -163,10 +155,22 @@ class HealthPinger(BaseWatcher):
163
155
  ):
164
156
  _force_open_breaker(target.circuit_breaker, target.name)
165
157
 
158
+ if previous == is_healthy:
159
+ return
160
+
161
+ self._last_status[target.name] = is_healthy
162
+
163
+ if self._on_health_change is not None:
164
+ self._on_health_change(target.name, is_healthy)
165
+
166
+ if is_healthy:
167
+ logger.info("Target '%s' is now healthy", target.name)
168
+ else:
169
+ logger.warning("Target '%s' is now unhealthy", target.name)
170
+
166
171
  async def _run(self) -> None:
167
- """Execute a single health-check cycle."""
168
- for target in self._targets:
169
- await self._process_target(target)
172
+ """Execute a single health-check cycle concurrently."""
173
+ await asyncio.gather(*(self._process_target(t) for t in self._targets))
170
174
 
171
175
 
172
176
  def _force_open_breaker(breaker: CircuitBreaker, target_name: str) -> None:
@@ -128,28 +128,26 @@ class ResourceWatcher(BaseWatcher):
128
128
  )
129
129
  return await super().start()
130
130
 
131
+ def _check_threshold(self, name: str, value: float, threshold: float) -> None:
132
+ if value >= threshold:
133
+ logger.warning(
134
+ "%s threshold breached: %.1f%% >= %.1f%%",
135
+ name.capitalize(),
136
+ value,
137
+ threshold,
138
+ )
139
+ if self._on_threshold_breach is not None:
140
+ self._on_threshold_breach(name, value)
141
+
142
+ def _handle_snapshot(self, snapshot: ResourceSnapshot) -> None:
143
+ self._check_threshold("cpu", snapshot.cpu_percent, self._cpu_threshold)
144
+ self._check_threshold("memory", snapshot.memory_percent, self._memory_threshold)
145
+
131
146
  async def _run(self) -> None:
132
147
  """Execute a single resource check cycle."""
133
148
  result = check_resources()
134
149
  match result:
135
150
  case Ok(snapshot):
136
- if snapshot.cpu_percent >= self._cpu_threshold:
137
- logger.warning(
138
- "CPU threshold breached: %.1f%% >= %.1f%%",
139
- snapshot.cpu_percent,
140
- self._cpu_threshold,
141
- )
142
- if self._on_threshold_breach is not None:
143
- self._on_threshold_breach("cpu", snapshot.cpu_percent)
144
-
145
- if snapshot.memory_percent >= self._memory_threshold:
146
- logger.warning(
147
- "Memory threshold breached: %.1f%% >= %.1f%%",
148
- snapshot.memory_percent,
149
- self._memory_threshold,
150
- )
151
- if self._on_threshold_breach is not None:
152
- self._on_threshold_breach("memory", snapshot.memory_percent)
153
-
151
+ self._handle_snapshot(snapshot)
154
152
  case Err(error):
155
153
  logger.error("Resource check failed: %s", error)
@@ -58,13 +58,11 @@ def _mask_data(data: JSONValue, _depth: int = 0) -> JSONValue:
58
58
  if _depth > _MAX_RECURSION_DEPTH:
59
59
  return "<MAX_DEPTH_REACHED>"
60
60
 
61
- match data:
62
- case dict():
63
- return _mask_dict(data, _depth + 1)
64
- case list():
65
- return _mask_list(data, _depth + 1)
66
- case _:
67
- return data
61
+ if isinstance(data, dict):
62
+ return _mask_dict(data, _depth + 1)
63
+ if isinstance(data, list):
64
+ return _mask_list(data, _depth + 1)
65
+ return data
68
66
 
69
67
 
70
68
  class SecureBaseModel(BaseModel):
@@ -25,6 +25,16 @@ MAX_LEGACY_ITERATIONS = 1_000_000
25
25
  MAX_PASSWORD_LENGTH = 1024
26
26
 
27
27
 
28
+ def _get_password_str(password: str | SecretStr) -> str:
29
+ if not isinstance(password, (str, SecretStr)):
30
+ msg = "password must be a string or SecretStr"
31
+ raise TypeError(msg)
32
+
33
+ if isinstance(password, SecretStr):
34
+ return password.get_secret_value()
35
+ return password
36
+
37
+
28
38
  def hash_password(password: str | SecretStr) -> str:
29
39
  """
30
40
  Hash a password using Argon2id.
@@ -40,14 +50,7 @@ def hash_password(password: str | SecretStr) -> str:
40
50
  ValueError: If `password` length exceeds the maximum allowed or is empty.
41
51
 
42
52
  """
43
- if not isinstance(password, (str, SecretStr)):
44
- msg = "password must be a string or SecretStr"
45
- raise TypeError(msg)
46
-
47
- if isinstance(password, SecretStr):
48
- password_str = password.get_secret_value()
49
- else:
50
- password_str = password
53
+ password_str = _get_password_str(password)
51
54
 
52
55
  if not password_str:
53
56
  msg = "password cannot be empty"
@@ -115,19 +118,12 @@ def verify_password(password: str | SecretStr, password_hash: str) -> bool:
115
118
  TypeError: If `password` or `password_hash` are not the correct types.
116
119
 
117
120
  """
118
- if not isinstance(password, (str, SecretStr)):
119
- msg = "password must be a string or SecretStr"
120
- raise TypeError(msg)
121
+ password_str = _get_password_str(password)
121
122
 
122
123
  if not isinstance(password_hash, str):
123
124
  msg = "password_hash must be a string"
124
125
  raise TypeError(msg)
125
126
 
126
- if isinstance(password, SecretStr):
127
- password_str = password.get_secret_value()
128
- else:
129
- password_str = password
130
-
131
127
  if not password_str:
132
128
  return False
133
129
 
@@ -81,6 +81,26 @@ def _check_project_name_length(name: str, max_length: int) -> None:
81
81
  raise ValueError(msg)
82
82
 
83
83
 
84
+ def _build_project_name_pattern(allow_hyphen: bool, allow_underscore: bool) -> str:
85
+ """Build the regex pattern for allowed characters."""
86
+ allowed = r"a-zA-Z0-9"
87
+ if allow_hyphen:
88
+ allowed += r"-"
89
+ if allow_underscore:
90
+ allowed += r"_"
91
+ return rf"^[a-zA-Z][{allowed}]*\Z"
92
+
93
+
94
+ def _build_invalid_chars_msg(allow_hyphen: bool, allow_underscore: bool) -> str:
95
+ """Build the error message for invalid characters."""
96
+ hyphen_msg = ", hyphens" if allow_hyphen else ""
97
+ underscore_msg = ", underscores" if allow_underscore else ""
98
+ return (
99
+ f"Project name contains invalid characters. "
100
+ f"Allowed: letters, numbers{hyphen_msg}{underscore_msg}"
101
+ )
102
+
103
+
84
104
  def _check_project_name_chars(
85
105
  name: str, allow_hyphen: bool, allow_underscore: bool
86
106
  ) -> None:
@@ -95,25 +115,13 @@ def _check_project_name_chars(
95
115
  ValueError: If name contains invalid characters.
96
116
 
97
117
  """
98
- # Build allowed characters
99
- allowed = r"a-zA-Z0-9"
100
- if allow_hyphen:
101
- allowed += r"-"
102
- if allow_underscore:
103
- allowed += r"_"
104
-
105
- pattern = rf"^[a-zA-Z][{allowed}]*\Z"
118
+ pattern = _build_project_name_pattern(allow_hyphen, allow_underscore)
106
119
 
107
120
  if not re.match(pattern, name):
108
121
  if not name[0].isalpha():
109
122
  msg = "Project name must start with a letter"
110
123
  raise ValueError(msg)
111
- hyphen_msg = ", hyphens" if allow_hyphen else ""
112
- underscore_msg = ", underscores" if allow_underscore else ""
113
- msg = (
114
- f"Project name contains invalid characters. "
115
- f"Allowed: letters, numbers{hyphen_msg}{underscore_msg}"
116
- )
124
+ msg = _build_invalid_chars_msg(allow_hyphen, allow_underscore)
117
125
  raise ValueError(msg)
118
126
 
119
127
 
@@ -229,8 +237,8 @@ def validate_python_version(version: str) -> str:
229
237
  return version
230
238
 
231
239
 
232
- def _check_email_format(email: str) -> None:
233
- """Check email format and basic constraints."""
240
+ def _check_email_basics(email: str) -> None:
241
+ """Check basic email constraints like empty, length and invalid characters."""
234
242
  if not email:
235
243
  msg = "Email cannot be empty"
236
244
  raise ValueError(msg)
@@ -243,6 +251,11 @@ def _check_email_format(email: str) -> None:
243
251
  msg = "Email contains invalid characters"
244
252
  raise ValueError(msg)
245
253
 
254
+
255
+ def _check_email_format(email: str) -> None:
256
+ """Check email format and basic constraints."""
257
+ _check_email_basics(email)
258
+
246
259
  # RFC 5322 compliant pattern (simplified)
247
260
  pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\Z"
248
261
 
@@ -204,8 +204,12 @@ def _perform_atomic_write(path: Path, content: str, opts: WriteOptions) -> None:
204
204
  )
205
205
  try:
206
206
  # Write directly to the returned file descriptor to prevent TOCTOU
207
+ # We MUST close the file descriptor before renaming/modifying it,
208
+ # otherwise Windows will throw a PermissionError (WinError 32).
207
209
  with os.fdopen(_fd, "w", encoding=opts.encoding) as f:
208
210
  f.write(content)
211
+ f.flush()
212
+ os.fsync(_fd)
209
213
 
210
214
  temp_file = Path(temp_path)
211
215
  # Preserve permissions if original exists
@@ -298,6 +298,38 @@ class StackLogger:
298
298
  self._logger.exception(self._format_message(message, **kwargs))
299
299
 
300
300
 
301
+ def _configure_structlog() -> None:
302
+ """Configure structlog with default processors and settings."""
303
+ structlog.configure(
304
+ processors=[
305
+ structlog.stdlib.filter_by_level,
306
+ structlog.stdlib.add_logger_name,
307
+ structlog.stdlib.add_log_level,
308
+ structlog.processors.TimeStamper(fmt="iso"),
309
+ correlation_id_processor,
310
+ mask_sensitive_data_processor,
311
+ structlog.processors.StackInfoRenderer(),
312
+ structlog.processors.format_exc_info,
313
+ structlog.processors.UnicodeDecoder(),
314
+ structlog.processors.JSONRenderer(),
315
+ ],
316
+ wrapper_class=structlog.stdlib.BoundLogger,
317
+ context_class=dict,
318
+ logger_factory=structlog.stdlib.LoggerFactory(),
319
+ )
320
+
321
+
322
+ def _get_log_format(format_type: str) -> str:
323
+ """Get the appropriate log format string."""
324
+ match format_type:
325
+ case "simple":
326
+ return "%(levelname)s: %(message)s"
327
+ case "json":
328
+ return JSON_FORMAT
329
+ case _:
330
+ return DEFAULT_FORMAT
331
+
332
+
301
333
  def setup_logging(
302
334
  level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO",
303
335
  *,
@@ -316,33 +348,10 @@ def setup_logging(
316
348
  """
317
349
  # Configure structlog if available and requested
318
350
  if use_structured and HAS_STRUCTLOG:
319
- structlog.configure(
320
- processors=[
321
- structlog.stdlib.filter_by_level,
322
- structlog.stdlib.add_logger_name,
323
- structlog.stdlib.add_log_level,
324
- structlog.processors.TimeStamper(fmt="iso"),
325
- correlation_id_processor,
326
- mask_sensitive_data_processor,
327
- structlog.processors.StackInfoRenderer(),
328
- structlog.processors.format_exc_info,
329
- structlog.processors.UnicodeDecoder(),
330
- structlog.processors.JSONRenderer(),
331
- ],
332
- wrapper_class=structlog.stdlib.BoundLogger,
333
- context_class=dict,
334
- logger_factory=structlog.stdlib.LoggerFactory(),
335
- )
351
+ _configure_structlog()
336
352
  return
337
353
 
338
- # Standard logging configuration
339
- match format_type:
340
- case "simple":
341
- log_format = "%(levelname)s: %(message)s"
342
- case "json":
343
- log_format = JSON_FORMAT
344
- case _:
345
- log_format = DEFAULT_FORMAT
354
+ log_format = _get_log_format(format_type)
346
355
 
347
356
  handlers: list[logging.Handler] = [logging.StreamHandler(sys.stdout)]
348
357
 
@@ -59,9 +59,12 @@ class RateLimiter:
59
59
 
60
60
  def _is_valid_bucket_state(self) -> bool:
61
61
  """Check if the bucket's time window and capacity are in a valid state."""
62
- if not math.isfinite(self.time_window) or self.time_window <= 0.0:
62
+ try:
63
+ if not math.isfinite(self.time_window) or self.time_window <= 0.0:
64
+ return False
65
+ return math.isfinite(self.capacity) and self.capacity > 0.0
66
+ except TypeError:
63
67
  return False
64
- return math.isfinite(self.capacity) and self.capacity > 0.0
65
68
 
66
69
  def _add_tokens(self, now: float) -> bool:
67
70
  """Calculate and add new tokens to the bucket based on elapsed time.
@@ -73,33 +76,32 @@ class RateLimiter:
73
76
  True if token update succeeds, False if state corruption is detected.
74
77
 
75
78
  """
76
- elapsed = max(0.0, now - self.last_update)
77
- self.last_update = now
79
+ try:
80
+ elapsed = max(0.0, now - self.last_update)
81
+ self.last_update = now
78
82
 
79
- # Prevent state corruption from raising exceptions or poisoning state
80
- if not self._is_valid_bucket_state():
81
- return False
83
+ # Prevent state corruption or infinite elapsed time
84
+ if not (self._is_valid_bucket_state() and math.isfinite(elapsed)):
85
+ return False
82
86
 
83
- # Prevent infinite or NaN tokens by checking elapsed time calculations
84
- if not math.isfinite(elapsed):
85
- return False
87
+ # Add tokens for elapsed time based on fill rate
88
+ new_tokens = elapsed * (self.capacity / self.time_window)
86
89
 
87
- # Add tokens for elapsed time based on fill rate
88
- new_tokens = elapsed * (self.capacity / self.time_window)
90
+ if not math.isfinite(new_tokens):
91
+ return False
89
92
 
90
- if not math.isfinite(new_tokens):
91
- return False
93
+ self.tokens += new_tokens
92
94
 
93
- self.tokens += new_tokens
95
+ if not math.isfinite(self.tokens):
96
+ # Reset to previous state or capacity if corrupted
97
+ self.tokens = self.capacity
98
+ return False
94
99
 
95
- if not math.isfinite(self.tokens):
96
- # Reset to previous state or capacity if corrupted
97
- self.tokens = self.capacity
100
+ self.tokens = min(self.tokens, self.capacity)
101
+ return True
102
+ except TypeError:
98
103
  return False
99
104
 
100
- self.tokens = min(self.tokens, self.capacity)
101
- return True
102
-
103
105
  def consume(self, tokens: float = 1.0) -> bool:
104
106
  """Try to consume tokens.
105
107
 
@@ -114,25 +116,21 @@ class RateLimiter:
114
116
  return True
115
117
 
116
118
  with self._lock:
117
- now = time.monotonic()
119
+ try:
120
+ now = time.monotonic()
121
+
122
+ # Prevent time corruption from poisoning the bucket state.
123
+ # Only try to add tokens if time is finite.
124
+ if math.isfinite(now) and not self._add_tokens(now):
125
+ return False
118
126
 
119
- # Prevent time corruption from poisoning the bucket state.
120
- if not math.isfinite(now):
121
- # We do not update last_update or add tokens.
122
- # We just check if there are currently enough tokens to consume.
123
127
  if self.tokens >= tokens:
124
128
  self.tokens -= tokens
125
129
  return True
126
130
  return False
127
-
128
- if not self._add_tokens(now):
131
+ except TypeError:
129
132
  return False
130
133
 
131
- if self.tokens >= tokens:
132
- self.tokens -= tokens
133
- return True
134
- return False
135
-
136
134
 
137
135
  class RateLimitDecorator(Protocol):
138
136
  """Protocol for the rate limit decorator."""
@@ -34,12 +34,10 @@ def default_encoder(obj: object) -> dict[str, object]:
34
34
  b'{"status":"error","message":"oops"}'
35
35
 
36
36
  """
37
- match obj:
38
- case Ok(ok_value) if isinstance(ok_value, dict):
39
- return {"status": "success", **ok_value}
40
- case Ok(ok_value):
41
- return {"status": "success", "data": ok_value}
42
- case Err(err_value):
43
- return {"status": "error", "message": str(err_value)}
44
- case _:
45
- raise TypeError(f"Type {type(obj).__name__} is not JSON serializable")
37
+ if isinstance(obj, Ok):
38
+ if isinstance(obj.ok_value, dict):
39
+ return {"status": "success", **obj.ok_value}
40
+ return {"status": "success", "data": obj.ok_value}
41
+ if isinstance(obj, Err):
42
+ return {"status": "error", "message": str(obj.err_value)}
43
+ raise TypeError(f"Type {type(obj).__name__} is not JSON serializable")
@@ -146,6 +146,21 @@ def _validate_and_resolve_command(
146
146
  return validated_cmd
147
147
 
148
148
 
149
+ def _get_allowed_keys(allowed_env_vars: Sequence[str] | None) -> set[str]:
150
+ """Get the allowed environment variable keys.
151
+
152
+ Args:
153
+ allowed_env_vars: Whitelist of allowed environment variable names.
154
+
155
+ Returns:
156
+ Set of allowed keys in uppercase.
157
+
158
+ """
159
+ if allowed_env_vars is None:
160
+ return {"PATH"}
161
+ return {k.upper() for k in allowed_env_vars}
162
+
163
+
149
164
  def _filter_environment(
150
165
  env: dict[str, str] | None,
151
166
  allowed_env_vars: Sequence[str] | None = None,
@@ -162,23 +177,30 @@ def _filter_environment(
162
177
  Filtered environment variables containing only allowed keys.
163
178
 
164
179
  """
165
- safe_env: dict[str, str] = {}
166
180
  env_to_filter = env if env is not None else dict(os.environ)
167
-
168
- if allowed_env_vars is None:
169
- # Default minimal whitelist
170
- allowed_keys = {"PATH"}
171
- else:
172
- allowed_keys = {k.upper() for k in allowed_env_vars}
181
+ allowed_keys = _get_allowed_keys(allowed_env_vars)
173
182
 
174
183
  if not allowed_keys:
175
- return safe_env
184
+ return {}
185
+
186
+ return {k: str(v) for k, v in env_to_filter.items() if k.upper() in allowed_keys}
187
+
188
+
189
+ def _extract_timeout_stdout(e: subprocess.TimeoutExpired) -> str:
190
+ """Extract stdout from a TimeoutExpired exception safely.
176
191
 
177
- for env_key, env_val in env_to_filter.items():
178
- if env_key.upper() in allowed_keys:
179
- safe_env[env_key] = str(env_val)
192
+ Args:
193
+ e: The TimeoutExpired exception.
194
+
195
+ Returns:
196
+ The extracted stdout string.
180
197
 
181
- return safe_env
198
+ """
199
+ if not hasattr(e, "stdout") or e.stdout is None:
200
+ return ""
201
+ if isinstance(e.stdout, str):
202
+ return e.stdout
203
+ return e.stdout.decode("utf-8", errors="replace")
182
204
 
183
205
 
184
206
  def _execute_command(
@@ -216,16 +238,10 @@ def _execute_command(
216
238
  )
217
239
  except subprocess.TimeoutExpired as e:
218
240
  duration = time.time() - start_time
219
- stdout_str = ""
220
- if hasattr(e, "stdout") and e.stdout is not None:
221
- if isinstance(e.stdout, str):
222
- stdout_str = e.stdout
223
- else:
224
- stdout_str = e.stdout.decode("utf-8", errors="replace")
225
241
  return SafeCommandResult(
226
242
  command=validated_cmd,
227
243
  returncode=-1,
228
- stdout=stdout_str,
244
+ stdout=_extract_timeout_stdout(e),
229
245
  stderr=f"Command timed out after {timeout}s",
230
246
  duration_seconds=duration,
231
247
  )
@@ -265,6 +281,20 @@ def _handle_dry_run(validated_cmd: list[str]) -> SafeCommandResult:
265
281
  )
266
282
 
267
283
 
284
+ def _validate_timeout(timeout: float) -> None:
285
+ """Validate that the timeout is a finite, non-negative number.
286
+
287
+ Args:
288
+ timeout: The timeout value to validate.
289
+
290
+ Raises:
291
+ ValueError: If timeout is invalid.
292
+
293
+ """
294
+ if timeout is not None and not (math.isfinite(timeout) and timeout >= 0):
295
+ raise ValueError("timeout must be a finite non-negative number")
296
+
297
+
268
298
  def run_safe_command(
269
299
  command: Sequence[str],
270
300
  *,
@@ -311,8 +341,7 @@ def run_safe_command(
311
341
  # Security Enhancement: Prevent DoS via infinite blocking behaviors or
312
342
  # unhandled exceptions from threading/asyncio primitives by explicitly
313
343
  # validating that timeout is a finite, non-negative number.
314
- if timeout is not None and not (math.isfinite(timeout) and timeout >= 0):
315
- raise ValueError("timeout must be a finite non-negative number")
344
+ _validate_timeout(timeout)
316
345
 
317
346
  validated_cmd = _validate_and_resolve_command(command, allowed_commands)
318
347
  safe_env = _filter_environment(env, allowed_env_vars)
File without changes