Coverage for /Users/les/Projects/crackerjack/crackerjack/services/dependency_monitor.py: 0%
303 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 json
2import subprocess
3import tempfile
4import time
5import tomllib
6import typing as t
7from contextlib import suppress
8from dataclasses import dataclass
9from pathlib import Path
11from rich.console import Console
13from crackerjack.models.protocols import FileSystemInterface
16@dataclass
17class DependencyVulnerability:
18 package: str
19 installed_version: str
20 vulnerability_id: str
21 severity: str
22 advisory_url: str
23 vulnerable_versions: str
24 patched_version: str
27@dataclass
28class MajorUpdate:
29 package: str
30 current_version: str
31 latest_version: str
32 release_date: str
33 breaking_changes: bool
36class DependencyMonitorService:
37 def __init__(
38 self,
39 filesystem: FileSystemInterface,
40 console: Console | None = None,
41 ) -> None:
42 self.filesystem = filesystem
43 self.console = console or Console()
44 self.project_root = Path.cwd()
45 self.pyproject_path = self.project_root / "pyproject.toml"
46 self.cache_file = self.project_root / ".crackerjack" / "dependency_cache.json"
48 def check_dependency_updates(self) -> bool:
49 if not self.pyproject_path.exists():
50 return False
52 dependencies = self._parse_dependencies()
53 if not dependencies:
54 return False
56 vulnerabilities = self._check_security_vulnerabilities(dependencies)
57 major_updates = self._check_major_updates(dependencies)
59 if vulnerabilities:
60 self._report_vulnerabilities(vulnerabilities)
61 return True
63 if major_updates and self._should_notify_major_updates():
64 self._report_major_updates(major_updates)
65 return True
67 return False
69 def _parse_dependencies(self) -> dict[str, str]:
70 try:
71 with self.pyproject_path.open("rb") as f:
72 data = tomllib.load(f)
74 dependencies = {}
75 project_data = data.get("project", {})
77 self._extract_main_dependencies(project_data, dependencies)
78 self._extract_optional_dependencies(project_data, dependencies)
80 return dependencies
82 except Exception as e:
83 self.console.print(
84 f"[yellow]Warning: Failed to parse pyproject.toml: {e}[/ yellow]",
85 )
86 return {}
88 def _extract_main_dependencies(
89 self,
90 project_data: dict[str, t.Any],
91 dependencies: dict[str, str],
92 ) -> None:
93 if "dependencies" not in project_data:
94 return
96 for dep in project_data["dependencies"]:
97 name, version = self._parse_dependency_spec(dep)
98 if name and version:
99 dependencies[name] = version
101 def _extract_optional_dependencies(
102 self,
103 project_data: dict[str, t.Any],
104 dependencies: dict[str, str],
105 ) -> None:
106 if "optional-dependencies" not in project_data:
107 return
109 for group_deps in project_data["optional-dependencies"].values():
110 for dep in group_deps:
111 name, version = self._parse_dependency_spec(dep)
112 if name and version:
113 dependencies[name] = version
115 def _parse_dependency_spec(self, spec: str) -> tuple[str | None, str | None]:
116 if not spec or spec.startswith("-"):
117 return None, None
119 for operator in ("> =", "< =", "= =", "~=", "! =", ">", "<"):
120 if operator in spec:
121 parts = spec.split(operator, 1)
122 if len(parts) == 2:
123 package = parts[0].strip()
124 version = parts[1].strip()
125 return package, version
127 return spec.strip(), "latest"
129 def _check_security_vulnerabilities(
130 self,
131 dependencies: dict[str, str],
132 ) -> list[DependencyVulnerability]:
133 vulnerabilities: list[DependencyVulnerability] = []
135 safety_vulns = self._check_with_safety(dependencies)
136 vulnerabilities.extend(safety_vulns)
138 if not vulnerabilities:
139 pip_audit_vulns = self._check_with_pip_audit(dependencies)
140 vulnerabilities.extend(pip_audit_vulns)
142 return vulnerabilities
144 def _check_with_safety(
145 self,
146 dependencies: dict[str, str],
147 ) -> list[DependencyVulnerability]:
148 cmd = ["uv", "run", "safety", "check", "--file", "__TEMP_FILE__", "--json"]
149 return self._run_vulnerability_tool(
150 dependencies,
151 cmd,
152 self._parse_safety_output,
153 )
155 def _check_with_pip_audit(
156 self,
157 dependencies: dict[str, str],
158 ) -> list[DependencyVulnerability]:
159 cmd = [
160 "uv",
161 "run",
162 "pip-audit",
163 "--requirement",
164 "__TEMP_FILE__",
165 "--format",
166 "json",
167 ]
168 return self._run_vulnerability_tool(
169 dependencies,
170 cmd,
171 self._parse_pip_audit_output,
172 )
174 def _run_vulnerability_tool(
175 self,
176 dependencies: dict[str, str],
177 command_template: list[str],
178 parser_func: t.Callable[[t.Any], list[DependencyVulnerability]],
179 ) -> list[DependencyVulnerability]:
180 try:
181 temp_file = self._create_requirements_file(dependencies)
182 try:
183 result = self._execute_vulnerability_command(
184 command_template,
185 temp_file,
186 )
187 return self._process_vulnerability_result(result, parser_func)
188 finally:
189 Path(temp_file).unlink(missing_ok=True)
190 except (
191 subprocess.CalledProcessError,
192 subprocess.TimeoutExpired,
193 json.JSONDecodeError,
194 Exception,
195 ):
196 return []
198 def _create_requirements_file(self, dependencies: dict[str, str]) -> str:
199 with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as f:
200 for package, version in dependencies.items():
201 if version != "latest":
202 f.write(f"{package}= ={version}\n")
203 else:
204 f.write(f"{package}\n")
205 return f.name
207 def _execute_vulnerability_command(
208 self,
209 command_template: list[str],
210 temp_file: str,
211 ) -> subprocess.CompletedProcess[str]:
212 cmd = [part.replace("__TEMP_FILE__", temp_file) for part in command_template]
213 return subprocess.run(
214 cmd,
215 check=False,
216 capture_output=True,
217 text=True,
218 timeout=30,
219 )
221 def _process_vulnerability_result(
222 self,
223 result: subprocess.CompletedProcess[str],
224 parser_func: t.Callable[[t.Any], list[DependencyVulnerability]],
225 ) -> list[DependencyVulnerability]:
226 if result.returncode == 0:
227 return []
229 if result.stdout:
230 data = json.loads(result.stdout)
231 return parser_func(data)
233 return []
235 def _parse_safety_output(self, safety_data: t.Any) -> list[DependencyVulnerability]:
236 vulnerabilities: list[DependencyVulnerability] = []
238 with suppress(Exception):
239 for vuln in safety_data:
240 vulnerabilities.append(
241 DependencyVulnerability(
242 package=vuln.get("package", ""),
243 installed_version=vuln.get("installed_version", ""),
244 vulnerability_id=vuln.get("vulnerability_id", ""),
245 severity=vuln.get("severity", "unknown"),
246 advisory_url=vuln.get("more_info_url", ""),
247 vulnerable_versions=vuln.get("vulnerable_spec", ""),
248 patched_version=vuln.get("analyzed_version", ""),
249 ),
250 )
252 return vulnerabilities
254 def _parse_pip_audit_output(
255 self,
256 audit_data: t.Any,
257 ) -> list[DependencyVulnerability]:
258 vulnerabilities: list[DependencyVulnerability] = []
260 with suppress(Exception):
261 for vuln in audit_data.get("vulnerabilities", []):
262 package = vuln.get("package", {})
263 vulnerabilities.append(
264 DependencyVulnerability(
265 package=package.get("name", ""),
266 installed_version=package.get("version", ""),
267 vulnerability_id=vuln.get("id", ""),
268 severity=vuln.get("severity", "unknown"),
269 advisory_url=vuln.get("link", ""),
270 vulnerable_versions=vuln.get("vulnerable_ranges", ""),
271 patched_version=vuln.get("fix_versions", [""])[0],
272 ),
273 )
275 return vulnerabilities
277 def _check_major_updates(self, dependencies: dict[str, str]) -> list[MajorUpdate]:
278 major_updates: list[MajorUpdate] = []
279 cache = self._load_update_cache()
280 current_time = time.time()
282 for package, current_version in dependencies.items():
283 if current_version == "latest":
284 continue
286 update = self._check_package_major_update(
287 package,
288 current_version,
289 cache,
290 current_time,
291 )
292 if update:
293 major_updates.append(update)
295 self._save_update_cache(cache)
296 return major_updates
298 def _check_package_major_update(
299 self,
300 package: str,
301 current_version: str,
302 cache: dict[str, t.Any],
303 current_time: float,
304 ) -> MajorUpdate | None:
305 cache_key = self._build_cache_key(package, current_version)
307 cached_update = self._get_cached_major_update(
308 cache_key,
309 cache,
310 current_time,
311 package,
312 current_version,
313 )
314 if cached_update is not None:
315 return cached_update
317 return self._fetch_and_cache_update_info(
318 package,
319 current_version,
320 cache_key,
321 cache,
322 current_time,
323 )
325 def _build_cache_key(self, package: str, current_version: str) -> str:
326 return f"{package}_{current_version}"
328 def _get_cached_major_update(
329 self,
330 cache_key: str,
331 cache: dict[str, t.Any],
332 current_time: float,
333 package: str,
334 current_version: str,
335 ) -> MajorUpdate | None:
336 if not self._is_cache_entry_valid(cache_key, cache, current_time):
337 return None
339 cached_data = cache[cache_key]
340 if not cached_data["has_major_update"]:
341 return None
343 return self._create_major_update_from_cache(
344 package,
345 current_version,
346 cached_data,
347 )
349 def _is_cache_entry_valid(
350 self,
351 cache_key: str,
352 cache: dict[str, t.Any],
353 current_time: float,
354 ) -> bool:
355 if cache_key not in cache:
356 return False
358 cached_data = cache[cache_key]
359 cache_age = current_time - cached_data["timestamp"]
360 return cache_age < 86400
362 def _create_major_update_from_cache(
363 self,
364 package: str,
365 current_version: str,
366 cached_data: dict[str, t.Any],
367 ) -> MajorUpdate:
368 return MajorUpdate(
369 package=package,
370 current_version=current_version,
371 latest_version=cached_data["latest_version"],
372 release_date=cached_data["release_date"],
373 breaking_changes=cached_data["breaking_changes"],
374 )
376 def _fetch_and_cache_update_info(
377 self,
378 package: str,
379 current_version: str,
380 cache_key: str,
381 cache: dict[str, t.Any],
382 current_time: float,
383 ) -> MajorUpdate | None:
384 latest_info = self._get_latest_version_info(package)
385 if not latest_info:
386 return None
388 has_major_update = self._is_major_version_update(
389 current_version,
390 latest_info["version"],
391 )
393 self._update_cache_entry(
394 cache,
395 cache_key,
396 current_time,
397 has_major_update,
398 latest_info,
399 )
401 return self._create_major_update_if_needed(
402 package,
403 current_version,
404 latest_info,
405 has_major_update,
406 )
408 def _create_major_update_if_needed(
409 self,
410 package: str,
411 current_version: str,
412 latest_info: dict[str, t.Any],
413 has_major_update: bool,
414 ) -> MajorUpdate | None:
415 if not has_major_update:
416 return None
418 return MajorUpdate(
419 package=package,
420 current_version=current_version,
421 latest_version=latest_info["version"],
422 release_date=latest_info["release_date"],
423 breaking_changes=latest_info["breaking_changes"],
424 )
426 def _update_cache_entry(
427 self,
428 cache: dict[str, t.Any],
429 cache_key: str,
430 current_time: float,
431 has_major_update: bool,
432 latest_info: dict[str, t.Any],
433 ) -> None:
434 cache[cache_key] = {
435 "timestamp": current_time,
436 "has_major_update": has_major_update,
437 "latest_version": latest_info["version"],
438 "release_date": latest_info["release_date"],
439 "breaking_changes": latest_info["breaking_changes"],
440 }
442 def _get_latest_version_info(self, package: str) -> dict[str, t.Any] | None:
443 try:
444 data = self._fetch_pypi_data(package)
445 return self._extract_version_info(data)
446 except Exception:
447 return None
449 def _fetch_pypi_data(self, package: str) -> dict[str, t.Any]:
450 import urllib.request
451 from urllib.parse import urlparse
453 url = f"https://pypi.org/pypi/{package}/json"
454 self._validate_pypi_url(url)
456 parsed = urlparse(url)
457 if parsed.scheme != "https" or parsed.netloc != "pypi.org":
458 msg = f"Invalid URL: only https://pypi.org URLs are allowed, got {url}"
459 raise ValueError(msg)
461 with urllib.request.urlopen(url, timeout=10) as response:
462 return json.load(response)
464 def _validate_pypi_url(self, url: str) -> None:
465 from urllib.parse import urlparse
467 parsed = urlparse(url)
469 if parsed.scheme != "https":
470 msg = f"Invalid URL scheme '{parsed.scheme}': only HTTPS is allowed"
471 raise ValueError(msg)
473 if parsed.netloc != "pypi.org":
474 msg = f"Invalid hostname '{parsed.netloc}': only pypi.org is allowed"
475 raise ValueError(msg)
477 if not parsed.path.startswith("/pypi/") or not parsed.path.endswith("/json"):
478 msg = f"Invalid PyPI API path: {parsed.path}"
479 raise ValueError(msg)
481 def _extract_version_info(self, data: dict[str, t.Any]) -> dict[str, t.Any] | None:
482 info = data.get("info", {})
483 releases = data.get("releases", {})
485 latest_version = info.get("version", "")
486 if not latest_version:
487 return None
489 release_date = self._get_release_date(releases, latest_version)
490 breaking_changes = self._has_breaking_changes(latest_version)
492 return {
493 "version": latest_version,
494 "release_date": release_date,
495 "breaking_changes": breaking_changes,
496 }
498 def _get_release_date(self, releases: dict[str, t.Any], version: str) -> str:
499 release_info = releases.get(version, [])
500 if release_info:
501 return release_info[0].get("upload_time", "")
502 return ""
504 def _has_breaking_changes(self, version: str) -> bool:
505 return version.split(".")[0] != "0" if "." in version else False
507 def _is_major_version_update(self, current: str, latest: str) -> bool:
508 with suppress(ValueError, IndexError):
509 current_parts = current.split(".")
510 latest_parts = latest.split(".")
512 if current_parts and latest_parts:
513 current_major = int(current_parts[0])
514 latest_major = int(latest_parts[0])
515 return latest_major > current_major
517 return False
519 def _should_notify_major_updates(self) -> bool:
520 cache = self._load_update_cache()
521 last_major_notification = cache.get("last_major_notification", 0)
522 current_time = time.time()
524 if current_time - last_major_notification > 604800:
525 cache["last_major_notification"] = current_time
526 self._save_update_cache(cache)
527 return True
529 return False
531 def _load_update_cache(self) -> dict[str, t.Any]:
532 with suppress(Exception):
533 if self.cache_file.exists():
534 with self.cache_file.open() as f:
535 return json.load(f)
536 return {}
538 def _save_update_cache(self, cache: dict[str, t.Any]) -> None:
539 with suppress(Exception):
540 self.cache_file.parent.mkdir(exist_ok=True)
541 with self.cache_file.open("w") as f:
542 json.dump(cache, f, indent=2)
544 def _report_vulnerabilities(
545 self,
546 vulnerabilities: list[DependencyVulnerability],
547 ) -> None:
548 self.console.print(
549 "\n[bold red]🚨 Security Vulnerabilities Found ![/ bold red]"
550 )
551 self.console.print(
552 "[red]Please update the following packages immediately: [/ red]\n",
553 )
555 for vuln in vulnerabilities:
556 self.console.print(f"[red]• {vuln.package} {vuln.installed_version}[/ red]")
557 self.console.print(
558 f" [dim]Vulnerability ID: {vuln.vulnerability_id}[/ dim]"
559 )
560 self.console.print(f" [dim]Severity: {vuln.severity.upper()}[/ dim]")
561 if vuln.patched_version:
562 self.console.print(
563 f" [green]Fix available: {vuln.patched_version}[/ green]",
564 )
565 if vuln.advisory_url:
566 self.console.print(f" [dim]More info: {vuln.advisory_url}[/ dim]")
567 self.console.print()
569 def _report_major_updates(self, major_updates: list[MajorUpdate]) -> None:
570 self.console.print(
571 "\n[bold yellow]📦 Major Version Updates Available[/ bold yellow]",
572 )
573 self.console.print(
574 "[yellow]The following packages have major updates: [/ yellow]\n",
575 )
577 for update in major_updates:
578 self.console.print(f"[yellow]• {update.package}[/ yellow]")
579 self.console.print(f" [dim]Current: {update.current_version}[/ dim]")
580 self.console.print(f" [dim]Latest: {update.latest_version}[/ dim]")
581 if update.release_date:
582 release_date = update.release_date[:10]
583 self.console.print(f" [dim]Released: {release_date}[/ dim]")
584 if update.breaking_changes:
585 self.console.print(" [red]⚠️ May contain breaking changes[/ red]")
586 self.console.print()
588 self.console.print(
589 "[dim]Review changelogs before updating to major versions.[/ dim]",
590 )
592 def force_check_updates(
593 self,
594 ) -> tuple[list[DependencyVulnerability], list[MajorUpdate]]:
595 if not self.pyproject_path.exists():
596 self.console.print("[yellow]⚠️ No pyproject.toml found[/ yellow]")
597 return [], []
599 self.console.print("[dim]Parsing dependencies from pyproject.toml...[/ dim]")
600 dependencies = self._parse_dependencies()
601 if not dependencies:
602 self.console.print(
603 "[yellow]⚠️ No dependencies found in pyproject.toml[/ yellow]",
604 )
605 return [], []
607 self.console.print(
608 f"[dim]Found {len(dependencies)} dependencies to check[/ dim]",
609 )
611 self.console.print("[dim]Checking for security vulnerabilities...[/ dim]")
612 vulnerabilities = self._check_security_vulnerabilities(dependencies)
614 self.console.print("[dim]Checking for major version updates...[/ dim]")
615 major_updates = self._check_major_updates(dependencies)
617 return vulnerabilities, major_updates