taipanstack 0.3.2__tar.gz → 0.3.4__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.
Files changed (27) hide show
  1. {taipanstack-0.3.2 → taipanstack-0.3.4}/PKG-INFO +1 -1
  2. {taipanstack-0.3.2 → taipanstack-0.3.4}/pyproject.toml +5 -3
  3. {taipanstack-0.3.2 → taipanstack-0.3.4}/src/taipanstack/__init__.py +1 -10
  4. {taipanstack-0.3.2 → taipanstack-0.3.4}/src/taipanstack/config/generators.py +13 -16
  5. {taipanstack-0.3.2 → taipanstack-0.3.4}/src/taipanstack/core/__init__.py +0 -22
  6. {taipanstack-0.3.2 → taipanstack-0.3.4}/src/taipanstack/core/optimizations.py +0 -1
  7. {taipanstack-0.3.2 → taipanstack-0.3.4}/src/taipanstack/core/result.py +40 -10
  8. {taipanstack-0.3.2 → taipanstack-0.3.4}/src/taipanstack/security/__init__.py +5 -0
  9. {taipanstack-0.3.2 → taipanstack-0.3.4}/src/taipanstack/security/decorators.py +0 -1
  10. {taipanstack-0.3.2 → taipanstack-0.3.4}/src/taipanstack/security/guards.py +141 -3
  11. taipanstack-0.3.4/src/taipanstack/security/password.py +87 -0
  12. {taipanstack-0.3.2 → taipanstack-0.3.4}/src/taipanstack/security/sanitizers.py +0 -1
  13. {taipanstack-0.3.2 → taipanstack-0.3.4}/src/taipanstack/security/validators.py +116 -49
  14. taipanstack-0.3.4/src/taipanstack/utils/__init__.py +20 -0
  15. {taipanstack-0.3.2 → taipanstack-0.3.4}/src/taipanstack/utils/circuit_breaker.py +22 -2
  16. {taipanstack-0.3.2 → taipanstack-0.3.4}/src/taipanstack/utils/logging.py +2 -3
  17. {taipanstack-0.3.2 → taipanstack-0.3.4}/src/taipanstack/utils/metrics.py +4 -5
  18. {taipanstack-0.3.2 → taipanstack-0.3.4}/src/taipanstack/utils/retry.py +27 -6
  19. {taipanstack-0.3.2 → taipanstack-0.3.4}/src/taipanstack/utils/subprocess.py +1 -2
  20. taipanstack-0.3.2/src/taipanstack/utils/__init__.py +0 -24
  21. {taipanstack-0.3.2 → taipanstack-0.3.4}/LICENSE +0 -0
  22. {taipanstack-0.3.2 → taipanstack-0.3.4}/README.md +0 -0
  23. {taipanstack-0.3.2 → taipanstack-0.3.4}/src/taipanstack/config/__init__.py +0 -0
  24. {taipanstack-0.3.2 → taipanstack-0.3.4}/src/taipanstack/config/models.py +0 -0
  25. {taipanstack-0.3.2 → taipanstack-0.3.4}/src/taipanstack/config/version_config.py +0 -0
  26. {taipanstack-0.3.2 → taipanstack-0.3.4}/src/taipanstack/core/compat.py +0 -0
  27. {taipanstack-0.3.2 → taipanstack-0.3.4}/src/taipanstack/utils/filesystem.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: taipanstack
3
- Version: 0.3.2
3
+ Version: 0.3.4
4
4
  Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "taipanstack"
3
- version = "0.3.2"
3
+ version = "0.3.4"
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.2"
8
+ __version__ = "0.3.4"
9
9
 
10
10
  from taipanstack.config.version_config import (
11
11
  VersionRecommendations,
@@ -19,11 +19,6 @@ from taipanstack.core.compat import (
19
19
  get_features,
20
20
  get_python_info,
21
21
  )
22
- from taipanstack.core.optimizations import apply_optimizations, get_optimization_profile
23
- from taipanstack.security.guards import (
24
- guard_command_injection,
25
- guard_path_traversal,
26
- )
27
22
  from taipanstack.security.validators import (
28
23
  validate_email,
29
24
  validate_project_name,
@@ -36,13 +31,9 @@ __all__ = [
36
31
  "PY314",
37
32
  "PY_VERSION",
38
33
  "VersionRecommendations",
39
- "apply_optimizations",
40
34
  "get_features",
41
- "get_optimization_profile",
42
35
  "get_python_info",
43
36
  "get_version_recommendations",
44
- "guard_command_injection",
45
- "guard_path_traversal",
46
37
  "validate_email",
47
38
  "validate_project_name",
48
39
  "validate_python_version",
@@ -5,13 +5,10 @@ This module generates configuration files (pyproject.toml, pre-commit, etc.)
5
5
  with proper validation and templating.
6
6
  """
7
7
 
8
- from __future__ import annotations
9
8
 
10
9
  from pathlib import Path
11
- from typing import TYPE_CHECKING
12
10
 
13
- if TYPE_CHECKING:
14
- from taipanstack.config.models import StackConfig
11
+ from taipanstack.config.models import StackConfig
15
12
 
16
13
 
17
14
  def _generate_ruff_config(target_version: str) -> str:
@@ -167,48 +164,48 @@ def generate_pre_commit_config(config: StackConfig) -> str:
167
164
  Pre-commit configuration YAML string.
168
165
 
169
166
  """
170
- security_hooks = ""
167
+ security_hooks: list[str] = []
171
168
 
172
169
  if config.security.enable_bandit:
173
170
  severity = config.security.bandit_severity[0].upper()
174
- security_hooks += f"""
171
+ security_hooks.append(f"""
175
172
  - repo: https://github.com/PyCQA/bandit
176
173
  rev: '1.8.0'
177
174
  hooks:
178
175
  - id: bandit
179
176
  args: ["-r", ".", "-l{severity}"]
180
- """
177
+ """)
181
178
 
182
179
  if config.security.enable_safety:
183
- security_hooks += """
180
+ security_hooks.append("""
184
181
  - repo: https://github.com/pyupio/safety
185
182
  rev: '3.2.11'
186
183
  hooks:
187
184
  - id: safety
188
185
  args: ["check", "--json"]
189
- """
186
+ """)
190
187
 
191
188
  if config.security.enable_semgrep:
192
- security_hooks += """
189
+ security_hooks.append("""
193
190
  - repo: https://github.com/semgrep/pre-commit
194
191
  rev: 'v1.99.0'
195
192
  hooks:
196
193
  - id: semgrep
197
194
  args: ['--config=auto']
198
- """
195
+ """)
199
196
 
200
197
  if config.security.enable_detect_secrets:
201
- security_hooks += """
198
+ security_hooks.append("""
202
199
  - repo: https://github.com/Yelp/detect-secrets
203
200
  rev: 'v1.5.0'
204
201
  hooks:
205
202
  - id: detect-secrets
206
203
  args: ['--baseline', '.secrets.baseline']
207
- """
204
+ """)
208
205
 
209
206
  # Add pip-audit for paranoid mode
210
207
  if config.security.level == "paranoid":
211
- security_hooks += """
208
+ security_hooks.append("""
212
209
  - repo: https://github.com/trailofbits/pip-audit
213
210
  rev: 'v2.7.3'
214
211
  hooks:
@@ -223,7 +220,7 @@ def generate_pre_commit_config(config: StackConfig) -> str:
223
220
  rev: 'v2.3.3'
224
221
  hooks:
225
222
  - id: tryceratops
226
- """
223
+ """)
227
224
 
228
225
  return f"""# Stack v2.0 Pre-commit Configuration
229
226
  # Security Level: {config.security.level}
@@ -251,7 +248,7 @@ repos:
251
248
  hooks:
252
249
  - id: mypy
253
250
  additional_dependencies: [types-all, pydantic]
254
- {security_hooks}"""
251
+ {"".join(security_hooks)}"""
255
252
 
256
253
 
257
254
  def generate_dependabot_config() -> str:
@@ -4,18 +4,6 @@ Provides core functionality including Result types, version compatibility,
4
4
  and optimization utilities.
5
5
  """
6
6
 
7
- from taipanstack.core.compat import (
8
- PY311,
9
- PY312,
10
- PY313,
11
- PY314,
12
- PY_VERSION,
13
- PythonFeatures,
14
- VersionTier,
15
- get_features,
16
- get_python_info,
17
- is_experimental_enabled,
18
- )
19
7
  from taipanstack.core.optimizations import (
20
8
  OptimizationProfile,
21
9
  OptimizationResult,
@@ -26,22 +14,12 @@ from taipanstack.core.optimizations import (
26
14
  from taipanstack.core.result import Err, Ok, Result
27
15
 
28
16
  __all__ = [
29
- "PY311",
30
- "PY312",
31
- "PY313",
32
- "PY314",
33
- "PY_VERSION",
34
17
  "Err",
35
18
  "Ok",
36
19
  "OptimizationProfile",
37
20
  "OptimizationResult",
38
- "PythonFeatures",
39
21
  "Result",
40
- "VersionTier",
41
22
  "apply_optimizations",
42
- "get_features",
43
23
  "get_optimization_profile",
44
- "get_python_info",
45
24
  "get_recommended_thread_pool_size",
46
- "is_experimental_enabled",
47
25
  ]
@@ -7,7 +7,6 @@ versions, enabling performance improvements while maintaining stability.
7
7
  Following Stack pillars: Security, Stability, Simplicity, Scalability, Compatibility.
8
8
  """
9
9
 
10
- from __future__ import annotations
11
10
 
12
11
  import gc
13
12
  import logging
@@ -22,11 +22,11 @@ Example:
22
22
 
23
23
  """
24
24
 
25
- from __future__ import annotations
26
25
 
27
26
  import functools
28
- from collections.abc import Callable, Iterable
29
- from typing import ParamSpec, TypeVar, overload
27
+ import inspect
28
+ from collections.abc import Callable, Coroutine, Iterable
29
+ from typing import Any, ParamSpec, TypeVar, overload
30
30
 
31
31
  from result import Err, Ok, Result
32
32
 
@@ -47,19 +47,36 @@ E = TypeVar("E", bound=Exception)
47
47
  U = TypeVar("U")
48
48
 
49
49
 
50
+ @overload
50
51
  def safe(
51
52
  func: Callable[P, T],
52
- ) -> Callable[P, Result[T, Exception]]:
53
- """Decorator to convert exceptions into Err results.
53
+ ) -> Callable[P, Result[T, Exception]]: ... # pragma: no cover
54
+
54
55
 
55
- Wraps a function so that any exception raised becomes an Err,
56
- while successful returns become Ok.
56
+ @overload
57
+ def safe(
58
+ func: Callable[P, Coroutine[Any, Any, T]],
59
+ ) -> Callable[P, Coroutine[Any, Any, Result[T, Exception]]]: ... # pragma: no cover
60
+
61
+
62
+ def safe(
63
+ func: Callable[P, T] | Callable[P, Coroutine[Any, Any, T]],
64
+ ) -> (
65
+ Callable[P, Result[T, Exception]]
66
+ | Callable[P, Coroutine[Any, Any, Result[T, Exception]]]
67
+ ):
68
+ """Wrap a sync or async function to convert exceptions into Err results.
69
+
70
+ Detect whether *func* is a coroutine function and choose the
71
+ appropriate wrapper so that ``await``-able functions remain
72
+ ``await``-able and synchronous functions stay synchronous.
57
73
 
58
74
  Args:
59
- func: The function to wrap.
75
+ func: The sync or async function to wrap.
60
76
 
61
77
  Returns:
62
- A wrapped function that returns Result[T, Exception].
78
+ A wrapped function that returns ``Result[T, Exception]``
79
+ (or a coroutine resolving to one).
63
80
 
64
81
  Example:
65
82
  >>> @safe
@@ -71,11 +88,24 @@ def safe(
71
88
  Err(ValueError("invalid literal for int()..."))
72
89
 
73
90
  """
91
+ if inspect.iscoroutinefunction(func):
92
+
93
+ @functools.wraps(func)
94
+ async def async_wrapper(
95
+ *args: P.args,
96
+ **kwargs: P.kwargs,
97
+ ) -> Result[T, Exception]:
98
+ try:
99
+ return Ok(await func(*args, **kwargs))
100
+ except Exception as e:
101
+ return Err(e)
102
+
103
+ return async_wrapper
74
104
 
75
105
  @functools.wraps(func)
76
106
  def wrapper(*args: P.args, **kwargs: P.kwargs) -> Result[T, Exception]:
77
107
  try:
78
- return Ok(func(*args, **kwargs))
108
+ return Ok(func(*args, **kwargs)) # type: ignore[arg-type]
79
109
  except Exception as e:
80
110
  return Err(e)
81
111
 
@@ -14,7 +14,9 @@ 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
  )
19
+ from taipanstack.security.password import hash_password, verify_password
18
20
  from taipanstack.security.sanitizers import (
19
21
  sanitize_filename,
20
22
  sanitize_path,
@@ -38,7 +40,10 @@ __all__ = [
38
40
  "guard_exceptions",
39
41
  "guard_file_extension",
40
42
  "guard_path_traversal",
43
+ "guard_ssrf",
44
+ "hash_password",
41
45
  "require_type",
46
+ "verify_password",
42
47
  # Sanitizers
43
48
  "sanitize_filename",
44
49
  "sanitize_path",
@@ -6,7 +6,6 @@ timeout control, and other security patterns. Compatible with
6
6
  any Python framework (Flask, FastAPI, Django, etc.).
7
7
  """
8
8
 
9
- from __future__ import annotations
10
9
 
11
10
  import functools
12
11
  import signal
@@ -6,12 +6,16 @@ and programming errors that can occur from incorrect AI-generated code.
6
6
  All guards raise SecurityError on violation.
7
7
  """
8
8
 
9
- from __future__ import annotations
10
9
 
10
+ import ipaddress
11
11
  import os
12
12
  import re
13
+ import socket
13
14
  from collections.abc import Sequence
14
15
  from pathlib import Path
16
+ from urllib.parse import urlparse
17
+
18
+ from result import Err, Ok, Result
15
19
 
16
20
  _TRAVERSAL_PATTERNS: frozenset[str] = frozenset(
17
21
  [
@@ -224,7 +228,7 @@ def guard_command_injection(
224
228
 
225
229
  cmd_list = list(command)
226
230
 
227
- # Validate all items are strings
231
+ # Validate all items are strings and check for dangerous patterns
228
232
  for i, arg in enumerate(cmd_list):
229
233
  if not isinstance(arg, str):
230
234
  raise TypeError(
@@ -232,7 +236,6 @@ def guard_command_injection(
232
236
  f"got {type(arg).__name__} at index {i}"
233
237
  )
234
238
 
235
- for arg in cmd_list:
236
239
  for pattern, description in _DANGEROUS_COMMAND_PATTERNS:
237
240
  if pattern in arg:
238
241
  raise SecurityError(
@@ -384,3 +387,138 @@ def guard_env_variable(
384
387
  )
385
388
 
386
389
  return value
390
+
391
+
392
+ # ── SSRF Private-Range Constants ─────────────────────────────────────────────
393
+ _PRIVATE_NETWORKS: tuple[ipaddress.IPv4Network | ipaddress.IPv6Network, ...] = (
394
+ ipaddress.ip_network("10.0.0.0/8"),
395
+ ipaddress.ip_network("172.16.0.0/12"),
396
+ ipaddress.ip_network("192.168.0.0/16"),
397
+ ipaddress.ip_network("169.254.0.0/16"), # Link-local / AWS metadata
398
+ ipaddress.ip_network("127.0.0.0/8"), # Loopback
399
+ ipaddress.ip_network("::1/128"), # IPv6 loopback
400
+ ipaddress.ip_network("fc00::/7"), # IPv6 unique local
401
+ ipaddress.ip_network("fe80::/10"), # IPv6 link-local
402
+ )
403
+
404
+ _ALLOWED_SSRF_SCHEMES: frozenset[str] = frozenset({"http", "https"})
405
+
406
+
407
+ def guard_ssrf( # noqa: PLR0911
408
+ url: str,
409
+ *,
410
+ allowed_schemes: frozenset[str] = _ALLOWED_SSRF_SCHEMES,
411
+ ) -> Result[str, SecurityError]:
412
+ """Validate a URL against Server-Side Request Forgery (SSRF) attacks.
413
+
414
+ Parse the URL, resolve its hostname via DNS, and reject it when the
415
+ resulting IP address falls inside a private, loopback, link-local, or
416
+ otherwise reserved network range.
417
+
418
+ Args:
419
+ url: The URL string to validate.
420
+ allowed_schemes: Set of URL schemes considered safe.
421
+ Defaults to ``{"http", "https"}``.
422
+
423
+ Returns:
424
+ ``Ok(url)`` when the URL is safe to fetch.
425
+ ``Err(SecurityError)`` when an SSRF risk is detected.
426
+
427
+ Raises:
428
+ TypeError: If *url* is not a :class:`str`.
429
+
430
+ Example:
431
+ >>> guard_ssrf("https://example.com")
432
+ Ok('https://example.com')
433
+ >>> guard_ssrf("http://169.254.169.254/metadata")
434
+ Err(SecurityError('[ssrf] ...))
435
+
436
+ """
437
+ if not isinstance(url, str):
438
+ raise TypeError(f"URL must be str, got {type(url).__name__}")
439
+
440
+ if not url:
441
+ return Err(
442
+ SecurityError(
443
+ "URL cannot be empty",
444
+ guard_name="ssrf",
445
+ )
446
+ )
447
+
448
+ try:
449
+ parsed = urlparse(url)
450
+ except ValueError as exc: # pragma: no cover — urlparse rarely raises
451
+ return Err(
452
+ SecurityError(
453
+ f"Malformed URL: {exc}",
454
+ guard_name="ssrf",
455
+ value=url[:80],
456
+ )
457
+ )
458
+
459
+ if not parsed.scheme or parsed.scheme.lower() not in allowed_schemes:
460
+ return Err(
461
+ SecurityError(
462
+ f"URL scheme '{parsed.scheme}' is not allowed",
463
+ guard_name="ssrf",
464
+ value=url[:80],
465
+ )
466
+ )
467
+
468
+ hostname = parsed.hostname
469
+ if not hostname:
470
+ return Err(
471
+ SecurityError(
472
+ "URL has no resolvable hostname",
473
+ guard_name="ssrf",
474
+ value=url[:80],
475
+ )
476
+ )
477
+
478
+ # Resolve hostname → list of IP addresses via DNS
479
+ try:
480
+ addr_infos = socket.getaddrinfo(hostname, None)
481
+ except socket.gaierror as exc:
482
+ return Err(
483
+ SecurityError(
484
+ f"Hostname could not be resolved: {exc}",
485
+ guard_name="ssrf",
486
+ value=hostname[:80],
487
+ )
488
+ )
489
+
490
+ for addr_info in addr_infos:
491
+ raw_ip = addr_info[4][0]
492
+ try:
493
+ addr = ipaddress.ip_address(raw_ip)
494
+ except ValueError:
495
+ continue
496
+
497
+ for network in _PRIVATE_NETWORKS:
498
+ if addr in network:
499
+ return Err(
500
+ SecurityError(
501
+ f"SSRF detected: hostname '{hostname}' resolves to "
502
+ f"private/reserved address {addr}",
503
+ guard_name="ssrf",
504
+ value=str(addr),
505
+ )
506
+ )
507
+
508
+ # Catch-all for remaining special addresses not in the explicit list
509
+ if (
510
+ addr.is_private
511
+ or addr.is_loopback
512
+ or addr.is_link_local
513
+ or addr.is_reserved
514
+ ):
515
+ return Err(
516
+ SecurityError(
517
+ f"SSRF detected: '{hostname}' resolves to a reserved "
518
+ f"address {addr}",
519
+ guard_name="ssrf",
520
+ value=str(addr),
521
+ )
522
+ )
523
+
524
+ return Ok(url)
@@ -0,0 +1,87 @@
1
+ """
2
+ Password hashing and verification utilities.
3
+
4
+ This module provides functions for secure password management using
5
+ PBKDF2-HMAC-SHA256.
6
+ """
7
+
8
+ import hashlib
9
+ import secrets
10
+
11
+ from pydantic import SecretStr
12
+
13
+ # Constants for PBKDF2
14
+ ITERATIONS = 600_000
15
+ SALT_SIZE = 16
16
+ HASH_ALGORITHM = "sha256"
17
+ FORMAT = "pbkdf2_sha256"
18
+
19
+
20
+ def hash_password(password: str | SecretStr) -> str:
21
+ """
22
+ Hash a password using PBKDF2-HMAC-SHA256.
23
+
24
+ Args:
25
+ password: The plaintext password to hash.
26
+
27
+ Returns:
28
+ The hashed password in the format:
29
+ pbkdf2_sha256$<iterations>$<salt_hex>$<hash_hex>
30
+
31
+ """
32
+ if isinstance(password, SecretStr):
33
+ password_str = password.get_secret_value()
34
+ else:
35
+ password_str = password
36
+
37
+ salt = secrets.token_bytes(SALT_SIZE)
38
+ hash_bytes = hashlib.pbkdf2_hmac(
39
+ HASH_ALGORITHM,
40
+ password_str.encode("utf-8"),
41
+ salt,
42
+ ITERATIONS,
43
+ )
44
+
45
+ return f"{FORMAT}${ITERATIONS}${salt.hex()}${hash_bytes.hex()}"
46
+
47
+
48
+ def verify_password(password: str | SecretStr, password_hash: str) -> bool:
49
+ """
50
+ Verify a password against a PBKDF2-HMAC-SHA256 hash.
51
+
52
+ Args:
53
+ password: The plaintext password to verify.
54
+ password_hash: The stored password hash.
55
+
56
+ Returns:
57
+ True if the password matches the hash, False otherwise.
58
+
59
+ """
60
+ if isinstance(password, SecretStr):
61
+ password_str = password.get_secret_value()
62
+ else:
63
+ password_str = password
64
+
65
+ try:
66
+ parts = password_hash.split("$")
67
+ if len(parts) != 4:
68
+ return False
69
+
70
+ algorithm, iterations_str, salt_hex, hash_hex = parts
71
+ if algorithm != FORMAT:
72
+ return False
73
+
74
+ iterations = int(iterations_str)
75
+ salt = bytes.fromhex(salt_hex)
76
+ stored_hash = bytes.fromhex(hash_hex)
77
+
78
+ new_hash = hashlib.pbkdf2_hmac(
79
+ HASH_ALGORITHM,
80
+ password_str.encode("utf-8"),
81
+ salt,
82
+ iterations,
83
+ )
84
+
85
+ return secrets.compare_digest(new_hash, stored_hash)
86
+ except (ValueError, TypeError):
87
+ return False
@@ -5,7 +5,6 @@ Provides functions to sanitize strings, filenames, and paths
5
5
  to remove potentially dangerous characters.
6
6
  """
7
7
 
8
- from __future__ import annotations
9
8
 
10
9
  import re
11
10
  import unicodedata
@@ -5,7 +5,6 @@ Provides validation functions for common input types like email,
5
5
  project names, URLs, etc. All validators raise ValueError on invalid input.
6
6
  """
7
7
 
8
- from __future__ import annotations
9
8
 
10
9
  import re
11
10
  from ipaddress import IPv4Address, IPv6Address, ip_address
@@ -20,39 +19,61 @@ MAX_EMAIL_DOMAIN_LENGTH = 255
20
19
  MAX_PORT_NUMBER = 65535
21
20
  MIN_PRIVILEGED_PORT = 1024
22
21
  LOCALHOST_DOMAINS = ("localhost", "127.0.0.1", "::1")
22
+ PROJECT_NAME_RESERVED = frozenset(
23
+ {
24
+ "test",
25
+ "tests",
26
+ "src",
27
+ "lib",
28
+ "bin",
29
+ "build",
30
+ "dist",
31
+ "setup",
32
+ "config",
33
+ "settings",
34
+ "core",
35
+ "main",
36
+ "app",
37
+ "site-packages",
38
+ }
39
+ )
23
40
 
24
41
 
25
- def validate_project_name(
26
- name: str,
27
- *,
28
- max_length: int = 100,
29
- allow_hyphen: bool = True,
30
- allow_underscore: bool = True,
31
- ) -> str:
32
- """Validate a project name.
42
+ def _validate_type(
43
+ value: object, expected_type: type | tuple[type, ...], name: str
44
+ ) -> None:
45
+ """Validate input type.
33
46
 
34
47
  Args:
35
- name: The project name to validate.
36
- max_length: Maximum allowed length.
37
- allow_hyphen: Allow hyphens in name.
38
- allow_underscore: Allow underscores in name.
39
-
40
- Returns:
41
- The validated project name.
48
+ value: The value to check.
49
+ expected_type: The expected type(s).
50
+ name: Name of the variable for the error message.
42
51
 
43
52
  Raises:
44
- ValueError: If the name is invalid.
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
53
+ TypeError: If value is not of the expected type.
51
54
 
52
55
  """
53
- if not isinstance(name, str):
54
- raise TypeError(f"Project name must be str, got {type(name).__name__}")
56
+ if not isinstance(value, expected_type):
57
+ type_name = (
58
+ expected_type.__name__
59
+ if isinstance(expected_type, type)
60
+ else " | ".join(t.__name__ for t in expected_type)
61
+ )
62
+ msg = f"{name} must be {type_name}, got {type(value).__name__}"
63
+ raise TypeError(msg)
55
64
 
65
+
66
+ def _check_project_name_length(name: str, max_length: int) -> None:
67
+ """Check project name length.
68
+
69
+ Args:
70
+ name: The project name.
71
+ max_length: Maximum allowed length.
72
+
73
+ Raises:
74
+ ValueError: If length is invalid.
75
+
76
+ """
56
77
  if not name:
57
78
  msg = "Project name cannot be empty"
58
79
  raise ValueError(msg)
@@ -61,6 +82,21 @@ def validate_project_name(
61
82
  msg = f"Project name exceeds maximum length of {max_length}"
62
83
  raise ValueError(msg)
63
84
 
85
+
86
+ def _check_project_name_chars(
87
+ name: str, allow_hyphen: bool, allow_underscore: bool
88
+ ) -> None:
89
+ """Check project name characters.
90
+
91
+ Args:
92
+ name: The project name.
93
+ allow_hyphen: Whether to allow hyphens.
94
+ allow_underscore: Whether to allow underscores.
95
+
96
+ Raises:
97
+ ValueError: If name contains invalid characters.
98
+
99
+ """
64
100
  # Build allowed characters
65
101
  allowed = r"a-zA-Z0-9"
66
102
  if allow_hyphen:
@@ -82,28 +118,55 @@ def validate_project_name(
82
118
  )
83
119
  raise ValueError(msg)
84
120
 
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
121
 
103
- if name.lower() in reserved:
122
+ def _check_project_name_reserved(name: str) -> None:
123
+ """Check if project name is reserved.
124
+
125
+ Args:
126
+ name: The project name.
127
+
128
+ Raises:
129
+ ValueError: If name is reserved.
130
+
131
+ """
132
+ if name.lower() in PROJECT_NAME_RESERVED:
104
133
  msg = f"Project name '{name}' is reserved"
105
134
  raise ValueError(msg)
106
135
 
136
+
137
+ def validate_project_name(
138
+ name: str,
139
+ *,
140
+ max_length: int = 100,
141
+ allow_hyphen: bool = True,
142
+ allow_underscore: bool = True,
143
+ ) -> str:
144
+ """Validate a project name.
145
+
146
+ Args:
147
+ name: The project name to validate.
148
+ max_length: Maximum allowed length.
149
+ allow_hyphen: Allow hyphens in name.
150
+ allow_underscore: Allow underscores in name.
151
+
152
+ Returns:
153
+ The validated project name.
154
+
155
+ Raises:
156
+ ValueError: If the name is invalid.
157
+
158
+ Example:
159
+ >>> validate_project_name("my_project")
160
+ 'my_project'
161
+ >>> validate_project_name("123project")
162
+ ValueError: Project name must start with a letter
163
+
164
+ """
165
+ _validate_type(name, str, "Project name")
166
+ _check_project_name_length(name, max_length)
167
+ _check_project_name_chars(name, allow_hyphen, allow_underscore)
168
+ _check_project_name_reserved(name)
169
+
107
170
  return name
108
171
 
109
172
 
@@ -120,8 +183,7 @@ def validate_python_version(version: str) -> str:
120
183
  ValueError: If version format is invalid or unsupported.
121
184
 
122
185
  """
123
- if not isinstance(version, str):
124
- raise TypeError(f"Version must be str, got {type(version).__name__}")
186
+ _validate_type(version, str, "Version")
125
187
 
126
188
  pattern = r"^\d+\.\d+$"
127
189
 
@@ -165,8 +227,7 @@ def validate_email(email: str) -> str:
165
227
  ValueError: If email format is invalid.
166
228
 
167
229
  """
168
- if not isinstance(email, str):
169
- raise TypeError(f"Email must be str, got {type(email).__name__}")
230
+ _validate_type(email, str, "Email")
170
231
 
171
232
  if not email:
172
233
  msg = "Email cannot be empty"
@@ -213,8 +274,7 @@ def validate_url(
213
274
  ValueError: If URL format is invalid.
214
275
 
215
276
  """
216
- if not isinstance(url, str):
217
- raise TypeError(f"URL must be str, got {type(url).__name__}")
277
+ _validate_type(url, str, "URL")
218
278
 
219
279
  if not url:
220
280
  msg = "URL cannot be empty"
@@ -222,6 +282,7 @@ def validate_url(
222
282
 
223
283
  try:
224
284
  parsed = urlparse(url)
285
+ _ = parsed.port
225
286
  except ValueError as e:
226
287
  msg = f"Invalid URL format: {e}"
227
288
  raise ValueError(msg) from e
@@ -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
 
@@ -0,0 +1,20 @@
1
+ """Utility modules for Stack."""
2
+
3
+ from .filesystem import ensure_dir, safe_read, safe_write
4
+ from .logging import get_logger, setup_logging
5
+ from .retry import Retrier, RetryConfig, RetryError, retry
6
+ from .subprocess import SafeCommandResult, run_safe_command
7
+
8
+ __all__ = (
9
+ "Retrier",
10
+ "RetryConfig",
11
+ "RetryError",
12
+ "SafeCommandResult",
13
+ "ensure_dir",
14
+ "get_logger",
15
+ "retry",
16
+ "run_safe_command",
17
+ "safe_read",
18
+ "safe_write",
19
+ "setup_logging",
20
+ )
@@ -6,7 +6,6 @@ blocking calls to a failing service. Compatible with any
6
6
  Python framework.
7
7
  """
8
8
 
9
- from __future__ import annotations
10
9
 
11
10
  import functools
12
11
  import logging
@@ -22,6 +21,15 @@ R = TypeVar("R")
22
21
 
23
22
  logger = logging.getLogger("taipanstack.utils.circuit_breaker")
24
23
 
24
+ try:
25
+ import structlog as _structlog
26
+
27
+ _structlog_logger = _structlog.get_logger("taipanstack.utils.circuit_breaker")
28
+ _HAS_STRUCTLOG = True
29
+ except ImportError: # pragma: no cover — structlog is optional
30
+ _structlog_logger = None
31
+ _HAS_STRUCTLOG = False
32
+
25
33
 
26
34
  class CircuitState(Enum):
27
35
  """States of the circuit breaker."""
@@ -142,9 +150,21 @@ class CircuitBreaker:
142
150
  old_state: CircuitState,
143
151
  new_state: CircuitState,
144
152
  ) -> None:
145
- """Notify callback of state transition if registered."""
153
+ """Notify callback of state transition if registered.
154
+
155
+ Emit a structured log via structlog when no callback is provided
156
+ and structlog is available.
157
+ """
146
158
  if self._on_state_change is not None:
147
159
  self._on_state_change(old_state, new_state)
160
+ elif _HAS_STRUCTLOG and _structlog_logger is not None: # pragma: no branch
161
+ _structlog_logger.warning(
162
+ "circuit_state_changed",
163
+ circuit=self.name,
164
+ old_state=old_state.value,
165
+ new_state=new_state.value,
166
+ failure_count=self._state.failure_count,
167
+ )
148
168
 
149
169
  def _should_attempt(self) -> bool:
150
170
  """Check if a call should be attempted."""
@@ -5,7 +5,6 @@ Provides a configured logger with support for structured output,
5
5
  context propagation, and proper formatting.
6
6
  """
7
7
 
8
- from __future__ import annotations
9
8
 
10
9
  import logging
11
10
  import sys
@@ -68,7 +67,7 @@ class StackLogger:
68
67
  self._logger.setLevel(getattr(logging, level.upper()))
69
68
  self._structured = False
70
69
 
71
- def bind(self, **context: Any) -> StackLogger:
70
+ def bind(self, **context: Any) -> "StackLogger":
72
71
  """Add context to logger.
73
72
 
74
73
  Args:
@@ -83,7 +82,7 @@ class StackLogger:
83
82
  self._logger = self._logger.bind(**context)
84
83
  return self
85
84
 
86
- def unbind(self, *keys: str) -> StackLogger:
85
+ def unbind(self, *keys: str) -> "StackLogger":
87
86
  """Remove context keys.
88
87
 
89
88
  Args:
@@ -6,7 +6,6 @@ application performance and health. Compatible with any
6
6
  Python framework.
7
7
  """
8
8
 
9
- from __future__ import annotations
10
9
 
11
10
  import functools
12
11
  import logging
@@ -84,11 +83,11 @@ class MetricsCollector:
84
83
 
85
84
  """
86
85
 
87
- _instance: MetricsCollector | None = None
86
+ _instance: "MetricsCollector | None" = None
88
87
  _lock = threading.Lock()
89
88
  _initialized: bool
90
89
 
91
- def __new__(cls) -> MetricsCollector:
90
+ def __new__(cls) -> "MetricsCollector":
92
91
  """Singleton pattern for global metrics access."""
93
92
  if cls._instance is None:
94
93
  with cls._lock:
@@ -130,7 +129,7 @@ class MetricsCollector:
130
129
  """Record a timing measurement."""
131
130
  self._timers[name].record(duration)
132
131
 
133
- def timer(self, name: str) -> Timer:
132
+ def timer(self, name: str) -> "Timer":
134
133
  """Create a context manager timer."""
135
134
  return Timer(name, self)
136
135
 
@@ -183,7 +182,7 @@ class Timer:
183
182
  self.collector = collector
184
183
  self.start_time: float = 0.0
185
184
 
186
- def __enter__(self) -> Timer:
185
+ def __enter__(self) -> "Timer":
187
186
  """Start the timer."""
188
187
  self.start_time = time.perf_counter()
189
188
  return self
@@ -6,11 +6,10 @@ with configurable backoff strategies. Compatible with any
6
6
  Python framework (sync and async).
7
7
  """
8
8
 
9
- from __future__ import annotations
10
9
 
11
10
  import functools
12
11
  import logging
13
- import random
12
+ import secrets
14
13
  import time
15
14
  from collections.abc import Callable
16
15
  from dataclasses import dataclass
@@ -22,6 +21,15 @@ R = TypeVar("R")
22
21
 
23
22
  logger = logging.getLogger("taipanstack.utils.retry")
24
23
 
24
+ try:
25
+ import structlog as _structlog
26
+
27
+ _structlog_logger = _structlog.get_logger("taipanstack.utils.retry")
28
+ _HAS_STRUCTLOG = True
29
+ except ImportError: # pragma: no cover — structlog is optional
30
+ _structlog_logger = None
31
+ _HAS_STRUCTLOG = False
32
+
25
33
 
26
34
  @dataclass(frozen=True)
27
35
  class RetryConfig:
@@ -89,10 +97,12 @@ def calculate_delay(
89
97
 
90
98
  # Add jitter if enabled
91
99
  # Note: Using random for jitter is intentionally non-cryptographic.
92
- # Jitter is for load distribution, not security. Using secrets would be overkill.
100
+ # However, to maintain a clean security baseline and satisfy Bandit,
101
+ # we use secrets.SystemRandom() which provides cryptographically
102
+ # secure random numbers.
93
103
  if config.jitter:
94
104
  jitter_amount = delay * config.jitter_factor
95
- delay += random.uniform(-jitter_amount, jitter_amount)
105
+ delay += secrets.SystemRandom().uniform(-jitter_amount, jitter_amount)
96
106
 
97
107
  return max(0, delay)
98
108
 
@@ -184,9 +194,20 @@ def retry(
184
194
  delay,
185
195
  )
186
196
 
187
- # Invoke callback if provided
197
+ # Invoke callback or emit structured log if no callback set
188
198
  if on_retry is not None:
189
199
  on_retry(attempt, max_attempts, e, delay)
200
+ elif (
201
+ _HAS_STRUCTLOG and _structlog_logger is not None
202
+ ): # pragma: no branch
203
+ _structlog_logger.warning(
204
+ "retry_attempted",
205
+ function=func.__name__,
206
+ attempt=attempt,
207
+ max_attempts=max_attempts,
208
+ error=str(e),
209
+ delay_seconds=round(delay, 3),
210
+ )
190
211
 
191
212
  time.sleep(delay)
192
213
 
@@ -279,7 +300,7 @@ class Retrier:
279
300
  self.attempt = 0
280
301
  self.last_exception: Exception | None = None
281
302
 
282
- def __enter__(self) -> Retrier:
303
+ def __enter__(self) -> "Retrier":
283
304
  """Enter the retry context."""
284
305
  self.attempt = 0
285
306
  self.last_exception = None
@@ -5,7 +5,6 @@ Provides secure wrappers around subprocess execution with
5
5
  command validation, timeout handling, and retry logic.
6
6
  """
7
7
 
8
- from __future__ import annotations
9
8
 
10
9
  import shutil
11
10
  import subprocess
@@ -42,7 +41,7 @@ class SafeCommandResult:
42
41
  """Check if command succeeded."""
43
42
  return self.returncode == 0
44
43
 
45
- def raise_on_error(self) -> SafeCommandResult:
44
+ def raise_on_error(self) -> "SafeCommandResult":
46
45
  """Raise an exception if command failed.
47
46
 
48
47
  Returns:
@@ -1,24 +0,0 @@
1
- """Utility modules for Stack."""
2
-
3
- from taipanstack.utils.filesystem import ensure_dir, safe_read, safe_write
4
- from taipanstack.utils.logging import get_logger, setup_logging
5
- from taipanstack.utils.retry import Retrier, RetryConfig, RetryError, retry
6
- from taipanstack.utils.subprocess import SafeCommandResult, run_safe_command
7
-
8
- __all__ = [
9
- # Retry
10
- "Retrier",
11
- "RetryConfig",
12
- "RetryError",
13
- # Subprocess
14
- "SafeCommandResult",
15
- # Filesystem
16
- "ensure_dir",
17
- # Logging
18
- "get_logger",
19
- "retry",
20
- "run_safe_command",
21
- "safe_read",
22
- "safe_write",
23
- "setup_logging",
24
- ]
File without changes
File without changes