taipanstack 0.3.7__tar.gz → 0.3.9__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.7 → taipanstack-0.3.9}/PKG-INFO +1 -1
- {taipanstack-0.3.7 → taipanstack-0.3.9}/pyproject.toml +2 -2
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/__init__.py +1 -1
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/config/generators.py +77 -24
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/security/__init__.py +2 -0
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/security/guards.py +25 -25
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/security/jwt.py +1 -1
- taipanstack-0.3.9/src/taipanstack/security/models.py +79 -0
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/security/sanitizers.py +6 -1
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/utils/__init__.py +5 -0
- taipanstack-0.3.9/src/taipanstack/utils/concurrency.py +136 -0
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/utils/filesystem.py +6 -1
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/utils/logging.py +26 -13
- taipanstack-0.3.9/src/taipanstack/utils/serialization.py +47 -0
- {taipanstack-0.3.7 → taipanstack-0.3.9}/LICENSE +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.9}/README.md +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/config/__init__.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/config/models.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/config/version_config.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/core/__init__.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/core/compat.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/core/optimizations.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/core/result.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/security/decorators.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/security/password.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/security/types.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/security/validators.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/utils/circuit_breaker.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/utils/metrics.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/utils/rate_limit.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.9}/src/taipanstack/utils/retry.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.9}/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.9"
|
|
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"}
|
|
@@ -119,7 +119,7 @@ max-complexity = 10
|
|
|
119
119
|
|
|
120
120
|
[tool.ruff.lint.per-file-ignores]
|
|
121
121
|
# Tests: allow asserts, skip docs, magic values, unused args, long lines, shadowing builtins
|
|
122
|
-
"tests/**/*.py" = ["S101", "D", "PLR2004", "ARG001", "ARG002", "SIM117", "RUF043", "PLC0415", "E501", "A004", "TRY301", "UP024"]
|
|
122
|
+
"tests/**/*.py" = ["S101", "S105", "S106", "D", "PLR2004", "ARG001", "ARG002", "SIM117", "RUF043", "PLC0415", "E501", "A004", "TRY301", "UP024"]
|
|
123
123
|
# TaipanStack bootstrapper: allow print, long lines, complex branches, docstring style, unused args
|
|
124
124
|
"taipanstack_bootstrapper.py" = ["T201", "E501", "PLR0912", "TRY300", "S603", "D205", "ARG001"]
|
|
125
125
|
# Utils: allow too many args, subprocess, random for jitter
|
|
@@ -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.9"
|
|
9
9
|
|
|
10
10
|
from taipanstack.config.version_config import (
|
|
11
11
|
VersionRecommendations,
|
|
@@ -153,58 +153,82 @@ def generate_pyproject_config(config: StackConfig) -> str:
|
|
|
153
153
|
{_generate_coverage_config()}"""
|
|
154
154
|
|
|
155
155
|
|
|
156
|
-
def
|
|
157
|
-
"""Generate
|
|
156
|
+
def _generate_bandit_hook(severity: str) -> str:
|
|
157
|
+
"""Generate Bandit pre-commit hook.
|
|
158
158
|
|
|
159
159
|
Args:
|
|
160
|
-
|
|
160
|
+
severity: Bandit severity level.
|
|
161
161
|
|
|
162
162
|
Returns:
|
|
163
|
-
|
|
163
|
+
Bandit hook YAML string.
|
|
164
164
|
|
|
165
165
|
"""
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
if config.security.enable_bandit:
|
|
169
|
-
severity = config.security.bandit_severity[0].upper()
|
|
170
|
-
security_hooks.append(f"""
|
|
166
|
+
sev_char = severity[0].upper()
|
|
167
|
+
return f"""
|
|
171
168
|
- repo: https://github.com/PyCQA/bandit
|
|
172
169
|
rev: '1.8.0'
|
|
173
170
|
hooks:
|
|
174
171
|
- id: bandit
|
|
175
|
-
args: ["-r", ".", "-l{
|
|
176
|
-
"""
|
|
172
|
+
args: ["-r", ".", "-l{sev_char}"]
|
|
173
|
+
"""
|
|
177
174
|
|
|
178
|
-
|
|
179
|
-
|
|
175
|
+
|
|
176
|
+
def _generate_safety_hook() -> str:
|
|
177
|
+
"""Generate Safety pre-commit hook.
|
|
178
|
+
|
|
179
|
+
Returns:
|
|
180
|
+
Safety hook YAML string.
|
|
181
|
+
|
|
182
|
+
"""
|
|
183
|
+
return """
|
|
180
184
|
- repo: https://github.com/pyupio/safety
|
|
181
185
|
rev: '3.2.11'
|
|
182
186
|
hooks:
|
|
183
187
|
- id: safety
|
|
184
188
|
args: ["check", "--json"]
|
|
185
|
-
"""
|
|
189
|
+
"""
|
|
186
190
|
|
|
187
|
-
|
|
188
|
-
|
|
191
|
+
|
|
192
|
+
def _generate_semgrep_hook() -> str:
|
|
193
|
+
"""Generate Semgrep pre-commit hook.
|
|
194
|
+
|
|
195
|
+
Returns:
|
|
196
|
+
Semgrep hook YAML string.
|
|
197
|
+
|
|
198
|
+
"""
|
|
199
|
+
return """
|
|
189
200
|
- repo: https://github.com/semgrep/pre-commit
|
|
190
201
|
rev: 'v1.99.0'
|
|
191
202
|
hooks:
|
|
192
203
|
- id: semgrep
|
|
193
204
|
args: ['--config=auto']
|
|
194
|
-
"""
|
|
205
|
+
"""
|
|
195
206
|
|
|
196
|
-
|
|
197
|
-
|
|
207
|
+
|
|
208
|
+
def _generate_detect_secrets_hook() -> str:
|
|
209
|
+
"""Generate detect-secrets pre-commit hook.
|
|
210
|
+
|
|
211
|
+
Returns:
|
|
212
|
+
Detect-secrets hook YAML string.
|
|
213
|
+
|
|
214
|
+
"""
|
|
215
|
+
return """
|
|
198
216
|
- repo: https://github.com/Yelp/detect-secrets
|
|
199
217
|
rev: 'v1.5.0'
|
|
200
218
|
hooks:
|
|
201
219
|
- id: detect-secrets
|
|
202
220
|
args: ['--baseline', '.secrets.baseline']
|
|
203
|
-
"""
|
|
221
|
+
"""
|
|
204
222
|
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
223
|
+
|
|
224
|
+
def _generate_paranoid_hooks() -> str:
|
|
225
|
+
"""Generate extra security hooks for paranoid mode.
|
|
226
|
+
|
|
227
|
+
Returns:
|
|
228
|
+
Paranoid hooks YAML string.
|
|
229
|
+
|
|
230
|
+
"""
|
|
231
|
+
return """
|
|
208
232
|
- repo: https://github.com/trailofbits/pip-audit
|
|
209
233
|
rev: 'v2.7.3'
|
|
210
234
|
hooks:
|
|
@@ -219,7 +243,36 @@ def generate_pre_commit_config(config: StackConfig) -> str:
|
|
|
219
243
|
rev: 'v2.3.3'
|
|
220
244
|
hooks:
|
|
221
245
|
- id: tryceratops
|
|
222
|
-
"""
|
|
246
|
+
"""
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def generate_pre_commit_config(config: StackConfig) -> str:
|
|
250
|
+
"""Generate .pre-commit-config.yaml content.
|
|
251
|
+
|
|
252
|
+
Args:
|
|
253
|
+
config: The Stack configuration.
|
|
254
|
+
|
|
255
|
+
Returns:
|
|
256
|
+
Pre-commit configuration YAML string.
|
|
257
|
+
|
|
258
|
+
"""
|
|
259
|
+
security_hooks: list[str] = []
|
|
260
|
+
|
|
261
|
+
if config.security.enable_bandit:
|
|
262
|
+
security_hooks.append(_generate_bandit_hook(config.security.bandit_severity))
|
|
263
|
+
|
|
264
|
+
if config.security.enable_safety:
|
|
265
|
+
security_hooks.append(_generate_safety_hook())
|
|
266
|
+
|
|
267
|
+
if config.security.enable_semgrep:
|
|
268
|
+
security_hooks.append(_generate_semgrep_hook())
|
|
269
|
+
|
|
270
|
+
if config.security.enable_detect_secrets:
|
|
271
|
+
security_hooks.append(_generate_detect_secrets_hook())
|
|
272
|
+
|
|
273
|
+
# Add extra hooks for paranoid mode
|
|
274
|
+
if config.security.level == "paranoid":
|
|
275
|
+
security_hooks.append(_generate_paranoid_hooks())
|
|
223
276
|
|
|
224
277
|
return f"""# Stack v2.0 Pre-commit Configuration
|
|
225
278
|
# Security Level: {config.security.level}
|
|
@@ -17,6 +17,7 @@ from taipanstack.security.guards import (
|
|
|
17
17
|
guard_ssrf,
|
|
18
18
|
)
|
|
19
19
|
from taipanstack.security.jwt import decode_jwt, encode_jwt
|
|
20
|
+
from taipanstack.security.models import SecureBaseModel
|
|
20
21
|
from taipanstack.security.password import hash_password, verify_password
|
|
21
22
|
from taipanstack.security.sanitizers import (
|
|
22
23
|
sanitize_filename,
|
|
@@ -43,6 +44,7 @@ __all__ = [
|
|
|
43
44
|
"SafePath",
|
|
44
45
|
"SafeProjectName",
|
|
45
46
|
"SafeUrl",
|
|
47
|
+
"SecureBaseModel",
|
|
46
48
|
"SecurityError",
|
|
47
49
|
"ValidationError",
|
|
48
50
|
"decode_jwt",
|
|
@@ -27,6 +27,10 @@ _TRAVERSAL_PATTERNS: frozenset[str] = frozenset(
|
|
|
27
27
|
]
|
|
28
28
|
)
|
|
29
29
|
|
|
30
|
+
_TRAVERSAL_REGEX = re.compile(
|
|
31
|
+
"|".join(re.escape(p) for p in sorted(_TRAVERSAL_PATTERNS, key=len, reverse=True))
|
|
32
|
+
)
|
|
33
|
+
|
|
30
34
|
_DANGEROUS_COMMAND_PATTERNS: tuple[tuple[str, str], ...] = (
|
|
31
35
|
(";", "command separator"),
|
|
32
36
|
("|", "pipe"),
|
|
@@ -81,12 +85,8 @@ _DEFAULT_DENIED_ENV_VARS = frozenset(
|
|
|
81
85
|
]
|
|
82
86
|
)
|
|
83
87
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
re.compile(r".*PASSWORD.*"),
|
|
87
|
-
re.compile(r".*TOKEN.*"),
|
|
88
|
-
re.compile(r".*PRIVATE.*KEY.*"),
|
|
89
|
-
re.compile(r".*API.*KEY.*"),
|
|
88
|
+
_SENSITIVE_ENV_VAR_PATTERN = re.compile(
|
|
89
|
+
r".*SECRET.*|.*PASSWORD.*|.*TOKEN.*|.*PRIVATE.*KEY.*|.*API.*KEY.*"
|
|
90
90
|
)
|
|
91
91
|
|
|
92
92
|
|
|
@@ -155,13 +155,14 @@ def guard_path_traversal(
|
|
|
155
155
|
path_str = str(path)
|
|
156
156
|
path_str_lower = path_str.lower()
|
|
157
157
|
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
158
|
+
match = _TRAVERSAL_REGEX.search(path_str_lower)
|
|
159
|
+
if match:
|
|
160
|
+
pattern = match.group(0)
|
|
161
|
+
raise SecurityError(
|
|
162
|
+
f"Path traversal pattern detected: {pattern}",
|
|
163
|
+
guard_name="path_traversal",
|
|
164
|
+
value=path_str[:50], # Truncate for safety
|
|
165
|
+
)
|
|
165
166
|
|
|
166
167
|
# Resolve the path
|
|
167
168
|
try:
|
|
@@ -364,23 +365,22 @@ def guard_env_variable(
|
|
|
364
365
|
value=name,
|
|
365
366
|
)
|
|
366
367
|
|
|
367
|
-
|
|
368
|
-
if
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
if name_upper not in allowed:
|
|
373
|
-
raise SecurityError(
|
|
374
|
-
f"Access to potentially sensitive variable '{name}' is denied",
|
|
375
|
-
guard_name="env_variable",
|
|
376
|
-
value=name,
|
|
377
|
-
)
|
|
378
|
-
else:
|
|
368
|
+
if _SENSITIVE_ENV_VAR_PATTERN.match(name_upper):
|
|
369
|
+
# Only block if not explicitly allowed
|
|
370
|
+
if allowed_names is not None:
|
|
371
|
+
allowed = {n.upper() for n in allowed_names}
|
|
372
|
+
if name_upper not in allowed:
|
|
379
373
|
raise SecurityError(
|
|
380
374
|
f"Access to potentially sensitive variable '{name}' is denied",
|
|
381
375
|
guard_name="env_variable",
|
|
382
376
|
value=name,
|
|
383
377
|
)
|
|
378
|
+
else:
|
|
379
|
+
raise SecurityError(
|
|
380
|
+
f"Access to potentially sensitive variable '{name}' is denied",
|
|
381
|
+
guard_name="env_variable",
|
|
382
|
+
value=name,
|
|
383
|
+
)
|
|
384
384
|
|
|
385
385
|
# Get the variable
|
|
386
386
|
value = os.environ.get(name)
|
|
@@ -72,7 +72,7 @@ def decode_jwt(
|
|
|
72
72
|
PyJWTError: If the token is invalid, expired, or has incorrect claims.
|
|
73
73
|
|
|
74
74
|
"""
|
|
75
|
-
if
|
|
75
|
+
if any(str(alg).strip().lower() == "none" for alg in algorithms):
|
|
76
76
|
raise ValueError('Algorithm "none" is explicitly disallowed for decoding.')
|
|
77
77
|
|
|
78
78
|
# We enforce 'exp' and 'aud' through PyJWT's options parameter
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Secure base models."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel
|
|
8
|
+
|
|
9
|
+
from taipanstack.utils.logging import REDACTED_VALUE, SENSITIVE_KEY_PATTERNS
|
|
10
|
+
|
|
11
|
+
__all__ = ["SecureBaseModel"]
|
|
12
|
+
|
|
13
|
+
_SENSITIVE_KEY_REGEX = (
|
|
14
|
+
re.compile("|".join(map(re.escape, SENSITIVE_KEY_PATTERNS)), re.IGNORECASE)
|
|
15
|
+
if SENSITIVE_KEY_PATTERNS
|
|
16
|
+
else None
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _mask_data(data: Any) -> Any:
|
|
21
|
+
"""Recursively mask sensitive keys in data."""
|
|
22
|
+
if _SENSITIVE_KEY_REGEX is None:
|
|
23
|
+
return data
|
|
24
|
+
|
|
25
|
+
if isinstance(data, dict):
|
|
26
|
+
masked = {}
|
|
27
|
+
for k, v in data.items():
|
|
28
|
+
if isinstance(k, str) and _SENSITIVE_KEY_REGEX.search(k):
|
|
29
|
+
masked[k] = REDACTED_VALUE
|
|
30
|
+
else:
|
|
31
|
+
masked[k] = _mask_data(v)
|
|
32
|
+
return masked
|
|
33
|
+
if isinstance(data, list):
|
|
34
|
+
return [_mask_data(item) for item in data]
|
|
35
|
+
return data
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class SecureBaseModel(BaseModel):
|
|
39
|
+
"""Secure base model that redacts sensitive fields when dumped."""
|
|
40
|
+
|
|
41
|
+
def model_dump(
|
|
42
|
+
self,
|
|
43
|
+
**kwargs: Any,
|
|
44
|
+
) -> dict[str, Any]:
|
|
45
|
+
"""Dump the model to a dictionary, redacting sensitive fields.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
**kwargs: Arguments to pass to Pydantic's model_dump.
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
The redacting dictionary representation of the model.
|
|
52
|
+
|
|
53
|
+
"""
|
|
54
|
+
data = super().model_dump(**kwargs)
|
|
55
|
+
return _mask_data(data) # type: ignore[no-any-return]
|
|
56
|
+
|
|
57
|
+
def model_dump_json(
|
|
58
|
+
self,
|
|
59
|
+
**kwargs: Any,
|
|
60
|
+
) -> str:
|
|
61
|
+
"""Dump the model to a JSON string, redacting sensitive fields.
|
|
62
|
+
|
|
63
|
+
Args:
|
|
64
|
+
**kwargs: Arguments to pass to Pydantic's model_dump.
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
The redacted JSON string representation of the model.
|
|
68
|
+
|
|
69
|
+
"""
|
|
70
|
+
# Extract indent if any, as model_dump does not accept it
|
|
71
|
+
indent = kwargs.pop("indent", None)
|
|
72
|
+
# Dump to JSON-compatible dict, mask, then serialize
|
|
73
|
+
dumped_dict = super().model_dump(mode="json", **kwargs)
|
|
74
|
+
masked_dict = _mask_data(dumped_dict)
|
|
75
|
+
# We need to respect Pydantic's indent/separators if possible,
|
|
76
|
+
# but json.dumps is the safest standard way.
|
|
77
|
+
if indent is not None:
|
|
78
|
+
return json.dumps(masked_dict, indent=indent)
|
|
79
|
+
return json.dumps(masked_dict)
|
|
@@ -14,6 +14,7 @@ MAX_SQL_IDENTIFIER_LENGTH = 128 # pragma: no mutate
|
|
|
14
14
|
|
|
15
15
|
# Pre-compiled regex and sets for Performance Benchmarks
|
|
16
16
|
_INVALID_FILENAME_CHARS_RE = re.compile(r'[<>:"/\\|?*\x00-\x1f]') # pragma: no mutate
|
|
17
|
+
_SQL_IDENTIFIER_DENY_RE = re.compile(r"[^a-zA-Z0-9_]") # pragma: no mutate
|
|
17
18
|
_WINDOWS_RESERVED_NAMES = frozenset( # pragma: no mutate
|
|
18
19
|
{
|
|
19
20
|
"CON",
|
|
@@ -317,7 +318,11 @@ def sanitize_sql_identifier(identifier: str) -> str:
|
|
|
317
318
|
raise ValueError(msg)
|
|
318
319
|
|
|
319
320
|
# Only allow alphanumeric and underscore
|
|
320
|
-
|
|
321
|
+
# Fast path: if already clean, skip sub
|
|
322
|
+
if _SQL_IDENTIFIER_DENY_RE.search(identifier):
|
|
323
|
+
result = _SQL_IDENTIFIER_DENY_RE.sub("", identifier)
|
|
324
|
+
else:
|
|
325
|
+
result = identifier
|
|
321
326
|
|
|
322
327
|
# Must start with letter or underscore
|
|
323
328
|
if result and not (result[0].isalpha() or result[0] == "_"):
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"""Utility modules for Stack."""
|
|
2
2
|
|
|
3
|
+
from .concurrency import OverloadError, limit_concurrency
|
|
3
4
|
from .filesystem import ensure_dir, safe_read, safe_write
|
|
4
5
|
from .logging import (
|
|
5
6
|
REDACTED_VALUE,
|
|
@@ -12,20 +13,24 @@ from .logging import (
|
|
|
12
13
|
)
|
|
13
14
|
from .rate_limit import RateLimiter, RateLimitError, rate_limit
|
|
14
15
|
from .retry import Retrier, RetryConfig, RetryError, retry
|
|
16
|
+
from .serialization import default_encoder
|
|
15
17
|
from .subprocess import SafeCommandResult, run_safe_command
|
|
16
18
|
|
|
17
19
|
__all__ = (
|
|
18
20
|
"REDACTED_VALUE",
|
|
19
21
|
"SENSITIVE_KEY_PATTERNS",
|
|
22
|
+
"OverloadError",
|
|
20
23
|
"RateLimitError",
|
|
21
24
|
"RateLimiter",
|
|
22
25
|
"Retrier",
|
|
23
26
|
"RetryConfig",
|
|
24
27
|
"RetryError",
|
|
25
28
|
"SafeCommandResult",
|
|
29
|
+
"default_encoder",
|
|
26
30
|
"ensure_dir",
|
|
27
31
|
"get_correlation_id",
|
|
28
32
|
"get_logger",
|
|
33
|
+
"limit_concurrency",
|
|
29
34
|
"log_operation",
|
|
30
35
|
"rate_limit",
|
|
31
36
|
"retry",
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Concurrency utilities.
|
|
3
|
+
|
|
4
|
+
Provides a bulkhead pattern concurrency limiter decorator for both
|
|
5
|
+
synchronous and asynchronous functions. Uses an `OverloadError` and
|
|
6
|
+
returns a `Result` type.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import functools
|
|
11
|
+
import inspect
|
|
12
|
+
import threading
|
|
13
|
+
from collections.abc import Callable, Coroutine
|
|
14
|
+
from typing import Any, ParamSpec, Protocol, TypeVar, overload
|
|
15
|
+
|
|
16
|
+
from taipanstack.core.result import Err, Ok, Result
|
|
17
|
+
|
|
18
|
+
__all__ = ["OverloadError", "limit_concurrency"]
|
|
19
|
+
|
|
20
|
+
P = ParamSpec("P")
|
|
21
|
+
T = TypeVar("T")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class OverloadError(Exception):
|
|
25
|
+
"""Exception raised when a concurrency limit is exceeded or timed out."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, message: str = "Concurrency limit reached") -> None:
|
|
28
|
+
"""Initialize the OverloadError.
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
message: The error message to display.
|
|
32
|
+
Defaults to "Concurrency limit reached".
|
|
33
|
+
|
|
34
|
+
"""
|
|
35
|
+
super().__init__(message)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ConcurrencyLimitDecorator(Protocol):
|
|
39
|
+
"""Protocol for the concurrency limit decorator."""
|
|
40
|
+
|
|
41
|
+
@overload
|
|
42
|
+
def __call__(
|
|
43
|
+
self, func: Callable[P, T]
|
|
44
|
+
) -> Callable[P, Result[T, OverloadError]]: ... # pragma: no cover
|
|
45
|
+
|
|
46
|
+
@overload
|
|
47
|
+
def __call__(
|
|
48
|
+
self, func: Callable[P, Coroutine[Any, Any, T]]
|
|
49
|
+
) -> Callable[
|
|
50
|
+
P, Coroutine[Any, Any, Result[T, OverloadError]]
|
|
51
|
+
]: ... # pragma: no cover
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def limit_concurrency(
|
|
55
|
+
max_tasks: int,
|
|
56
|
+
timeout: float = 0.0,
|
|
57
|
+
) -> ConcurrencyLimitDecorator:
|
|
58
|
+
"""Decorate a function to apply the bulkhead concurrency limit pattern.
|
|
59
|
+
|
|
60
|
+
If the maximum concurrent executions are reached, the wrapper will wait up
|
|
61
|
+
to `timeout` seconds to acquire a execution slot. If it fails, it returns
|
|
62
|
+
an ``Err(OverloadError)``.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
max_tasks: Maximum concurrent function executions allowed.
|
|
66
|
+
timeout: Maximum time in seconds to wait for a slot if limit is reached.
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
Decorated function returning a ``Result[T, OverloadError]``.
|
|
70
|
+
|
|
71
|
+
Example:
|
|
72
|
+
>>> @limit_concurrency(max_tasks=2, timeout=0.1)
|
|
73
|
+
... def process_data() -> str:
|
|
74
|
+
... return "data"
|
|
75
|
+
>>> process_data()
|
|
76
|
+
Ok('data')
|
|
77
|
+
|
|
78
|
+
"""
|
|
79
|
+
if max_tasks <= 0:
|
|
80
|
+
raise ValueError("max_tasks must be > 0")
|
|
81
|
+
if timeout < 0.0:
|
|
82
|
+
raise ValueError("timeout must be >= 0.0")
|
|
83
|
+
|
|
84
|
+
def decorator(
|
|
85
|
+
func: Callable[P, T] | Callable[P, Coroutine[Any, Any, T]],
|
|
86
|
+
) -> (
|
|
87
|
+
Callable[P, Result[T, OverloadError]]
|
|
88
|
+
| Callable[P, Coroutine[Any, Any, Result[T, OverloadError]]]
|
|
89
|
+
):
|
|
90
|
+
if inspect.iscoroutinefunction(func):
|
|
91
|
+
async_semaphore = asyncio.Semaphore(max_tasks)
|
|
92
|
+
|
|
93
|
+
@functools.wraps(func)
|
|
94
|
+
async def async_wrapper(
|
|
95
|
+
*args: P.args,
|
|
96
|
+
**kwargs: P.kwargs,
|
|
97
|
+
) -> Result[T, OverloadError]:
|
|
98
|
+
if timeout > 0.0:
|
|
99
|
+
try:
|
|
100
|
+
async with asyncio.timeout(timeout):
|
|
101
|
+
await async_semaphore.acquire()
|
|
102
|
+
except TimeoutError:
|
|
103
|
+
return Err(OverloadError())
|
|
104
|
+
else:
|
|
105
|
+
if async_semaphore.locked():
|
|
106
|
+
return Err(OverloadError())
|
|
107
|
+
await async_semaphore.acquire()
|
|
108
|
+
|
|
109
|
+
try:
|
|
110
|
+
return Ok(await func(*args, **kwargs))
|
|
111
|
+
finally:
|
|
112
|
+
async_semaphore.release()
|
|
113
|
+
|
|
114
|
+
return async_wrapper
|
|
115
|
+
|
|
116
|
+
sync_semaphore = threading.Semaphore(max_tasks)
|
|
117
|
+
|
|
118
|
+
@functools.wraps(func)
|
|
119
|
+
def wrapper(*args: P.args, **kwargs: P.kwargs) -> Result[T, OverloadError]:
|
|
120
|
+
if timeout > 0.0:
|
|
121
|
+
acquired = sync_semaphore.acquire(timeout=timeout)
|
|
122
|
+
if not acquired:
|
|
123
|
+
return Err(OverloadError())
|
|
124
|
+
else:
|
|
125
|
+
acquired = sync_semaphore.acquire(blocking=False)
|
|
126
|
+
if not acquired:
|
|
127
|
+
return Err(OverloadError())
|
|
128
|
+
|
|
129
|
+
try:
|
|
130
|
+
return Ok(func(*args, **kwargs)) # type: ignore[arg-type]
|
|
131
|
+
finally:
|
|
132
|
+
sync_semaphore.release()
|
|
133
|
+
|
|
134
|
+
return wrapper
|
|
135
|
+
|
|
136
|
+
return decorator # type: ignore[return-value]
|
|
@@ -6,6 +6,7 @@ atomic writes, and proper error handling using Result types.
|
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
8
|
import contextlib
|
|
9
|
+
import functools
|
|
9
10
|
import hashlib
|
|
10
11
|
import os
|
|
11
12
|
import shutil
|
|
@@ -362,11 +363,13 @@ def get_file_hash(
|
|
|
362
363
|
# Validate path
|
|
363
364
|
if base_dir is not None:
|
|
364
365
|
path = guard_path_traversal(path, Path(base_dir))
|
|
366
|
+
elif ".." in str(path):
|
|
367
|
+
path = guard_path_traversal(path, Path.cwd())
|
|
365
368
|
|
|
366
369
|
hasher = hashlib.new(algorithm)
|
|
367
370
|
|
|
368
371
|
with path.open("rb") as f:
|
|
369
|
-
for chunk in iter(
|
|
372
|
+
for chunk in iter(functools.partial(f.read, 8192), b""):
|
|
370
373
|
hasher.update(chunk)
|
|
371
374
|
|
|
372
375
|
return hasher.hexdigest()
|
|
@@ -398,6 +401,8 @@ def find_files(
|
|
|
398
401
|
# Validate path
|
|
399
402
|
if base_dir is not None:
|
|
400
403
|
directory = guard_path_traversal(directory, Path(base_dir))
|
|
404
|
+
elif ".." in str(directory):
|
|
405
|
+
directory = guard_path_traversal(directory, Path.cwd())
|
|
401
406
|
|
|
402
407
|
if not directory.exists():
|
|
403
408
|
return []
|
|
@@ -6,6 +6,7 @@ context propagation, and proper formatting.
|
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
8
|
import logging
|
|
9
|
+
import re
|
|
9
10
|
import sys
|
|
10
11
|
from collections.abc import MutableMapping
|
|
11
12
|
from contextlib import contextmanager
|
|
@@ -36,14 +37,21 @@ SENSITIVE_KEY_PATTERNS: tuple[str, ...] = (
|
|
|
36
37
|
"api_key",
|
|
37
38
|
)
|
|
38
39
|
|
|
40
|
+
# Pre-compile the regex for O(1) checks per key instead of O(N*M)
|
|
41
|
+
_SENSITIVE_KEY_REGEX = (
|
|
42
|
+
re.compile("|".join(map(re.escape, SENSITIVE_KEY_PATTERNS)), re.IGNORECASE)
|
|
43
|
+
if SENSITIVE_KEY_PATTERNS
|
|
44
|
+
else None
|
|
45
|
+
)
|
|
46
|
+
|
|
39
47
|
REDACTED_VALUE = "***REDACTED***"
|
|
40
48
|
|
|
41
49
|
|
|
42
50
|
def mask_sensitive_data_processor(
|
|
43
51
|
logger: Any, # noqa: ARG001
|
|
44
52
|
method: str, # noqa: ARG001
|
|
45
|
-
event_dict:
|
|
46
|
-
) ->
|
|
53
|
+
event_dict: MutableMapping[str, Any],
|
|
54
|
+
) -> MutableMapping[str, Any]:
|
|
47
55
|
"""Mask sensitive data in structlog event dictionaries.
|
|
48
56
|
|
|
49
57
|
Intercept the *event_dict* produced by structlog and replace the
|
|
@@ -51,20 +59,20 @@ def mask_sensitive_data_processor(
|
|
|
51
59
|
``"***REDACTED***"``. Matching is case-insensitive.
|
|
52
60
|
|
|
53
61
|
Args:
|
|
54
|
-
|
|
55
|
-
|
|
62
|
+
_logger: The wrapped logger object (unused, required by structlog).
|
|
63
|
+
_method: The name of the log method called (unused, required by structlog).
|
|
56
64
|
event_dict: The structured event dictionary.
|
|
57
65
|
|
|
58
66
|
Returns:
|
|
59
67
|
The event dictionary with sensitive values masked.
|
|
60
68
|
|
|
61
69
|
"""
|
|
70
|
+
if _SENSITIVE_KEY_REGEX is None:
|
|
71
|
+
return event_dict
|
|
72
|
+
|
|
62
73
|
for key in event_dict:
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
if pattern in key_lower:
|
|
66
|
-
event_dict[key] = REDACTED_VALUE
|
|
67
|
-
break
|
|
74
|
+
if _SENSITIVE_KEY_REGEX.search(key):
|
|
75
|
+
event_dict[key] = REDACTED_VALUE
|
|
68
76
|
return event_dict
|
|
69
77
|
|
|
70
78
|
|
|
@@ -96,15 +104,15 @@ def set_correlation_id(correlation_id: str | None) -> None:
|
|
|
96
104
|
|
|
97
105
|
|
|
98
106
|
def correlation_id_processor(
|
|
99
|
-
|
|
100
|
-
|
|
107
|
+
_logger: Any,
|
|
108
|
+
_method: str,
|
|
101
109
|
event_dict: MutableMapping[str, Any],
|
|
102
110
|
) -> MutableMapping[str, Any]:
|
|
103
111
|
"""Structlog processor to inject correlation ID into events.
|
|
104
112
|
|
|
105
113
|
Args:
|
|
106
|
-
|
|
107
|
-
|
|
114
|
+
_logger: The wrapped logger object.
|
|
115
|
+
_method: The name of the log method called.
|
|
108
116
|
event_dict: The structured event dictionary.
|
|
109
117
|
|
|
110
118
|
Returns:
|
|
@@ -202,6 +210,10 @@ class StackLogger:
|
|
|
202
210
|
return message
|
|
203
211
|
|
|
204
212
|
context = {**self._context, **kwargs}
|
|
213
|
+
if _SENSITIVE_KEY_REGEX is not None:
|
|
214
|
+
for key in context:
|
|
215
|
+
if _SENSITIVE_KEY_REGEX.search(key):
|
|
216
|
+
context[key] = REDACTED_VALUE
|
|
205
217
|
context_str = " ".join(f"{k}={v}" for k, v in context.items())
|
|
206
218
|
return f"{message} | {context_str}"
|
|
207
219
|
|
|
@@ -309,6 +321,7 @@ def setup_logging(
|
|
|
309
321
|
structlog.stdlib.add_log_level,
|
|
310
322
|
structlog.processors.TimeStamper(fmt="iso"),
|
|
311
323
|
correlation_id_processor,
|
|
324
|
+
mask_sensitive_data_processor,
|
|
312
325
|
structlog.processors.StackInfoRenderer(),
|
|
313
326
|
structlog.processors.format_exc_info,
|
|
314
327
|
structlog.processors.UnicodeDecoder(),
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Serialization utilities.
|
|
3
|
+
|
|
4
|
+
Provides an optimized default encoder for use with ``orjson.dumps``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from taipanstack.core.result import Err, Ok
|
|
10
|
+
|
|
11
|
+
__all__ = ["default_encoder"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def default_encoder(obj: Any) -> dict[str, Any]:
|
|
15
|
+
"""Default encoder for orjson.dumps handling Result types.
|
|
16
|
+
|
|
17
|
+
Intercepts objects of type ``Ok`` and ``Err``:
|
|
18
|
+
- ``Ok(value)``: Returns ``{"status": "success"}`` merged with ``value`` if
|
|
19
|
+
``value`` is a dict. Otherwise returns ``{"status": "success", "data": value}``.
|
|
20
|
+
- ``Err(error)``: Returns ``{"status": "error", "message": str(error)}``.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
obj: The object to encode.
|
|
24
|
+
|
|
25
|
+
Returns:
|
|
26
|
+
A serializable representation of the object.
|
|
27
|
+
|
|
28
|
+
Raises:
|
|
29
|
+
TypeError: If the object type is not supported.
|
|
30
|
+
|
|
31
|
+
Example:
|
|
32
|
+
>>> import orjson
|
|
33
|
+
>>> orjson.dumps(Ok({"id": 1}), default=default_encoder)
|
|
34
|
+
b'{"status":"success","id":1}'
|
|
35
|
+
>>> orjson.dumps(Err(ValueError("oops")), default=default_encoder)
|
|
36
|
+
b'{"status":"error","message":"oops"}'
|
|
37
|
+
|
|
38
|
+
"""
|
|
39
|
+
if isinstance(obj, Ok):
|
|
40
|
+
if isinstance(obj.value, dict):
|
|
41
|
+
return {"status": "success", **obj.value}
|
|
42
|
+
return {"status": "success", "data": obj.value}
|
|
43
|
+
|
|
44
|
+
if isinstance(obj, Err):
|
|
45
|
+
return {"status": "error", "message": str(obj.value)}
|
|
46
|
+
|
|
47
|
+
raise TypeError(f"Type {type(obj).__name__} is not JSON serializable")
|
|
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
|