taipanstack 0.5.1__tar.gz → 0.5.2__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.
- {taipanstack-0.5.1 → taipanstack-0.5.2}/PKG-INFO +12 -11
- {taipanstack-0.5.1 → taipanstack-0.5.2}/README.md +11 -10
- {taipanstack-0.5.1 → taipanstack-0.5.2}/pyproject.toml +3 -1
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/__init__.py +1 -1
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/bridges/http_bridge.py +2 -2
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/resilience/adaptive/orchestrator.py +36 -11
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/resilience/circuit_breaker.py +146 -71
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/resilience/retry.py +14 -7
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/resilience/watchdogs/config_watcher.py +27 -13
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/security/guards.py +6 -1
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/security/jwt.py +6 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/security/models.py +23 -10
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/security/sanitizers.py +0 -116
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/utils/logging.py +49 -15
- {taipanstack-0.5.1 → taipanstack-0.5.2}/LICENSE +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/bridges/__init__.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/bridges/_imports.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/bridges/db_bridge.py +4 -4
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/bridges/web_bridge.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/config/__init__.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/config/generators.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/config/models.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/config/version_config.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/core/__init__.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/core/compat.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/core/optimizations.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/core/result.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/resilience/__init__.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/resilience/adaptive/__init__.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/resilience/adaptive/adaptive_breaker.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/resilience/adaptive/adaptive_retry.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/resilience/adaptive/bulkhead.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/resilience/resilience.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/resilience/watchdogs/__init__.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/resilience/watchdogs/_base.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/resilience/watchdogs/health_pinger.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/resilience/watchdogs/resource_watcher.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/security/__init__.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/security/decorators.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/security/password.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/security/types.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/security/validators.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/utils/__init__.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/utils/cache.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/utils/circuit_breaker.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/utils/concurrency.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/utils/context.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/utils/filesystem.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/utils/rate_limit.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/utils/resilience.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/utils/retry.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/utils/serialization.py +0 -0
- {taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/utils/subprocess.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: taipanstack
|
|
3
|
-
Version: 0.5.
|
|
3
|
+
Version: 0.5.2
|
|
4
4
|
Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
|
|
5
5
|
License-Expression: MIT
|
|
6
6
|
License-File: LICENSE
|
|
@@ -75,7 +75,7 @@ Description-Content-Type: text/markdown
|
|
|
75
75
|
|
|
76
76
|
---
|
|
77
77
|
|
|
78
|
-
[**Features**](#-
|
|
78
|
+
[**Features**](#-why-taipan-stack) • [**Quick Start**](#-quick-start) • [**Architecture**](#-architecture) • [**DevSecOps**](#-devsecops) • [**API**](#-api-highlights) • [**Contributing**](#-contributing)
|
|
79
79
|
|
|
80
80
|
</div>
|
|
81
81
|
|
|
@@ -87,11 +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.5.
|
|
91
|
-
- **
|
|
92
|
-
- **Resilience
|
|
93
|
-
- **Complexity
|
|
94
|
-
- **QA
|
|
90
|
+
### ✨ What's New in v0.5.2
|
|
91
|
+
- **Sentinel Hardening**: Enforced multicast and unspecified IP address bounds checking inside `guard_ssrf` (PR #826) and added negative domain bounds checks to resilience LBYL type guards (PR #823).
|
|
92
|
+
- **Resilience under Chaos**: Protected `CircuitBreaker` and `Retry` against runtime property type mutations and configuration exception changes under chaos, and fixed `NaN` `last_failure_time` lockout vulnerability (PR #811, #819, #830).
|
|
93
|
+
- **Complexity Refactor**: Reduced cyclomatic and cognitive complexity in watchdogs, orchestrators, bridges, and circuit breakers (PR #813, #817, #821, #835).
|
|
94
|
+
- **QA & Typing**: Standardized test naming convention (`test_*.py`) and refactored test suite to achieve 100% genuine coverage over **1,226 passing tests** (PR #816, #825, #831, #837).
|
|
95
|
+
- **Bridges API Reference**: Added new API documentation reference for the Bridges module (PR #822).
|
|
95
96
|
|
|
96
97
|
<table>
|
|
97
98
|
<tr>
|
|
@@ -128,7 +129,7 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
|
|
|
128
129
|
|
|
129
130
|
### 🔧 Developer Experience
|
|
130
131
|
- Pre-configured quality tools
|
|
131
|
-
- **100% code coverage** (1,
|
|
132
|
+
- **100% code coverage** (1,226 tests)
|
|
132
133
|
- Architecture enforcement
|
|
133
134
|
- Hardened Docker template
|
|
134
135
|
|
|
@@ -170,7 +171,7 @@ make all
|
|
|
170
171
|
### Verify Installation
|
|
171
172
|
|
|
172
173
|
```bash
|
|
173
|
-
# Run tests with 100% coverage (1,
|
|
174
|
+
# Run tests with 100% coverage (1,226 tests)
|
|
174
175
|
make test
|
|
175
176
|
|
|
176
177
|
# Check architecture contracts
|
|
@@ -223,7 +224,7 @@ TaipanStack/
|
|
|
223
224
|
│ ├── config/ # ⚙️ Configuration models & generators
|
|
224
225
|
│ ├── security/ # 🛡️ Guards, sanitizers, validators
|
|
225
226
|
│ └── utils/ # 🔧 Logging, metrics, retry, filesystem
|
|
226
|
-
├── tests/ # ✅ 1,
|
|
227
|
+
├── tests/ # ✅ 1,226 tests, 100% coverage
|
|
227
228
|
├── .semgrep/ # 🔍 Custom SAST rules
|
|
228
229
|
├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
|
|
229
230
|
├── Dockerfile # 🐳 Hardened multi-stage container
|
|
@@ -484,7 +485,7 @@ This project is open-sourced under the [MIT License](LICENSE).
|
|
|
484
485
|
|
|
485
486
|
**Made with ❤️ for the Python community**
|
|
486
487
|
|
|
487
|
-
[⬆ Back to Top](#-
|
|
488
|
+
[⬆ Back to Top](#-taipan-stack)
|
|
488
489
|
|
|
489
490
|
</div>
|
|
490
491
|
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
|
|
19
19
|
---
|
|
20
20
|
|
|
21
|
-
[**Features**](#-
|
|
21
|
+
[**Features**](#-why-taipan-stack) • [**Quick Start**](#-quick-start) • [**Architecture**](#-architecture) • [**DevSecOps**](#-devsecops) • [**API**](#-api-highlights) • [**Contributing**](#-contributing)
|
|
22
22
|
|
|
23
23
|
</div>
|
|
24
24
|
|
|
@@ -30,11 +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.5.
|
|
34
|
-
- **
|
|
35
|
-
- **Resilience
|
|
36
|
-
- **Complexity
|
|
37
|
-
- **QA
|
|
33
|
+
### ✨ What's New in v0.5.2
|
|
34
|
+
- **Sentinel Hardening**: Enforced multicast and unspecified IP address bounds checking inside `guard_ssrf` (PR #826) and added negative domain bounds checks to resilience LBYL type guards (PR #823).
|
|
35
|
+
- **Resilience under Chaos**: Protected `CircuitBreaker` and `Retry` against runtime property type mutations and configuration exception changes under chaos, and fixed `NaN` `last_failure_time` lockout vulnerability (PR #811, #819, #830).
|
|
36
|
+
- **Complexity Refactor**: Reduced cyclomatic and cognitive complexity in watchdogs, orchestrators, bridges, and circuit breakers (PR #813, #817, #821, #835).
|
|
37
|
+
- **QA & Typing**: Standardized test naming convention (`test_*.py`) and refactored test suite to achieve 100% genuine coverage over **1,226 passing tests** (PR #816, #825, #831, #837).
|
|
38
|
+
- **Bridges API Reference**: Added new API documentation reference for the Bridges module (PR #822).
|
|
38
39
|
|
|
39
40
|
<table>
|
|
40
41
|
<tr>
|
|
@@ -71,7 +72,7 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
|
|
|
71
72
|
|
|
72
73
|
### 🔧 Developer Experience
|
|
73
74
|
- Pre-configured quality tools
|
|
74
|
-
- **100% code coverage** (1,
|
|
75
|
+
- **100% code coverage** (1,226 tests)
|
|
75
76
|
- Architecture enforcement
|
|
76
77
|
- Hardened Docker template
|
|
77
78
|
|
|
@@ -113,7 +114,7 @@ make all
|
|
|
113
114
|
### Verify Installation
|
|
114
115
|
|
|
115
116
|
```bash
|
|
116
|
-
# Run tests with 100% coverage (1,
|
|
117
|
+
# Run tests with 100% coverage (1,226 tests)
|
|
117
118
|
make test
|
|
118
119
|
|
|
119
120
|
# Check architecture contracts
|
|
@@ -166,7 +167,7 @@ TaipanStack/
|
|
|
166
167
|
│ ├── config/ # ⚙️ Configuration models & generators
|
|
167
168
|
│ ├── security/ # 🛡️ Guards, sanitizers, validators
|
|
168
169
|
│ └── utils/ # 🔧 Logging, metrics, retry, filesystem
|
|
169
|
-
├── tests/ # ✅ 1,
|
|
170
|
+
├── tests/ # ✅ 1,226 tests, 100% coverage
|
|
170
171
|
├── .semgrep/ # 🔍 Custom SAST rules
|
|
171
172
|
├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
|
|
172
173
|
├── Dockerfile # 🐳 Hardened multi-stage container
|
|
@@ -427,6 +428,6 @@ This project is open-sourced under the [MIT License](LICENSE).
|
|
|
427
428
|
|
|
428
429
|
**Made with ❤️ for the Python community**
|
|
429
430
|
|
|
430
|
-
[⬆ Back to Top](#-
|
|
431
|
+
[⬆ Back to Top](#-taipan-stack)
|
|
431
432
|
|
|
432
433
|
</div>
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "taipanstack"
|
|
3
|
-
version = "0.5.
|
|
3
|
+
version = "0.5.2"
|
|
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"}
|
|
@@ -104,6 +104,7 @@ dev = [
|
|
|
104
104
|
"authlib (>=1.6.11,<2.0.0)",
|
|
105
105
|
"cryptography (>=46.0.7,<49.0.0)",
|
|
106
106
|
"mutmut (>=3.0.0,<4.0.0)",
|
|
107
|
+
"mkdocs-material (>=9.7.6,<10.0.0)",
|
|
107
108
|
]
|
|
108
109
|
|
|
109
110
|
docs = [
|
|
@@ -197,6 +198,7 @@ plugins = ["pydantic.mypy"]
|
|
|
197
198
|
[[tool.mypy.overrides]]
|
|
198
199
|
module = [
|
|
199
200
|
"mutmut.*",
|
|
201
|
+
"tests.*",
|
|
200
202
|
]
|
|
201
203
|
ignore_missing_imports = true
|
|
202
204
|
ignore_errors = true
|
|
@@ -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.5.
|
|
8
|
+
__version__ = "0.5.2"
|
|
9
9
|
|
|
10
10
|
from taipanstack.config.version_config import (
|
|
11
11
|
VersionRecommendations,
|
|
@@ -218,7 +218,7 @@ async def _execute_with_retries(
|
|
|
218
218
|
|
|
219
219
|
"""
|
|
220
220
|
max_attempts = retry_config.max_attempts if retry_config is not None else 1
|
|
221
|
-
last_error: Exception
|
|
221
|
+
last_error: Exception = RuntimeError("Request failed")
|
|
222
222
|
|
|
223
223
|
for attempt in range(1, max_attempts + 1):
|
|
224
224
|
outcome = await _execute_single_attempt(
|
|
@@ -234,7 +234,7 @@ async def _execute_with_retries(
|
|
|
234
234
|
if isinstance(outcome, Exception):
|
|
235
235
|
last_error = outcome
|
|
236
236
|
|
|
237
|
-
return Err(last_error
|
|
237
|
+
return Err(last_error)
|
|
238
238
|
|
|
239
239
|
|
|
240
240
|
async def safe_request(
|
|
@@ -165,7 +165,7 @@ class ResilienceOrchestrator(Generic[T]):
|
|
|
165
165
|
self._fallback_value = value
|
|
166
166
|
return self
|
|
167
167
|
|
|
168
|
-
async def execute(
|
|
168
|
+
async def execute( # noqa: PLR0911
|
|
169
169
|
self,
|
|
170
170
|
fn: Callable[P, Awaitable[T]],
|
|
171
171
|
*args: P.args,
|
|
@@ -217,12 +217,18 @@ class ResilienceOrchestrator(Generic[T]):
|
|
|
217
217
|
|
|
218
218
|
bh._active += 1
|
|
219
219
|
try:
|
|
220
|
-
|
|
220
|
+
try:
|
|
221
|
+
return await self._execute_inner(fn, *args, **kwargs)
|
|
222
|
+
except Exception as exc:
|
|
223
|
+
return self._apply_fallback(Err(exc))
|
|
221
224
|
finally:
|
|
222
225
|
bh._active -= 1
|
|
223
226
|
bh._semaphore.release()
|
|
224
227
|
|
|
225
|
-
|
|
228
|
+
try:
|
|
229
|
+
return await self._execute_inner(fn, *args, **kwargs)
|
|
230
|
+
except Exception as exc:
|
|
231
|
+
return self._apply_fallback(Err(exc))
|
|
226
232
|
|
|
227
233
|
def _evaluate_circuit_breaker(self) -> Err[Exception] | None:
|
|
228
234
|
"""Check if execution is allowed by the circuit breaker."""
|
|
@@ -304,6 +310,28 @@ class ResilienceOrchestrator(Generic[T]):
|
|
|
304
310
|
return self._apply_fallback(cb_err)
|
|
305
311
|
return cb_err.err_value
|
|
306
312
|
|
|
313
|
+
async def _execute_single_attempt(
|
|
314
|
+
self,
|
|
315
|
+
attempt: int,
|
|
316
|
+
fn: Callable[P, Awaitable[T]],
|
|
317
|
+
*args: P.args,
|
|
318
|
+
**kwargs: P.kwargs,
|
|
319
|
+
) -> Result[T, Exception]:
|
|
320
|
+
"""Execute a single attempt including timeout."""
|
|
321
|
+
result = await self._execute_with_timeout(fn, *args, **kwargs)
|
|
322
|
+
if isinstance(result, Ok):
|
|
323
|
+
self._record_success_outcome(attempt)
|
|
324
|
+
return result
|
|
325
|
+
|
|
326
|
+
def _check_circuit_breaker_for_attempt(
|
|
327
|
+
self, attempt: int
|
|
328
|
+
) -> Result[T, Exception] | Exception | None:
|
|
329
|
+
"""Evaluate circuit breaker for the current attempt."""
|
|
330
|
+
cb_err = self._evaluate_circuit_breaker()
|
|
331
|
+
if cb_err is not None:
|
|
332
|
+
return self._handle_circuit_breaker_open(cb_err, attempt)
|
|
333
|
+
return None
|
|
334
|
+
|
|
307
335
|
async def _execute_with_retries(
|
|
308
336
|
self,
|
|
309
337
|
max_attempts: int,
|
|
@@ -313,23 +341,20 @@ class ResilienceOrchestrator(Generic[T]):
|
|
|
313
341
|
) -> Result[T, Exception]:
|
|
314
342
|
last_error: Exception = RuntimeError("Execution failed")
|
|
315
343
|
for attempt in range(1, max_attempts + 1):
|
|
316
|
-
|
|
317
|
-
if
|
|
318
|
-
cb_res = self._handle_circuit_breaker_open(cb_err, attempt)
|
|
344
|
+
cb_res = self._check_circuit_breaker_for_attempt(attempt)
|
|
345
|
+
if cb_res is not None:
|
|
319
346
|
if isinstance(cb_res, Exception):
|
|
320
347
|
last_error = cb_res
|
|
321
348
|
break
|
|
322
349
|
return cb_res
|
|
323
350
|
|
|
324
|
-
result = await self.
|
|
351
|
+
result = await self._execute_single_attempt(attempt, fn, *args, **kwargs)
|
|
325
352
|
if isinstance(result, Ok):
|
|
326
|
-
self._record_success_outcome(attempt)
|
|
327
353
|
return result
|
|
328
354
|
|
|
329
355
|
last_error = result.err_value
|
|
330
|
-
if await self._handle_retry_failure(last_error, attempt, max_attempts):
|
|
331
|
-
|
|
332
|
-
break
|
|
356
|
+
if not await self._handle_retry_failure(last_error, attempt, max_attempts):
|
|
357
|
+
break
|
|
333
358
|
|
|
334
359
|
return self._apply_fallback(Err(last_error))
|
|
335
360
|
|
|
@@ -239,51 +239,82 @@ class CircuitBreaker:
|
|
|
239
239
|
failure_count=self._state.failure_count,
|
|
240
240
|
)
|
|
241
241
|
|
|
242
|
+
def _calculate_elapsed_time(self, now: float) -> float | None:
|
|
243
|
+
"""Calculate time elapsed since last failure."""
|
|
244
|
+
if not isinstance(self._state.last_failure_time, (int, float)):
|
|
245
|
+
return None
|
|
246
|
+
|
|
247
|
+
if not math.isfinite(self._state.last_failure_time):
|
|
248
|
+
return float(self.config.timeout)
|
|
249
|
+
|
|
250
|
+
elapsed = now - float(self._state.last_failure_time)
|
|
251
|
+
|
|
252
|
+
# Safe check against NaN and Inf time corruption
|
|
253
|
+
# If elapsed < 0, a backward clock jump occurred. We should
|
|
254
|
+
# allow a transition to prevent permanent lockout.
|
|
255
|
+
if elapsed < 0:
|
|
256
|
+
return float(self.config.timeout)
|
|
257
|
+
return elapsed
|
|
258
|
+
|
|
259
|
+
def _transition_to_half_open(
|
|
260
|
+
self, elapsed: float
|
|
261
|
+
) -> tuple[bool, tuple[CircuitState, CircuitState] | None]:
|
|
262
|
+
"""Transition the circuit to half-open state."""
|
|
263
|
+
# Before transitioning, verify if we can make an attempt
|
|
264
|
+
# This happens in a lock, so it's thread-safe. However, once
|
|
265
|
+
# the state changes to HALF_OPEN, subsequent threads in the
|
|
266
|
+
# same lock block will hit the HALF_OPEN case.
|
|
267
|
+
self._state.state = CircuitState.HALF_OPEN
|
|
268
|
+
self._state.success_count = 0
|
|
269
|
+
# Initialize half_open_attempts to 1 because this first call
|
|
270
|
+
# that transitions the state is also an attempt.
|
|
271
|
+
self._state.half_open_attempts = 1
|
|
272
|
+
logger.info(
|
|
273
|
+
"Circuit %s entering half-open state (was open for %.1fs, failures=%d)",
|
|
274
|
+
self.name,
|
|
275
|
+
elapsed,
|
|
276
|
+
self._state.failure_count,
|
|
277
|
+
)
|
|
278
|
+
return True, (CircuitState.OPEN, CircuitState.HALF_OPEN)
|
|
279
|
+
|
|
242
280
|
def _handle_open_state(
|
|
243
281
|
self,
|
|
244
282
|
) -> tuple[bool, tuple[CircuitState, CircuitState] | None]:
|
|
245
283
|
"""Handle logic for OPEN state in _should_attempt."""
|
|
246
284
|
now = time.monotonic()
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
# Type corruption detected (e.g. last_failure_time is string)
|
|
285
|
+
elapsed = self._calculate_elapsed_time(now)
|
|
286
|
+
|
|
287
|
+
if elapsed is None:
|
|
251
288
|
return False, None
|
|
252
289
|
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
self._state.state = CircuitState.HALF_OPEN
|
|
265
|
-
self._state.success_count = 0
|
|
266
|
-
# Initialize half_open_attempts to 1 because this first call
|
|
267
|
-
# that transitions the state is also an attempt.
|
|
268
|
-
self._state.half_open_attempts = 1
|
|
269
|
-
logger.info(
|
|
270
|
-
"Circuit %s entering half-open state (was open for %.1fs, failures=%d)",
|
|
271
|
-
self.name,
|
|
272
|
-
elapsed,
|
|
273
|
-
self._state.failure_count,
|
|
274
|
-
)
|
|
275
|
-
return True, (CircuitState.OPEN, CircuitState.HALF_OPEN)
|
|
290
|
+
timeout = self.config.timeout
|
|
291
|
+
if (
|
|
292
|
+
not isinstance(timeout, (int, float))
|
|
293
|
+
or not math.isfinite(timeout)
|
|
294
|
+
or timeout < 0
|
|
295
|
+
):
|
|
296
|
+
timeout = 30.0
|
|
297
|
+
|
|
298
|
+
if math.isfinite(now) and elapsed >= timeout:
|
|
299
|
+
return self._transition_to_half_open(elapsed)
|
|
300
|
+
|
|
276
301
|
return False, None
|
|
277
302
|
|
|
278
303
|
def _handle_attempt_half_open(self) -> bool:
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
except TypeError:
|
|
283
|
-
# Type corruption detected, deny attempt to be safe
|
|
304
|
+
if not isinstance(
|
|
305
|
+
self._state.half_open_attempts, (int, float)
|
|
306
|
+
) or not math.isfinite(self._state.half_open_attempts):
|
|
284
307
|
return False
|
|
285
308
|
|
|
286
|
-
|
|
309
|
+
success_threshold = self.config.success_threshold
|
|
310
|
+
if (
|
|
311
|
+
not isinstance(success_threshold, (int, float))
|
|
312
|
+
or not math.isfinite(success_threshold)
|
|
313
|
+
or success_threshold < 1
|
|
314
|
+
):
|
|
315
|
+
success_threshold = 2
|
|
316
|
+
|
|
317
|
+
if self._state.half_open_attempts < success_threshold:
|
|
287
318
|
self._state.half_open_attempts += 1
|
|
288
319
|
return True
|
|
289
320
|
return False
|
|
@@ -307,15 +338,25 @@ class CircuitBreaker:
|
|
|
307
338
|
return should_attempt
|
|
308
339
|
|
|
309
340
|
def _handle_success_half_open(self) -> tuple[CircuitState, CircuitState] | None:
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
self._state.success_count
|
|
314
|
-
|
|
341
|
+
if (
|
|
342
|
+
not isinstance(self._state.success_count, (int, float))
|
|
343
|
+
or not math.isfinite(self._state.success_count)
|
|
344
|
+
or self._state.success_count < 0
|
|
345
|
+
):
|
|
315
346
|
# Type corruption detected, reset and increment
|
|
316
347
|
self._state.success_count = 1
|
|
348
|
+
else:
|
|
349
|
+
self._state.success_count += 1
|
|
317
350
|
|
|
318
|
-
|
|
351
|
+
success_threshold = self.config.success_threshold
|
|
352
|
+
if (
|
|
353
|
+
not isinstance(success_threshold, (int, float))
|
|
354
|
+
or not math.isfinite(success_threshold)
|
|
355
|
+
or success_threshold < 1
|
|
356
|
+
):
|
|
357
|
+
success_threshold = 2
|
|
358
|
+
|
|
359
|
+
if self._state.success_count >= success_threshold:
|
|
319
360
|
self._state.state = CircuitState.CLOSED
|
|
320
361
|
self._state.failure_count = 0
|
|
321
362
|
self._state.half_open_attempts = 0
|
|
@@ -356,42 +397,49 @@ class CircuitBreaker:
|
|
|
356
397
|
def _handle_failure_closed(self) -> tuple[CircuitState, CircuitState] | None:
|
|
357
398
|
"""Handle failure when in CLOSED state."""
|
|
358
399
|
# Check against corrupted NaN/Inf failure_count
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
self.name,
|
|
365
|
-
)
|
|
366
|
-
return (CircuitState.CLOSED, CircuitState.OPEN)
|
|
367
|
-
except TypeError:
|
|
400
|
+
if (
|
|
401
|
+
not isinstance(self._state.failure_count, (int, float))
|
|
402
|
+
or not math.isfinite(self._state.failure_count)
|
|
403
|
+
or self._state.failure_count < 0
|
|
404
|
+
):
|
|
368
405
|
self._state.state = CircuitState.OPEN
|
|
369
406
|
logger.warning(
|
|
370
|
-
"Circuit %s opened due to type corruption in failure_count",
|
|
407
|
+
"Circuit %s opened due to state/type corruption in failure_count",
|
|
371
408
|
self.name,
|
|
372
409
|
)
|
|
373
410
|
return (CircuitState.CLOSED, CircuitState.OPEN)
|
|
374
411
|
|
|
375
|
-
|
|
412
|
+
failure_threshold = self.config.failure_threshold
|
|
413
|
+
if (
|
|
414
|
+
not isinstance(failure_threshold, (int, float))
|
|
415
|
+
or not math.isfinite(failure_threshold)
|
|
416
|
+
or failure_threshold < 1
|
|
417
|
+
):
|
|
418
|
+
failure_threshold = 5
|
|
419
|
+
|
|
420
|
+
if self._state.failure_count >= failure_threshold:
|
|
376
421
|
self._state.state = CircuitState.OPEN
|
|
377
422
|
logger.warning(
|
|
378
423
|
"Circuit %s opened after %d failures (threshold=%d)",
|
|
379
424
|
self.name,
|
|
380
425
|
self._state.failure_count,
|
|
381
|
-
|
|
426
|
+
failure_threshold,
|
|
382
427
|
)
|
|
383
428
|
return (CircuitState.CLOSED, CircuitState.OPEN)
|
|
384
429
|
|
|
385
430
|
return None
|
|
386
431
|
|
|
387
432
|
def _update_failure_metrics(self) -> None:
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
433
|
+
if (
|
|
434
|
+
not isinstance(self._state.failure_count, (int, float))
|
|
435
|
+
or not math.isfinite(self._state.failure_count)
|
|
436
|
+
or self._state.failure_count < 0
|
|
437
|
+
):
|
|
438
|
+
# Handle type mutation (e.g. failure_count became string) or Inf/NaN
|
|
393
439
|
# Safe degradation: reset to max so it opens immediately
|
|
394
440
|
self._state.failure_count = self.config.failure_threshold
|
|
441
|
+
else:
|
|
442
|
+
self._state.failure_count += 1
|
|
395
443
|
|
|
396
444
|
now = time.monotonic()
|
|
397
445
|
if math.isfinite(now):
|
|
@@ -408,8 +456,11 @@ class CircuitBreaker:
|
|
|
408
456
|
def _record_failure(self, exc: Exception) -> None:
|
|
409
457
|
"""Record a failed call."""
|
|
410
458
|
# Check if exception should be excluded
|
|
411
|
-
|
|
412
|
-
|
|
459
|
+
try:
|
|
460
|
+
if isinstance(exc, self.config.excluded_exceptions):
|
|
461
|
+
return
|
|
462
|
+
except TypeError:
|
|
463
|
+
pass # Corrupted type, do not exclude
|
|
413
464
|
|
|
414
465
|
state_change: tuple[CircuitState, CircuitState] | None = None
|
|
415
466
|
|
|
@@ -441,7 +492,11 @@ class CircuitBreaker:
|
|
|
441
492
|
"""
|
|
442
493
|
if isinstance(result, Err):
|
|
443
494
|
err_val = result.unwrap_err()
|
|
444
|
-
|
|
495
|
+
try:
|
|
496
|
+
is_failure = isinstance(err_val, self.config.failure_exceptions)
|
|
497
|
+
except TypeError:
|
|
498
|
+
is_failure = True
|
|
499
|
+
if is_failure:
|
|
445
500
|
self._record_failure(err_val)
|
|
446
501
|
return result
|
|
447
502
|
# Ignored exception in Result monad
|
|
@@ -449,18 +504,26 @@ class CircuitBreaker:
|
|
|
449
504
|
self._record_success()
|
|
450
505
|
return result
|
|
451
506
|
|
|
507
|
+
def _is_valid_half_open_attempts(self) -> bool:
|
|
508
|
+
"""Validate half-open attempts value against corruption."""
|
|
509
|
+
return (
|
|
510
|
+
isinstance(self._state.half_open_attempts, (int, float))
|
|
511
|
+
and math.isfinite(self._state.half_open_attempts)
|
|
512
|
+
and self._state.half_open_attempts >= 0
|
|
513
|
+
)
|
|
514
|
+
|
|
452
515
|
def _safe_decrement_half_open_attempts(self) -> None:
|
|
453
516
|
"""Safely decrement half-open attempts."""
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
and self._state.half_open_attempts > 0
|
|
459
|
-
):
|
|
460
|
-
self._state.half_open_attempts -= 1
|
|
461
|
-
except TypeError:
|
|
517
|
+
if self._state.state != CircuitState.HALF_OPEN:
|
|
518
|
+
return
|
|
519
|
+
|
|
520
|
+
if not self._is_valid_half_open_attempts():
|
|
462
521
|
# Reset if state is corrupted to prevent crash
|
|
463
522
|
self._state.half_open_attempts = 0
|
|
523
|
+
return
|
|
524
|
+
|
|
525
|
+
if self._state.half_open_attempts > 0:
|
|
526
|
+
self._state.half_open_attempts -= 1
|
|
464
527
|
|
|
465
528
|
def _decrement_half_open(self, is_half_open: bool) -> None:
|
|
466
529
|
"""Decrement half-open attempt count if applicable.
|
|
@@ -493,8 +556,14 @@ class CircuitBreaker:
|
|
|
493
556
|
try:
|
|
494
557
|
result = await func_coro(*args, **kwargs)
|
|
495
558
|
return self._process_result(result)
|
|
496
|
-
except
|
|
497
|
-
|
|
559
|
+
except Exception as e:
|
|
560
|
+
try:
|
|
561
|
+
is_failure = isinstance(e, self.config.failure_exceptions)
|
|
562
|
+
except TypeError:
|
|
563
|
+
is_failure = True
|
|
564
|
+
if is_failure:
|
|
565
|
+
self._record_failure(e)
|
|
566
|
+
raise
|
|
498
567
|
raise
|
|
499
568
|
finally:
|
|
500
569
|
self._decrement_half_open(is_half_open)
|
|
@@ -516,8 +585,14 @@ class CircuitBreaker:
|
|
|
516
585
|
try:
|
|
517
586
|
result = func_sync(*args, **kwargs)
|
|
518
587
|
return self._process_result(result)
|
|
519
|
-
except
|
|
520
|
-
|
|
588
|
+
except Exception as e:
|
|
589
|
+
try:
|
|
590
|
+
is_failure = isinstance(e, self.config.failure_exceptions)
|
|
591
|
+
except TypeError:
|
|
592
|
+
is_failure = True
|
|
593
|
+
if is_failure:
|
|
594
|
+
self._record_failure(e)
|
|
595
|
+
raise
|
|
521
596
|
raise
|
|
522
597
|
finally:
|
|
523
598
|
self._decrement_half_open(is_half_open)
|
|
@@ -561,17 +561,24 @@ class Retrier:
|
|
|
561
561
|
|
|
562
562
|
def _increment_attempt(self) -> bool:
|
|
563
563
|
"""Increment attempt counter safely."""
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
self.attempt
|
|
568
|
-
|
|
569
|
-
except TypeError:
|
|
564
|
+
if (
|
|
565
|
+
not isinstance(self.attempt, (int, float))
|
|
566
|
+
or not math.isfinite(self.attempt)
|
|
567
|
+
or self.attempt < 0
|
|
568
|
+
):
|
|
570
569
|
return False
|
|
571
570
|
|
|
571
|
+
self.attempt += 1
|
|
572
|
+
return True
|
|
573
|
+
|
|
572
574
|
def _should_retry(self, exc_type: type[BaseException] | None) -> bool:
|
|
573
575
|
"""Determine if an exception should trigger a retry."""
|
|
574
|
-
if exc_type is None
|
|
576
|
+
if exc_type is None:
|
|
577
|
+
return False
|
|
578
|
+
try:
|
|
579
|
+
if not issubclass(exc_type, self.exception_types):
|
|
580
|
+
return False
|
|
581
|
+
except TypeError:
|
|
575
582
|
return False
|
|
576
583
|
|
|
577
584
|
if not self._increment_attempt():
|
{taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/resilience/watchdogs/config_watcher.py
RENAMED
|
@@ -89,18 +89,8 @@ def _parse_json(text: str) -> Result[dict[str, object], Exception]:
|
|
|
89
89
|
return Err(exc)
|
|
90
90
|
|
|
91
91
|
|
|
92
|
-
def
|
|
93
|
-
"""Read
|
|
94
|
-
|
|
95
|
-
Supported extensions: ``.env``, ``.json``.
|
|
96
|
-
|
|
97
|
-
Args:
|
|
98
|
-
path: Path to the config file.
|
|
99
|
-
|
|
100
|
-
Returns:
|
|
101
|
-
``Ok(dict)`` with parsed data, or ``Err`` on failure.
|
|
102
|
-
|
|
103
|
-
"""
|
|
92
|
+
def _read_file_content(path: Path) -> Result[str, Exception]:
|
|
93
|
+
"""Read file content with size validation."""
|
|
104
94
|
try:
|
|
105
95
|
if path.stat().st_size > MAX_CONFIG_FILE_SIZE:
|
|
106
96
|
return Err(
|
|
@@ -108,10 +98,15 @@ def _load_file_data(path: Path) -> Result[dict[str, object], Exception]:
|
|
|
108
98
|
f"File {path} exceeds max size ({MAX_CONFIG_FILE_SIZE} bytes)"
|
|
109
99
|
)
|
|
110
100
|
)
|
|
111
|
-
|
|
101
|
+
return Ok(path.read_text(encoding="utf-8"))
|
|
112
102
|
except OSError as exc:
|
|
113
103
|
return Err(exc)
|
|
114
104
|
|
|
105
|
+
|
|
106
|
+
def _parse_content_by_extension(
|
|
107
|
+
path: Path, text: str
|
|
108
|
+
) -> Result[dict[str, object], Exception]:
|
|
109
|
+
"""Parse file content based on extension."""
|
|
115
110
|
suffix = path.suffix.lower()
|
|
116
111
|
if suffix == ".json":
|
|
117
112
|
return _parse_json(text)
|
|
@@ -121,6 +116,25 @@ def _load_file_data(path: Path) -> Result[dict[str, object], Exception]:
|
|
|
121
116
|
return Err(ValueError(f"Unsupported config file extension: {suffix}"))
|
|
122
117
|
|
|
123
118
|
|
|
119
|
+
def _load_file_data(path: Path) -> Result[dict[str, object], Exception]:
|
|
120
|
+
"""Read and parse a configuration file based on its extension.
|
|
121
|
+
|
|
122
|
+
Supported extensions: ``.env``, ``.json``.
|
|
123
|
+
|
|
124
|
+
Args:
|
|
125
|
+
path: Path to the config file.
|
|
126
|
+
|
|
127
|
+
Returns:
|
|
128
|
+
``Ok(dict)`` with parsed data, or ``Err`` on failure.
|
|
129
|
+
|
|
130
|
+
"""
|
|
131
|
+
content_result = _read_file_content(path)
|
|
132
|
+
if isinstance(content_result, Err):
|
|
133
|
+
return content_result
|
|
134
|
+
|
|
135
|
+
return _parse_content_by_extension(path, content_result.ok_value)
|
|
136
|
+
|
|
137
|
+
|
|
124
138
|
def validate_config(
|
|
125
139
|
data: dict[str, object],
|
|
126
140
|
model: type[BaseModel],
|
|
@@ -625,7 +625,12 @@ def _is_ip_safe(raw_ip: str) -> bool:
|
|
|
625
625
|
return True
|
|
626
626
|
|
|
627
627
|
return not (
|
|
628
|
-
addr.is_private
|
|
628
|
+
addr.is_private
|
|
629
|
+
or addr.is_loopback
|
|
630
|
+
or addr.is_link_local
|
|
631
|
+
or addr.is_reserved
|
|
632
|
+
or getattr(addr, "is_multicast", False)
|
|
633
|
+
or getattr(addr, "is_unspecified", False)
|
|
629
634
|
)
|
|
630
635
|
|
|
631
636
|
|
|
@@ -97,6 +97,12 @@ def decode_jwt(
|
|
|
97
97
|
PyJWTError: If the token is invalid, expired, or has incorrect claims.
|
|
98
98
|
|
|
99
99
|
"""
|
|
100
|
+
if not isinstance(algorithms, list):
|
|
101
|
+
raise TypeError("Algorithms must be a list of strings")
|
|
102
|
+
|
|
103
|
+
if not isinstance(audience, (str, list, tuple, set)):
|
|
104
|
+
raise TypeError("Audience must be a string or iterable of strings")
|
|
105
|
+
|
|
100
106
|
if any(
|
|
101
107
|
isinstance(alg, str) and secrets.compare_digest(alg.strip().lower(), "none")
|
|
102
108
|
for alg in algorithms
|
|
@@ -14,10 +14,6 @@ else:
|
|
|
14
14
|
|
|
15
15
|
from taipanstack.utils.logging import REDACTED_VALUE, SENSITIVE_KEY_PATTERNS
|
|
16
16
|
|
|
17
|
-
JSONValue: TypeAlias = (
|
|
18
|
-
dict[str, "JSONValue"] | list["JSONValue"] | str | int | float | bool | None
|
|
19
|
-
)
|
|
20
|
-
|
|
21
17
|
__all__ = ["SecureBaseModel"]
|
|
22
18
|
|
|
23
19
|
_SENSITIVE_KEY_REGEX = (
|
|
@@ -29,9 +25,9 @@ _SENSITIVE_KEY_REGEX = (
|
|
|
29
25
|
_MAX_RECURSION_DEPTH = 100
|
|
30
26
|
|
|
31
27
|
|
|
32
|
-
def _mask_dict(data: dict[str,
|
|
28
|
+
def _mask_dict(data: dict[str, object], depth: int) -> dict[str, object]:
|
|
33
29
|
"""Mask sensitive keys in a dictionary."""
|
|
34
|
-
masked: dict[str,
|
|
30
|
+
masked: dict[str, object] = {}
|
|
35
31
|
for k, v in data.items():
|
|
36
32
|
if (
|
|
37
33
|
isinstance(k, str)
|
|
@@ -44,12 +40,22 @@ def _mask_dict(data: dict[str, JSONValue], depth: int) -> dict[str, JSONValue]:
|
|
|
44
40
|
return masked
|
|
45
41
|
|
|
46
42
|
|
|
47
|
-
def _mask_list(data: list[
|
|
43
|
+
def _mask_list(data: list[object], depth: int) -> list[object]:
|
|
48
44
|
"""Mask sensitive keys in a list."""
|
|
49
45
|
return [_mask_data(item, depth) for item in data]
|
|
50
46
|
|
|
51
47
|
|
|
52
|
-
def
|
|
48
|
+
def _mask_tuple(data: tuple[object, ...], depth: int) -> tuple[object, ...]:
|
|
49
|
+
"""Mask sensitive keys in a tuple."""
|
|
50
|
+
return tuple(_mask_data(item, depth) for item in data)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _mask_set(data: set[object], depth: int) -> set[object]:
|
|
54
|
+
"""Mask sensitive keys in a set."""
|
|
55
|
+
return {_mask_data(item, depth) for item in data}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _mask_data(data: object, _depth: int = 0) -> object: # noqa: PLR0911
|
|
53
59
|
"""Recursively mask sensitive keys in data."""
|
|
54
60
|
if _SENSITIVE_KEY_REGEX is None:
|
|
55
61
|
return data
|
|
@@ -59,9 +65,16 @@ def _mask_data(data: JSONValue, _depth: int = 0) -> JSONValue:
|
|
|
59
65
|
return "<MAX_DEPTH_REACHED>"
|
|
60
66
|
|
|
61
67
|
if isinstance(data, dict):
|
|
62
|
-
|
|
68
|
+
# The cast ensures that we type check against the dictionary types,
|
|
69
|
+
# but technically we only mask string keys in dicts in Pydantic.
|
|
70
|
+
# We can safely cast it because Pydantic mostly yields dict[str, object].
|
|
71
|
+
return _mask_dict(cast(dict[str, object], data), _depth + 1)
|
|
63
72
|
if isinstance(data, list):
|
|
64
|
-
return _mask_list(data, _depth + 1)
|
|
73
|
+
return _mask_list(cast(list[object], data), _depth + 1)
|
|
74
|
+
if isinstance(data, tuple):
|
|
75
|
+
return _mask_tuple(cast(tuple[object, ...], data), _depth + 1)
|
|
76
|
+
if isinstance(data, set):
|
|
77
|
+
return _mask_set(cast(set[object], data), _depth + 1)
|
|
65
78
|
return data
|
|
66
79
|
|
|
67
80
|
|
|
@@ -9,13 +9,10 @@ import re
|
|
|
9
9
|
from pathlib import Path
|
|
10
10
|
|
|
11
11
|
# Constants to avoid magic values (PLR2004)
|
|
12
|
-
MAX_SQL_IDENTIFIER_LENGTH = 128 # pragma: no mutate
|
|
13
12
|
MAX_PATH_LENGTH = 4096 # pragma: no mutate
|
|
14
|
-
MAX_ENV_VALUE_LENGTH = 65535 # pragma: no mutate
|
|
15
13
|
|
|
16
14
|
# Pre-compiled regex and sets for Performance Benchmarks
|
|
17
15
|
_INVALID_FILENAME_CHARS_RE = re.compile(r'[<>:"/\\|?*\x00-\x1f]') # pragma: no mutate
|
|
18
|
-
_SQL_IDENTIFIER_DENY_RE = re.compile(r"[^a-zA-Z0-9_]") # pragma: no mutate
|
|
19
16
|
_HTML_TAGS_RE = re.compile(r"<[^>]+>") # pragma: no mutate
|
|
20
17
|
# Remove control characters (C0 and C1 sets)
|
|
21
18
|
_CONTROL_CHARS_RE = re.compile(
|
|
@@ -398,116 +395,3 @@ def sanitize_path(
|
|
|
398
395
|
|
|
399
396
|
_validate_path_depth(sanitized, max_depth)
|
|
400
397
|
return _apply_base_dir_constraint(sanitized, base_dir, resolve)
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
def _sanitize_env_multiline(value: str, max_length: int) -> str:
|
|
404
|
-
"""Sanitize an environment value allowing multiline characters."""
|
|
405
|
-
if "\x00" not in value and len(value) <= max_length:
|
|
406
|
-
return value
|
|
407
|
-
return value.replace("\x00", "")
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
def _sanitize_env_singleline(value: str, max_length: int) -> str:
|
|
411
|
-
"""Sanitize an environment value, converting multiline to spaces."""
|
|
412
|
-
if (
|
|
413
|
-
"\x00" not in value
|
|
414
|
-
and "\n" not in value
|
|
415
|
-
and "\r" not in value
|
|
416
|
-
and len(value) <= max_length
|
|
417
|
-
):
|
|
418
|
-
return value
|
|
419
|
-
return value.replace("\x00", "").replace("\n", " ").replace("\r", " ")
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
def sanitize_env_value(
|
|
423
|
-
value: str,
|
|
424
|
-
*,
|
|
425
|
-
max_length: int = 4096,
|
|
426
|
-
allow_multiline: bool = False,
|
|
427
|
-
) -> str:
|
|
428
|
-
"""Sanitize a value for use as an environment variable.
|
|
429
|
-
|
|
430
|
-
Args:
|
|
431
|
-
value: The value to sanitize.
|
|
432
|
-
max_length: Maximum length allowed.
|
|
433
|
-
allow_multiline: Whether to allow newlines.
|
|
434
|
-
|
|
435
|
-
Returns:
|
|
436
|
-
The sanitized value.
|
|
437
|
-
|
|
438
|
-
Raises:
|
|
439
|
-
TypeError: If value is not a string.
|
|
440
|
-
|
|
441
|
-
"""
|
|
442
|
-
if not isinstance(value, str):
|
|
443
|
-
raise TypeError(f"value must be str, got {type(value).__name__}")
|
|
444
|
-
|
|
445
|
-
if len(value) > MAX_ENV_VALUE_LENGTH:
|
|
446
|
-
raise ValueError("Environment value length exceeds maximum allowed limit")
|
|
447
|
-
|
|
448
|
-
if not value:
|
|
449
|
-
return ""
|
|
450
|
-
|
|
451
|
-
if allow_multiline:
|
|
452
|
-
result = _sanitize_env_multiline(value, max_length)
|
|
453
|
-
else:
|
|
454
|
-
result = _sanitize_env_singleline(value, max_length)
|
|
455
|
-
|
|
456
|
-
if len(result) > max_length:
|
|
457
|
-
return result[:max_length]
|
|
458
|
-
return result
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
def _sanitize_sql_identifier_slow_path(identifier: str) -> str:
|
|
462
|
-
"""Apply slow path sanitization for SQL identifiers."""
|
|
463
|
-
result = _SQL_IDENTIFIER_DENY_RE.sub("", identifier)
|
|
464
|
-
|
|
465
|
-
# Must start with letter or underscore
|
|
466
|
-
if result and not result[0].isalpha() and result[0] != "_":
|
|
467
|
-
result = f"_{result}"
|
|
468
|
-
|
|
469
|
-
# Check length (most DBs limit to 128 chars)
|
|
470
|
-
if len(result) > MAX_SQL_IDENTIFIER_LENGTH:
|
|
471
|
-
result = result[:MAX_SQL_IDENTIFIER_LENGTH]
|
|
472
|
-
|
|
473
|
-
if not result:
|
|
474
|
-
msg = "SQL identifier contains no valid characters"
|
|
475
|
-
raise ValueError(msg)
|
|
476
|
-
|
|
477
|
-
return result
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
def sanitize_sql_identifier(identifier: str) -> str:
|
|
481
|
-
"""Sanitize a SQL identifier (table/column name).
|
|
482
|
-
|
|
483
|
-
Note: This is NOT for SQL values - use parameterized queries for those!
|
|
484
|
-
|
|
485
|
-
Args:
|
|
486
|
-
identifier: The identifier to sanitize.
|
|
487
|
-
|
|
488
|
-
Returns:
|
|
489
|
-
The sanitized identifier.
|
|
490
|
-
|
|
491
|
-
Raises:
|
|
492
|
-
TypeError: If identifier is not a string.
|
|
493
|
-
ValueError: If identifier is empty or too long.
|
|
494
|
-
|
|
495
|
-
"""
|
|
496
|
-
if type(identifier) is str:
|
|
497
|
-
if (
|
|
498
|
-
len(identifier) <= 128 # noqa: PLR2004
|
|
499
|
-
and identifier.isascii()
|
|
500
|
-
and identifier.isidentifier()
|
|
501
|
-
):
|
|
502
|
-
return identifier
|
|
503
|
-
|
|
504
|
-
if not identifier:
|
|
505
|
-
msg = "SQL identifier cannot be empty"
|
|
506
|
-
raise ValueError(msg)
|
|
507
|
-
|
|
508
|
-
if len(identifier) > MAX_PATH_LENGTH:
|
|
509
|
-
raise ValueError("SQL identifier length exceeds maximum allowed limit")
|
|
510
|
-
|
|
511
|
-
return _sanitize_sql_identifier_slow_path(identifier)
|
|
512
|
-
|
|
513
|
-
raise TypeError(f"identifier must be str, got {type(identifier).__name__}")
|
|
@@ -68,7 +68,49 @@ def _is_sensitive(key: object, regex: re.Pattern[str] | None) -> bool:
|
|
|
68
68
|
return bool(regex.search(key))
|
|
69
69
|
|
|
70
70
|
|
|
71
|
-
def
|
|
71
|
+
def _redact_mapping(
|
|
72
|
+
obj: MutableMapping[object, object], seen: set[int]
|
|
73
|
+
) -> dict[object, object]:
|
|
74
|
+
"""Redact a mapping object."""
|
|
75
|
+
seen.add(id(obj))
|
|
76
|
+
return {
|
|
77
|
+
k: (
|
|
78
|
+
REDACTED_VALUE
|
|
79
|
+
if _is_sensitive(k, _SENSITIVE_KEY_REGEX)
|
|
80
|
+
else _redact(v, seen)
|
|
81
|
+
)
|
|
82
|
+
for k, v in obj.items()
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _redact_list(obj: list[object], seen: set[int]) -> list[object]:
|
|
87
|
+
"""Redact a list object."""
|
|
88
|
+
seen.add(id(obj))
|
|
89
|
+
return [_redact(item, seen) for item in obj]
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _redact_tuple(obj: tuple[object, ...], seen: set[int]) -> tuple[object, ...]:
|
|
93
|
+
"""Redact a tuple object."""
|
|
94
|
+
seen.add(id(obj))
|
|
95
|
+
return tuple(_redact(item, seen) for item in obj)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _redact_set(obj: set[object], seen: set[int]) -> set[object]:
|
|
99
|
+
"""Redact a set object."""
|
|
100
|
+
seen.add(id(obj))
|
|
101
|
+
redacted = set()
|
|
102
|
+
for item in obj:
|
|
103
|
+
redacted_item = _redact(item, seen)
|
|
104
|
+
try:
|
|
105
|
+
redacted.add(redacted_item)
|
|
106
|
+
except TypeError:
|
|
107
|
+
# If the redacted item is unhashable (e.g. a nested mutable object
|
|
108
|
+
# that was partially redacted or changed type), fallback to string
|
|
109
|
+
redacted.add(str(redacted_item))
|
|
110
|
+
return redacted
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _redact(obj: object, seen: set[int] | None = None) -> object: # noqa: PLR0911
|
|
72
114
|
"""Redact sensitive data recursively with circular reference protection.
|
|
73
115
|
|
|
74
116
|
Args:
|
|
@@ -90,24 +132,16 @@ def _redact(obj: object, seen: set[int] | None = None) -> object:
|
|
|
90
132
|
return REDACTED_VALUE
|
|
91
133
|
|
|
92
134
|
if isinstance(obj, MutableMapping):
|
|
93
|
-
|
|
94
|
-
# Create a new dict to avoid in-place mutation of shared state
|
|
95
|
-
return {
|
|
96
|
-
k: (
|
|
97
|
-
REDACTED_VALUE
|
|
98
|
-
if _is_sensitive(k, _SENSITIVE_KEY_REGEX)
|
|
99
|
-
else _redact(v, seen)
|
|
100
|
-
)
|
|
101
|
-
for k, v in obj.items()
|
|
102
|
-
}
|
|
135
|
+
return _redact_mapping(obj, seen)
|
|
103
136
|
|
|
104
137
|
if isinstance(obj, list):
|
|
105
|
-
|
|
106
|
-
return [_redact(item, seen) for item in obj]
|
|
138
|
+
return _redact_list(obj, seen)
|
|
107
139
|
|
|
108
140
|
if isinstance(obj, tuple):
|
|
109
|
-
|
|
110
|
-
|
|
141
|
+
return _redact_tuple(obj, seen)
|
|
142
|
+
|
|
143
|
+
if isinstance(obj, set):
|
|
144
|
+
return _redact_set(obj, seen)
|
|
111
145
|
|
|
112
146
|
return obj
|
|
113
147
|
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
@@ -11,6 +11,10 @@ import asyncio
|
|
|
11
11
|
import logging
|
|
12
12
|
from typing import TYPE_CHECKING
|
|
13
13
|
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
import redis.asyncio as aioredis
|
|
16
|
+
from sqlalchemy.ext.asyncio import AsyncEngine
|
|
17
|
+
|
|
14
18
|
from taipanstack.core.result import Err, Ok, Result
|
|
15
19
|
from taipanstack.resilience.circuit_breaker import (
|
|
16
20
|
CircuitBreaker,
|
|
@@ -39,10 +43,6 @@ try:
|
|
|
39
43
|
except ImportError:
|
|
40
44
|
_HAS_REDIS = False
|
|
41
45
|
|
|
42
|
-
if TYPE_CHECKING:
|
|
43
|
-
import redis.asyncio as aioredis
|
|
44
|
-
from sqlalchemy.ext.asyncio import AsyncEngine
|
|
45
|
-
|
|
46
46
|
|
|
47
47
|
def _breaker_is_open(cb: CircuitBreaker) -> CircuitBreakerError | None:
|
|
48
48
|
"""Return a ``CircuitBreakerError`` if the breaker is OPEN.
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/resilience/adaptive/adaptive_breaker.py
RENAMED
|
File without changes
|
{taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/resilience/adaptive/adaptive_retry.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/resilience/watchdogs/health_pinger.py
RENAMED
|
File without changes
|
{taipanstack-0.5.1 → taipanstack-0.5.2}/src/taipanstack/resilience/watchdogs/resource_watcher.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|