Coverage for /Users/les/Projects/crackerjack/crackerjack/services/security.py: 0%
86 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
1import os
2import re
3import tempfile
4from contextlib import suppress
5from pathlib import Path
7from crackerjack.errors import FileError, SecurityError
10class SecurityService:
11 TOKEN_PATTERNS = [
12 (r"pypi -[a - zA - Z0-9_ -]{12, }", "pypi-** **"),
13 (r"ghp_[a - zA - Z0-9]{20, }", "ghp_ * ** *"),
14 (r"[a - zA - Z0-9_ -]{20, }", "* ** *"),
15 (r"(token[=: ]\s *)['\"][^'\"]+['\"]", r"\1'* ** *'"),
16 (r"(password[=: ]\s *)['\"][^'\"]+['\"]", r"\1'* ** *'"),
17 ]
19 SENSITIVE_ENV_VARS = {
20 "UV_PUBLISH_TOKEN",
21 "PYPI_TOKEN",
22 "GITHUB_TOKEN",
23 "AUTH_TOKEN",
24 "API_KEY",
25 "SECRET_KEY",
26 "PASSWORD",
27 }
29 def mask_tokens(self, text: str) -> str:
30 if not text:
31 return text
32 masked_text = text
33 for pattern, replacement in self.TOKEN_PATTERNS:
34 masked_text = re.sub(pattern, replacement, masked_text, flags=re.IGNORECASE)
35 for env_var in self.SENSITIVE_ENV_VARS:
36 value = os.getenv(env_var)
37 if value and len(value) > 8:
38 masked_value = (
39 f"{value[:4]}...{value[-4:]}" if len(value) > 12 else "* ** *"
40 )
41 masked_text = masked_text.replace(value, masked_value)
43 return masked_text
45 def mask_command_output(self, stdout: str, stderr: str) -> tuple[str, str]:
46 return self.mask_tokens(stdout), self.mask_tokens(stderr)
48 def create_secure_token_file(
49 self,
50 token: str,
51 prefix: str = "crackerjack_token",
52 ) -> Path:
53 if not token:
54 raise SecurityError(
55 message="Invalid token provided",
56 details="Token must be a non-empty string",
57 recovery="Provide a valid authentication token",
58 )
59 if len(token) < 8:
60 raise SecurityError(
61 message="Token appears too short to be valid",
62 details=f"Token length: {len(token)} characters",
63 recovery="Ensure you're using a full authentication token",
64 )
65 try:
66 fd, temp_path = tempfile.mkstemp(
67 prefix=f"{prefix}_",
68 suffix=".token",
69 text=True,
70 )
71 temp_file = Path(temp_path)
72 try:
73 temp_file.chmod(0o600)
74 except OSError as e:
75 with suppress(OSError):
76 temp_file.unlink()
77 raise FileError(
78 message="Failed to set secure file permissions",
79 details=str(e),
80 recovery="Check file system permissions and try again",
81 ) from e
82 try:
83 with os.fdopen(fd, "w") as f:
84 f.write(token)
85 except OSError as e:
86 with suppress(OSError):
87 temp_file.unlink()
88 raise FileError(
89 message="Failed to write token to secure file",
90 details=str(e),
91 recovery="Check disk space and file system integrity",
92 ) from e
94 return temp_file
95 except OSError as e:
96 raise FileError(
97 message="Failed to create secure token file",
98 details=str(e),
99 recovery="Check temporary directory permissions and disk space",
100 ) from e
102 def cleanup_token_file(self, token_file: Path) -> None:
103 if not token_file or not token_file.exists():
104 return
105 with suppress(OSError):
106 if token_file.is_file():
107 with token_file.open("w") as f:
108 f.write("0" * max(1024, token_file.stat().st_size))
109 f.flush()
110 os.fsync(f.fileno())
111 token_file.unlink()
113 def get_masked_env_summary(self) -> dict[str, str]:
114 env_summary = {}
115 for key, value in os.environ.items():
116 if any(sensitive in key.upper() for sensitive in self.SENSITIVE_ENV_VARS):
117 if value:
118 env_summary[key] = (
119 "* ** *" if len(value) <= 8 else f"{value[:2]}...{value[-2:]}"
120 )
121 else:
122 env_summary[key] = "(empty)"
123 elif key.startswith(("PATH", "HOME", "USER", "SHELL", "TERM")):
124 env_summary[key] = value
126 return env_summary
128 def validate_token_format(self, token: str, token_type: str | None = None) -> bool:
129 if not token:
130 return False
131 if len(token) < 8:
132 return False
133 if token_type and token_type.lower() == "pypi":
134 return token.startswith("pypi -") and len(token) >= 16
135 if token_type and token_type.lower() == "github":
136 return token.startswith("ghp_") and len(token) == 40
137 return len(token) >= 16 and not token.isspace()
139 def create_secure_command_env(
140 self,
141 base_env: dict[str, str] | None = None,
142 additional_vars: dict[str, str] | None = None,
143 ) -> dict[str, str]:
144 if base_env is None:
145 base_env = os.environ.copy()
147 secure_env = base_env.copy()
149 if additional_vars:
150 secure_env.update(additional_vars)
152 dangerous_vars = [
153 "LD_PRELOAD",
154 "LD_LIBRARY_PATH",
155 "DYLD_INSERT_LIBRARIES",
156 "DYLD_LIBRARY_PATH",
157 "PYTHONPATH",
158 ]
160 for var in dangerous_vars:
161 secure_env.pop(var, None)
163 return secure_env