taipanstack 0.3.10__tar.gz → 0.3.11__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.3.10 → taipanstack-0.3.11}/PKG-INFO +1 -1
- {taipanstack-0.3.10 → taipanstack-0.3.11}/pyproject.toml +2 -2
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/__init__.py +1 -1
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/core/optimizations.py +24 -25
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/core/result.py +0 -84
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/security/decorators.py +19 -10
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/security/guards.py +93 -70
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/security/jwt.py +2 -2
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/security/models.py +9 -3
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/security/sanitizers.py +23 -8
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/utils/circuit_breaker.py +17 -3
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/utils/resilience.py +15 -18
- {taipanstack-0.3.10 → taipanstack-0.3.11}/LICENSE +0 -0
- {taipanstack-0.3.10 → taipanstack-0.3.11}/README.md +0 -0
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/config/__init__.py +0 -0
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/config/generators.py +0 -0
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/config/models.py +0 -0
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/config/version_config.py +0 -0
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/core/__init__.py +0 -0
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/core/compat.py +0 -0
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/security/__init__.py +0 -0
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/security/password.py +0 -0
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/security/types.py +0 -0
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/security/validators.py +0 -0
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/utils/__init__.py +0 -0
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/utils/cache.py +0 -0
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/utils/concurrency.py +0 -0
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/utils/context.py +0 -0
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/utils/filesystem.py +0 -0
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/utils/logging.py +0 -0
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/utils/metrics.py +0 -0
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/utils/rate_limit.py +0 -0
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/utils/retry.py +0 -0
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/utils/serialization.py +0 -0
- {taipanstack-0.3.10 → taipanstack-0.3.11}/src/taipanstack/utils/subprocess.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "taipanstack"
|
|
3
|
-
version = "0.3.
|
|
3
|
+
version = "0.3.11"
|
|
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"}
|
|
@@ -202,7 +202,7 @@ exclude_lines = [
|
|
|
202
202
|
"if __name__ == .__main__.:",
|
|
203
203
|
"@abstractmethod",
|
|
204
204
|
"@overload",
|
|
205
|
-
"def __call__\\(.*\\) -> .*:\\s
|
|
205
|
+
"def __call__\\(.*\\) -> .*:\\s*(?:\"\"\".*?\"\"\"\\s*)?\\.\\.\\.",
|
|
206
206
|
]
|
|
207
207
|
partial_branches = [
|
|
208
208
|
"pragma: no branch",
|
|
@@ -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.3.
|
|
8
|
+
__version__ = "0.3.11"
|
|
9
9
|
|
|
10
10
|
from taipanstack.config.version_config import (
|
|
11
11
|
VersionRecommendations,
|
|
@@ -206,32 +206,31 @@ def get_optimization_profile(*, force_refresh: bool = False) -> OptimizationProf
|
|
|
206
206
|
profile = _PROFILE_311
|
|
207
207
|
|
|
208
208
|
# Adjust for optimization level
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
209
|
+
match opt_level:
|
|
210
|
+
case opt if opt == OPT_LEVEL_NONE:
|
|
211
|
+
# Minimal optimizations - use 3.11 baseline
|
|
212
|
+
_cached_optimization_profile = _PROFILE_311
|
|
213
|
+
case opt if opt == OPT_LEVEL_AGGRESSIVE and experimental:
|
|
214
|
+
# Aggressive mode - enable experimental features
|
|
215
|
+
_cached_optimization_profile = OptimizationProfile(
|
|
216
|
+
gc_threshold_0=profile.gc_threshold_0,
|
|
217
|
+
gc_threshold_1=profile.gc_threshold_1,
|
|
218
|
+
gc_threshold_2=profile.gc_threshold_2,
|
|
219
|
+
gc_freeze_enabled=profile.gc_freeze_enabled,
|
|
220
|
+
thread_pool_multiplier=profile.thread_pool_multiplier,
|
|
221
|
+
max_thread_pool_size=profile.max_thread_pool_size,
|
|
222
|
+
prefer_slots=profile.prefer_slots,
|
|
223
|
+
use_frozen_dataclasses=profile.use_frozen_dataclasses,
|
|
224
|
+
prefer_match_statements=profile.prefer_match_statements,
|
|
225
|
+
prefer_exception_groups=profile.prefer_exception_groups,
|
|
226
|
+
prefer_type_params=profile.prefer_type_params,
|
|
227
|
+
enable_perf_hints=profile.enable_perf_hints,
|
|
228
|
+
aggressive_inlining=profile.aggressive_inlining,
|
|
229
|
+
enable_experimental=True,
|
|
230
|
+
)
|
|
231
|
+
case _:
|
|
232
|
+
_cached_optimization_profile = profile
|
|
233
233
|
|
|
234
|
-
_cached_optimization_profile = profile
|
|
235
234
|
return _cached_optimization_profile
|
|
236
235
|
|
|
237
236
|
|
|
@@ -38,8 +38,6 @@ __all__ = [
|
|
|
38
38
|
"map_async",
|
|
39
39
|
"safe",
|
|
40
40
|
"safe_from",
|
|
41
|
-
"unwrap_or",
|
|
42
|
-
"unwrap_or_else",
|
|
43
41
|
]
|
|
44
42
|
|
|
45
43
|
P = ParamSpec("P")
|
|
@@ -211,88 +209,6 @@ def collect_results(
|
|
|
211
209
|
return Ok(values)
|
|
212
210
|
|
|
213
211
|
|
|
214
|
-
@overload
|
|
215
|
-
def unwrap_or(result: Ok[T], default: U) -> T: ...
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
@overload
|
|
219
|
-
def unwrap_or(result: Err[E], default: U) -> U: ...
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
@overload
|
|
223
|
-
def unwrap_or(result: Result[T, E], default: U) -> T | U: ...
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
def unwrap_or(result: Result[T, E], default: U) -> T | U:
|
|
227
|
-
"""Extract value from Result or return default.
|
|
228
|
-
|
|
229
|
-
Args:
|
|
230
|
-
result: The Result to unwrap.
|
|
231
|
-
default: Default value if result is Err.
|
|
232
|
-
|
|
233
|
-
Returns:
|
|
234
|
-
The Ok value or the default.
|
|
235
|
-
|
|
236
|
-
Example:
|
|
237
|
-
>>> unwrap_or(Ok(42), 0)
|
|
238
|
-
42
|
|
239
|
-
>>> unwrap_or(Err("error"), 0)
|
|
240
|
-
0
|
|
241
|
-
|
|
242
|
-
"""
|
|
243
|
-
try:
|
|
244
|
-
return result.ok_value # type: ignore[union-attr]
|
|
245
|
-
except AttributeError:
|
|
246
|
-
return default
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
@overload
|
|
250
|
-
def unwrap_or_else(
|
|
251
|
-
result: Ok[T],
|
|
252
|
-
default_fn: Callable[[E], U],
|
|
253
|
-
) -> T: ...
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
@overload
|
|
257
|
-
def unwrap_or_else(
|
|
258
|
-
result: Err[E],
|
|
259
|
-
default_fn: Callable[[E], U],
|
|
260
|
-
) -> U: ...
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
@overload
|
|
264
|
-
def unwrap_or_else(
|
|
265
|
-
result: Result[T, E],
|
|
266
|
-
default_fn: Callable[[E], U],
|
|
267
|
-
) -> T | U: ...
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
def unwrap_or_else(
|
|
271
|
-
result: Result[T, E],
|
|
272
|
-
default_fn: Callable[[E], U],
|
|
273
|
-
) -> T | U:
|
|
274
|
-
"""Extract value from Result or compute default from error.
|
|
275
|
-
|
|
276
|
-
Args:
|
|
277
|
-
result: The Result to unwrap.
|
|
278
|
-
default_fn: Function to compute default from error.
|
|
279
|
-
|
|
280
|
-
Returns:
|
|
281
|
-
The Ok value or computed default.
|
|
282
|
-
|
|
283
|
-
Example:
|
|
284
|
-
>>> unwrap_or_else(Ok(42), lambda e: 0)
|
|
285
|
-
42
|
|
286
|
-
>>> unwrap_or_else(Err(ValueError("x")), lambda e: len(str(e)))
|
|
287
|
-
1
|
|
288
|
-
|
|
289
|
-
"""
|
|
290
|
-
try:
|
|
291
|
-
return result.ok_value # type: ignore[union-attr]
|
|
292
|
-
except AttributeError:
|
|
293
|
-
return default_fn(result.err_value) # type: ignore[union-attr]
|
|
294
|
-
|
|
295
|
-
|
|
296
212
|
@overload
|
|
297
213
|
async def map_async(
|
|
298
214
|
result: Ok[T],
|
|
@@ -11,16 +11,25 @@ import inspect
|
|
|
11
11
|
import signal
|
|
12
12
|
import sys
|
|
13
13
|
import threading
|
|
14
|
-
import
|
|
15
|
-
from collections.abc import Callable, Mapping
|
|
14
|
+
from collections.abc import Callable
|
|
16
15
|
from types import FrameType
|
|
17
|
-
from typing import ParamSpec, TypeVar
|
|
16
|
+
from typing import Any, ParamSpec, Protocol, TypeVar
|
|
18
17
|
|
|
19
18
|
from taipanstack.security.guards import SecurityError
|
|
20
19
|
|
|
21
20
|
P = ParamSpec("P")
|
|
22
21
|
R = TypeVar("R")
|
|
23
22
|
T = TypeVar("T")
|
|
23
|
+
V_contra = TypeVar("V_contra", contravariant=True)
|
|
24
|
+
V_co = TypeVar("V_co", covariant=True)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ValidatorFunc(Protocol[V_contra, V_co]):
|
|
28
|
+
"""Protocol defining the signature of input validators."""
|
|
29
|
+
|
|
30
|
+
def __call__(self, value: V_contra, /) -> V_co:
|
|
31
|
+
"""Validate an input value."""
|
|
32
|
+
...
|
|
24
33
|
|
|
25
34
|
|
|
26
35
|
class OperationTimeoutError(Exception):
|
|
@@ -62,7 +71,7 @@ class ValidationError(Exception):
|
|
|
62
71
|
|
|
63
72
|
|
|
64
73
|
def validate_inputs(
|
|
65
|
-
**validators:
|
|
74
|
+
**validators: ValidatorFunc[Any, Any],
|
|
66
75
|
) -> Callable[[Callable[P, R]], Callable[P, R]]:
|
|
67
76
|
"""Decorator to validate function inputs.
|
|
68
77
|
|
|
@@ -222,13 +231,13 @@ def timeout(
|
|
|
222
231
|
func,
|
|
223
232
|
seconds,
|
|
224
233
|
args,
|
|
225
|
-
kwargs,
|
|
234
|
+
dict(kwargs),
|
|
226
235
|
)
|
|
227
236
|
return _timeout_with_thread(
|
|
228
237
|
func,
|
|
229
238
|
seconds,
|
|
230
239
|
args,
|
|
231
|
-
kwargs,
|
|
240
|
+
dict(kwargs),
|
|
232
241
|
)
|
|
233
242
|
|
|
234
243
|
return wrapper
|
|
@@ -239,8 +248,8 @@ def timeout(
|
|
|
239
248
|
def _timeout_with_signal( # pragma: no cover
|
|
240
249
|
func: Callable[P, R],
|
|
241
250
|
seconds: float,
|
|
242
|
-
args: tuple[
|
|
243
|
-
kwargs:
|
|
251
|
+
args: tuple[Any, ...],
|
|
252
|
+
kwargs: dict[str, Any],
|
|
244
253
|
) -> R:
|
|
245
254
|
"""Implement timeout using Unix signals."""
|
|
246
255
|
|
|
@@ -262,8 +271,8 @@ def _timeout_with_signal( # pragma: no cover
|
|
|
262
271
|
def _timeout_with_thread(
|
|
263
272
|
func: Callable[P, R],
|
|
264
273
|
seconds: float,
|
|
265
|
-
args: tuple[
|
|
266
|
-
kwargs:
|
|
274
|
+
args: tuple[Any, ...],
|
|
275
|
+
kwargs: dict[str, Any],
|
|
267
276
|
) -> R:
|
|
268
277
|
"""Implement timeout using a separate thread."""
|
|
269
278
|
result: list[R] = []
|
|
@@ -129,6 +129,51 @@ class SecurityError(Exception):
|
|
|
129
129
|
super().__init__(f"[{guard_name}] {message}")
|
|
130
130
|
|
|
131
131
|
|
|
132
|
+
def _check_traversal_patterns(path_str: str) -> None:
|
|
133
|
+
"""Check for explicit traversal patterns before resolution."""
|
|
134
|
+
match = TRAVERSAL_REGEX.search(path_str.lower())
|
|
135
|
+
if match:
|
|
136
|
+
raise SecurityError(
|
|
137
|
+
f"Path traversal pattern detected: {match.group(0)}",
|
|
138
|
+
guard_name="path_traversal",
|
|
139
|
+
value=path_str[:50], # Truncate for safety
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _resolve_and_check_bounds(path: Path, base_dir: Path) -> tuple[Path, Path]:
|
|
144
|
+
"""Resolve the path and check if it is within base_dir."""
|
|
145
|
+
try:
|
|
146
|
+
full_path = path if path.is_absolute() else (base_dir / path)
|
|
147
|
+
resolved = full_path.resolve()
|
|
148
|
+
except (OSError, ValueError) as e:
|
|
149
|
+
raise SecurityError(
|
|
150
|
+
f"Invalid path: {e}",
|
|
151
|
+
guard_name="path_traversal",
|
|
152
|
+
) from e
|
|
153
|
+
|
|
154
|
+
if not resolved.is_relative_to(base_dir):
|
|
155
|
+
raise SecurityError(
|
|
156
|
+
"Path escapes base directory",
|
|
157
|
+
guard_name="path_traversal",
|
|
158
|
+
)
|
|
159
|
+
return full_path, resolved
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _check_symlink_safety(full_path: Path, base_dir: Path) -> None:
|
|
163
|
+
"""Check for symlinks recursively up to the base directory."""
|
|
164
|
+
current = full_path
|
|
165
|
+
# Only check components from the user-provided path, not the base_dir
|
|
166
|
+
while current not in (base_dir, current.parent):
|
|
167
|
+
# We don't check .exists() because it returns False for broken symlinks
|
|
168
|
+
if current.is_symlink():
|
|
169
|
+
raise SecurityError(
|
|
170
|
+
"Symlinks are not allowed",
|
|
171
|
+
guard_name="path_traversal",
|
|
172
|
+
value=str(current),
|
|
173
|
+
)
|
|
174
|
+
current = current.parent
|
|
175
|
+
|
|
176
|
+
|
|
132
177
|
def guard_path_traversal(
|
|
133
178
|
path: Path | str,
|
|
134
179
|
base_dir: Path | str | None = None,
|
|
@@ -158,52 +203,15 @@ def guard_path_traversal(
|
|
|
158
203
|
"""
|
|
159
204
|
if not isinstance(path, (str, Path)):
|
|
160
205
|
raise TypeError(f"path must be str or Path, got {type(path).__name__}")
|
|
161
|
-
path = Path(path) if isinstance(path, str) else path
|
|
162
|
-
base_dir = Path(base_dir).resolve() if base_dir else Path.cwd().resolve()
|
|
163
|
-
|
|
164
|
-
# Check for explicit traversal patterns before resolution
|
|
165
|
-
path_str = str(path)
|
|
166
|
-
path_str_lower = path_str.lower()
|
|
167
|
-
|
|
168
|
-
match = TRAVERSAL_REGEX.search(path_str_lower)
|
|
169
|
-
if match:
|
|
170
|
-
pattern = match.group(0)
|
|
171
|
-
raise SecurityError(
|
|
172
|
-
f"Path traversal pattern detected: {pattern}",
|
|
173
|
-
guard_name="path_traversal",
|
|
174
|
-
value=path_str[:50], # Truncate for safety
|
|
175
|
-
)
|
|
176
206
|
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
full_path = path if path.is_absolute() else (base_dir / path)
|
|
180
|
-
resolved = full_path.resolve()
|
|
181
|
-
except (OSError, ValueError) as e:
|
|
182
|
-
raise SecurityError(
|
|
183
|
-
f"Invalid path: {e}",
|
|
184
|
-
guard_name="path_traversal",
|
|
185
|
-
) from e
|
|
207
|
+
path_obj = Path(path) if isinstance(path, str) else path
|
|
208
|
+
base = Path(base_dir).resolve() if base_dir else Path.cwd().resolve()
|
|
186
209
|
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
raise SecurityError(
|
|
190
|
-
"Path escapes base directory",
|
|
191
|
-
guard_name="path_traversal",
|
|
192
|
-
)
|
|
210
|
+
_check_traversal_patterns(str(path_obj))
|
|
211
|
+
full_path, resolved = _resolve_and_check_bounds(path_obj, base)
|
|
193
212
|
|
|
194
|
-
# Check for symlinks if not allowed
|
|
195
213
|
if not allow_symlinks:
|
|
196
|
-
|
|
197
|
-
# Only check components from the user-provided path, not the base_dir
|
|
198
|
-
while current not in (base_dir, current.parent):
|
|
199
|
-
# We don't check .exists() because it returns False for broken symlinks
|
|
200
|
-
if current.is_symlink():
|
|
201
|
-
raise SecurityError(
|
|
202
|
-
"Symlinks are not allowed",
|
|
203
|
-
guard_name="path_traversal",
|
|
204
|
-
value=str(current),
|
|
205
|
-
)
|
|
206
|
-
current = current.parent
|
|
214
|
+
_check_symlink_safety(full_path, base)
|
|
207
215
|
|
|
208
216
|
return resolved
|
|
209
217
|
|
|
@@ -332,6 +340,47 @@ def guard_file_extension(
|
|
|
332
340
|
return path
|
|
333
341
|
|
|
334
342
|
|
|
343
|
+
def _check_env_denied(
|
|
344
|
+
name_upper: str,
|
|
345
|
+
name: str,
|
|
346
|
+
denied_names: Sequence[str] | None,
|
|
347
|
+
) -> None:
|
|
348
|
+
"""Check if the environment variable is in the denied list."""
|
|
349
|
+
if denied_names is not None:
|
|
350
|
+
denied = frozenset(n.upper() for n in denied_names)
|
|
351
|
+
else:
|
|
352
|
+
denied = _DEFAULT_DENIED_ENV_VARS
|
|
353
|
+
|
|
354
|
+
if name_upper in denied:
|
|
355
|
+
raise SecurityError(
|
|
356
|
+
f"Access to sensitive variable '{name}' is denied",
|
|
357
|
+
guard_name="env_variable",
|
|
358
|
+
value=name,
|
|
359
|
+
)
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def _check_env_sensitive(
|
|
363
|
+
name_upper: str,
|
|
364
|
+
name: str,
|
|
365
|
+
allowed_names: Sequence[str] | None,
|
|
366
|
+
) -> None:
|
|
367
|
+
"""Check if the environment variable matches sensitive patterns."""
|
|
368
|
+
if not _SENSITIVE_ENV_VAR_PATTERN.search(name_upper):
|
|
369
|
+
return
|
|
370
|
+
|
|
371
|
+
# Only block if not explicitly allowed
|
|
372
|
+
if allowed_names is not None:
|
|
373
|
+
allowed = {n.upper() for n in allowed_names}
|
|
374
|
+
if name_upper in allowed:
|
|
375
|
+
return
|
|
376
|
+
|
|
377
|
+
raise SecurityError(
|
|
378
|
+
f"Access to potentially sensitive variable '{name}' is denied",
|
|
379
|
+
guard_name="env_variable",
|
|
380
|
+
value=name,
|
|
381
|
+
)
|
|
382
|
+
|
|
383
|
+
|
|
335
384
|
def guard_env_variable(
|
|
336
385
|
name: str,
|
|
337
386
|
*,
|
|
@@ -365,34 +414,8 @@ def guard_env_variable(
|
|
|
365
414
|
|
|
366
415
|
name_upper = name.upper()
|
|
367
416
|
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
else:
|
|
371
|
-
denied = _DEFAULT_DENIED_ENV_VARS
|
|
372
|
-
|
|
373
|
-
if name_upper in denied:
|
|
374
|
-
raise SecurityError(
|
|
375
|
-
f"Access to sensitive variable '{name}' is denied",
|
|
376
|
-
guard_name="env_variable",
|
|
377
|
-
value=name,
|
|
378
|
-
)
|
|
379
|
-
|
|
380
|
-
if _SENSITIVE_ENV_VAR_PATTERN.search(name_upper):
|
|
381
|
-
# Only block if not explicitly allowed
|
|
382
|
-
if allowed_names is not None:
|
|
383
|
-
allowed = {n.upper() for n in allowed_names}
|
|
384
|
-
if name_upper not in allowed:
|
|
385
|
-
raise SecurityError(
|
|
386
|
-
f"Access to potentially sensitive variable '{name}' is denied",
|
|
387
|
-
guard_name="env_variable",
|
|
388
|
-
value=name,
|
|
389
|
-
)
|
|
390
|
-
else:
|
|
391
|
-
raise SecurityError(
|
|
392
|
-
f"Access to potentially sensitive variable '{name}' is denied",
|
|
393
|
-
guard_name="env_variable",
|
|
394
|
-
value=name,
|
|
395
|
-
)
|
|
417
|
+
_check_env_denied(name_upper, name, denied_names)
|
|
418
|
+
_check_env_sensitive(name_upper, name, allowed_names)
|
|
396
419
|
|
|
397
420
|
# Get the variable
|
|
398
421
|
value = os.environ.get(name)
|
|
@@ -19,7 +19,7 @@ __all__ = ["decode_jwt", "encode_jwt"]
|
|
|
19
19
|
JWTPayload: TypeAlias = dict[str, object]
|
|
20
20
|
|
|
21
21
|
|
|
22
|
-
@safe_from(PyJWTError, ValueError)
|
|
22
|
+
@safe_from(PyJWTError, ValueError, TypeError)
|
|
23
23
|
def encode_jwt(
|
|
24
24
|
payload: JWTPayload,
|
|
25
25
|
secret_key: str,
|
|
@@ -48,7 +48,7 @@ def encode_jwt(
|
|
|
48
48
|
return jwt.encode(payload, secret_key, algorithm=algorithm)
|
|
49
49
|
|
|
50
50
|
|
|
51
|
-
@safe_from(PyJWTError, ValueError)
|
|
51
|
+
@safe_from(PyJWTError, ValueError, TypeError, AttributeError)
|
|
52
52
|
def decode_jwt(
|
|
53
53
|
token: str,
|
|
54
54
|
secret_key: str,
|
|
@@ -21,22 +21,28 @@ _SENSITIVE_KEY_REGEX = (
|
|
|
21
21
|
else None
|
|
22
22
|
)
|
|
23
23
|
|
|
24
|
+
_MAX_RECURSION_DEPTH = 100
|
|
24
25
|
|
|
25
|
-
|
|
26
|
+
|
|
27
|
+
def _mask_data(data: JSONValue, _depth: int = 0) -> JSONValue:
|
|
26
28
|
"""Recursively mask sensitive keys in data."""
|
|
27
29
|
if _SENSITIVE_KEY_REGEX is None:
|
|
28
30
|
return data
|
|
29
31
|
|
|
32
|
+
# Prevent ReDoS or stack overflow on deeply nested payloads
|
|
33
|
+
if _depth > _MAX_RECURSION_DEPTH:
|
|
34
|
+
return "<MAX_DEPTH_REACHED>"
|
|
35
|
+
|
|
30
36
|
if isinstance(data, dict):
|
|
31
37
|
masked: dict[str, JSONValue] = {}
|
|
32
38
|
for k, v in data.items():
|
|
33
39
|
if isinstance(k, str) and _SENSITIVE_KEY_REGEX.search(k):
|
|
34
40
|
masked[k] = REDACTED_VALUE
|
|
35
41
|
else:
|
|
36
|
-
masked[k] = _mask_data(v)
|
|
42
|
+
masked[k] = _mask_data(v, _depth + 1)
|
|
37
43
|
return masked
|
|
38
44
|
if isinstance(data, list):
|
|
39
|
-
return [_mask_data(item) for item in data]
|
|
45
|
+
return [_mask_data(item, _depth + 1) for item in data]
|
|
40
46
|
return data
|
|
41
47
|
|
|
42
48
|
|
|
@@ -145,7 +145,7 @@ def sanitize_filename(
|
|
|
145
145
|
raise TypeError(f"filename must be str, got {type(filename).__name__}")
|
|
146
146
|
|
|
147
147
|
if not filename:
|
|
148
|
-
|
|
148
|
+
filename = "unnamed"
|
|
149
149
|
|
|
150
150
|
# Get parts
|
|
151
151
|
original_path = Path(filename)
|
|
@@ -153,7 +153,11 @@ def sanitize_filename(
|
|
|
153
153
|
suffix = original_path.suffix if preserve_extension else ""
|
|
154
154
|
|
|
155
155
|
# Remove invalid characters using precompiled regex for performance
|
|
156
|
-
|
|
156
|
+
try:
|
|
157
|
+
# Use lambda to avoid processing regex escape sequences in replacement string
|
|
158
|
+
safe_stem = _INVALID_FILENAME_CHARS_RE.sub(lambda _: replacement, stem)
|
|
159
|
+
except re.error: # pragma: no cover
|
|
160
|
+
safe_stem = _INVALID_FILENAME_CHARS_RE.sub("_", stem)
|
|
157
161
|
|
|
158
162
|
# Remove leading/trailing dots and spaces (Windows issues)
|
|
159
163
|
safe_stem = safe_stem.strip(". ")
|
|
@@ -164,7 +168,18 @@ def sanitize_filename(
|
|
|
164
168
|
|
|
165
169
|
# Collapse multiple replacement chars
|
|
166
170
|
if replacement:
|
|
167
|
-
|
|
171
|
+
try:
|
|
172
|
+
safe_stem = re.sub(
|
|
173
|
+
f"({re.escape(replacement)})+",
|
|
174
|
+
lambda _: replacement,
|
|
175
|
+
safe_stem,
|
|
176
|
+
)
|
|
177
|
+
except re.error: # pragma: no cover
|
|
178
|
+
safe_stem = re.sub(
|
|
179
|
+
f"({re.escape(replacement)})+",
|
|
180
|
+
"_",
|
|
181
|
+
safe_stem,
|
|
182
|
+
)
|
|
168
183
|
safe_stem = safe_stem.strip(replacement)
|
|
169
184
|
|
|
170
185
|
# Handle reserved names (Windows)
|
|
@@ -225,7 +240,7 @@ def _apply_base_dir_constraint(
|
|
|
225
240
|
if not sanitized.is_absolute(): # pragma: no branch
|
|
226
241
|
return base / sanitized
|
|
227
242
|
|
|
228
|
-
return sanitized
|
|
243
|
+
return sanitized
|
|
229
244
|
|
|
230
245
|
|
|
231
246
|
def sanitize_path(
|
|
@@ -261,12 +276,12 @@ def sanitize_path(
|
|
|
261
276
|
|
|
262
277
|
# Reconstruct path
|
|
263
278
|
if path.is_absolute(): # pragma: no branch
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
)
|
|
279
|
+
# Use path.anchor to correctly preserve absolute roots on Windows (e.g. C:\)
|
|
280
|
+
anchor = Path(path.anchor)
|
|
281
|
+
sanitized = anchor.joinpath(*parts) if parts else anchor
|
|
267
282
|
elif parts: # pragma: no branch
|
|
268
283
|
sanitized = Path().joinpath(*parts)
|
|
269
|
-
else:
|
|
284
|
+
else:
|
|
270
285
|
sanitized = Path()
|
|
271
286
|
|
|
272
287
|
# Check depth
|
|
@@ -94,6 +94,7 @@ class CircuitBreakerState:
|
|
|
94
94
|
state: CircuitState = CircuitState.CLOSED
|
|
95
95
|
failure_count: int = 0
|
|
96
96
|
success_count: int = 0
|
|
97
|
+
half_open_attempts: int = 0
|
|
97
98
|
last_failure_time: float = 0.0
|
|
98
99
|
lock: threading.Lock = field(default_factory=threading.Lock)
|
|
99
100
|
|
|
@@ -190,8 +191,15 @@ class CircuitBreaker:
|
|
|
190
191
|
# Check if timeout has passed
|
|
191
192
|
elapsed = time.monotonic() - self._state.last_failure_time
|
|
192
193
|
if elapsed >= self.config.timeout:
|
|
194
|
+
# Before transitioning, verify if we can make an attempt
|
|
195
|
+
# This happens in a lock, so it's thread-safe. However, once
|
|
196
|
+
# the state changes to HALF_OPEN, subsequent threads in the
|
|
197
|
+
# same lock block will hit the HALF_OPEN case.
|
|
193
198
|
self._state.state = CircuitState.HALF_OPEN
|
|
194
199
|
self._state.success_count = 0
|
|
200
|
+
# Initialize half_open_attempts to 1 because this first call
|
|
201
|
+
# that transitions the state is also an attempt.
|
|
202
|
+
self._state.half_open_attempts = 1
|
|
195
203
|
logger.info(
|
|
196
204
|
"Circuit %s entering half-open state "
|
|
197
205
|
"(was open for %.1fs, failures=%d)",
|
|
@@ -206,9 +214,12 @@ class CircuitBreaker:
|
|
|
206
214
|
return True
|
|
207
215
|
return False
|
|
208
216
|
|
|
209
|
-
case CircuitState.HALF_OPEN:
|
|
210
|
-
# Allow limited attempts
|
|
211
|
-
|
|
217
|
+
case CircuitState.HALF_OPEN:
|
|
218
|
+
# Allow limited attempts to prevent thundering herd
|
|
219
|
+
if self._state.half_open_attempts < self.config.success_threshold:
|
|
220
|
+
self._state.half_open_attempts += 1
|
|
221
|
+
return True
|
|
222
|
+
return False
|
|
212
223
|
|
|
213
224
|
return False # pragma: no cover — unreachable, satisfies type checker
|
|
214
225
|
|
|
@@ -221,6 +232,7 @@ class CircuitBreaker:
|
|
|
221
232
|
if self._state.success_count >= self.config.success_threshold:
|
|
222
233
|
self._state.state = CircuitState.CLOSED
|
|
223
234
|
self._state.failure_count = 0
|
|
235
|
+
self._state.half_open_attempts = 0
|
|
224
236
|
logger.info(
|
|
225
237
|
"Circuit %s closed after recovery "
|
|
226
238
|
"(%d consecutive successes)",
|
|
@@ -253,6 +265,7 @@ class CircuitBreaker:
|
|
|
253
265
|
case CircuitState.HALF_OPEN:
|
|
254
266
|
# Any failure in half-open reopens circuit
|
|
255
267
|
self._state.state = CircuitState.OPEN
|
|
268
|
+
self._state.half_open_attempts = 0
|
|
256
269
|
logger.warning(
|
|
257
270
|
"Circuit %s reopened after failure in half-open "
|
|
258
271
|
"(total failures=%d)",
|
|
@@ -287,6 +300,7 @@ class CircuitBreaker:
|
|
|
287
300
|
self._state.state = CircuitState.CLOSED
|
|
288
301
|
self._state.failure_count = 0
|
|
289
302
|
self._state.success_count = 0
|
|
303
|
+
self._state.half_open_attempts = 0
|
|
290
304
|
logger.info("Circuit %s manually reset", self.name)
|
|
291
305
|
|
|
292
306
|
def __call__(
|
|
@@ -9,7 +9,7 @@ import functools
|
|
|
9
9
|
import inspect
|
|
10
10
|
import threading
|
|
11
11
|
from collections.abc import Callable, Coroutine
|
|
12
|
-
from typing import Any, ParamSpec, Protocol, TypeVar, cast, overload
|
|
12
|
+
from typing import Any, ParamSpec, Protocol, TypeAlias, TypeVar, cast, overload
|
|
13
13
|
|
|
14
14
|
from taipanstack.core.result import Err, Ok, Result
|
|
15
15
|
|
|
@@ -17,19 +17,22 @@ P = ParamSpec("P")
|
|
|
17
17
|
T = TypeVar("T")
|
|
18
18
|
E = TypeVar("E", bound=Exception)
|
|
19
19
|
|
|
20
|
+
ResultFunc: TypeAlias = Callable[P, Result[T, E]]
|
|
21
|
+
AsyncResultFunc: TypeAlias = Callable[P, Coroutine[Any, Any, Result[T, E]]]
|
|
22
|
+
|
|
20
23
|
|
|
21
24
|
class FallbackDecorator(Protocol):
|
|
22
25
|
"""Protocol for the fallback decorator."""
|
|
23
26
|
|
|
24
27
|
@overload
|
|
25
28
|
def __call__(
|
|
26
|
-
self, func:
|
|
27
|
-
) ->
|
|
29
|
+
self, func: ResultFunc[P, T, E]
|
|
30
|
+
) -> ResultFunc[P, T, E]: ... # pragma: no cover
|
|
28
31
|
|
|
29
32
|
@overload
|
|
30
33
|
def __call__(
|
|
31
|
-
self, func:
|
|
32
|
-
) ->
|
|
34
|
+
self, func: AsyncResultFunc[P, T, E]
|
|
35
|
+
) -> AsyncResultFunc[P, T, E]: ... # pragma: no cover
|
|
33
36
|
|
|
34
37
|
|
|
35
38
|
def fallback(
|
|
@@ -51,19 +54,15 @@ def fallback(
|
|
|
51
54
|
"""
|
|
52
55
|
|
|
53
56
|
def decorator(
|
|
54
|
-
func:
|
|
55
|
-
|
|
56
|
-
),
|
|
57
|
-
) -> Callable[P, Result[T, E]] | Callable[P, Coroutine[Any, Any, Result[T, E]]]:
|
|
57
|
+
func: ResultFunc[P, T, E] | AsyncResultFunc[P, T, E],
|
|
58
|
+
) -> ResultFunc[P, T, E] | AsyncResultFunc[P, T, E]:
|
|
58
59
|
if inspect.iscoroutinefunction(func):
|
|
59
60
|
|
|
60
61
|
@functools.wraps(func)
|
|
61
62
|
async def async_wrapper(*args: P.args, **kwargs: P.kwargs) -> Result[T, E]:
|
|
62
63
|
try:
|
|
63
64
|
# func is a coroutine function here
|
|
64
|
-
func_coro = cast(
|
|
65
|
-
Callable[P, Coroutine[Any, Any, Result[T, E]]], func
|
|
66
|
-
)
|
|
65
|
+
func_coro = cast(AsyncResultFunc[P, T, E], func)
|
|
67
66
|
result = await func_coro(*args, **kwargs)
|
|
68
67
|
match result:
|
|
69
68
|
case Err():
|
|
@@ -80,7 +79,7 @@ def fallback(
|
|
|
80
79
|
def sync_wrapper(*args: P.args, **kwargs: P.kwargs) -> Result[T, E]:
|
|
81
80
|
try:
|
|
82
81
|
# func is a normal function here
|
|
83
|
-
func_sync = cast(
|
|
82
|
+
func_sync = cast(ResultFunc[P, T, E], func)
|
|
84
83
|
result = func_sync(*args, **kwargs)
|
|
85
84
|
match result:
|
|
86
85
|
case Err():
|
|
@@ -101,12 +100,12 @@ class TimeoutDecorator(Protocol):
|
|
|
101
100
|
|
|
102
101
|
@overload
|
|
103
102
|
def __call__(
|
|
104
|
-
self, func:
|
|
103
|
+
self, func: ResultFunc[P, T, E]
|
|
105
104
|
) -> Callable[P, Result[T, TimeoutError | E]]: ... # pragma: no cover
|
|
106
105
|
|
|
107
106
|
@overload
|
|
108
107
|
def __call__(
|
|
109
|
-
self, func:
|
|
108
|
+
self, func: AsyncResultFunc[P, T, E]
|
|
110
109
|
) -> Callable[
|
|
111
110
|
P, Coroutine[Any, Any, Result[T, TimeoutError | E]]
|
|
112
111
|
]: ... # pragma: no cover
|
|
@@ -126,9 +125,7 @@ def timeout(seconds: float) -> TimeoutDecorator:
|
|
|
126
125
|
"""
|
|
127
126
|
|
|
128
127
|
def decorator(
|
|
129
|
-
func:
|
|
130
|
-
Callable[P, Result[T, E]] | Callable[P, Coroutine[Any, Any, Result[T, E]]]
|
|
131
|
-
),
|
|
128
|
+
func: ResultFunc[P, T, E] | AsyncResultFunc[P, T, E],
|
|
132
129
|
) -> (
|
|
133
130
|
Callable[P, Result[T, TimeoutError | E]]
|
|
134
131
|
| Callable[P, Coroutine[Any, Any, Result[T, TimeoutError | E]]]
|
|
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|