taipanstack 0.3.2__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.2 → taipanstack-0.3.3}/PKG-INFO +1 -1
- {taipanstack-0.3.2 → taipanstack-0.3.3}/pyproject.toml +5 -3
- {taipanstack-0.3.2 → taipanstack-0.3.3}/src/taipanstack/__init__.py +1 -1
- {taipanstack-0.3.2 → taipanstack-0.3.3}/src/taipanstack/core/result.py +40 -9
- {taipanstack-0.3.2 → taipanstack-0.3.3}/src/taipanstack/security/__init__.py +2 -0
- {taipanstack-0.3.2 → taipanstack-0.3.3}/src/taipanstack/security/guards.py +141 -2
- {taipanstack-0.3.2 → taipanstack-0.3.3}/src/taipanstack/security/validators.py +115 -48
- {taipanstack-0.3.2 → taipanstack-0.3.3}/src/taipanstack/utils/circuit_breaker.py +22 -1
- {taipanstack-0.3.2 → taipanstack-0.3.3}/src/taipanstack/utils/retry.py +26 -4
- {taipanstack-0.3.2 → taipanstack-0.3.3}/LICENSE +0 -0
- {taipanstack-0.3.2 → taipanstack-0.3.3}/README.md +0 -0
- {taipanstack-0.3.2 → taipanstack-0.3.3}/src/taipanstack/config/__init__.py +0 -0
- {taipanstack-0.3.2 → taipanstack-0.3.3}/src/taipanstack/config/generators.py +0 -0
- {taipanstack-0.3.2 → taipanstack-0.3.3}/src/taipanstack/config/models.py +0 -0
- {taipanstack-0.3.2 → taipanstack-0.3.3}/src/taipanstack/config/version_config.py +0 -0
- {taipanstack-0.3.2 → taipanstack-0.3.3}/src/taipanstack/core/__init__.py +0 -0
- {taipanstack-0.3.2 → taipanstack-0.3.3}/src/taipanstack/core/compat.py +0 -0
- {taipanstack-0.3.2 → taipanstack-0.3.3}/src/taipanstack/core/optimizations.py +0 -0
- {taipanstack-0.3.2 → taipanstack-0.3.3}/src/taipanstack/security/decorators.py +0 -0
- {taipanstack-0.3.2 → taipanstack-0.3.3}/src/taipanstack/security/sanitizers.py +0 -0
- {taipanstack-0.3.2 → taipanstack-0.3.3}/src/taipanstack/utils/__init__.py +0 -0
- {taipanstack-0.3.2 → taipanstack-0.3.3}/src/taipanstack/utils/filesystem.py +0 -0
- {taipanstack-0.3.2 → taipanstack-0.3.3}/src/taipanstack/utils/logging.py +0 -0
- {taipanstack-0.3.2 → taipanstack-0.3.3}/src/taipanstack/utils/metrics.py +0 -0
- {taipanstack-0.3.2 → taipanstack-0.3.3}/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.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"}
|
|
@@ -67,6 +67,7 @@ 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
|
|
|
@@ -171,6 +172,7 @@ warn_required_dynamic_aliases = true
|
|
|
171
172
|
[tool.pytest.ini_options]
|
|
172
173
|
testpaths = ["tests"]
|
|
173
174
|
addopts = "-v --cov=src --cov-report=html --cov-report=term-missing --strict-markers --timeout=30"
|
|
175
|
+
asyncio_mode = "auto"
|
|
174
176
|
markers = [
|
|
175
177
|
"slow: marks tests as slow (deselect with '-m \"not slow\"')",
|
|
176
178
|
"security: marks tests as security-related",
|
|
@@ -222,7 +224,7 @@ fail-under = 80
|
|
|
222
224
|
verbose = 1
|
|
223
225
|
|
|
224
226
|
[tool.mutmut]
|
|
225
|
-
paths_to_mutate = "src/taipanstack/security/sanitizers.py"
|
|
226
|
-
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"
|
|
227
229
|
runner = "python -m pytest -x -q --tb=no --timeout=10 --no-cov"
|
|
228
230
|
dict_synonyms = "Struct, NamedStruct"
|
|
@@ -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.3"
|
|
9
9
|
|
|
10
10
|
from taipanstack.config.version_config import (
|
|
11
11
|
VersionRecommendations,
|
|
@@ -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
|
|
|
@@ -14,6 +14,7 @@ from taipanstack.security.guards import (
|
|
|
14
14
|
guard_env_variable,
|
|
15
15
|
guard_file_extension,
|
|
16
16
|
guard_path_traversal,
|
|
17
|
+
guard_ssrf,
|
|
17
18
|
)
|
|
18
19
|
from taipanstack.security.sanitizers import (
|
|
19
20
|
sanitize_filename,
|
|
@@ -38,6 +39,7 @@ __all__ = [
|
|
|
38
39
|
"guard_exceptions",
|
|
39
40
|
"guard_file_extension",
|
|
40
41
|
"guard_path_traversal",
|
|
42
|
+
"guard_ssrf",
|
|
41
43
|
"require_type",
|
|
42
44
|
# Sanitizers
|
|
43
45
|
"sanitize_filename",
|
|
@@ -8,10 +8,15 @@ 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
|
|
15
20
|
|
|
16
21
|
_TRAVERSAL_PATTERNS: frozenset[str] = frozenset(
|
|
17
22
|
[
|
|
@@ -224,7 +229,7 @@ def guard_command_injection(
|
|
|
224
229
|
|
|
225
230
|
cmd_list = list(command)
|
|
226
231
|
|
|
227
|
-
# Validate all items are strings
|
|
232
|
+
# Validate all items are strings and check for dangerous patterns
|
|
228
233
|
for i, arg in enumerate(cmd_list):
|
|
229
234
|
if not isinstance(arg, str):
|
|
230
235
|
raise TypeError(
|
|
@@ -232,7 +237,6 @@ def guard_command_injection(
|
|
|
232
237
|
f"got {type(arg).__name__} at index {i}"
|
|
233
238
|
)
|
|
234
239
|
|
|
235
|
-
for arg in cmd_list:
|
|
236
240
|
for pattern, description in _DANGEROUS_COMMAND_PATTERNS:
|
|
237
241
|
if pattern in arg:
|
|
238
242
|
raise SecurityError(
|
|
@@ -384,3 +388,138 @@ def guard_env_variable(
|
|
|
384
388
|
)
|
|
385
389
|
|
|
386
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)
|
|
@@ -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
|
|
|
@@ -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."""
|
|
@@ -142,9 +151,21 @@ class CircuitBreaker:
|
|
|
142
151
|
old_state: CircuitState,
|
|
143
152
|
new_state: CircuitState,
|
|
144
153
|
) -> None:
|
|
145
|
-
"""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
|
+
"""
|
|
146
159
|
if self._on_state_change is not None:
|
|
147
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
|
+
)
|
|
148
169
|
|
|
149
170
|
def _should_attempt(self) -> bool:
|
|
150
171
|
"""Check if a call should be attempted."""
|
|
@@ -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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|