taipanstack 0.4.1__tar.gz → 0.4.2__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 (54) hide show
  1. {taipanstack-0.4.1 → taipanstack-0.4.2}/PKG-INFO +4 -4
  2. {taipanstack-0.4.1 → taipanstack-0.4.2}/README.md +3 -3
  3. {taipanstack-0.4.1 → taipanstack-0.4.2}/pyproject.toml +1 -2
  4. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/__init__.py +1 -1
  5. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/bridges/http_bridge.py +5 -1
  6. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/resilience/circuit_breaker.py +17 -1
  7. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/security/password.py +15 -0
  8. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/security/sanitizers.py +51 -31
  9. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/utils/cache.py +3 -5
  10. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/utils/filesystem.py +32 -35
  11. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/utils/logging.py +4 -2
  12. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/utils/subprocess.py +23 -12
  13. {taipanstack-0.4.1 → taipanstack-0.4.2}/LICENSE +0 -0
  14. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/bridges/__init__.py +0 -0
  15. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/bridges/_imports.py +0 -0
  16. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/bridges/db_bridge.py +0 -0
  17. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/bridges/web_bridge.py +0 -0
  18. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/config/__init__.py +0 -0
  19. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/config/generators.py +0 -0
  20. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/config/models.py +0 -0
  21. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/config/version_config.py +0 -0
  22. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/core/__init__.py +0 -0
  23. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/core/compat.py +0 -0
  24. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/core/optimizations.py +0 -0
  25. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/core/result.py +0 -0
  26. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/resilience/__init__.py +0 -0
  27. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/resilience/adaptive/__init__.py +0 -0
  28. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/resilience/adaptive/adaptive_breaker.py +0 -0
  29. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/resilience/adaptive/adaptive_retry.py +0 -0
  30. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/resilience/adaptive/adaptive_timeout.py +0 -0
  31. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/resilience/adaptive/bulkhead.py +0 -0
  32. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/resilience/adaptive/orchestrator.py +0 -0
  33. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/resilience/resilience.py +0 -0
  34. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/resilience/retry.py +0 -0
  35. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/resilience/watchdogs/__init__.py +0 -0
  36. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/resilience/watchdogs/_base.py +0 -0
  37. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/resilience/watchdogs/config_watcher.py +0 -0
  38. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/resilience/watchdogs/health_pinger.py +0 -0
  39. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/resilience/watchdogs/resource_watcher.py +0 -0
  40. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/security/__init__.py +0 -0
  41. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/security/decorators.py +0 -0
  42. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/security/guards.py +0 -0
  43. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/security/jwt.py +0 -0
  44. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/security/models.py +0 -0
  45. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/security/types.py +0 -0
  46. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/security/validators.py +0 -0
  47. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/utils/__init__.py +0 -0
  48. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/utils/circuit_breaker.py +0 -0
  49. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/utils/concurrency.py +0 -0
  50. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/utils/context.py +0 -0
  51. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/utils/rate_limit.py +0 -0
  52. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/utils/resilience.py +0 -0
  53. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/utils/retry.py +0 -0
  54. {taipanstack-0.4.1 → taipanstack-0.4.2}/src/taipanstack/utils/serialization.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: taipanstack
3
- Version: 0.4.1
3
+ Version: 0.4.2
4
4
  Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -128,7 +128,7 @@ TaipanStack is a battle-tested foundation for production-grade Python projects t
128
128
 
129
129
  ### 🔧 Developer Experience
130
130
  - Pre-configured quality tools
131
- - **100% code coverage** (1184 tests)
131
+ - **100% code coverage** (1158 tests)
132
132
  - Architecture enforcement
133
133
  - Hardened Docker template
134
134
 
@@ -170,7 +170,7 @@ make all
170
170
  ### Verify Installation
171
171
 
172
172
  ```bash
173
- # Run tests with 100% coverage (1184 tests)
173
+ # Run tests with 100% coverage (1158 tests)
174
174
  make test
175
175
 
176
176
  # Check architecture contracts
@@ -225,7 +225,7 @@ TaipanStack/
225
225
  │ ├── config/ # ⚙️ Configuration models & generators
226
226
  │ ├── security/ # 🛡️ Guards, sanitizers, validators
227
227
  │ └── utils/ # 🔧 Logging, metrics, retry, filesystem
228
- ├── tests/ # ✅ 1184 tests, 100% coverage
228
+ ├── tests/ # ✅ 1158 tests, 100% coverage
229
229
  ├── .semgrep/ # 🔍 Custom SAST rules
230
230
  ├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
231
231
  ├── Dockerfile # 🐳 Hardened multi-stage container
@@ -72,7 +72,7 @@ TaipanStack is a battle-tested foundation for production-grade Python projects t
72
72
 
73
73
  ### 🔧 Developer Experience
74
74
  - Pre-configured quality tools
75
- - **100% code coverage** (1184 tests)
75
+ - **100% code coverage** (1158 tests)
76
76
  - Architecture enforcement
77
77
  - Hardened Docker template
78
78
 
@@ -114,7 +114,7 @@ make all
114
114
  ### Verify Installation
115
115
 
116
116
  ```bash
117
- # Run tests with 100% coverage (1184 tests)
117
+ # Run tests with 100% coverage (1158 tests)
118
118
  make test
119
119
 
120
120
  # Check architecture contracts
@@ -169,7 +169,7 @@ TaipanStack/
169
169
  │ ├── config/ # ⚙️ Configuration models & generators
170
170
  │ ├── security/ # 🛡️ Guards, sanitizers, validators
171
171
  │ └── utils/ # 🔧 Logging, metrics, retry, filesystem
172
- ├── tests/ # ✅ 1184 tests, 100% coverage
172
+ ├── tests/ # ✅ 1158 tests, 100% coverage
173
173
  ├── .semgrep/ # 🔍 Custom SAST rules
174
174
  ├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
175
175
  ├── Dockerfile # 🐳 Hardened multi-stage container
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "taipanstack"
3
- version = "0.4.1"
3
+ version = "0.4.2"
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"}
@@ -222,7 +222,6 @@ markers = [
222
222
  ]
223
223
  filterwarnings = [
224
224
 
225
- "ignore::ResourceWarning",
226
225
  "ignore::pytest.PytestUnraisableExceptionWarning",
227
226
  ]
228
227
 
@@ -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.4.1"
8
+ __version__ = "0.4.2"
9
9
 
10
10
  from taipanstack.config.version_config import (
11
11
  VersionRecommendations,
@@ -140,6 +140,7 @@ async def safe_request(
140
140
  retry_config: RetryConfig | None = None,
141
141
  circuit_breaker: CircuitBreaker | None = None,
142
142
  retryable_status_codes: frozenset[int] = _RETRYABLE_STATUS_CODES,
143
+ timeout: float | None = 10.0,
143
144
  **kwargs: Any,
144
145
  ) -> Result[Any, Exception]:
145
146
  """Perform a one-shot HTTP request with safety features.
@@ -151,6 +152,7 @@ async def safe_request(
151
152
  retry_config: Optional retry configuration.
152
153
  circuit_breaker: Optional circuit breaker.
153
154
  retryable_status_codes: Status codes that trigger retries.
155
+ timeout: Explicit timeout in seconds (default: 10.0).
154
156
  **kwargs: Passed to ``httpx.AsyncClient.request``.
155
157
 
156
158
  Returns:
@@ -177,7 +179,7 @@ async def safe_request(
177
179
  return Err(cb_err)
178
180
 
179
181
  async def _do_request() -> Any:
180
- async with httpx.AsyncClient() as client:
182
+ async with httpx.AsyncClient(timeout=timeout) as client:
181
183
  return await client.request(method, url, **kwargs)
182
184
 
183
185
  return await _execute_with_retries(
@@ -224,6 +226,7 @@ class SafeHttpClient:
224
226
  circuit_breaker: Circuit breaker instance.
225
227
  retryable_status_codes: Status codes to retry.
226
228
  **client_kwargs: Keyword args for httpx.AsyncClient.
229
+ Default timeout is 10.0 seconds if not provided.
227
230
 
228
231
  """
229
232
  self._ssrf_protection = ssrf_protection
@@ -231,6 +234,7 @@ class SafeHttpClient:
231
234
  self._circuit_breaker = circuit_breaker
232
235
  self._retryable_status_codes = retryable_status_codes
233
236
  self._client_kwargs = client_kwargs
237
+ self._client_kwargs.setdefault("timeout", 10.0)
234
238
  self._client: Any = None
235
239
 
236
240
  async def __aenter__(self) -> SafeHttpClient:
@@ -170,7 +170,23 @@ class CircuitBreaker:
170
170
  and structlog is available.
171
171
  """
172
172
  if self._on_state_change is not None:
173
- self._on_state_change(old_state, new_state)
173
+ try:
174
+ self._on_state_change(old_state, new_state)
175
+ except Exception as e:
176
+ if _HAS_STRUCTLOG and _structlog_logger is not None:
177
+ _structlog_logger.error(
178
+ "circuit_state_change_callback_failed",
179
+ circuit=self.name,
180
+ old_state=old_state.value,
181
+ new_state=new_state.value,
182
+ error=str(e),
183
+ )
184
+ else:
185
+ logger.error(
186
+ "Circuit %s state change callback failed: %s",
187
+ self.name,
188
+ str(e),
189
+ )
174
190
  elif _HAS_STRUCTLOG and _structlog_logger is not None: # pragma: no branch
175
191
  _structlog_logger.warning(
176
192
  "circuit_state_changed",
@@ -20,6 +20,7 @@ LEGACY_ITERATIONS = 600_000
20
20
  LEGACY_SALT_SIZE = 16
21
21
  LEGACY_HASH_ALGORITHM = "sha256"
22
22
  LEGACY_FORMAT = "pbkdf2_sha256"
23
+ MAX_LEGACY_ITERATIONS = 1_000_000
23
24
 
24
25
 
25
26
  def hash_password(password: str | SecretStr) -> str:
@@ -52,7 +53,18 @@ def verify_password(password: str | SecretStr, password_hash: str) -> bool:
52
53
  Returns:
53
54
  True if the password matches the hash, False otherwise.
54
55
 
56
+ Raises:
57
+ TypeError: If `password` or `password_hash` are not the correct types.
58
+
55
59
  """
60
+ if not isinstance(password, (str, SecretStr)):
61
+ msg = "password must be a string or SecretStr"
62
+ raise TypeError(msg)
63
+
64
+ if not isinstance(password_hash, str):
65
+ msg = "password_hash must be a string"
66
+ raise TypeError(msg)
67
+
56
68
  if isinstance(password, SecretStr):
57
69
  password_str = password.get_secret_value()
58
70
  else:
@@ -68,6 +80,9 @@ def verify_password(password: str | SecretStr, password_hash: str) -> bool:
68
80
  _algorithm, iterations_str, salt_hex, hash_hex = parts
69
81
 
70
82
  iterations = int(iterations_str)
83
+ if iterations > MAX_LEGACY_ITERATIONS:
84
+ return False
85
+
71
86
  salt = bytes.fromhex(salt_hex)
72
87
  stored_hash = bytes.fromhex(hash_hex)
73
88
 
@@ -326,6 +326,25 @@ def sanitize_path(
326
326
  return _apply_base_dir_constraint(sanitized, base_dir, resolve)
327
327
 
328
328
 
329
+ def _sanitize_env_multiline(value: str, max_length: int) -> str:
330
+ """Sanitize an environment value allowing multiline characters."""
331
+ if "\x00" not in value and len(value) <= max_length:
332
+ return value
333
+ return value.replace("\x00", "")
334
+
335
+
336
+ def _sanitize_env_singleline(value: str, max_length: int) -> str:
337
+ """Sanitize an environment value, converting multiline to spaces."""
338
+ if (
339
+ "\x00" not in value
340
+ and "\n" not in value
341
+ and "\r" not in value
342
+ and len(value) <= max_length
343
+ ):
344
+ return value
345
+ return value.replace("\x00", "").replace("\n", " ").replace("\r", " ")
346
+
347
+
329
348
  def sanitize_env_value(
330
349
  value: str,
331
350
  *,
@@ -353,24 +372,43 @@ def sanitize_env_value(
353
372
  return ""
354
373
 
355
374
  if allow_multiline:
356
- if "\x00" not in value and len(value) <= max_length:
357
- return value
358
- result = value.replace("\x00", "")
375
+ result = _sanitize_env_multiline(value, max_length)
359
376
  else:
360
- if (
361
- "\x00" not in value
362
- and "\n" not in value
363
- and "\r" not in value
364
- and len(value) <= max_length
365
- ):
366
- return value
367
- result = value.replace("\x00", "").replace("\n", " ").replace("\r", " ")
377
+ result = _sanitize_env_singleline(value, max_length)
368
378
 
369
379
  if len(result) > max_length:
370
380
  return result[:max_length]
371
381
  return result
372
382
 
373
383
 
384
+ def _is_valid_sql_identifier_fast_path(identifier: str) -> bool:
385
+ """Check if an identifier meets fast-path criteria."""
386
+ return (
387
+ identifier.isidentifier()
388
+ and identifier.isascii()
389
+ and len(identifier) <= MAX_SQL_IDENTIFIER_LENGTH
390
+ )
391
+
392
+
393
+ def _sanitize_sql_identifier_slow_path(identifier: str) -> str:
394
+ """Apply slow path sanitization for SQL identifiers."""
395
+ result = _SQL_IDENTIFIER_DENY_RE.sub("", identifier)
396
+
397
+ # Must start with letter or underscore
398
+ if result and not result[0].isalpha() and result[0] != "_":
399
+ result = f"_{result}"
400
+
401
+ # Check length (most DBs limit to 128 chars)
402
+ if len(result) > MAX_SQL_IDENTIFIER_LENGTH:
403
+ result = result[:MAX_SQL_IDENTIFIER_LENGTH]
404
+
405
+ if not result:
406
+ msg = "SQL identifier contains no valid characters"
407
+ raise ValueError(msg)
408
+
409
+ return result
410
+
411
+
374
412
  def sanitize_sql_identifier(identifier: str) -> str:
375
413
  """Sanitize a SQL identifier (table/column name).
376
414
 
@@ -395,25 +433,7 @@ def sanitize_sql_identifier(identifier: str) -> str:
395
433
  raise ValueError(msg)
396
434
 
397
435
  # Fast path: already clean and valid
398
- if (
399
- identifier.isidentifier()
400
- and identifier.isascii()
401
- and len(identifier) <= MAX_SQL_IDENTIFIER_LENGTH
402
- ):
436
+ if _is_valid_sql_identifier_fast_path(identifier):
403
437
  return identifier
404
438
 
405
- result = _SQL_IDENTIFIER_DENY_RE.sub("", identifier)
406
-
407
- # Must start with letter or underscore
408
- if result and not result[0].isalpha() and result[0] != "_":
409
- result = f"_{result}"
410
-
411
- # Check length (most DBs limit to 128 chars)
412
- if len(result) > MAX_SQL_IDENTIFIER_LENGTH:
413
- result = result[:MAX_SQL_IDENTIFIER_LENGTH]
414
-
415
- if not result:
416
- msg = "SQL identifier contains no valid characters"
417
- raise ValueError(msg)
418
-
419
- return result
439
+ return _sanitize_sql_identifier_slow_path(identifier)
@@ -56,11 +56,9 @@ def cached(ttl: float) -> CacheDecorator:
56
56
  return tuple(sorted((k, _make_hashable(v)) for k, v in val.items()))
57
57
  if isinstance(val, set):
58
58
  return frozenset(_make_hashable(item) for item in val)
59
- try:
60
- hash(val)
61
- return val
62
- except TypeError:
63
- return str(val)
59
+
60
+ hash(val)
61
+ return val
64
62
 
65
63
  hashable_args = tuple(_make_hashable(arg) for arg in args)
66
64
  hashable_kwargs = tuple(
@@ -5,12 +5,12 @@ Provides secure wrappers around file operations with path validation,
5
5
  atomic writes, and proper error handling using Result types.
6
6
  """
7
7
 
8
- import contextlib
9
8
  import functools
10
9
  import hashlib
11
10
  import os
12
11
  import shutil
13
12
  import tempfile
13
+ from collections.abc import Iterator
14
14
  from dataclasses import dataclass
15
15
  from pathlib import Path
16
16
  from typing import TypeAlias
@@ -30,13 +30,11 @@ class FileNotFoundErr:
30
30
  """Error when file is not found."""
31
31
 
32
32
  path: Path
33
- message: str = ""
34
33
 
35
- def __post_init__(self) -> None:
36
- """Set default message."""
37
- object.__setattr__(
38
- self, "message", self.message or f"File not found: {self.path}"
39
- )
34
+ @property
35
+ def message(self) -> str:
36
+ """Get the error message."""
37
+ return f"File not found: {self.path}"
40
38
 
41
39
 
42
40
  @dataclass(frozen=True)
@@ -44,11 +42,11 @@ class NotAFileErr:
44
42
  """Error when path is not a file."""
45
43
 
46
44
  path: Path
47
- message: str = ""
48
45
 
49
- def __post_init__(self) -> None:
50
- """Set default message."""
51
- object.__setattr__(self, "message", self.message or f"Not a file: {self.path}")
46
+ @property
47
+ def message(self) -> str:
48
+ """Get the error message."""
49
+ return f"Not a file: {self.path}"
52
50
 
53
51
 
54
52
  def _validate_path(
@@ -85,15 +83,11 @@ class FileTooLargeErr:
85
83
  path: Path
86
84
  size: int
87
85
  max_size: int
88
- message: str = ""
89
-
90
- def __post_init__(self) -> None:
91
- """Set default message."""
92
- object.__setattr__(
93
- self,
94
- "message",
95
- self.message or f"File too large: {self.size} bytes (max: {self.max_size})",
96
- )
86
+
87
+ @property
88
+ def message(self) -> str:
89
+ """Get the error message."""
90
+ return f"File too large: {self.size} bytes (max: {self.max_size})"
97
91
 
98
92
 
99
93
  @dataclass(frozen=True)
@@ -213,6 +207,13 @@ def safe_write(
213
207
 
214
208
  # Sanitize filename
215
209
  safe_name = sanitize_filename(path.name)
210
+ if safe_name != path.name:
211
+ raise SecurityError(
212
+ f"Unsafe or invalid characters in filename: '{path.name}'. "
213
+ f"Expected safe name: '{safe_name}'",
214
+ guard_name="sanitize_filename",
215
+ value=path.name,
216
+ )
216
217
  path = path.parent / safe_name
217
218
 
218
219
  # Create parents if needed
@@ -246,8 +247,7 @@ def safe_write(
246
247
  temp_file.rename(path)
247
248
  except Exception:
248
249
  # Clean up temp file on error
249
- with contextlib.suppress(OSError):
250
- Path(temp_path).unlink(missing_ok=True)
250
+ Path(temp_path).unlink(missing_ok=True)
251
251
  raise
252
252
  else:
253
253
  path.write_text(content, encoding=opts.encoding)
@@ -421,7 +421,7 @@ def find_files(
421
421
  base_dir: Path | str | None = None,
422
422
  recursive: bool = True,
423
423
  include_hidden: bool = False,
424
- ) -> list[Path]:
424
+ ) -> Iterator[Path]:
425
425
  """Find files matching a pattern.
426
426
 
427
427
  Args:
@@ -432,7 +432,7 @@ def find_files(
432
432
  include_hidden: Include hidden files (starting with .).
433
433
 
434
434
  Returns:
435
- List of matching file paths.
435
+ Iterator of matching file paths.
436
436
 
437
437
  """
438
438
  directory = Path(directory)
@@ -441,16 +441,13 @@ def find_files(
441
441
  directory = _validate_path(directory, base_dir)
442
442
 
443
443
  if not directory.exists():
444
- return []
445
-
446
- if recursive:
447
- files = list(directory.rglob(pattern))
448
- else:
449
- files = list(directory.glob(pattern))
444
+ return iter([])
450
445
 
451
- # Filter hidden files if needed
452
- if not include_hidden:
453
- files = [f for f in files if not any(p.startswith(".") for p in f.parts)]
446
+ iterator = directory.rglob(pattern) if recursive else directory.glob(pattern)
454
447
 
455
- # Only return files, not directories
456
- return [f for f in files if f.is_file()]
448
+ return (
449
+ f
450
+ for f in iterator
451
+ if f.is_file()
452
+ and (include_hidden or not any(p.startswith(".") for p in f.parts))
453
+ )
@@ -50,7 +50,7 @@ REDACTED_VALUE = "***REDACTED***"
50
50
 
51
51
 
52
52
  @lru_cache(maxsize=1024)
53
- def _is_sensitive(key: str, regex: re.Pattern[str] | None) -> bool:
53
+ def _is_sensitive(key: Any, regex: re.Pattern[str] | None) -> bool:
54
54
  """Check if a key is sensitive using cached regex matching.
55
55
 
56
56
  Args:
@@ -58,11 +58,13 @@ def _is_sensitive(key: str, regex: re.Pattern[str] | None) -> bool:
58
58
  regex: The regex pattern to use for matching.
59
59
 
60
60
  Returns:
61
- True if the key is sensitive, False otherwise.
61
+ True if the key is a string and sensitive, False otherwise.
62
62
 
63
63
  """
64
64
  if regex is None:
65
65
  return False
66
+ if not isinstance(key, str):
67
+ return False
66
68
  return bool(regex.search(key))
67
69
 
68
70
 
@@ -14,8 +14,6 @@ from dataclasses import dataclass
14
14
  from pathlib import Path
15
15
 
16
16
  from taipanstack.security.guards import (
17
- _DEFAULT_DENIED_ENV_VARS,
18
- _SENSITIVE_ENV_VAR_PATTERN,
19
17
  SecurityError,
20
18
  guard_command_injection,
21
19
  )
@@ -147,25 +145,36 @@ def _validate_and_resolve_command(
147
145
  return validated_cmd
148
146
 
149
147
 
150
- def _filter_environment(env: dict[str, str] | None) -> dict[str, str]:
151
- """Filter environment variables for safe execution.
148
+ def _filter_environment(
149
+ env: dict[str, str] | None,
150
+ allowed_env_vars: Sequence[str] | None = None,
151
+ ) -> dict[str, str]:
152
+ """Filter environment variables for safe execution using a whitelist approach.
152
153
 
153
154
  Args:
154
- env: Environment variables to filter.
155
+ env: Environment variables to filter. If None, uses os.environ.
156
+ allowed_env_vars: Whitelist of allowed environment variable names.
157
+ If None, only minimal necessary variables (e.g. PATH) are inherited.
158
+ Pass an empty list for a completely empty environment.
155
159
 
156
160
  Returns:
157
- Filtered environment variables.
161
+ Filtered environment variables containing only allowed keys.
158
162
 
159
163
  """
160
164
  safe_env: dict[str, str] = {}
161
165
  env_to_filter = env if env is not None else dict(os.environ)
162
166
 
167
+ if allowed_env_vars is None:
168
+ # Default minimal whitelist
169
+ allowed_keys = {"PATH"}
170
+ else:
171
+ allowed_keys = {k.upper() for k in allowed_env_vars}
172
+
173
+ if not allowed_keys:
174
+ return safe_env
175
+
163
176
  for env_key, env_val in env_to_filter.items():
164
- name_upper = env_key.upper()
165
- if (
166
- name_upper not in _DEFAULT_DENIED_ENV_VARS
167
- and not _SENSITIVE_ENV_VAR_PATTERN.search(name_upper)
168
- ):
177
+ if env_key.upper() in allowed_keys:
169
178
  safe_env[env_key] = str(env_val)
170
179
 
171
180
  return safe_env
@@ -240,6 +249,7 @@ def run_safe_command(
240
249
  check: bool = False,
241
250
  allowed_commands: Sequence[str] | None = None,
242
251
  env: dict[str, str] | None = None,
252
+ allowed_env_vars: Sequence[str] | None = None,
243
253
  dry_run: bool = False,
244
254
  ) -> SafeCommandResult:
245
255
  """Execute a command safely with security guards.
@@ -256,6 +266,7 @@ def run_safe_command(
256
266
  check: Whether to raise on non-zero exit.
257
267
  allowed_commands: Whitelist of allowed commands.
258
268
  env: Environment variables to set.
269
+ allowed_env_vars: Whitelist of allowed environment variables.
259
270
  dry_run: If True, don't actually execute the command.
260
271
 
261
272
  Returns:
@@ -273,7 +284,7 @@ def run_safe_command(
273
284
 
274
285
  """
275
286
  validated_cmd = _validate_and_resolve_command(command, allowed_commands)
276
- safe_env = _filter_environment(env)
287
+ safe_env = _filter_environment(env, allowed_env_vars)
277
288
 
278
289
  if dry_run:
279
290
  return SafeCommandResult(
File without changes