taipanstack 0.3.1__tar.gz → 0.3.3__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.1 → taipanstack-0.3.3}/PKG-INFO +2 -2
- {taipanstack-0.3.1 → taipanstack-0.3.3}/pyproject.toml +11 -4
- {taipanstack-0.3.1 → taipanstack-0.3.3}/src/taipanstack/__init__.py +1 -5
- {taipanstack-0.3.1 → taipanstack-0.3.3}/src/taipanstack/config/__init__.py +0 -2
- {taipanstack-0.3.1 → taipanstack-0.3.3}/src/taipanstack/config/generators.py +59 -13
- {taipanstack-0.3.1 → taipanstack-0.3.3}/src/taipanstack/config/models.py +1 -3
- {taipanstack-0.3.1 → taipanstack-0.3.3}/src/taipanstack/config/version_config.py +0 -2
- {taipanstack-0.3.1 → taipanstack-0.3.3}/src/taipanstack/core/compat.py +1 -6
- {taipanstack-0.3.1 → taipanstack-0.3.3}/src/taipanstack/core/result.py +40 -9
- {taipanstack-0.3.1 → taipanstack-0.3.3}/src/taipanstack/security/__init__.py +2 -2
- {taipanstack-0.3.1 → taipanstack-0.3.3}/src/taipanstack/security/guards.py +221 -79
- {taipanstack-0.3.1 → taipanstack-0.3.3}/src/taipanstack/security/sanitizers.py +8 -4
- {taipanstack-0.3.1 → taipanstack-0.3.3}/src/taipanstack/security/validators.py +116 -49
- {taipanstack-0.3.1 → taipanstack-0.3.3}/src/taipanstack/utils/circuit_breaker.py +31 -2
- {taipanstack-0.3.1 → taipanstack-0.3.3}/src/taipanstack/utils/filesystem.py +0 -2
- {taipanstack-0.3.1 → taipanstack-0.3.3}/src/taipanstack/utils/logging.py +3 -1
- {taipanstack-0.3.1 → taipanstack-0.3.3}/src/taipanstack/utils/retry.py +26 -4
- {taipanstack-0.3.1 → taipanstack-0.3.3}/LICENSE +0 -0
- {taipanstack-0.3.1 → taipanstack-0.3.3}/README.md +0 -0
- {taipanstack-0.3.1 → taipanstack-0.3.3}/src/taipanstack/core/__init__.py +0 -0
- {taipanstack-0.3.1 → taipanstack-0.3.3}/src/taipanstack/core/optimizations.py +0 -0
- {taipanstack-0.3.1 → taipanstack-0.3.3}/src/taipanstack/security/decorators.py +0 -0
- {taipanstack-0.3.1 → taipanstack-0.3.3}/src/taipanstack/utils/__init__.py +0 -0
- {taipanstack-0.3.1 → taipanstack-0.3.3}/src/taipanstack/utils/metrics.py +0 -0
- {taipanstack-0.3.1 → taipanstack-0.3.3}/src/taipanstack/utils/subprocess.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: taipanstack
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.3
|
|
4
4
|
Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
|
|
5
5
|
License-Expression: MIT
|
|
6
6
|
License-File: LICENSE
|
|
@@ -27,7 +27,7 @@ Requires-Dist: result (>=0.17.0)
|
|
|
27
27
|
Requires-Dist: structlog (>=23.0.0) ; extra == "runtime"
|
|
28
28
|
Requires-Dist: uvloop (>=0.19.0) ; (sys_platform != "win32") and (extra == "runtime")
|
|
29
29
|
Project-URL: Changelog, https://github.com/gabrielima7/TaipanStack/blob/main/CHANGELOG.md
|
|
30
|
-
Project-URL: Documentation, https://github.
|
|
30
|
+
Project-URL: Documentation, https://gabrielima7.github.io/TaipanStack/
|
|
31
31
|
Project-URL: Homepage, https://github.com/gabrielima7/TaipanStack
|
|
32
32
|
Project-URL: Issues, https://github.com/gabrielima7/TaipanStack/issues
|
|
33
33
|
Project-URL: Repository, https://github.com/gabrielima7/TaipanStack
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "taipanstack"
|
|
3
|
-
version = "0.3.
|
|
3
|
+
version = "0.3.3"
|
|
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"}
|
|
@@ -31,7 +31,7 @@ dependencies = [
|
|
|
31
31
|
|
|
32
32
|
[project.urls]
|
|
33
33
|
Homepage = "https://github.com/gabrielima7/TaipanStack"
|
|
34
|
-
Documentation = "https://github.
|
|
34
|
+
Documentation = "https://gabrielima7.github.io/TaipanStack/"
|
|
35
35
|
Repository = "https://github.com/gabrielima7/TaipanStack"
|
|
36
36
|
Changelog = "https://github.com/gabrielima7/TaipanStack/blob/main/CHANGELOG.md"
|
|
37
37
|
Issues = "https://github.com/gabrielima7/TaipanStack/issues"
|
|
@@ -67,11 +67,17 @@ dev = [
|
|
|
67
67
|
"gitingest (>=0.1.0)",
|
|
68
68
|
"mutmut (>=3.0.0)",
|
|
69
69
|
"pytest-benchmark (>=5.0.0)",
|
|
70
|
+
"pytest-asyncio (>=0.23.0)",
|
|
70
71
|
]
|
|
71
72
|
|
|
72
73
|
|
|
73
74
|
|
|
75
|
+
|
|
74
76
|
# --- TaipanStack v2.0 Quality Configuration ---
|
|
77
|
+
docs = [
|
|
78
|
+
"mkdocs-material (>=9.7.3,<10.0.0)",
|
|
79
|
+
"mkdocstrings[python] (>=1.0.3,<2.0.0)"
|
|
80
|
+
]
|
|
75
81
|
[tool.ruff]
|
|
76
82
|
line-length = 88
|
|
77
83
|
target-version = "py311"
|
|
@@ -166,6 +172,7 @@ warn_required_dynamic_aliases = true
|
|
|
166
172
|
[tool.pytest.ini_options]
|
|
167
173
|
testpaths = ["tests"]
|
|
168
174
|
addopts = "-v --cov=src --cov-report=html --cov-report=term-missing --strict-markers --timeout=30"
|
|
175
|
+
asyncio_mode = "auto"
|
|
169
176
|
markers = [
|
|
170
177
|
"slow: marks tests as slow (deselect with '-m \"not slow\"')",
|
|
171
178
|
"security: marks tests as security-related",
|
|
@@ -217,7 +224,7 @@ fail-under = 80
|
|
|
217
224
|
verbose = 1
|
|
218
225
|
|
|
219
226
|
[tool.mutmut]
|
|
220
|
-
paths_to_mutate = "src/taipanstack/security/sanitizers.py"
|
|
221
|
-
tests_dir = "tests/test_property_sanitizers.py"
|
|
227
|
+
paths_to_mutate = "src/taipanstack/security/sanitizers.py,src/taipanstack/security/validators.py,src/taipanstack/security/guards.py"
|
|
228
|
+
tests_dir = "tests/test_property_sanitizers.py,tests/test_security_validators.py,tests/test_security_guards.py,tests/test_security_ssrf.py"
|
|
222
229
|
runner = "python -m pytest -x -q --tb=no --timeout=10 --no-cov"
|
|
223
230
|
dict_synonyms = "Struct, NamedStruct"
|
|
@@ -5,15 +5,13 @@ 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.3"
|
|
9
9
|
|
|
10
|
-
from taipanstack.config.models import StackConfig
|
|
11
10
|
from taipanstack.config.version_config import (
|
|
12
11
|
VersionRecommendations,
|
|
13
12
|
get_version_recommendations,
|
|
14
13
|
)
|
|
15
14
|
from taipanstack.core.compat import (
|
|
16
|
-
PY311,
|
|
17
15
|
PY312,
|
|
18
16
|
PY313,
|
|
19
17
|
PY314,
|
|
@@ -33,12 +31,10 @@ from taipanstack.security.validators import (
|
|
|
33
31
|
)
|
|
34
32
|
|
|
35
33
|
__all__ = [
|
|
36
|
-
"PY311",
|
|
37
34
|
"PY312",
|
|
38
35
|
"PY313",
|
|
39
36
|
"PY314",
|
|
40
37
|
"PY_VERSION",
|
|
41
|
-
"StackConfig",
|
|
42
38
|
"VersionRecommendations",
|
|
43
39
|
"apply_optimizations",
|
|
44
40
|
"get_features",
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
"""Configuration models package."""
|
|
2
2
|
|
|
3
3
|
from taipanstack.config.generators import (
|
|
4
|
-
generate_dependabot_config,
|
|
5
4
|
generate_pre_commit_config,
|
|
6
5
|
generate_pyproject_config,
|
|
7
6
|
generate_security_policy,
|
|
@@ -18,7 +17,6 @@ __all__ = [
|
|
|
18
17
|
"LoggingConfig",
|
|
19
18
|
"SecurityConfig",
|
|
20
19
|
"StackConfig",
|
|
21
|
-
"generate_dependabot_config",
|
|
22
20
|
"generate_pre_commit_config",
|
|
23
21
|
"generate_pyproject_config",
|
|
24
22
|
"generate_security_policy",
|
|
@@ -14,22 +14,17 @@ if TYPE_CHECKING:
|
|
|
14
14
|
from taipanstack.config.models import StackConfig
|
|
15
15
|
|
|
16
16
|
|
|
17
|
-
def
|
|
18
|
-
"""Generate Ruff
|
|
17
|
+
def _generate_ruff_config(target_version: str) -> str:
|
|
18
|
+
"""Generate Ruff configuration.
|
|
19
19
|
|
|
20
20
|
Args:
|
|
21
|
-
|
|
21
|
+
target_version: The target Python version.
|
|
22
22
|
|
|
23
23
|
Returns:
|
|
24
|
-
|
|
24
|
+
Ruff configuration string.
|
|
25
25
|
|
|
26
26
|
"""
|
|
27
|
-
|
|
28
|
-
python_version = config.python_version
|
|
29
|
-
|
|
30
|
-
return f"""
|
|
31
|
-
# --- Stack v2.0 Quality Configuration ---
|
|
32
|
-
[tool.ruff]
|
|
27
|
+
return f"""[tool.ruff]
|
|
33
28
|
line-length = 88
|
|
34
29
|
target-version = "{target_version}"
|
|
35
30
|
|
|
@@ -72,8 +67,20 @@ max-complexity = 10
|
|
|
72
67
|
[tool.ruff.format]
|
|
73
68
|
quote-style = "double"
|
|
74
69
|
indent-style = "space"
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _generate_mypy_config(python_version: str) -> str:
|
|
74
|
+
"""Generate Mypy configuration.
|
|
75
75
|
|
|
76
|
-
|
|
76
|
+
Args:
|
|
77
|
+
python_version: The target Python version.
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
Mypy configuration string.
|
|
81
|
+
|
|
82
|
+
"""
|
|
83
|
+
return f"""[tool.mypy]
|
|
77
84
|
python_version = "{python_version}"
|
|
78
85
|
warn_return_any = true
|
|
79
86
|
warn_unused_configs = true
|
|
@@ -86,16 +93,34 @@ strict_equality = true
|
|
|
86
93
|
ignore_missing_imports = true
|
|
87
94
|
show_error_codes = true
|
|
88
95
|
enable_error_code = ["ignore-without-code", "redundant-cast", "truthy-bool"]
|
|
96
|
+
"""
|
|
89
97
|
|
|
90
|
-
|
|
98
|
+
|
|
99
|
+
def _generate_pytest_config() -> str:
|
|
100
|
+
"""Generate Pytest configuration.
|
|
101
|
+
|
|
102
|
+
Returns:
|
|
103
|
+
Pytest configuration string.
|
|
104
|
+
|
|
105
|
+
"""
|
|
106
|
+
return """[tool.pytest.ini_options]
|
|
91
107
|
testpaths = ["tests"]
|
|
92
108
|
addopts = "-v --cov=src --cov-report=html --cov-report=term-missing --cov-fail-under=80 --strict-markers"
|
|
93
109
|
markers = [
|
|
94
110
|
"slow: marks tests as slow (deselect with '-m \"not slow\"')",
|
|
95
111
|
"security: marks tests as security-related",
|
|
96
112
|
]
|
|
113
|
+
"""
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _generate_coverage_config() -> str:
|
|
117
|
+
"""Generate Coverage configuration.
|
|
97
118
|
|
|
98
|
-
|
|
119
|
+
Returns:
|
|
120
|
+
Coverage configuration string.
|
|
121
|
+
|
|
122
|
+
"""
|
|
123
|
+
return """[tool.coverage.run]
|
|
99
124
|
branch = true
|
|
100
125
|
source = ["src"]
|
|
101
126
|
omit = ["*/tests/*", "*/__pycache__/*"]
|
|
@@ -111,6 +136,27 @@ exclude_lines = [
|
|
|
111
136
|
"""
|
|
112
137
|
|
|
113
138
|
|
|
139
|
+
def generate_pyproject_config(config: StackConfig) -> str:
|
|
140
|
+
"""Generate Ruff, Mypy, and Pytest configuration for pyproject.toml.
|
|
141
|
+
|
|
142
|
+
Args:
|
|
143
|
+
config: The Stack configuration.
|
|
144
|
+
|
|
145
|
+
Returns:
|
|
146
|
+
Configuration string to append to pyproject.toml.
|
|
147
|
+
|
|
148
|
+
"""
|
|
149
|
+
target_version = config.to_target_version()
|
|
150
|
+
python_version = config.python_version
|
|
151
|
+
|
|
152
|
+
return f"""
|
|
153
|
+
# --- Stack v2.0 Quality Configuration ---
|
|
154
|
+
{_generate_ruff_config(target_version)}
|
|
155
|
+
{_generate_mypy_config(python_version)}
|
|
156
|
+
{_generate_pytest_config()}
|
|
157
|
+
{_generate_coverage_config()}"""
|
|
158
|
+
|
|
159
|
+
|
|
114
160
|
def generate_pre_commit_config(config: StackConfig) -> str:
|
|
115
161
|
"""Generate .pre-commit-config.yaml content.
|
|
116
162
|
|
|
@@ -5,8 +5,6 @@ This module provides type-safe configuration models that validate
|
|
|
5
5
|
all inputs at runtime, preventing errors and AI hallucinations.
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
|
-
from __future__ import annotations
|
|
9
|
-
|
|
10
8
|
import re
|
|
11
9
|
import sys
|
|
12
10
|
from pathlib import Path
|
|
@@ -281,7 +279,7 @@ class StackConfig(BaseModel):
|
|
|
281
279
|
return resolved
|
|
282
280
|
|
|
283
281
|
@model_validator(mode="after")
|
|
284
|
-
def validate_config_consistency(self) -> StackConfig:
|
|
282
|
+
def validate_config_consistency(self) -> "StackConfig":
|
|
285
283
|
"""Validate configuration consistency.
|
|
286
284
|
|
|
287
285
|
Returns:
|
|
@@ -8,17 +8,12 @@ maintaining compatibility with Python 3.11+.
|
|
|
8
8
|
Following Stack pillars: Security, Stability, Simplicity, Scalability, Compatibility.
|
|
9
9
|
"""
|
|
10
10
|
|
|
11
|
-
from __future__ import annotations
|
|
12
|
-
|
|
13
11
|
import logging
|
|
14
12
|
import os
|
|
15
13
|
import sys
|
|
16
14
|
from dataclasses import dataclass
|
|
17
15
|
from enum import StrEnum
|
|
18
|
-
from typing import
|
|
19
|
-
|
|
20
|
-
if TYPE_CHECKING:
|
|
21
|
-
from typing import Final
|
|
16
|
+
from typing import Final
|
|
22
17
|
|
|
23
18
|
__all__ = [
|
|
24
19
|
"PY311",
|
|
@@ -25,8 +25,9 @@ Example:
|
|
|
25
25
|
from __future__ import annotations
|
|
26
26
|
|
|
27
27
|
import functools
|
|
28
|
-
|
|
29
|
-
from
|
|
28
|
+
import inspect
|
|
29
|
+
from collections.abc import Callable, Coroutine, Iterable
|
|
30
|
+
from typing import Any, ParamSpec, TypeVar, overload
|
|
30
31
|
|
|
31
32
|
from result import Err, Ok, Result
|
|
32
33
|
|
|
@@ -47,19 +48,36 @@ E = TypeVar("E", bound=Exception)
|
|
|
47
48
|
U = TypeVar("U")
|
|
48
49
|
|
|
49
50
|
|
|
51
|
+
@overload
|
|
50
52
|
def safe(
|
|
51
53
|
func: Callable[P, T],
|
|
52
|
-
) -> Callable[P, Result[T, Exception]]:
|
|
53
|
-
|
|
54
|
+
) -> Callable[P, Result[T, Exception]]: ... # pragma: no cover
|
|
55
|
+
|
|
54
56
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
+
@overload
|
|
58
|
+
def safe(
|
|
59
|
+
func: Callable[P, Coroutine[Any, Any, T]],
|
|
60
|
+
) -> Callable[P, Coroutine[Any, Any, Result[T, Exception]]]: ... # pragma: no cover
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def safe(
|
|
64
|
+
func: Callable[P, T] | Callable[P, Coroutine[Any, Any, T]],
|
|
65
|
+
) -> (
|
|
66
|
+
Callable[P, Result[T, Exception]]
|
|
67
|
+
| Callable[P, Coroutine[Any, Any, Result[T, Exception]]]
|
|
68
|
+
):
|
|
69
|
+
"""Wrap a sync or async function to convert exceptions into Err results.
|
|
70
|
+
|
|
71
|
+
Detect whether *func* is a coroutine function and choose the
|
|
72
|
+
appropriate wrapper so that ``await``-able functions remain
|
|
73
|
+
``await``-able and synchronous functions stay synchronous.
|
|
57
74
|
|
|
58
75
|
Args:
|
|
59
|
-
func: The function to wrap.
|
|
76
|
+
func: The sync or async function to wrap.
|
|
60
77
|
|
|
61
78
|
Returns:
|
|
62
|
-
A wrapped function that returns Result[T, Exception]
|
|
79
|
+
A wrapped function that returns ``Result[T, Exception]``
|
|
80
|
+
(or a coroutine resolving to one).
|
|
63
81
|
|
|
64
82
|
Example:
|
|
65
83
|
>>> @safe
|
|
@@ -71,11 +89,24 @@ def safe(
|
|
|
71
89
|
Err(ValueError("invalid literal for int()..."))
|
|
72
90
|
|
|
73
91
|
"""
|
|
92
|
+
if inspect.iscoroutinefunction(func):
|
|
93
|
+
|
|
94
|
+
@functools.wraps(func)
|
|
95
|
+
async def async_wrapper(
|
|
96
|
+
*args: P.args,
|
|
97
|
+
**kwargs: P.kwargs,
|
|
98
|
+
) -> Result[T, Exception]:
|
|
99
|
+
try:
|
|
100
|
+
return Ok(await func(*args, **kwargs))
|
|
101
|
+
except Exception as e:
|
|
102
|
+
return Err(e)
|
|
103
|
+
|
|
104
|
+
return async_wrapper
|
|
74
105
|
|
|
75
106
|
@functools.wraps(func)
|
|
76
107
|
def wrapper(*args: P.args, **kwargs: P.kwargs) -> Result[T, Exception]:
|
|
77
108
|
try:
|
|
78
|
-
return Ok(func(*args, **kwargs))
|
|
109
|
+
return Ok(func(*args, **kwargs)) # type: ignore[arg-type]
|
|
79
110
|
except Exception as e:
|
|
80
111
|
return Err(e)
|
|
81
112
|
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
"""Security package for runtime protection."""
|
|
2
2
|
|
|
3
3
|
from taipanstack.security.decorators import (
|
|
4
|
-
OperationTimeoutError,
|
|
5
4
|
ValidationError,
|
|
6
5
|
deprecated,
|
|
7
6
|
guard_exceptions,
|
|
@@ -15,6 +14,7 @@ from taipanstack.security.guards import (
|
|
|
15
14
|
guard_env_variable,
|
|
16
15
|
guard_file_extension,
|
|
17
16
|
guard_path_traversal,
|
|
17
|
+
guard_ssrf,
|
|
18
18
|
)
|
|
19
19
|
from taipanstack.security.sanitizers import (
|
|
20
20
|
sanitize_filename,
|
|
@@ -30,7 +30,6 @@ from taipanstack.security.validators import (
|
|
|
30
30
|
|
|
31
31
|
__all__ = [
|
|
32
32
|
# Decorators
|
|
33
|
-
"OperationTimeoutError",
|
|
34
33
|
# Guards
|
|
35
34
|
"SecurityError",
|
|
36
35
|
"ValidationError",
|
|
@@ -40,6 +39,7 @@ __all__ = [
|
|
|
40
39
|
"guard_exceptions",
|
|
41
40
|
"guard_file_extension",
|
|
42
41
|
"guard_path_traversal",
|
|
42
|
+
"guard_ssrf",
|
|
43
43
|
"require_type",
|
|
44
44
|
# Sanitizers
|
|
45
45
|
"sanitize_filename",
|
|
@@ -8,10 +8,87 @@ All guards raise SecurityError on violation.
|
|
|
8
8
|
|
|
9
9
|
from __future__ import annotations
|
|
10
10
|
|
|
11
|
+
import ipaddress
|
|
11
12
|
import os
|
|
12
13
|
import re
|
|
14
|
+
import socket
|
|
13
15
|
from collections.abc import Sequence
|
|
14
16
|
from pathlib import Path
|
|
17
|
+
from urllib.parse import urlparse
|
|
18
|
+
|
|
19
|
+
from result import Err, Ok, Result
|
|
20
|
+
|
|
21
|
+
_TRAVERSAL_PATTERNS: frozenset[str] = frozenset(
|
|
22
|
+
[
|
|
23
|
+
"..",
|
|
24
|
+
"~",
|
|
25
|
+
r"\.\.",
|
|
26
|
+
"%2e%2e", # URL encoded ..
|
|
27
|
+
"%252e%252e", # Double URL encoded
|
|
28
|
+
]
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
_DANGEROUS_COMMAND_PATTERNS: tuple[tuple[str, str], ...] = (
|
|
32
|
+
(";", "command separator"),
|
|
33
|
+
("|", "pipe"),
|
|
34
|
+
("&", "background/and operator"),
|
|
35
|
+
("$", "variable expansion"),
|
|
36
|
+
("`", "command substitution"),
|
|
37
|
+
("$(", "command substitution"),
|
|
38
|
+
("${", "variable expansion"),
|
|
39
|
+
(">", "redirect"),
|
|
40
|
+
("<", "redirect"),
|
|
41
|
+
(">>", "redirect append"),
|
|
42
|
+
("||", "or operator"),
|
|
43
|
+
("&&", "and operator"),
|
|
44
|
+
("\n", "newline"),
|
|
45
|
+
("\r", "carriage return"),
|
|
46
|
+
("\x00", "null byte"),
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
_DEFAULT_DENIED_EXTENSIONS = frozenset(
|
|
50
|
+
[
|
|
51
|
+
"exe",
|
|
52
|
+
"dll",
|
|
53
|
+
"so",
|
|
54
|
+
"dylib", # Executables
|
|
55
|
+
"sh",
|
|
56
|
+
"bash",
|
|
57
|
+
"zsh",
|
|
58
|
+
"ps1",
|
|
59
|
+
"bat",
|
|
60
|
+
"cmd", # Scripts
|
|
61
|
+
"php",
|
|
62
|
+
"jsp",
|
|
63
|
+
"asp",
|
|
64
|
+
"aspx", # Server-side scripts
|
|
65
|
+
]
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
_DEFAULT_DENIED_ENV_VARS = frozenset(
|
|
69
|
+
[
|
|
70
|
+
"AWS_SECRET_ACCESS_KEY",
|
|
71
|
+
"AWS_SESSION_TOKEN",
|
|
72
|
+
"GITHUB_TOKEN",
|
|
73
|
+
"GH_TOKEN",
|
|
74
|
+
"GITLAB_TOKEN",
|
|
75
|
+
"DATABASE_URL",
|
|
76
|
+
"DB_PASSWORD",
|
|
77
|
+
"PASSWORD",
|
|
78
|
+
"SECRET_KEY",
|
|
79
|
+
"PRIVATE_KEY",
|
|
80
|
+
"API_KEY",
|
|
81
|
+
"API_SECRET",
|
|
82
|
+
]
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
_SENSITIVE_ENV_VAR_PATTERNS = (
|
|
86
|
+
re.compile(r".*SECRET.*"),
|
|
87
|
+
re.compile(r".*PASSWORD.*"),
|
|
88
|
+
re.compile(r".*TOKEN.*"),
|
|
89
|
+
re.compile(r".*PRIVATE.*KEY.*"),
|
|
90
|
+
re.compile(r".*API.*KEY.*"),
|
|
91
|
+
)
|
|
15
92
|
|
|
16
93
|
|
|
17
94
|
class SecurityError(Exception):
|
|
@@ -77,15 +154,8 @@ def guard_path_traversal(
|
|
|
77
154
|
|
|
78
155
|
# Check for explicit traversal patterns before resolution
|
|
79
156
|
path_str = str(path)
|
|
80
|
-
traversal_patterns = [
|
|
81
|
-
"..",
|
|
82
|
-
"~",
|
|
83
|
-
r"\.\.",
|
|
84
|
-
"%2e%2e", # URL encoded ..
|
|
85
|
-
"%252e%252e", # Double URL encoded
|
|
86
|
-
]
|
|
87
157
|
|
|
88
|
-
for pattern in
|
|
158
|
+
for pattern in _TRAVERSAL_PATTERNS:
|
|
89
159
|
if pattern.lower() in path_str.lower():
|
|
90
160
|
raise SecurityError(
|
|
91
161
|
f"Path traversal pattern detected: {pattern}",
|
|
@@ -159,7 +229,7 @@ def guard_command_injection(
|
|
|
159
229
|
|
|
160
230
|
cmd_list = list(command)
|
|
161
231
|
|
|
162
|
-
# Validate all items are strings
|
|
232
|
+
# Validate all items are strings and check for dangerous patterns
|
|
163
233
|
for i, arg in enumerate(cmd_list):
|
|
164
234
|
if not isinstance(arg, str):
|
|
165
235
|
raise TypeError(
|
|
@@ -167,27 +237,7 @@ def guard_command_injection(
|
|
|
167
237
|
f"got {type(arg).__name__} at index {i}"
|
|
168
238
|
)
|
|
169
239
|
|
|
170
|
-
|
|
171
|
-
dangerous_patterns: list[tuple[str, str]] = [
|
|
172
|
-
(";", "command separator"),
|
|
173
|
-
("|", "pipe"),
|
|
174
|
-
("&", "background/and operator"),
|
|
175
|
-
("$", "variable expansion"),
|
|
176
|
-
("`", "command substitution"),
|
|
177
|
-
("$(", "command substitution"),
|
|
178
|
-
("${", "variable expansion"),
|
|
179
|
-
(">", "redirect"),
|
|
180
|
-
("<", "redirect"),
|
|
181
|
-
(">>", "redirect append"),
|
|
182
|
-
("||", "or operator"),
|
|
183
|
-
("&&", "and operator"),
|
|
184
|
-
("\n", "newline"),
|
|
185
|
-
("\r", "carriage return"),
|
|
186
|
-
("\x00", "null byte"),
|
|
187
|
-
]
|
|
188
|
-
|
|
189
|
-
for arg in cmd_list:
|
|
190
|
-
for pattern, description in dangerous_patterns:
|
|
240
|
+
for pattern, description in _DANGEROUS_COMMAND_PATTERNS:
|
|
191
241
|
if pattern in arg:
|
|
192
242
|
raise SecurityError(
|
|
193
243
|
f"Dangerous shell character detected: {description}",
|
|
@@ -237,32 +287,14 @@ def guard_file_extension(
|
|
|
237
287
|
path = Path(filename)
|
|
238
288
|
ext = path.suffix.lower().lstrip(".")
|
|
239
289
|
|
|
240
|
-
# Default dangerous extensions
|
|
241
|
-
default_denied = {
|
|
242
|
-
"exe",
|
|
243
|
-
"dll",
|
|
244
|
-
"so",
|
|
245
|
-
"dylib", # Executables
|
|
246
|
-
"sh",
|
|
247
|
-
"bash",
|
|
248
|
-
"zsh",
|
|
249
|
-
"ps1",
|
|
250
|
-
"bat",
|
|
251
|
-
"cmd", # Scripts
|
|
252
|
-
"php",
|
|
253
|
-
"jsp",
|
|
254
|
-
"asp",
|
|
255
|
-
"aspx", # Server-side scripts
|
|
256
|
-
}
|
|
257
|
-
|
|
258
290
|
# Normalize extension lists
|
|
259
291
|
def normalize_ext(e: str) -> str:
|
|
260
292
|
return e.lower().lstrip(".")
|
|
261
293
|
|
|
262
294
|
if denied_extensions is not None:
|
|
263
|
-
denied =
|
|
295
|
+
denied = frozenset(normalize_ext(e) for e in denied_extensions)
|
|
264
296
|
else:
|
|
265
|
-
denied =
|
|
297
|
+
denied = _DEFAULT_DENIED_EXTENSIONS
|
|
266
298
|
|
|
267
299
|
if ext in denied:
|
|
268
300
|
raise SecurityError(
|
|
@@ -303,22 +335,6 @@ def guard_env_variable(
|
|
|
303
335
|
SecurityError: If variable access is not allowed.
|
|
304
336
|
|
|
305
337
|
"""
|
|
306
|
-
# Default sensitive variables
|
|
307
|
-
default_denied = {
|
|
308
|
-
"AWS_SECRET_ACCESS_KEY",
|
|
309
|
-
"AWS_SESSION_TOKEN",
|
|
310
|
-
"GITHUB_TOKEN",
|
|
311
|
-
"GH_TOKEN",
|
|
312
|
-
"GITLAB_TOKEN",
|
|
313
|
-
"DATABASE_URL",
|
|
314
|
-
"DB_PASSWORD",
|
|
315
|
-
"PASSWORD",
|
|
316
|
-
"SECRET_KEY",
|
|
317
|
-
"PRIVATE_KEY",
|
|
318
|
-
"API_KEY",
|
|
319
|
-
"API_SECRET",
|
|
320
|
-
}
|
|
321
|
-
|
|
322
338
|
# Validate input type
|
|
323
339
|
if not isinstance(name, str):
|
|
324
340
|
raise TypeError(f"Variable name must be str, got {type(name).__name__}")
|
|
@@ -333,18 +349,9 @@ def guard_env_variable(
|
|
|
333
349
|
name_upper = name.upper()
|
|
334
350
|
|
|
335
351
|
if denied_names is not None:
|
|
336
|
-
denied =
|
|
352
|
+
denied = frozenset(n.upper() for n in denied_names)
|
|
337
353
|
else:
|
|
338
|
-
denied =
|
|
339
|
-
|
|
340
|
-
# Check against patterns
|
|
341
|
-
sensitive_patterns = [
|
|
342
|
-
r".*SECRET.*",
|
|
343
|
-
r".*PASSWORD.*",
|
|
344
|
-
r".*TOKEN.*",
|
|
345
|
-
r".*PRIVATE.*KEY.*",
|
|
346
|
-
r".*API.*KEY.*",
|
|
347
|
-
]
|
|
354
|
+
denied = _DEFAULT_DENIED_ENV_VARS
|
|
348
355
|
|
|
349
356
|
if name_upper in denied:
|
|
350
357
|
raise SecurityError(
|
|
@@ -353,8 +360,8 @@ def guard_env_variable(
|
|
|
353
360
|
value=name,
|
|
354
361
|
)
|
|
355
362
|
|
|
356
|
-
for pattern in
|
|
357
|
-
if
|
|
363
|
+
for pattern in _SENSITIVE_ENV_VAR_PATTERNS:
|
|
364
|
+
if pattern.match(name_upper):
|
|
358
365
|
# Only block if not explicitly allowed
|
|
359
366
|
if allowed_names is not None:
|
|
360
367
|
allowed = {n.upper() for n in allowed_names}
|
|
@@ -381,3 +388,138 @@ def guard_env_variable(
|
|
|
381
388
|
)
|
|
382
389
|
|
|
383
390
|
return value
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
# ── SSRF Private-Range Constants ─────────────────────────────────────────────
|
|
394
|
+
_PRIVATE_NETWORKS: tuple[ipaddress.IPv4Network | ipaddress.IPv6Network, ...] = (
|
|
395
|
+
ipaddress.ip_network("10.0.0.0/8"),
|
|
396
|
+
ipaddress.ip_network("172.16.0.0/12"),
|
|
397
|
+
ipaddress.ip_network("192.168.0.0/16"),
|
|
398
|
+
ipaddress.ip_network("169.254.0.0/16"), # Link-local / AWS metadata
|
|
399
|
+
ipaddress.ip_network("127.0.0.0/8"), # Loopback
|
|
400
|
+
ipaddress.ip_network("::1/128"), # IPv6 loopback
|
|
401
|
+
ipaddress.ip_network("fc00::/7"), # IPv6 unique local
|
|
402
|
+
ipaddress.ip_network("fe80::/10"), # IPv6 link-local
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
_ALLOWED_SSRF_SCHEMES: frozenset[str] = frozenset({"http", "https"})
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def guard_ssrf( # noqa: PLR0911
|
|
409
|
+
url: str,
|
|
410
|
+
*,
|
|
411
|
+
allowed_schemes: frozenset[str] = _ALLOWED_SSRF_SCHEMES,
|
|
412
|
+
) -> Result[str, SecurityError]:
|
|
413
|
+
"""Validate a URL against Server-Side Request Forgery (SSRF) attacks.
|
|
414
|
+
|
|
415
|
+
Parse the URL, resolve its hostname via DNS, and reject it when the
|
|
416
|
+
resulting IP address falls inside a private, loopback, link-local, or
|
|
417
|
+
otherwise reserved network range.
|
|
418
|
+
|
|
419
|
+
Args:
|
|
420
|
+
url: The URL string to validate.
|
|
421
|
+
allowed_schemes: Set of URL schemes considered safe.
|
|
422
|
+
Defaults to ``{"http", "https"}``.
|
|
423
|
+
|
|
424
|
+
Returns:
|
|
425
|
+
``Ok(url)`` when the URL is safe to fetch.
|
|
426
|
+
``Err(SecurityError)`` when an SSRF risk is detected.
|
|
427
|
+
|
|
428
|
+
Raises:
|
|
429
|
+
TypeError: If *url* is not a :class:`str`.
|
|
430
|
+
|
|
431
|
+
Example:
|
|
432
|
+
>>> guard_ssrf("https://example.com")
|
|
433
|
+
Ok('https://example.com')
|
|
434
|
+
>>> guard_ssrf("http://169.254.169.254/metadata")
|
|
435
|
+
Err(SecurityError('[ssrf] ...))
|
|
436
|
+
|
|
437
|
+
"""
|
|
438
|
+
if not isinstance(url, str):
|
|
439
|
+
raise TypeError(f"URL must be str, got {type(url).__name__}")
|
|
440
|
+
|
|
441
|
+
if not url:
|
|
442
|
+
return Err(
|
|
443
|
+
SecurityError(
|
|
444
|
+
"URL cannot be empty",
|
|
445
|
+
guard_name="ssrf",
|
|
446
|
+
)
|
|
447
|
+
)
|
|
448
|
+
|
|
449
|
+
try:
|
|
450
|
+
parsed = urlparse(url)
|
|
451
|
+
except ValueError as exc: # pragma: no cover — urlparse rarely raises
|
|
452
|
+
return Err(
|
|
453
|
+
SecurityError(
|
|
454
|
+
f"Malformed URL: {exc}",
|
|
455
|
+
guard_name="ssrf",
|
|
456
|
+
value=url[:80],
|
|
457
|
+
)
|
|
458
|
+
)
|
|
459
|
+
|
|
460
|
+
if not parsed.scheme or parsed.scheme.lower() not in allowed_schemes:
|
|
461
|
+
return Err(
|
|
462
|
+
SecurityError(
|
|
463
|
+
f"URL scheme '{parsed.scheme}' is not allowed",
|
|
464
|
+
guard_name="ssrf",
|
|
465
|
+
value=url[:80],
|
|
466
|
+
)
|
|
467
|
+
)
|
|
468
|
+
|
|
469
|
+
hostname = parsed.hostname
|
|
470
|
+
if not hostname:
|
|
471
|
+
return Err(
|
|
472
|
+
SecurityError(
|
|
473
|
+
"URL has no resolvable hostname",
|
|
474
|
+
guard_name="ssrf",
|
|
475
|
+
value=url[:80],
|
|
476
|
+
)
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
# Resolve hostname → list of IP addresses via DNS
|
|
480
|
+
try:
|
|
481
|
+
addr_infos = socket.getaddrinfo(hostname, None)
|
|
482
|
+
except socket.gaierror as exc:
|
|
483
|
+
return Err(
|
|
484
|
+
SecurityError(
|
|
485
|
+
f"Hostname could not be resolved: {exc}",
|
|
486
|
+
guard_name="ssrf",
|
|
487
|
+
value=hostname[:80],
|
|
488
|
+
)
|
|
489
|
+
)
|
|
490
|
+
|
|
491
|
+
for addr_info in addr_infos:
|
|
492
|
+
raw_ip = addr_info[4][0]
|
|
493
|
+
try:
|
|
494
|
+
addr = ipaddress.ip_address(raw_ip)
|
|
495
|
+
except ValueError:
|
|
496
|
+
continue
|
|
497
|
+
|
|
498
|
+
for network in _PRIVATE_NETWORKS:
|
|
499
|
+
if addr in network:
|
|
500
|
+
return Err(
|
|
501
|
+
SecurityError(
|
|
502
|
+
f"SSRF detected: hostname '{hostname}' resolves to "
|
|
503
|
+
f"private/reserved address {addr}",
|
|
504
|
+
guard_name="ssrf",
|
|
505
|
+
value=str(addr),
|
|
506
|
+
)
|
|
507
|
+
)
|
|
508
|
+
|
|
509
|
+
# Catch-all for remaining special addresses not in the explicit list
|
|
510
|
+
if (
|
|
511
|
+
addr.is_private
|
|
512
|
+
or addr.is_loopback
|
|
513
|
+
or addr.is_link_local
|
|
514
|
+
or addr.is_reserved
|
|
515
|
+
):
|
|
516
|
+
return Err(
|
|
517
|
+
SecurityError(
|
|
518
|
+
f"SSRF detected: '{hostname}' resolves to a reserved "
|
|
519
|
+
f"address {addr}",
|
|
520
|
+
guard_name="ssrf",
|
|
521
|
+
value=str(addr),
|
|
522
|
+
)
|
|
523
|
+
)
|
|
524
|
+
|
|
525
|
+
return Ok(url)
|
|
@@ -65,8 +65,10 @@ def sanitize_string(
|
|
|
65
65
|
The sanitized string.
|
|
66
66
|
|
|
67
67
|
Example:
|
|
68
|
-
|
|
69
|
-
"
|
|
68
|
+
```python
|
|
69
|
+
sanitize_string("<script>alert('xss')</script>Hello")
|
|
70
|
+
# Returns: "scriptalert('xss')/scriptHello"
|
|
71
|
+
```
|
|
70
72
|
|
|
71
73
|
"""
|
|
72
74
|
if not isinstance(value, str):
|
|
@@ -130,8 +132,10 @@ def sanitize_filename(
|
|
|
130
132
|
The sanitized filename.
|
|
131
133
|
|
|
132
134
|
Example:
|
|
133
|
-
|
|
134
|
-
|
|
135
|
+
```python
|
|
136
|
+
sanitize_filename("my/../file<>:name.txt")
|
|
137
|
+
# Returns: 'my_file_name.txt'
|
|
138
|
+
```
|
|
135
139
|
|
|
136
140
|
"""
|
|
137
141
|
if not isinstance(filename, str):
|
|
@@ -20,39 +20,61 @@ MAX_EMAIL_DOMAIN_LENGTH = 255
|
|
|
20
20
|
MAX_PORT_NUMBER = 65535
|
|
21
21
|
MIN_PRIVILEGED_PORT = 1024
|
|
22
22
|
LOCALHOST_DOMAINS = ("localhost", "127.0.0.1", "::1")
|
|
23
|
+
PROJECT_NAME_RESERVED = frozenset(
|
|
24
|
+
{
|
|
25
|
+
"test",
|
|
26
|
+
"tests",
|
|
27
|
+
"src",
|
|
28
|
+
"lib",
|
|
29
|
+
"bin",
|
|
30
|
+
"build",
|
|
31
|
+
"dist",
|
|
32
|
+
"setup",
|
|
33
|
+
"config",
|
|
34
|
+
"settings",
|
|
35
|
+
"core",
|
|
36
|
+
"main",
|
|
37
|
+
"app",
|
|
38
|
+
"site-packages",
|
|
39
|
+
}
|
|
40
|
+
)
|
|
23
41
|
|
|
24
42
|
|
|
25
|
-
def
|
|
26
|
-
name: str
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
allow_hyphen: bool = True,
|
|
30
|
-
allow_underscore: bool = True,
|
|
31
|
-
) -> str:
|
|
32
|
-
"""Validate a project name.
|
|
43
|
+
def _validate_type(
|
|
44
|
+
value: object, expected_type: type | tuple[type, ...], name: str
|
|
45
|
+
) -> None:
|
|
46
|
+
"""Validate input type.
|
|
33
47
|
|
|
34
48
|
Args:
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
allow_underscore: Allow underscores in name.
|
|
39
|
-
|
|
40
|
-
Returns:
|
|
41
|
-
The validated project name.
|
|
49
|
+
value: The value to check.
|
|
50
|
+
expected_type: The expected type(s).
|
|
51
|
+
name: Name of the variable for the error message.
|
|
42
52
|
|
|
43
53
|
Raises:
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
Example:
|
|
47
|
-
>>> validate_project_name("my_project")
|
|
48
|
-
'my_project'
|
|
49
|
-
>>> validate_project_name("123project")
|
|
50
|
-
ValueError: Project name must start with a letter
|
|
54
|
+
TypeError: If value is not of the expected type.
|
|
51
55
|
|
|
52
56
|
"""
|
|
53
|
-
if not isinstance(
|
|
54
|
-
|
|
57
|
+
if not isinstance(value, expected_type):
|
|
58
|
+
type_name = (
|
|
59
|
+
expected_type.__name__
|
|
60
|
+
if isinstance(expected_type, type)
|
|
61
|
+
else " | ".join(t.__name__ for t in expected_type)
|
|
62
|
+
)
|
|
63
|
+
msg = f"{name} must be {type_name}, got {type(value).__name__}"
|
|
64
|
+
raise TypeError(msg)
|
|
55
65
|
|
|
66
|
+
|
|
67
|
+
def _check_project_name_length(name: str, max_length: int) -> None:
|
|
68
|
+
"""Check project name length.
|
|
69
|
+
|
|
70
|
+
Args:
|
|
71
|
+
name: The project name.
|
|
72
|
+
max_length: Maximum allowed length.
|
|
73
|
+
|
|
74
|
+
Raises:
|
|
75
|
+
ValueError: If length is invalid.
|
|
76
|
+
|
|
77
|
+
"""
|
|
56
78
|
if not name:
|
|
57
79
|
msg = "Project name cannot be empty"
|
|
58
80
|
raise ValueError(msg)
|
|
@@ -61,6 +83,21 @@ def validate_project_name(
|
|
|
61
83
|
msg = f"Project name exceeds maximum length of {max_length}"
|
|
62
84
|
raise ValueError(msg)
|
|
63
85
|
|
|
86
|
+
|
|
87
|
+
def _check_project_name_chars(
|
|
88
|
+
name: str, allow_hyphen: bool, allow_underscore: bool
|
|
89
|
+
) -> None:
|
|
90
|
+
"""Check project name characters.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
name: The project name.
|
|
94
|
+
allow_hyphen: Whether to allow hyphens.
|
|
95
|
+
allow_underscore: Whether to allow underscores.
|
|
96
|
+
|
|
97
|
+
Raises:
|
|
98
|
+
ValueError: If name contains invalid characters.
|
|
99
|
+
|
|
100
|
+
"""
|
|
64
101
|
# Build allowed characters
|
|
65
102
|
allowed = r"a-zA-Z0-9"
|
|
66
103
|
if allow_hyphen:
|
|
@@ -82,28 +119,55 @@ def validate_project_name(
|
|
|
82
119
|
)
|
|
83
120
|
raise ValueError(msg)
|
|
84
121
|
|
|
85
|
-
# Check for reserved names
|
|
86
|
-
reserved = {
|
|
87
|
-
"test",
|
|
88
|
-
"tests",
|
|
89
|
-
"src",
|
|
90
|
-
"lib",
|
|
91
|
-
"bin",
|
|
92
|
-
"build",
|
|
93
|
-
"dist",
|
|
94
|
-
"setup",
|
|
95
|
-
"config",
|
|
96
|
-
"settings",
|
|
97
|
-
"core",
|
|
98
|
-
"main",
|
|
99
|
-
"app",
|
|
100
|
-
"site-packages",
|
|
101
|
-
}
|
|
102
122
|
|
|
103
|
-
|
|
123
|
+
def _check_project_name_reserved(name: str) -> None:
|
|
124
|
+
"""Check if project name is reserved.
|
|
125
|
+
|
|
126
|
+
Args:
|
|
127
|
+
name: The project name.
|
|
128
|
+
|
|
129
|
+
Raises:
|
|
130
|
+
ValueError: If name is reserved.
|
|
131
|
+
|
|
132
|
+
"""
|
|
133
|
+
if name.lower() in PROJECT_NAME_RESERVED:
|
|
104
134
|
msg = f"Project name '{name}' is reserved"
|
|
105
135
|
raise ValueError(msg)
|
|
106
136
|
|
|
137
|
+
|
|
138
|
+
def validate_project_name(
|
|
139
|
+
name: str,
|
|
140
|
+
*,
|
|
141
|
+
max_length: int = 100,
|
|
142
|
+
allow_hyphen: bool = True,
|
|
143
|
+
allow_underscore: bool = True,
|
|
144
|
+
) -> str:
|
|
145
|
+
"""Validate a project name.
|
|
146
|
+
|
|
147
|
+
Args:
|
|
148
|
+
name: The project name to validate.
|
|
149
|
+
max_length: Maximum allowed length.
|
|
150
|
+
allow_hyphen: Allow hyphens in name.
|
|
151
|
+
allow_underscore: Allow underscores in name.
|
|
152
|
+
|
|
153
|
+
Returns:
|
|
154
|
+
The validated project name.
|
|
155
|
+
|
|
156
|
+
Raises:
|
|
157
|
+
ValueError: If the name is invalid.
|
|
158
|
+
|
|
159
|
+
Example:
|
|
160
|
+
>>> validate_project_name("my_project")
|
|
161
|
+
'my_project'
|
|
162
|
+
>>> validate_project_name("123project")
|
|
163
|
+
ValueError: Project name must start with a letter
|
|
164
|
+
|
|
165
|
+
"""
|
|
166
|
+
_validate_type(name, str, "Project name")
|
|
167
|
+
_check_project_name_length(name, max_length)
|
|
168
|
+
_check_project_name_chars(name, allow_hyphen, allow_underscore)
|
|
169
|
+
_check_project_name_reserved(name)
|
|
170
|
+
|
|
107
171
|
return name
|
|
108
172
|
|
|
109
173
|
|
|
@@ -120,8 +184,7 @@ def validate_python_version(version: str) -> str:
|
|
|
120
184
|
ValueError: If version format is invalid or unsupported.
|
|
121
185
|
|
|
122
186
|
"""
|
|
123
|
-
|
|
124
|
-
raise TypeError(f"Version must be str, got {type(version).__name__}")
|
|
187
|
+
_validate_type(version, str, "Version")
|
|
125
188
|
|
|
126
189
|
pattern = r"^\d+\.\d+$"
|
|
127
190
|
|
|
@@ -131,7 +194,7 @@ def validate_python_version(version: str) -> str:
|
|
|
131
194
|
|
|
132
195
|
try:
|
|
133
196
|
major, minor = map(int, version.split("."))
|
|
134
|
-
except ValueError as e:
|
|
197
|
+
except ValueError as e:
|
|
135
198
|
msg = f"Invalid version numbers in '{version}'"
|
|
136
199
|
raise ValueError(msg) from e
|
|
137
200
|
|
|
@@ -165,8 +228,7 @@ def validate_email(email: str) -> str:
|
|
|
165
228
|
ValueError: If email format is invalid.
|
|
166
229
|
|
|
167
230
|
"""
|
|
168
|
-
|
|
169
|
-
raise TypeError(f"Email must be str, got {type(email).__name__}")
|
|
231
|
+
_validate_type(email, str, "Email")
|
|
170
232
|
|
|
171
233
|
if not email:
|
|
172
234
|
msg = "Email cannot be empty"
|
|
@@ -213,8 +275,7 @@ def validate_url(
|
|
|
213
275
|
ValueError: If URL format is invalid.
|
|
214
276
|
|
|
215
277
|
"""
|
|
216
|
-
|
|
217
|
-
raise TypeError(f"URL must be str, got {type(url).__name__}")
|
|
278
|
+
_validate_type(url, str, "URL")
|
|
218
279
|
|
|
219
280
|
if not url:
|
|
220
281
|
msg = "URL cannot be empty"
|
|
@@ -270,6 +331,8 @@ def validate_ip_address(
|
|
|
270
331
|
ValueError: If IP address is invalid.
|
|
271
332
|
|
|
272
333
|
"""
|
|
334
|
+
_validate_type(ip, str, "IP address")
|
|
335
|
+
|
|
273
336
|
try:
|
|
274
337
|
addr = ip_address(ip)
|
|
275
338
|
except ValueError as e:
|
|
@@ -309,6 +372,8 @@ def validate_port(
|
|
|
309
372
|
ValueError: If port is invalid.
|
|
310
373
|
|
|
311
374
|
"""
|
|
375
|
+
_validate_type(port, (int, str), "Port")
|
|
376
|
+
|
|
312
377
|
try:
|
|
313
378
|
port_int = int(port)
|
|
314
379
|
except ValueError as e:
|
|
@@ -339,6 +404,8 @@ def validate_semver(version: str) -> tuple[int, int, int]:
|
|
|
339
404
|
ValueError: If version format is invalid.
|
|
340
405
|
|
|
341
406
|
"""
|
|
407
|
+
_validate_type(version, str, "Version")
|
|
408
|
+
|
|
342
409
|
# Remove leading 'v' if present
|
|
343
410
|
version = version.lstrip("vV")
|
|
344
411
|
|
|
@@ -22,6 +22,15 @@ R = TypeVar("R")
|
|
|
22
22
|
|
|
23
23
|
logger = logging.getLogger("taipanstack.utils.circuit_breaker")
|
|
24
24
|
|
|
25
|
+
try:
|
|
26
|
+
import structlog as _structlog
|
|
27
|
+
|
|
28
|
+
_structlog_logger = _structlog.get_logger("taipanstack.utils.circuit_breaker")
|
|
29
|
+
_HAS_STRUCTLOG = True
|
|
30
|
+
except ImportError: # pragma: no cover — structlog is optional
|
|
31
|
+
_structlog_logger = None
|
|
32
|
+
_HAS_STRUCTLOG = False
|
|
33
|
+
|
|
25
34
|
|
|
26
35
|
class CircuitState(Enum):
|
|
27
36
|
"""States of the circuit breaker."""
|
|
@@ -55,6 +64,7 @@ class CircuitBreakerConfig:
|
|
|
55
64
|
success_threshold: Successes needed in half-open to close.
|
|
56
65
|
timeout: Seconds before trying half-open after open.
|
|
57
66
|
excluded_exceptions: Exceptions that don't count as failures.
|
|
67
|
+
failure_exceptions: Exceptions that count as failures.
|
|
58
68
|
|
|
59
69
|
"""
|
|
60
70
|
|
|
@@ -62,6 +72,7 @@ class CircuitBreakerConfig:
|
|
|
62
72
|
success_threshold: int = 2
|
|
63
73
|
timeout: float = 30.0
|
|
64
74
|
excluded_exceptions: tuple[type[Exception], ...] = ()
|
|
75
|
+
failure_exceptions: tuple[type[Exception], ...] = (Exception,)
|
|
65
76
|
|
|
66
77
|
|
|
67
78
|
@dataclass
|
|
@@ -97,6 +108,7 @@ class CircuitBreaker:
|
|
|
97
108
|
success_threshold: int = 2,
|
|
98
109
|
timeout: float = 30.0,
|
|
99
110
|
excluded_exceptions: tuple[type[Exception], ...] = (),
|
|
111
|
+
failure_exceptions: tuple[type[Exception], ...] = (Exception,),
|
|
100
112
|
name: str = "default",
|
|
101
113
|
on_state_change: Callable[[CircuitState, CircuitState], None] | None = None,
|
|
102
114
|
) -> None:
|
|
@@ -107,6 +119,7 @@ class CircuitBreaker:
|
|
|
107
119
|
success_threshold: Successes to close from half-open.
|
|
108
120
|
timeout: Seconds before attempting half-open.
|
|
109
121
|
excluded_exceptions: Exceptions that don't trip circuit.
|
|
122
|
+
failure_exceptions: Exceptions that count as failures.
|
|
110
123
|
name: Name for logging/identification.
|
|
111
124
|
on_state_change: Optional callback invoked on state transitions
|
|
112
125
|
with (old_state, new_state). Useful for custom monitoring.
|
|
@@ -117,6 +130,7 @@ class CircuitBreaker:
|
|
|
117
130
|
success_threshold=success_threshold,
|
|
118
131
|
timeout=timeout,
|
|
119
132
|
excluded_exceptions=excluded_exceptions,
|
|
133
|
+
failure_exceptions=failure_exceptions,
|
|
120
134
|
)
|
|
121
135
|
self.name = name
|
|
122
136
|
self._state = CircuitBreakerState()
|
|
@@ -137,9 +151,21 @@ class CircuitBreaker:
|
|
|
137
151
|
old_state: CircuitState,
|
|
138
152
|
new_state: CircuitState,
|
|
139
153
|
) -> None:
|
|
140
|
-
"""Notify callback of state transition if registered.
|
|
154
|
+
"""Notify callback of state transition if registered.
|
|
155
|
+
|
|
156
|
+
Emit a structured log via structlog when no callback is provided
|
|
157
|
+
and structlog is available.
|
|
158
|
+
"""
|
|
141
159
|
if self._on_state_change is not None:
|
|
142
160
|
self._on_state_change(old_state, new_state)
|
|
161
|
+
elif _HAS_STRUCTLOG and _structlog_logger is not None: # pragma: no branch
|
|
162
|
+
_structlog_logger.warning(
|
|
163
|
+
"circuit_state_changed",
|
|
164
|
+
circuit=self.name,
|
|
165
|
+
old_state=old_state.value,
|
|
166
|
+
new_state=new_state.value,
|
|
167
|
+
failure_count=self._state.failure_count,
|
|
168
|
+
)
|
|
143
169
|
|
|
144
170
|
def _should_attempt(self) -> bool:
|
|
145
171
|
"""Check if a call should be attempted."""
|
|
@@ -266,7 +292,7 @@ class CircuitBreaker:
|
|
|
266
292
|
result = func(*args, **kwargs)
|
|
267
293
|
self._record_success()
|
|
268
294
|
return result
|
|
269
|
-
except
|
|
295
|
+
except self.config.failure_exceptions as e:
|
|
270
296
|
self._record_failure(e)
|
|
271
297
|
raise
|
|
272
298
|
|
|
@@ -279,6 +305,7 @@ def circuit_breaker(
|
|
|
279
305
|
success_threshold: int = 2,
|
|
280
306
|
timeout: float = 30.0,
|
|
281
307
|
excluded_exceptions: tuple[type[Exception], ...] = (),
|
|
308
|
+
failure_exceptions: tuple[type[Exception], ...] = (Exception,),
|
|
282
309
|
name: str | None = None,
|
|
283
310
|
on_state_change: Callable[[CircuitState, CircuitState], None] | None = None,
|
|
284
311
|
) -> Callable[[Callable[P, R]], Callable[P, R]]:
|
|
@@ -289,6 +316,7 @@ def circuit_breaker(
|
|
|
289
316
|
success_threshold: Successes to close from half-open.
|
|
290
317
|
timeout: Seconds before attempting half-open.
|
|
291
318
|
excluded_exceptions: Exceptions that don't trip circuit.
|
|
319
|
+
failure_exceptions: Exceptions that count as failures.
|
|
292
320
|
name: Optional name for the circuit.
|
|
293
321
|
on_state_change: Optional callback invoked on state transitions
|
|
294
322
|
with (old_state, new_state).
|
|
@@ -316,6 +344,7 @@ def circuit_breaker(
|
|
|
316
344
|
success_threshold=success_threshold,
|
|
317
345
|
timeout=timeout,
|
|
318
346
|
excluded_exceptions=excluded_exceptions,
|
|
347
|
+
failure_exceptions=failure_exceptions,
|
|
319
348
|
name=name or func.__name__,
|
|
320
349
|
on_state_change=on_state_change,
|
|
321
350
|
)
|
|
@@ -281,6 +281,7 @@ def log_operation(
|
|
|
281
281
|
*,
|
|
282
282
|
logger: StackLogger | None = None,
|
|
283
283
|
level: str = "INFO",
|
|
284
|
+
expected_exceptions: tuple[type[Exception], ...] | type[Exception] = Exception,
|
|
284
285
|
) -> Any:
|
|
285
286
|
"""Context manager for logging operations.
|
|
286
287
|
|
|
@@ -288,6 +289,7 @@ def log_operation(
|
|
|
288
289
|
operation: Name of the operation.
|
|
289
290
|
logger: Logger to use (creates one if not provided).
|
|
290
291
|
level: Log level for messages.
|
|
292
|
+
expected_exceptions: Exceptions to catch and log as failures.
|
|
291
293
|
|
|
292
294
|
Yields:
|
|
293
295
|
The logger instance.
|
|
@@ -314,7 +316,7 @@ def log_operation(
|
|
|
314
316
|
yield logger
|
|
315
317
|
duration = (datetime.now(UTC) - start_time).total_seconds()
|
|
316
318
|
log_method(f"Completed: {operation}", duration_seconds=duration)
|
|
317
|
-
except
|
|
319
|
+
except expected_exceptions as e:
|
|
318
320
|
duration = (datetime.now(UTC) - start_time).total_seconds()
|
|
319
321
|
logger.exception(
|
|
320
322
|
f"Failed: {operation}",
|
|
@@ -10,7 +10,7 @@ from __future__ import annotations
|
|
|
10
10
|
|
|
11
11
|
import functools
|
|
12
12
|
import logging
|
|
13
|
-
import
|
|
13
|
+
import secrets
|
|
14
14
|
import time
|
|
15
15
|
from collections.abc import Callable
|
|
16
16
|
from dataclasses import dataclass
|
|
@@ -22,6 +22,15 @@ R = TypeVar("R")
|
|
|
22
22
|
|
|
23
23
|
logger = logging.getLogger("taipanstack.utils.retry")
|
|
24
24
|
|
|
25
|
+
try:
|
|
26
|
+
import structlog as _structlog
|
|
27
|
+
|
|
28
|
+
_structlog_logger = _structlog.get_logger("taipanstack.utils.retry")
|
|
29
|
+
_HAS_STRUCTLOG = True
|
|
30
|
+
except ImportError: # pragma: no cover — structlog is optional
|
|
31
|
+
_structlog_logger = None
|
|
32
|
+
_HAS_STRUCTLOG = False
|
|
33
|
+
|
|
25
34
|
|
|
26
35
|
@dataclass(frozen=True)
|
|
27
36
|
class RetryConfig:
|
|
@@ -89,10 +98,12 @@ def calculate_delay(
|
|
|
89
98
|
|
|
90
99
|
# Add jitter if enabled
|
|
91
100
|
# Note: Using random for jitter is intentionally non-cryptographic.
|
|
92
|
-
#
|
|
101
|
+
# However, to maintain a clean security baseline and satisfy Bandit,
|
|
102
|
+
# we use secrets.SystemRandom() which provides cryptographically
|
|
103
|
+
# secure random numbers.
|
|
93
104
|
if config.jitter:
|
|
94
105
|
jitter_amount = delay * config.jitter_factor
|
|
95
|
-
delay +=
|
|
106
|
+
delay += secrets.SystemRandom().uniform(-jitter_amount, jitter_amount)
|
|
96
107
|
|
|
97
108
|
return max(0, delay)
|
|
98
109
|
|
|
@@ -184,9 +195,20 @@ def retry(
|
|
|
184
195
|
delay,
|
|
185
196
|
)
|
|
186
197
|
|
|
187
|
-
# Invoke callback if
|
|
198
|
+
# Invoke callback or emit structured log if no callback set
|
|
188
199
|
if on_retry is not None:
|
|
189
200
|
on_retry(attempt, max_attempts, e, delay)
|
|
201
|
+
elif (
|
|
202
|
+
_HAS_STRUCTLOG and _structlog_logger is not None
|
|
203
|
+
): # pragma: no branch
|
|
204
|
+
_structlog_logger.warning(
|
|
205
|
+
"retry_attempted",
|
|
206
|
+
function=func.__name__,
|
|
207
|
+
attempt=attempt,
|
|
208
|
+
max_attempts=max_attempts,
|
|
209
|
+
error=str(e),
|
|
210
|
+
delay_seconds=round(delay, 3),
|
|
211
|
+
)
|
|
190
212
|
|
|
191
213
|
time.sleep(delay)
|
|
192
214
|
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|