diff --git a/README.md b/README.md index e4b1d5b..1d9d7e6 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,16 @@ pipx install pydoctor-cli pip install pydoctor-cli ``` +> Install `pydoctor-cli`, not `pydoctor`: that is an unrelated project (Twisted's API doc generator) that installs a command with the same name. + +PyDoctor scans your **project's** Python, wherever PyDoctor itself is installed. It uses the active virtualenv, or a `.venv`/`venv` in the project, and tells you which interpreter it chose. To choose one yourself: + +```bash +pydoctor diagnose --python .venv/bin/python # or set PYDOCTOR_PYTHON +``` + +๐Ÿ“– Full documentation: **https://pydoctor-docs.thally.app** + --- ## โšก Usage @@ -75,6 +85,19 @@ pydoctor fix ## Release History +### v2.2.0 +Results you can trust: every fix in this release removes a case where PyDoctor reported a problem as fine, or got a severity wrong. + +- **Scans the right environment:** facts come from your project's interpreter, not PyDoctor's. Under pipx or `uv tool`, and in uv environments (which have no pip), 2.1.0 saw 0 packages and reported everything as OK. Works without pip (package metadata, `uv pip list --outdated`). New `--python` / `PYDOCTOR_PYTHON`; the report shows which interpreter was scanned and why. +- **Fails loudly:** `ENV_PACKAGES_UNAVAILABLE` (error) when the environment can't be read, `ENV_DEPS_NOT_INSTALLED` when the scanned Python has none of your dependencies, and outdated checks that can't run say so instead of "all up to date". +- **Virtualenv detection works:** it was always "active". The `diagnose` no-venv prompt now appears, and never blocks CI or piped runs. +- **Real CVSS scores:** severity is computed from the CVSS v3 vector. Previously a 3.1 (Low) and a 9.8 (Critical) vulnerability were both shown as critical. GitHub's `MODERATE` is now medium. +- **Right fix version:** for advisories with one fix per release line, `fix` targets your line (Django 5.1.2 โ†’ 5.1.4, not 4.2.17). +- **CI guard finds real leaks:** scans every committed text file, adds Stripe, OpenAI, Anthropic, Slack, Google, private-key, database-URL and `SECRET_KEY` rules, flags committed `.env` files, and checks workflows for `pull_request_target` "pwn requests", script injection and `write-all` permissions. Findings have line numbers; add `# pydoctor: ignore` to silence one. Zero findings on Flask, Django, requests, httpx, FastAPI, DRF and pip. +- **A score that moves:** a package's advisories count once, categories have diminishing returns, and any critical issue keeps the score below "Good". Expect different (usually higher) scores than 2.1.0. +- **JSON:** includes `health`; `scan-security --json` reports advisory IDs, aliases, fixed version and CVSS score. +- Smaller: database drivers, hashers and cache clients picked by Django settings count as used; faster advisory fetching; `--no-cache` no longer wipes the cache; circular import fixed; `github ` and `docker` describe what they actually do. + ### v2.1.0 - **`pydoctor fix` reports what really happened:** upgrades are verified against the installed version. If a pin in `pyproject.toml` blocks an upgrade, pydoctor says so and shows the constraint instead of printing "fixed". - **One prompt per package:** vulnerable packages are offered once, with the advisory count, and upgraded to the lowest version that fixes every advisory. diff --git a/pydoctor/__init__.py b/pydoctor/__init__.py index f4bedfa..ea99e5d 100644 --- a/pydoctor/__init__.py +++ b/pydoctor/__init__.py @@ -9,6 +9,6 @@ License: MIT """ -__version__ = "2.1.0" +__version__ = "2.2.0" __author__ = "Favour Bamgboye" __description__ = "Python environment diagnostic CLI โ€” your project's doctor." diff --git a/pydoctor/analysis/health_score.py b/pydoctor/analysis/health_score.py index 3e77502..b12fb44 100644 --- a/pydoctor/analysis/health_score.py +++ b/pydoctor/analysis/health_score.py @@ -6,6 +6,7 @@ from __future__ import annotations +import math from dataclasses import dataclass from pydoctor.core.report import DiagnosisReport, Issue @@ -18,20 +19,62 @@ class HealthMetrics: message: str +# Each category can cost at most this many points. Within a category every +# extra issue still lowers the score, but by less (diminishing returns), so +# fixing issues in a project with dozens of them visibly moves the score. +CATEGORY_CAPS: dict[str, float] = { + "security": 60, + "ci": 50, + "dependencies": 40, + "environment": 30, + "outdated": 15, + "unused": 10, +} + +# A project with any critical issue can't be rated Good or Excellent. +CRITICAL_CEILING = 69 + +# Issues that mean part of the scan didn't run. +INCOMPLETE_CODES = {"ENV_PACKAGES_UNAVAILABLE", "SEC_SCAN_INCOMPLETE"} + + def calculate_health(report: DiagnosisReport) -> HealthMetrics: """ Calculate project health score (0-100) based on identified issues. """ score = _compute_score(report) - categories = list({i.category for i in report.issues}) - return _get_verdict(score, categories) + categories = list({i.category for i in report.issues if i.code not in INCOMPLETE_CODES}) + metrics = _get_verdict(score, categories) + if any(i.code in INCOMPLETE_CODES for i in report.issues): + metrics.verdict = "Incomplete" + metrics.message = ( + "Some checks couldn't run, so this score only covers what was checked. " + "See the errors above." + ) + return metrics def _compute_score(report: DiagnosisReport) -> int: - score = 100 + raw: dict[str, float] = {} + # One upgrade usually fixes every advisory for a package, so a package + # costs the penalty of its worst advisory, not one penalty per advisory. + per_package: dict[str, int] = {} for issue in report.issues: - score -= _calculate_issue_penalty(issue) - return max(0, score) + penalty = _calculate_issue_penalty(issue) + if issue.code == "SEC_VULNERABILITY" and issue.package: + per_package[issue.package] = max(per_package.get(issue.package, 0), penalty) + continue + raw[issue.category] = raw.get(issue.category, 0) + penalty + if per_package: + raw["security"] = raw.get("security", 0) + sum(per_package.values()) + lost = 0.0 + for category, points in raw.items(): + cap = CATEGORY_CAPS.get(category) + lost += cap * (1 - math.exp(-points / cap)) if cap else points + score = max(0, round(100 - lost)) + if any(i.severity.lower() == "critical" for i in report.issues): + score = min(score, CRITICAL_CEILING) + return score def _calculate_issue_penalty(issue: Issue) -> int: diff --git a/pydoctor/cache/cache_manager.py b/pydoctor/cache/cache_manager.py index e6eb804..8f60a23 100644 --- a/pydoctor/cache/cache_manager.py +++ b/pydoctor/cache/cache_manager.py @@ -79,7 +79,7 @@ def get(self, key: str) -> Any | None: return entry.get("value") - def set(self, key: str, value: Any) -> None: + def set(self, key: str, value: Any, save: bool = True) -> None: """ Store a value in the cache with the current timestamp. @@ -87,8 +87,15 @@ def set(self, key: str, value: Any) -> None: ---------- key: Cache key. value: Any JSON-serialisable value. + save: Write to disk now. Pass False when setting many keys, then call + ``save()`` once (writing the whole file per key is quadratic). """ self._data[key] = {"_ts": time.time(), "value": value} + if save: + self._save() + + def save(self) -> None: + """Persist the cache to disk.""" self._save() def invalidate(self, key: str) -> None: diff --git a/pydoctor/cli/main.py b/pydoctor/cli/main.py index 5b8dbc7..53957b1 100644 --- a/pydoctor/cli/main.py +++ b/pydoctor/cli/main.py @@ -84,8 +84,8 @@ def version_callback(value: bool): [section]๐Ÿฅ COMMUNITY & SUPPORT[/] - [label]Docs:[/][pkg] https://pydoctor.vercel.app/docs[/] - [label]Version:[/][info] v2.1.0 (Premium Kernel Edition)[/] + [label]Docs:[/][pkg] https://pydoctor-docs.thally.app[/] + [label]Version:[/][info] v2.2.0 (Premium Kernel Edition)[/] [kernel]Healthy code leads to healthy deployments. Keep your environment sterile.[/] """ @@ -122,6 +122,12 @@ def main_callback( _JSON_ARG = typer.Option(..., "--json", "-j", help="Output results as JSON.") _VERBOSE_ARG = typer.Option(..., "--verbose", "-v", help="Show detailed output and timing.") _NO_CACHE_ARG = typer.Option(..., "--no-cache", help="Bypass the local vulnerability cache.") +_PYTHON_ARG = typer.Option( + ..., + "--python", + help="Python interpreter of the project to scan (default: auto-detect). " + "Also settable with PYDOCTOR_PYTHON.", +) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @@ -137,11 +143,10 @@ def _run_scan( as_json: bool = False, ci_mode: bool = False, command: str | None = None, + python: str | None = None, + ctx: ProjectContext | None = None, ) -> DiagnosisReport: # noqa: C901 """Run the Analyzer with Rich progress indicators.""" - if no_cache: - CacheManager().clear() - if not as_json: console.print("[section]Scanning project...[/]") @@ -158,7 +163,14 @@ def progress_callback(key: str) -> None: console.print(f"[kernel]ยป[/] Checking {label.lower().replace(' ', ' ')}") if as_json: - analyzer = Analyzer(project_path=path, scanners=scanners, verbose=verbose) + analyzer = Analyzer( + project_path=path, + scanners=scanners, + verbose=verbose, + python=python, + ctx=ctx, + no_cache=no_cache, + ) report = analyzer.run(on_progress=None) report.command = command return report @@ -175,6 +187,9 @@ def progress_callback(key: str) -> None: project_path=path, scanners=scanners, verbose=verbose, + python=python, + ctx=ctx, + no_cache=no_cache, ) report = analyzer.run(on_progress=progress_callback) report.command = command @@ -182,6 +197,14 @@ def progress_callback(key: str) -> None: return report +def _is_interactive() -> bool: + """True when a person can answer prompts (not CI, not piped input).""" + try: + return sys.stdin.isatty() + except (AttributeError, ValueError): + return False + + def _output(report: DiagnosisReport, as_json: bool, verbose: bool = False) -> None: if as_json: render_json(report) @@ -213,23 +236,37 @@ def _exit_code(report: DiagnosisReport, path: str = ".") -> int: @app.command(rich_help_panel="CORE COMMANDS") def diagnose( path: Annotated[str, _PATH_ARG] = ".", + python: Annotated[str | None, _PYTHON_ARG] = None, json: Annotated[bool, _JSON_ARG] = False, verbose: Annotated[bool, _VERBOSE_ARG] = False, no_cache: Annotated[bool, _NO_CACHE_ARG] = False, ) -> None: # noqa: C901 """๐Ÿฉบ Run a **full** diagnosis of your Python project.""" + ctx = None if not json: - ctx = ProjectContext.from_path(path) - if not ctx.in_virtualenv: - console.print("[warning]โš  No virtual environment detected in this project.[/]") - if not Confirm.ask("Do you want to proceed using global system packages?"): + ctx = ProjectContext.from_path(path, python=python) + if not ctx.env_error and not ctx.in_virtualenv: + console.print( + "[warning]โš  No virtual environment detected. Scanning " + f"{ctx.python_executable} ({ctx.python_source}).[/]" + ) + # Never block a non-interactive run (CI, pipes) on a prompt. + if _is_interactive() and not Confirm.ask( + "Do you want to proceed using global system packages?" + ): console.print( "\n[info]โ„น Cancelled. Please activate a virtual environment and try again.[/]" ) raise typer.Exit() report = _run_scan( - path=path, verbose=verbose, no_cache=no_cache, as_json=json, command="diagnose" + path=path, + verbose=verbose, + no_cache=no_cache, + as_json=json, + command="diagnose", + python=python, + ctx=ctx, ) _output(report, as_json=json, verbose=verbose) raise typer.Exit(code=_exit_code(report, path)) @@ -238,12 +275,15 @@ def diagnose( @app.command(rich_help_panel="CORE COMMANDS") def check( path: Annotated[str, _PATH_ARG] = ".", + python: Annotated[str | None, _PYTHON_ARG] = None, ci: bool = typer.Option(False, "--ci", help="Run in CI/CD guard mode."), json: Annotated[bool, _JSON_ARG] = False, verbose: Annotated[bool, _VERBOSE_ARG] = False, ) -> None: """๐Ÿ›ก๏ธ Perform security and health checks. Use --ci for pipeline shielding.""" - report = _run_scan(path=path, ci_mode=ci, verbose=verbose, as_json=json, command="check") + report = _run_scan( + path=path, ci_mode=ci, verbose=verbose, as_json=json, command="check", python=python + ) _output(report, as_json=json, verbose=verbose) raise typer.Exit(code=_exit_code(report, path)) @@ -253,7 +293,7 @@ def docker( image: Annotated[str | None, typer.Argument(help="Docker image to scan (optional).")] = None, path: Annotated[str, _PATH_ARG] = ".", ) -> None: - """๐Ÿณ Diagnose Python issues inside **Docker** containers.""" + """๐Ÿณ [Preview] Check that a Dockerfile exists and uses a Python base image.""" console.print(Panel("[section]๐Ÿณ Docker Environment Doctor[/]", border_style="rule")) console.print("[kernel]Scanning for Dockerfile and container runtime...[/]") dockerfile = Path(path) / "Dockerfile" @@ -268,17 +308,26 @@ def docker( ) else: console.print("[ok]โœ”[/] Python base image identified.") - console.print("\n[info]โ„น This feature is in beta. Full container introspection coming soon.[/]") + console.print( + "\n[info]โ„น Preview: this only checks the Dockerfile. It doesn't inspect images or " + "containers yet.[/]" + ) @app.command(rich_help_panel="SECURITY & CI/CD") def github( repo: Annotated[str | None, typer.Argument(help="GitHub repository URL (optional).")] = None, path: Annotated[str, _PATH_ARG] = ".", + python: Annotated[str | None, _PYTHON_ARG] = None, json: Annotated[bool, _JSON_ARG] = False, verbose: Annotated[bool, _VERBOSE_ARG] = False, ) -> None: - """๐Ÿ™ Integrate with **GitHub** for repository-wide health scans.""" + """๐Ÿ™ Run the CI/CD guard on a local git checkout.""" + if repo: + err_console.print( + "[warning]โš  Scanning remote repositories isn't supported yet; " + f"ignoring {repo} and scanning {path}.[/]" + ) if not json: console.print(Panel("[section]๐Ÿ™ GitHub Repository Doctor[/]", border_style="rule")) if not repo: @@ -295,7 +344,9 @@ def github( console.print("[ok]โœ”[/] Local git repository detected.") console.print("\n[info]โ„น Running pydoctor on the current branch...[/]") - report = _run_scan(path=path, ci_mode=True, verbose=verbose, as_json=json, command="github") + report = _run_scan( + path=path, ci_mode=True, verbose=verbose, as_json=json, command="github", python=python + ) _output(report, as_json=json, verbose=verbose) raise typer.Exit(code=_exit_code(report, path)) @@ -306,12 +357,18 @@ def github( @app.command(name="scan-security", rich_help_panel="SECURITY & CI/CD") def scan_security( path: Annotated[str, _PATH_ARG] = ".", + python: Annotated[str | None, _PYTHON_ARG] = None, json: Annotated[bool, _JSON_ARG] = False, verbose: Annotated[bool, _VERBOSE_ARG] = False, ) -> None: """๐Ÿ”’ Scan installed packages for known vulnerabilities (OSV).""" report = _run_scan( - scanners=["security"], path=path, verbose=verbose, as_json=json, command="scan-security" + scanners=["security"], + path=path, + verbose=verbose, + as_json=json, + command="scan-security", + python=python, ) _output(report, as_json=json, verbose=verbose) raise typer.Exit(code=_exit_code(report, path)) @@ -325,12 +382,18 @@ def scan_security( @app.command(name="scan-unused", rich_help_panel="RESOURCE HYGIENE") def scan_unused( path: Annotated[str, _PATH_ARG] = ".", + python: Annotated[str | None, _PYTHON_ARG] = None, json: Annotated[bool, _JSON_ARG] = False, verbose: Annotated[bool, _VERBOSE_ARG] = False, ) -> None: """๐Ÿงน Detect unused packages via AST analysis.""" report = _run_scan( - scanners=["unused"], path=path, verbose=verbose, as_json=json, command="scan-unused" + scanners=["unused"], + path=path, + verbose=verbose, + as_json=json, + command="scan-unused", + python=python, ) _output(report, as_json=json, verbose=verbose) raise typer.Exit(code=_exit_code(report, path)) @@ -339,12 +402,18 @@ def scan_unused( @app.command(name="scan-deps", rich_help_panel="RESOURCE HYGIENE") def scan_deps( path: Annotated[str, _PATH_ARG] = ".", + python: Annotated[str | None, _PYTHON_ARG] = None, json: Annotated[bool, _JSON_ARG] = False, verbose: Annotated[bool, _VERBOSE_ARG] = False, ) -> None: """๐Ÿ“ฆ Scan for dependency version conflicts.""" report = _run_scan( - scanners=["dependencies"], path=path, verbose=verbose, as_json=json, command="scan-deps" + scanners=["dependencies"], + path=path, + verbose=verbose, + as_json=json, + command="scan-deps", + python=python, ) _output(report, as_json=json, verbose=verbose) raise typer.Exit(code=_exit_code(report, path)) @@ -353,12 +422,18 @@ def scan_deps( @app.command(name="check-env", rich_help_panel="RESOURCE HYGIENE") def check_env( path: Annotated[str, _PATH_ARG] = ".", + python: Annotated[str | None, _PYTHON_ARG] = None, json: Annotated[bool, _JSON_ARG] = False, verbose: Annotated[bool, _VERBOSE_ARG] = False, ) -> None: """๐ŸŒ Verify Python and virtual environment health.""" report = _run_scan( - scanners=["environment"], path=path, verbose=verbose, as_json=json, command="check-env" + scanners=["environment"], + path=path, + verbose=verbose, + as_json=json, + command="check-env", + python=python, ) _output(report, as_json=json, verbose=verbose) raise typer.Exit(code=_exit_code(report, path)) @@ -373,6 +448,7 @@ def fix( list[str] | None, typer.Argument(help="Specific packages to fix (optional).") ] = None, path: Annotated[str, _PATH_ARG] = ".", + python: Annotated[str | None, _PYTHON_ARG] = None, safe: bool = typer.Option(True, "--safe/--no-safe", help="Confirm each action."), upgrade: bool = typer.Option(True, "--upgrade/--no-upgrade", help="Upgrade outdated."), remove: bool = typer.Option(False, "--remove/--no-remove", help="Remove unused."), @@ -383,8 +459,8 @@ def fix( "[section]๐Ÿ”ง PyDoctor Auto-Fix[/]\n\nScanning for fixable issues โ€ฆ", border_style="rule" ) ) - report_data = _run_scan(path=path) - ctx = ProjectContext.from_path(path) + report_data = _run_scan(path=path, python=python) + ctx = report_data.ctx # reuse the scan's context instead of probing again if packages: _filter_issues_by_targets(report_data, packages) actions = 0 @@ -463,8 +539,16 @@ def _norm(name: str) -> str: def _installed_version(ctx, pkg: str) -> str | None: """Return the version of ``pkg`` installed in the project's environment.""" + from pydoctor.utils.env_probe import probe_environment + + probe, _ = probe_environment(ctx.project_python) + packages = ( + probe.packages + if probe + else get_installed_packages(python_executable=ctx.project_python) # fallback: pip + ) target = _norm(pkg) - for name, version in get_installed_packages(python_executable=ctx.project_python).items(): + for name, version in packages.items(): if _norm(name) == target: return version return None diff --git a/pydoctor/core/__init__.py b/pydoctor/core/__init__.py index 58b7b33..a0b9561 100644 --- a/pydoctor/core/__init__.py +++ b/pydoctor/core/__init__.py @@ -1,7 +1,17 @@ """pydoctor/core/__init__.py""" -from pydoctor.core.analyzer import Analyzer from pydoctor.core.project import ProjectContext from pydoctor.core.report import DiagnosisReport, Issue __all__ = ["Issue", "DiagnosisReport", "ProjectContext", "Analyzer"] + + +def __getattr__(name: str): + # Imported lazily: Analyzer imports every scanner, and scanners import + # pydoctor.core, so an eager import here made + # `import pydoctor.scanners.vulnerability_scanner` fail with a circular import. + if name == "Analyzer": + from pydoctor.core.analyzer import Analyzer + + return Analyzer + raise AttributeError(name) diff --git a/pydoctor/core/analyzer.py b/pydoctor/core/analyzer.py index 7d01547..88eb709 100644 --- a/pydoctor/core/analyzer.py +++ b/pydoctor/core/analyzer.py @@ -48,6 +48,64 @@ } +# Scanners that read the installed environment (everything except "ci"). +_ENV_SCANNERS = {"environment", "dependencies", "outdated", "security", "unused"} + + +def context_issues(ctx: ProjectContext, scanner_keys: list[str]) -> list[Issue]: + """ + Problems with the scan itself, reported once regardless of which scanners run. + + These exist so that a scan which couldn't see the project's packages fails + loudly instead of returning a clean bill of health. + """ + if not _ENV_SCANNERS.intersection(scanner_keys): + return [] + if ctx.env_error: + return [ + Issue( + category="environment", + code="ENV_PACKAGES_UNAVAILABLE", + severity=Severity.ERROR, + title="Couldn't read the project's installed packages", + description=( + f"PyDoctor tried {ctx.project_python} ({ctx.python_source}) and got: " + f"{ctx.env_error}. Security, dependency, outdated and unused checks " + "were not run." + ), + recommendation=( + "Activate the project's virtualenv, or point PyDoctor at its interpreter " + "with --python path/to/python (or PYDOCTOR_PYTHON)." + ), + extra={"python": ctx.project_python, "source": ctx.python_source}, + ) + ] + if ctx.declared_deps: + from pydoctor.utils.env_probe import normalise_name + + missing = [d for d in ctx.declared_deps if normalise_name(d) not in ctx.installed_packages] + if len(missing) == len(ctx.declared_deps): + return [ + Issue( + category="environment", + code="ENV_DEPS_NOT_INSTALLED", + severity=Severity.WARNING, + title="None of the project's dependencies are installed in the scanned Python", + description=( + f"Scanned {ctx.python_executable} ({ctx.python_source}), which has none " + f"of the {len(ctx.declared_deps)} declared dependencies installed. " + "Results describe that interpreter, not your project." + ), + recommendation=( + "Install the dependencies, activate the project's virtualenv, or use " + "--python path/to/python." + ), + extra={"python": ctx.project_python, "missing": sorted(missing)}, + ) + ] + return [] + + # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Analyzer # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @@ -70,10 +128,16 @@ def __init__( project_path: str = ".", scanners: list[str] | None = None, verbose: bool = False, + python: str | None = None, + ctx: ProjectContext | None = None, + no_cache: bool = False, ) -> None: self._project_path = project_path self._scanner_keys = scanners or list(SCANNER_REGISTRY.keys()) self._verbose = verbose + self._python = python + self._ctx = ctx + self._no_cache = no_cache # โ”€โ”€ Public API โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @@ -92,9 +156,11 @@ def run(self, on_progress: Callable[[str], None] | None = None) -> DiagnosisRepo wall_start = time.perf_counter() # Build project context once โ€” shared across all scanners - ctx = ProjectContext.from_path(self._project_path) + ctx = self._ctx or ProjectContext.from_path(self._project_path, python=self._python) + ctx.no_cache = self._no_cache report = DiagnosisReport(scan_path=str(ctx.root), ctx=ctx) scanner_timings: dict[str, float] = {} + report.extend(context_issues(ctx, self._scanner_keys)) # Parallel execution for independence (each scanner gets its own thread) with ThreadPoolExecutor(max_workers=min(MAX_WORKERS, len(self._scanner_keys))) as pool: diff --git a/pydoctor/core/project.py b/pydoctor/core/project.py index a62bcce..80b0edb 100644 --- a/pydoctor/core/project.py +++ b/pydoctor/core/project.py @@ -14,6 +14,7 @@ import os import re +import shutil import sys from dataclasses import dataclass, field from pathlib import Path @@ -34,9 +35,12 @@ class ProjectContext: python_files: All .py files found under ``root`` (excluding ignored dirs). installed_packages: Mapping of package_name โ†’ installed_version. declared_deps: Packages listed in requirements.txt / pyproject.toml. - python_executable: Path to the Python interpreter being used. + python_executable: Path to the project's Python interpreter (the one scanned). python_version: (major, minor, micro) tuple of that interpreter. - in_virtualenv: Whether we're running inside a virtual environment. + in_virtualenv: Whether that interpreter belongs to a virtual environment. + python_source: How the interpreter was chosen (shown to the user). + pip_version: pip version inside the project environment, or None. + env_error: Why the environment could not be read, or None. """ root: Path @@ -65,46 +69,58 @@ class ProjectContext: git_repo: str | None = None git_branch: str | None = None git_origin: str | None = None + python_source: str = "" + pip_version: str | None = None + env_error: str | None = None + distributions: dict[str, dict] = field(default_factory=dict) + marker_env: dict[str, str] = field(default_factory=dict) + no_cache: bool = False # --no-cache: ignore cached advisories (still refresh them) # โ”€โ”€ Factory method โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @classmethod - def from_path(cls, path: str | Path) -> ProjectContext: - """Build a ProjectContext by scanning ``path``.""" + def from_path(cls, path: str | Path, python: str | None = None) -> ProjectContext: + """ + Build a ProjectContext by scanning ``path``. + + ``python`` (or the ``PYDOCTOR_PYTHON`` environment variable) forces the + interpreter to scan. Otherwise it is discovered; see + ``_find_project_python``. Every fact about the environment comes from + that interpreter, never from the one PyDoctor itself is running on. + """ + import platform + + from pydoctor.utils.env_probe import probe_environment + from pydoctor.utils.pip_utils import get_dependency_graph + root = Path(path).resolve() python_files = collect_python_files(root) declared = cls._parse_dependencies(root) meta = cls._extract_pyproject_metadata(root) - # Detect virtual environment and project python - import os - import platform - - project_py = cls._find_project_python(root, meta) - from pydoctor.utils.pip_utils import get_dependency_graph, get_installed_packages - - installed = get_installed_packages(python_executable=project_py) - in_venv = (project_py != sys.base_prefix) or bool(os.environ.get("VIRTUAL_ENV")) - graph = get_dependency_graph(python_executable=project_py) + project_py, source = cls._find_project_python( + root, meta, python or os.environ.get("PYDOCTOR_PYTHON") + ) + probe, env_error = probe_environment(project_py) venv_path = None venv_name = None - if in_venv: - # project_py is something like /bin/python or /Scripts/python.exe - v_path = Path(project_py).parents[1] - venv_path = str(v_path) - venv_name = v_path.name + if probe and probe.in_virtualenv: + venv_path = probe.prefix + venv_name = Path(probe.prefix).name git_info = cls._get_git_info(root) return cls( root=root, python_files=python_files, - installed_packages=installed, + installed_packages=probe.packages if probe else {}, declared_deps=declared, - in_virtualenv=in_venv, - dependency_graph=graph, + python_executable=probe.executable if probe else project_py, + python_version=probe.version if probe else (0, 0, 0), + in_virtualenv=probe.in_virtualenv if probe else False, + dependency_graph=get_dependency_graph(python_executable=project_py) if probe else [], platform_info=platform.platform(), os_name=platform.system(), config=meta.get("config", {}), @@ -117,77 +133,88 @@ def from_path(cls, path: str | Path) -> ProjectContext: git_repo=git_info.get("repo"), git_branch=git_info.get("branch"), git_origin=git_info.get("origin"), + python_source=source, + pip_version=probe.pip_version if probe else None, + env_error=env_error, + distributions=probe.distributions if probe else {}, + marker_env=probe.markers if probe else {}, ) @classmethod - def _find_project_python(cls, root: Path, meta: dict) -> str: - """Find the Python interpreter for the project.""" - # 1. Check for common venv names - venv_py = cls._find_venv_python(root) - if venv_py: - return venv_py - - # 2. Check package managers + def _find_project_python( + cls, root: Path, meta: dict, explicit: str | None = None + ) -> tuple[str, str]: + """ + Choose the interpreter to scan and say why. + + Order: explicit ``--python`` / ``PYDOCTOR_PYTHON``, the active + virtualenv, a virtualenv in the project (or its parent), Poetry/PDM, + then ``python3`` on PATH. PyDoctor's own interpreter is the last + resort, because under pipx or ``uv tool`` it only contains PyDoctor's + dependencies. + """ + if explicit: + resolved = shutil.which(explicit) or explicit + return resolved, "--python option" + + venv = cls._find_venv_python(root) + if venv: + return venv + mgr_py = cls._find_manager_python(root, meta) if mgr_py: - return mgr_py + return mgr_py, "Poetry environment" if meta.get("is_poetry") else "PDM environment" + + for name in ("python3", "python"): + found = shutil.which(name) + if found: + return found, f"`{name}` on PATH (no project virtualenv found)" - # 3. Fallback to current interpreter - return sys.executable + return sys.executable, "PyDoctor's own interpreter (no other Python found)" @staticmethod - def _find_venv_python(root: Path) -> str | None: # noqa: C901 - """Search for virtualenv locations including non-conventional names.""" - # 1. Check if an environment is already active + def _venv_python(base: Path) -> Path: + return base / "Scripts" / "python.exe" if os.name == "nt" else base / "bin" / "python" + + @classmethod + def _find_venv_python(cls, root: Path) -> tuple[str, str] | None: + """Find a virtualenv for the project and describe where it came from.""" active_venv = os.environ.get("VIRTUAL_ENV") if active_venv: - base = Path(active_venv) - py = base / "Scripts" / "python.exe" if os.name == "nt" else base / "bin" / "python" + py = cls._venv_python(Path(active_venv)) if py.exists(): - return str(py) - - # 2. Check current directory and its parent for common name matches - search_dirs = [root, root.parent] - venv_names = [ - ".venv", - "venv", - ".env", - "env", - "dev", - ".dev", - "test", - ".test", - "prod", - ".prod", - "kernel", - ] - - for search_dir in search_dirs: - for venv_dir in venv_names: - if os.name == "nt": - py_path = search_dir / venv_dir / "Scripts" / "python.exe" - else: - py_path = search_dir / venv_dir / "bin" / "python" + return str(py), f"active virtualenv ({active_venv})" + + venv_names = [".venv", "venv", "env", ".env"] + for venv_dir in venv_names: + py = cls._venv_python(root / venv_dir) + if py.exists(): + return str(py), f"{venv_dir}/ in the project" + + found = cls._find_pyvenv_cfg_dir(root) + if found: + return found + + # Monorepos often keep one .venv at the repository root. Only the + # conventional names are considered, and the source says so. + for venv_dir in (".venv", "venv"): + py = cls._venv_python(root.parent / venv_dir) + if py.exists(): + return str(py), f"{venv_dir}/ in the parent directory ({root.parent})" - if py_path.exists(): - return str(py_path) + return None - # 3. Dynamic scan for pyvenv.cfg in subdirectories (shallow scan of current root) + @classmethod + def _find_pyvenv_cfg_dir(cls, root: Path) -> tuple[str, str] | None: + """Any directory in the project root that contains pyvenv.cfg.""" try: - for entry in root.iterdir(): - if entry.is_dir() and not entry.name.startswith("."): - # Check for pyvenv.cfg which is a strong indicator - if (entry / "pyvenv.cfg").exists(): - py = ( - entry / "Scripts" / "python.exe" - if os.name == "nt" - else entry / "bin" / "python" - ) - if py.exists(): - return str(py) - except PermissionError: + for entry in sorted(root.iterdir()): + if entry.is_dir() and (entry / "pyvenv.cfg").exists(): + py = cls._venv_python(entry) + if py.exists(): + return str(py), f"{entry.name}/ in the project" + except OSError: pass - return None @staticmethod diff --git a/pydoctor/performance/__init__.py b/pydoctor/performance/__init__.py deleted file mode 100644 index 2db250d..0000000 --- a/pydoctor/performance/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -"""pydoctor/performance/__init__.py""" - -from pydoctor.performance.executor import run_parallel, run_parallel_dict, timed - -__all__ = ["run_parallel", "run_parallel_dict", "timed"] diff --git a/pydoctor/performance/executor.py b/pydoctor/performance/executor.py deleted file mode 100644 index 83dbcd9..0000000 --- a/pydoctor/performance/executor.py +++ /dev/null @@ -1,132 +0,0 @@ -""" -pydoctor/performance/executor.py -โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ -Parallel task execution helpers. - -Wraps ``concurrent.futures.ThreadPoolExecutor`` with a clean interface -that PyDoctor's scanners use to fan-out work across multiple packages or -files concurrently. - -Why threads and not processes? -Most scanner work is I/O-bound (network calls to OSV/PyPI, reading files). -Threads share the GIL effectively here โ€” no need for multiprocessing overhead. -""" - -from __future__ import annotations - -import time -from collections.abc import Callable, Iterable -from concurrent.futures import Future, ThreadPoolExecutor, as_completed -from typing import Any, TypeVar - -from pydoctor.config.settings import MAX_WORKERS - -T = TypeVar("T") - - -# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ -# Public helpers -# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ - - -def run_parallel( - fn: Callable[..., T], - items: Iterable[Any], - *, - workers: int = MAX_WORKERS, - timeout: float | None = None, -) -> list[T]: - """ - Apply ``fn`` to each item in ``items`` concurrently. - - Parameters - ---------- - fn: The function to call for each item. - Called as ``fn(item)`` โ€” use ``functools.partial`` for extra args. - items: Iterable of items to process. - workers: Maximum number of concurrent worker threads. - timeout: Optional per-future wait timeout in seconds. - - Returns - ------- - list[T] - Results in an unspecified (completion) order. - Exceptions raised by ``fn`` are caught and silently dropped to - ensure one failing item doesn't abort the whole batch. - """ - results: list[T] = [] - item_list = list(items) - - if not item_list: - return results - - with ThreadPoolExecutor(max_workers=min(workers, len(item_list))) as executor: - future_map: dict[Future, Any] = {executor.submit(fn, item): item for item in item_list} - for future in as_completed(future_map, timeout=timeout): - try: - result = future.result() - if result is not None: - results.append(result) - except Exception: - # Individual item failure โ€” skip it - pass - - return results - - -def run_parallel_dict( - fn: Callable[[str, Any], T], - mapping: dict[str, Any], - *, - workers: int = MAX_WORKERS, -) -> list[T]: - """ - Like ``run_parallel`` but operates on a dict, passing key and value to fn. - - Parameters - ---------- - fn: Called as ``fn(key, value)`` for each dict entry. - mapping: Input dictionary. - workers: Max threads. - - Returns - ------- - list[T] - """ - - results: list[T] = [] - if not mapping: - return results - - with ThreadPoolExecutor(max_workers=min(workers, len(mapping))) as executor: - futures = {executor.submit(fn, k, v): k for k, v in mapping.items()} - for future in as_completed(futures): - try: - result = future.result() - if result is not None: - results.append(result) - except Exception: - pass - - return results - - -def timed(fn: Callable[..., T], *args, **kwargs) -> tuple[T, float]: - """ - Call ``fn(*args, **kwargs)`` and return ``(result, elapsed_ms)``. - - Parameters - ---------- - fn: Function to call. - *args: Positional arguments. - **kwargs: Keyword arguments. - - Returns - ------- - tuple[T, float] - The function's return value and elapsed time in milliseconds. - """ - start = time.perf_counter() - result = fn(*args, **kwargs) - elapsed_ms = (time.perf_counter() - start) * 1000 - return result, elapsed_ms diff --git a/pydoctor/performance/parallel.py b/pydoctor/performance/parallel.py deleted file mode 100644 index 459e394..0000000 --- a/pydoctor/performance/parallel.py +++ /dev/null @@ -1,40 +0,0 @@ -""" -pydoctor/performance/parallel.py -โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ -Parallel execution utilities for large codebases. -""" - -from __future__ import annotations - -import concurrent.futures -from collections.abc import Callable, Iterable -from typing import TypeVar - -T = TypeVar("T") -R = TypeVar("R") - - -def run_parallel( - func: Callable[[T], R], items: Iterable[T], max_workers: int | None = None -) -> list[R]: - """ - Run a function over a list of items using a thread pool. - - Threads are often better for I/O bound tasks like reading many small files - or making network requests for vulnerability checks. - """ - with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor: - return list(executor.map(func, items)) - - -def run_parallel_proc( - func: Callable[[T], R], items: Iterable[T], max_workers: int | None = None -) -> list[R]: - """ - Run a function over a list of items using a process pool. - - Process pools bypass the GIL and are better for CPU-intensive tasks - like regex-heavy secret scanning over thousands of lines. - """ - with concurrent.futures.ProcessPoolExecutor(max_workers=max_workers) as executor: - return list(executor.map(func, items)) diff --git a/pydoctor/reports/json_formatter.py b/pydoctor/reports/json_formatter.py index 8e4b1c9..0ec8b29 100644 --- a/pydoctor/reports/json_formatter.py +++ b/pydoctor/reports/json_formatter.py @@ -50,24 +50,22 @@ def render_json( str The serialised JSON string. """ + from pydoctor.analysis.health_score import calculate_health + + health = calculate_health(report) data = report.to_dict() + data["health"] = {"score": health.score, "verdict": health.verdict} - # Special case: map purely security outputs to simple output - categories = {i.category for i in report.issues} + # Security-only scans keep their compact shape, now with advisory IDs. + categories = {i.category for i in report.issues if i.code not in _CONTEXT_CODES} if categories == {"security"}: - vulns = [] - for issue in report.issues: - if issue.severity in ("ok", "info"): - continue - vulns.append( - { - "package": issue.package, - "version": issue.extra.get("version", "unknown"), - "advisory": issue.code, - "severity": issue.severity, - } - ) - data = {"scan_type": "security", "vulnerabilities": vulns} + data = { + "scan_type": "security", + "health": data["health"], + "vulnerabilities": [ + _vuln_entry(i) for i in report.issues if i.severity not in ("ok", "info") + ], + } json_str = json.dumps( data, @@ -83,6 +81,37 @@ def render_json( return json_str +_CONTEXT_CODES = {"ENV_PACKAGES_UNAVAILABLE", "ENV_DEPS_NOT_INSTALLED"} + + +def _vuln_entry(issue) -> dict: + """ + One entry of the security-only JSON. + + `advisory` used to hold the issue code ("SEC_VULNERABILITY") for every + finding, so the GHSA/CVE id was lost. It is now the advisory id; `code` + carries the issue code. + """ + extra = issue.extra or {} + return { + "package": issue.package, + "version": extra.get("version", "unknown"), + "advisory": extra.get("vuln_id", issue.code), + "aliases": extra.get("aliases", []), + "fixed_in": extra.get("fixed_in") or None, + "cvss_score": extra.get("cvss_score"), + "severity": issue.severity, + "summary": issue.description, + "code": issue.code, + **( + {"unchecked_packages": extra["unchecked_packages"]} + if "unchecked_packages" in extra + else {} + ), + **({"python": extra["python"]} if "python" in extra else {}), + } + + def report_to_dict(report: DiagnosisReport) -> dict: """ Return the report as a plain Python dictionary. diff --git a/pydoctor/reports/table_formatter.py b/pydoctor/reports/table_formatter.py index c235064..0e76084 100644 --- a/pydoctor/reports/table_formatter.py +++ b/pydoctor/reports/table_formatter.py @@ -94,7 +94,8 @@ def _render_kernel_logs(report: DiagnosisReport) -> None: os_name = report.ctx.os_name if report.ctx else "Unknown" console.print(f"STDOUT: [stdout][SUCCESS][/] Runtime: Python {py_ver} ({os_name})") - console.print("STDOUT: [stdout][SUCCESS][/] Entropy Check: PASS") + if report.ctx and getattr(report.ctx, "python_executable", None): + console.print(f"STDOUT: [stdout][SUCCESS][/] Interpreter: {report.ctx.python_executable}") console.print("\n[kernel]Orchestrating Dependency Audit...[/]") @@ -108,8 +109,12 @@ def _render_boxed_environment(report: DiagnosisReport) -> None: table.add_column("Key", style="label") table.add_column("Value") - # Python Version + # Python Version and which interpreter was scanned (and why) table.add_row(f"{ICON_OK} Python Version:", f"{'.'.join(map(str, ctx.python_version))}") + if getattr(ctx, "python_executable", None): + table.add_row(f"{ICON_OK} Interpreter:", f"[dim]{ctx.python_executable}[/]") + if getattr(ctx, "python_source", ""): + table.add_row(" Found via:", ctx.python_source) # Venv status status = "Active" if ctx.in_virtualenv else "[warning]System (Not Isolated)[/]" diff --git a/pydoctor/scanners/ci_scanner.py b/pydoctor/scanners/ci_scanner.py index 271571b..8abb5d2 100644 --- a/pydoctor/scanners/ci_scanner.py +++ b/pydoctor/scanners/ci_scanner.py @@ -3,8 +3,8 @@ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ CI/CD Guard Mode scanner. -Checks for exposed secrets in the codebase and verifies that GitHub Actions/GitLab CI -workflows follow best security practices (e.g. pinned versions, no cleartext secrets). +Checks for exposed secrets in the files you commit, and for risky patterns in +GitHub Actions / GitLab CI workflows. """ from __future__ import annotations @@ -15,19 +15,23 @@ from pydoctor.config.settings import Severity from pydoctor.core.project import ProjectContext from pydoctor.core.report import Issue +from pydoctor.security.secrets import ( + _looks_like_placeholder, + _looks_random, + candidate_files, + is_env_file, + scan_files, +) from pydoctor.utils.file_utils import is_test_file CATEGORY = "ci" +MAX_SECRET_FINDINGS = 50 -# Simple regex patterns for common secrets (can be expanded) -SECRET_PATTERNS = { - "AWS_KEY": re.compile(r"(?:AWS|AKIA)[A-Z0-9]{16}"), - "GH_TOKEN": re.compile(r"ghp_[a-zA-Z0-9]{36}"), - "PYPI_TOKEN": re.compile(r"pypi-[a-zA-Z0-9\-_]{50,}"), - "GENERIC_SECRET": re.compile( - r"(?:secret|password|passwd|api_key|apikey)\s*[:=]\s*['\"][a-zA-Z0-9\-_{}]{8,}['\"]", re.I - ), -} +_SECRET_RECOMMENDATION = ( + "Revoke or rotate this credential now (it may already be in git history), then " + "load it from an environment variable or a secret manager. If this is a false " + "positive, add `# pydoctor: ignore` to the line." +) def scan(ctx: ProjectContext) -> list[Issue]: @@ -55,87 +59,261 @@ def scan(ctx: ProjectContext) -> list[Issue]: return issues +# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +# Secrets +# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + +def _rel(path: Path, root: Path) -> str: + try: + return str(path.relative_to(root)) + except ValueError: + return str(path) + + def _scan_for_secrets(ctx: ProjectContext) -> list[Issue]: - """Scan all project files for hardcoded secrets.""" + """Scan committed (or about-to-be-committed) files for hardcoded secrets.""" + files, tracked, using_git = candidate_files(ctx.root, ctx.python_files) issues: list[Issue] = [] - # We only scan files collected in the context to avoid node_modules, .git etc. - for file_path in ctx.python_files: - if is_test_file(file_path, ctx.root): - continue - - try: - content = file_path.read_text(errors="ignore") - for name, pattern in SECRET_PATTERNS.items(): - if pattern.search(content): - issues.append( - Issue( - category=CATEGORY, - code=f"SECRET_EXPOSED_{name}", - severity=Severity.CRITICAL, - title=f"Potential Secret Exposed: {name}", - description=f"Possible sensitive credential found in {file_path.relative_to(ctx.root)}", - recommendation="Move secrets to environment variables or a secure secret manager (e.g. GitHub Secrets).", + if using_git: + env_files = [f for f in files if is_env_file(f) and not is_test_file(f, ctx.root)] + for env_file in env_files: + committed = env_file in tracked + rel = _rel(env_file, ctx.root) + issues.append( + Issue( + category=CATEGORY, + code="CI_ENV_FILE_COMMITTED" if committed else "CI_ENV_FILE_NOT_IGNORED", + severity=Severity.ERROR if committed else Severity.WARNING, + title=( + f"Environment file committed to git: {rel}" + if committed + else f"Environment file not ignored by git: {rel}" + ), + description=( + f"{rel} usually holds real credentials. " + + ( + "It is tracked by git, so everyone with access to the repository " + "(and its history) can read it." + if committed + else "It isn't in .gitignore, so the next `git add .` commits it." ) - ) - except Exception: - continue + ), + recommendation=( + f"git rm --cached {rel}, add it to .gitignore, rotate the values it " + "contained, and commit a .env.example with placeholders instead." + if committed + else f"Add {rel} to .gitignore. Commit a .env.example with placeholders." + ), + extra={"file": rel}, + ) + ) + findings = scan_files(files, lambda p: is_test_file(p, ctx.root)) + for f in findings[:MAX_SECRET_FINDINGS]: + rel = _rel(f.path, ctx.root) + issues.append( + Issue( + category=CATEGORY, + code=f"SECRET_EXPOSED_{f.code}", + severity=Severity.CRITICAL if f.high_confidence else Severity.ERROR, + title=f"Exposed secret: {f.label} ({rel}:{f.line})", + description=( + f"{'Found' if f.high_confidence else 'Possible'} {f.label.lower()} " + f"in {rel} on line {f.line}: {f.preview}" + ), + recommendation=_SECRET_RECOMMENDATION, + extra={"file": rel, "line": f.line, "preview": f.preview}, + ) + ) + if len(findings) > MAX_SECRET_FINDINGS: + issues.append( + Issue( + category=CATEGORY, + code="SECRET_FINDINGS_TRUNCATED", + severity=Severity.ERROR, + title=f"{len(findings) - MAX_SECRET_FINDINGS} more possible secrets not shown", + description=f"{len(findings)} findings in total; the first {MAX_SECRET_FINDINGS} are listed.", + recommendation="Fix the listed findings and scan again.", + ) + ) return issues +# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +# Workflows +# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + +_BRANCH_REFS = {"main", "master", "head", "dev", "develop", "trunk"} +_USES = re.compile(r"^\s*(?:-\s*)?uses:\s*['\"]?([^@\s'\"#]+)@([^\s'\"#]+)") +_RUN = re.compile(r"^(\s*)(?:-\s*)?run:\s*(.*)$") +_UNTRUSTED = re.compile( + r"\$\{\{\s*(github\.head_ref|github\.event\.(?:issue|pull_request|comment|review|" + r"review_comment|discussion|discussion_comment|pages|commits|head_commit|workflow_run)" + r"[\w.\[\]*'\"-]*(?:title|body|message|name|email|label|ref|head_branch|default_branch|" + r"page_name)[\w.]*)\s*\}\}" +) +_SECRET_ENV = re.compile( + r"^\s*([A-Z0-9_]*(?:SECRET|PASSWORD|PASSWD|TOKEN|API_KEY|APIKEY|PRIVATE_KEY)[A-Z0-9_]*)" + r"\s*:\s*['\"]?([^'\"\s#]+)" +) + + def _scan_workflows(ctx: ProjectContext) -> list[Issue]: """Scan CI workflow files for insecure patterns.""" issues: list[Issue] = [] + wf_dir = ctx.root / ".github" / "workflows" + files = ( + sorted(list(wf_dir.glob("*.yml")) + list(wf_dir.glob("*.yaml"))) if wf_dir.is_dir() else [] + ) + gitlab = ctx.root / ".gitlab-ci.yml" + if gitlab.is_file(): + files.append(gitlab) + for f in files: + _check_workflow_file(f, issues, ctx) + return issues - workflow_dirs = [ - ctx.root / ".github" / "workflows", - ctx.root / ".gitlab-ci.yml", - ] - - for path in workflow_dirs: - if path.exists(): - if path.is_file(): - _check_workflow_file(path, issues, ctx) - else: - for f in path.glob("*.yml"): - _check_workflow_file(f, issues, ctx) - for f in path.glob("*.yaml"): - _check_workflow_file(f, issues, ctx) - return issues +def _issue(code, severity, title, description, recommendation, rel, line) -> Issue: + return Issue( + category=CATEGORY, + code=code, + severity=severity, + title=f"{title} ({rel}:{line})", + description=description, + recommendation=recommendation, + extra={"file": rel, "line": line}, + ) -def _check_workflow_file(file_path: Path, issues: list[Issue], ctx: ProjectContext): - """Check a single workflow file for best practices.""" - try: - content = file_path.read_text(errors="ignore") - rel_path = file_path.relative_to(ctx.root) +def _check_uses(line: str, rel: str, no: int) -> Issue | None: + m = _USES.match(line) + if not m: + return None + action, ref = m.group(1), m.group(2) + if action.startswith(("./", "docker://")) or ref.lower() not in _BRANCH_REFS: + return None + return _issue( + "CI_UNPINNED_ACTION", + Severity.WARNING, + f"Unpinned GitHub Action {action}@{ref}", + f"{rel} runs {action} from the {ref} branch, which can change at any time.", + "Pin to a release tag, or better, a full commit SHA.", + rel, + no, + ) - # Check for unpinned actions (using @master or @main instead of hash) - if "@master" in content or "@main" in content: - issues.append( - Issue( - category=CATEGORY, - code="CI_UNPINNED_ACTION", - severity=Severity.WARNING, - title="Unpinned GitHub Action", - description=f"Workflow {rel_path} uses unpinned (@main/@master) actions.", - recommendation="Pin actions to a specific commit hash or version tag for supply-chain security.", - ) - ) - # Check for cleartext environment variables that look like secrets - if re.search(r"env:\s*SECRET_", content, re.I): - issues.append( - Issue( - category=CATEGORY, - code="CI_CLEARTEXT_ENV", - severity=Severity.WARNING, - title="Potential cleartext secret in workflow", - description=f"Workflow {rel_path} defines environment variables that might contain secrets.", - recommendation="Ensure sensitive values are passed via ${{ secrets.VARIABLE_NAME }}.", - ) - ) - except Exception: - pass +def _check_injection(line: str, rel: str, no: int) -> Issue | None: + m = _UNTRUSTED.search(line) + if not m: + return None + return _issue( + "CI_SCRIPT_INJECTION", + Severity.ERROR, + "Untrusted input interpolated into a shell script", + f"`{m.group(0)}` is controlled by whoever opens the issue or pull request. " + "Inside `run:` it is pasted into the script, so crafted text can run " + "commands in your workflow.", + f"Pass it through an environment variable instead: `env: VALUE: {m.group(0)}` " + 'and use "$VALUE" in the script.', + rel, + no, + ) + + +def _check_permissions(line: str, rel: str, no: int) -> Issue | None: + if not re.match(r"^\s*permissions:\s*write-all\s*$", line): + return None + return _issue( + "CI_BROAD_PERMISSIONS", + Severity.WARNING, + "Workflow token has write access to everything", + "`permissions: write-all` lets any step, including third-party actions, " + "push code, publish releases and change settings.", + "Grant only what the job needs, e.g. `permissions: { contents: read }`.", + rel, + no, + ) + + +def _check_pr_target_checkout(line: str, rel: str, no: int) -> Issue | None: + if not re.search(r"ref:\s*.*(github\.event\.pull_request\.head|github\.head_ref)", line): + return None + return _issue( + "CI_PULL_REQUEST_TARGET_CHECKOUT", + Severity.CRITICAL, + "pull_request_target workflow checks out pull request code", + "pull_request_target runs with your repository's secrets and a write token. " + "Checking out the PR's code there lets anyone who opens a PR run code with " + 'those privileges (a "pwn request").', + "Use the `pull_request` trigger for building or testing PR code, or don't " + "check out the PR head in this workflow.", + rel, + no, + ) + + +def _check_cleartext(line: str, rel: str, no: int) -> Issue | None: + m = _SECRET_ENV.match(line) + if not m or "$" in line: + return None + value = m.group(2) + # CI service containers commonly use throwaway values like + # POSTGRES_PASSWORD: postgres; only flag values that look real. + if len(value) < 8 or not _looks_random(value) or _looks_like_placeholder(value): + return None + return _issue( + "CI_CLEARTEXT_ENV", + Severity.ERROR, + f"Secret value written in the workflow: {m.group(1)}", + f"{m.group(1)} is set to a literal value in {rel}, visible to anyone " + "who can read the repository.", + "Store it as a repository secret and use ${{ secrets.NAME }}.", + rel, + no, + ) + + +def _run_block_lines(lines: list[str]) -> set[int]: + """Line numbers that belong to a `run:` script (inline or block).""" + inside: set[int] = set() + run_indent: int | None = None + for no, line in enumerate(lines, start=1): + indent = len(line) - len(line.lstrip()) + if run_indent is not None and line.strip() and indent <= run_indent: + run_indent = None + if run_indent is not None: + inside.add(no) + run = _RUN.match(line) + if run: + inside.add(no) + if run.group(2).strip() in ("|", ">", "|-", ">-", "|+", ">+", ""): + run_indent = len(run.group(1)) + return inside + + +def _check_workflow_file(file_path: Path, issues: list[Issue], ctx: ProjectContext) -> None: + """Check a single workflow file for risky patterns, with line numbers.""" + try: + content = file_path.read_text(encoding="utf-8", errors="ignore") + except OSError: + return + rel = _rel(file_path, ctx.root) + lines = content.splitlines() + is_prt = bool(re.search(r"\bpull_request_target\b", content)) + run_lines = _run_block_lines(lines) + + for no, line in enumerate(lines, start=1): + if "pydoctor: ignore" in line.lower(): + continue + checks = [_check_uses, _check_permissions, _check_cleartext] + if no in run_lines: + checks.append(_check_injection) + if is_prt: + checks.append(_check_pr_target_checkout) + for check in checks: + found = check(line, rel, no) + if found: + issues.append(found) diff --git a/pydoctor/scanners/dependency_scanner.py b/pydoctor/scanners/dependency_scanner.py index cdbcdc3..21a1d68 100644 --- a/pydoctor/scanners/dependency_scanner.py +++ b/pydoctor/scanners/dependency_scanner.py @@ -10,12 +10,13 @@ Algorithm โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ -1. Run ``pip check`` which reports broken requirements natively. -2. Parse the output and produce structured Issue objects. - -``pip check`` is the authoritative source here โ€” it uses pip's own -resolver to identify conflicts, which is more reliable than us -re-implementing constraint satisfaction. +1. If pip is installed in the project environment, run ``pip check`` there + and parse its output. +2. Otherwise (for example uv-created environments, which have no pip), + check every installed distribution's ``Requires-Dist`` metadata against + the installed versions, evaluating environment markers with the project + interpreter's own marker values. This is the same check ``pip check`` + performs. """ from __future__ import annotations @@ -63,11 +64,17 @@ def scan(ctx: ProjectContext) -> list[Issue]: list[Issue] """ issues: list[Issue] = [] - - pip_check_issues = _run_pip_check(python_executable=ctx.project_python) + if ctx.env_error: + # Reported once by the analyzer as ENV_PACKAGES_UNAVAILABLE. + return issues + + if ctx.pip_version or not ctx.distributions: + pip_check_issues = _run_pip_check(python_executable=ctx.project_python) + else: + pip_check_issues = _check_from_metadata(ctx) issues.extend(pip_check_issues) - # If pip check found nothing, emit an OK + # If the check found nothing, emit an OK if not pip_check_issues: issues.append( Issue( @@ -149,6 +156,44 @@ def _run_pip_check(python_executable: str | None = None) -> list[Issue]: return issues +def _check_from_metadata(ctx: ProjectContext) -> list[Issue]: + """Equivalent of ``pip check`` using metadata read from the project interpreter.""" + from packaging.requirements import InvalidRequirement, Requirement + + from pydoctor.utils.env_probe import normalise_name + + installed = {normalise_name(n): d["version"] for n, d in ctx.distributions.items()} + marker_env = dict(ctx.marker_env) + marker_env["extra"] = "" + issues: list[Issue] = [] + + for name, dist in sorted(ctx.distributions.items()): + for raw in dist.get("requires", []): + try: + req = Requirement(raw) + except InvalidRequirement: + continue + if req.marker is not None: + try: + if not req.marker.evaluate(marker_env): + continue + except Exception: + continue + dep = normalise_name(req.name) + if dep not in installed: + issues.append(_make_missing_issue(pkg=name, req=req.name)) + elif req.specifier and not req.specifier.contains(installed[dep], prereleases=True): + issues.append( + _make_conflict_issue( + pkg=name, + ver=dist["version"], + req=f"{req.name}{req.specifier}", + installed=f"{req.name} {installed[dep]}", + ) + ) + return issues + + def _make_conflict_issue(pkg: str, ver: str, req: str, installed: str) -> Issue: """Build an Issue for a version conflict.""" return Issue( diff --git a/pydoctor/scanners/env_scanner.py b/pydoctor/scanners/env_scanner.py index ca32ced..d372716 100644 --- a/pydoctor/scanners/env_scanner.py +++ b/pydoctor/scanners/env_scanner.py @@ -22,7 +22,6 @@ ) from pydoctor.core.project import ProjectContext from pydoctor.core.report import Issue -from pydoctor.utils.pip_utils import get_pip_version # โ”€โ”€ Category label โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ CATEGORY = "environment" @@ -44,7 +43,7 @@ def scan(ctx: ProjectContext) -> list[Issue]: issues.extend(_check_python_version(ctx)) issues.extend(_check_virtual_environment(ctx)) - issues.extend(_check_pip_version()) + issues.extend(_check_pip_version(ctx)) issues.extend(_check_platform(ctx)) return issues @@ -148,22 +147,40 @@ def _check_virtual_environment(ctx: ProjectContext) -> list[Issue]: ] -def _check_pip_version() -> list[Issue]: - """Check that pip is installed and not critically outdated.""" - pip_ver = get_pip_version() +def _check_pip_version(ctx: ProjectContext) -> list[Issue]: + """Check pip inside the project environment (not PyDoctor's own).""" + if ctx.env_error: + return [] + pip_ver = ctx.pip_version if pip_ver is None: + import shutil + + if ctx.is_uv or shutil.which("uv"): + return [ + Issue( + category=CATEGORY, + code="ENV_PIP_ABSENT_UV", + severity=Severity.INFO, + title="pip isn't installed (uv-managed environment)", + description=( + "Environments created by uv don't include pip. PyDoctor reads " + "package metadata directly and uses uv where a tool is needed." + ), + recommendation="", + ) + ] return [ Issue( category=CATEGORY, code="ENV_PIP_MISSING", - severity=Severity.ERROR, - title="pip is not available", - description="pip could not be found or invoked.", - recommendation=( - "Reinstall pip: python -m ensurepip --upgrade " - "or python -m pip install --upgrade pip" + severity=Severity.WARNING, + title="pip isn't installed in the project environment", + description=( + f"{ctx.python_executable} has no pip, and uv isn't on PATH. PyDoctor " + "can still scan, but can't check for outdated packages or apply fixes." ), + recommendation=f"{ctx.python_executable} -m ensurepip --upgrade", ) ] @@ -203,6 +220,7 @@ def _check_platform(ctx: ProjectContext) -> list[Issue]: arch = platform.machine() # e.g. "AMD64", "x86_64" release = platform.release() python_path = ctx.python_executable + source = f" ({ctx.python_source})" if ctx.python_source else "" return [ Issue( @@ -210,7 +228,7 @@ def _check_platform(ctx: ProjectContext) -> list[Issue]: code="ENV_PLATFORM_INFO", severity=Severity.INFO, title=f"Platform: {os_name} {release} ({arch})", - description=(f"OS: {os_name} {release}\n" f"Arch: {arch}\n" f"Python: {python_path}"), + description=f"OS: {os_name} {release}\nArch: {arch}\nPython: {python_path}{source}", recommendation="", ) ] diff --git a/pydoctor/scanners/outdated_package_scanner.py b/pydoctor/scanners/outdated_package_scanner.py index 1f07f9f..9dbea98 100644 --- a/pydoctor/scanners/outdated_package_scanner.py +++ b/pydoctor/scanners/outdated_package_scanner.py @@ -17,29 +17,53 @@ from pydoctor.config.settings import Severity from pydoctor.core.project import ProjectContext from pydoctor.core.report import Issue -from pydoctor.utils.pip_utils import get_outdated_packages +from pydoctor.utils.pip_utils import get_outdated_packages, get_outdated_packages_uv CATEGORY = "outdated" -def scan(ctx: ProjectContext) -> list[Issue]: - """ - Detect outdated packages in the active environment. +def _unavailable(reason: str) -> Issue: + return Issue( + category=CATEGORY, + code="PKG_OUTDATED_UNAVAILABLE", + severity=Severity.INFO, + title="Outdated-package check skipped", + description=f"PyDoctor couldn't list outdated packages: {reason}", + recommendation=( + "Install pip in the project environment, or install uv, then run the scan again." + ), + ) - Parameters - ---------- - ctx: Project context (not directly used but kept for API consistency). - Returns - ------- - list[Issue] +def scan(ctx: ProjectContext) -> list[Issue]: """ - issues: list[Issue] = [] + Detect outdated packages in the project environment. + Uses ``pip list --outdated`` when pip is installed in the project, and + ``uv pip list --outdated`` otherwise. If neither can run, the check is + reported as skipped, never as "all up to date". + """ + import shutil import subprocess + issues: list[Issue] = [] + if ctx.env_error: + return issues + + uv = shutil.which("uv") try: - outdated = get_outdated_packages(python_executable=ctx.project_python) + # ctx.distributions is empty only for contexts built without a probe + # (for example in tests); keep pip as the default there. + if ctx.pip_version or not ctx.distributions: + outdated = get_outdated_packages(python_executable=ctx.project_python) + elif uv: + outdated = get_outdated_packages_uv(uv, ctx.project_python) + else: + return [ + _unavailable( + "pip isn't installed in the project environment, and uv isn't on PATH." + ) + ] except subprocess.TimeoutExpired: issues.append( Issue( @@ -52,9 +76,11 @@ def scan(ctx: ProjectContext) -> list[Issue]: ) ) return issues + except Exception as exc: + return [_unavailable(str(exc) or exc.__class__.__name__)] - except Exception: - outdated = [] + if outdated is None: + return [_unavailable("the package index couldn't be queried.")] if not outdated: issues.append( diff --git a/pydoctor/scanners/unused_package_scanner.py b/pydoctor/scanners/unused_package_scanner.py index 1db52ca..531d4fc 100644 --- a/pydoctor/scanners/unused_package_scanner.py +++ b/pydoctor/scanners/unused_package_scanner.py @@ -44,8 +44,9 @@ from pydoctor.core.report import Issue from pydoctor.utils.parser_utils import ( extract_imports_from_project, - extract_string_module_refs, + extract_string_constants, import_name_to_package, + module_refs_from_strings, ) CATEGORY = "unused" @@ -58,6 +59,9 @@ def scan(ctx: ProjectContext) -> list[Issue]: """ Detect packages that are declared in requirements but never imported. """ + if ctx.env_error: + # Reported once by the analyzer as ENV_PACKAGES_UNAVAILABLE. + return [] precondition_issues = _check_preconditions(ctx) if precondition_issues: return precondition_issues @@ -162,12 +166,53 @@ def _get_imported_packages(ctx: ProjectContext) -> set[str]: pkgs.update(_norm(d) for d in dist_map.get(n, [])) # Module paths held in strings only count when they match an installed # distribution, so arbitrary strings can't mark random packages as used. - for n in extract_string_module_refs(ctx.python_files): + strings = extract_string_constants(ctx.python_files) + for n in module_refs_from_strings(strings): pkgs.update(_norm(d) for d in dist_map.get(n, [])) + pkgs.update(_packages_behind_backends(strings)) pkgs.update(_packages_named_in_run_files(ctx)) return pkgs +_POSTGRES = ("psycopg2", "psycopg2-binary", "psycopg", "psycopg-binary") +_MYSQL = ("mysqlclient", "pymysql") + +# Settings whose string never names the package that implements them. +_BACKEND_PACKAGES: dict[str, tuple[str, ...]] = { + "django.db.backends.postgresql": _POSTGRES, + "django.db.backends.postgresql_psycopg2": _POSTGRES, + "django.contrib.gis.db.backends.postgis": _POSTGRES, + "django.db.backends.mysql": _MYSQL, + "django.contrib.gis.db.backends.mysql": _MYSQL, + "django.db.backends.oracle": ("oracledb", "cx-oracle"), + "django.contrib.auth.hashers.Argon2PasswordHasher": ("argon2-cffi",), + "django.contrib.auth.hashers.BCryptSHA256PasswordHasher": ("bcrypt",), + "django.contrib.auth.hashers.BCryptPasswordHasher": ("bcrypt",), + "django.core.cache.backends.redis.RedisCache": ("redis", "hiredis"), + "django.core.cache.backends.memcached.PyMemcacheCache": ("pymemcache",), + "django.core.cache.backends.memcached.PyLibMCCache": ("pylibmc",), +} +_URL_SCHEME_PACKAGES: dict[str, tuple[str, ...]] = { + "postgres://": _POSTGRES, + "postgresql://": _POSTGRES, + "mysql://": _MYSQL, + "redis://": ("redis", "hiredis"), + "rediss://": ("redis", "hiredis"), +} + + +def _packages_behind_backends(strings: set[str]) -> set[str]: + """Database drivers, hashers and cache clients selected by a settings string.""" + found: set[str] = set() + for value in strings: + if value in _BACKEND_PACKAGES: + found.update(_BACKEND_PACKAGES[value]) + for scheme, pkgs in _URL_SCHEME_PACKAGES.items(): + if value.startswith(scheme): + found.update(pkgs) + return found + + _DIST_MAP_SNIPPET = ( "import json, importlib.metadata as m; print(json.dumps(m.packages_distributions()))" ) @@ -182,12 +227,16 @@ def _distribution_map(ctx: ProjectContext) -> dict[str, list[str]]: """ python = getattr(ctx, "project_python", None) or sys.executable try: - result = subprocess.run( - [python, "-c", _DIST_MAP_SNIPPET], - capture_output=True, - text=True, - timeout=30, - ) + import tempfile + + with tempfile.TemporaryDirectory(prefix="pydoctor-") as cwd: + result = subprocess.run( + [python, "-c", _DIST_MAP_SNIPPET], + capture_output=True, + text=True, + timeout=30, + cwd=cwd, # keep project files from shadowing the stdlib + ) if result.returncode == 0: data = json.loads(result.stdout) if isinstance(data, dict): diff --git a/pydoctor/scanners/vulnerability_scanner.py b/pydoctor/scanners/vulnerability_scanner.py index 0d412ce..7225868 100644 --- a/pydoctor/scanners/vulnerability_scanner.py +++ b/pydoctor/scanners/vulnerability_scanner.py @@ -34,6 +34,9 @@ def scan(ctx: ProjectContext) -> list[Issue]: ------- list[Issue] """ + if ctx.env_error: + # Reported once by the analyzer as ENV_PACKAGES_UNAVAILABLE. + return [] if not ctx.installed_packages: return [ Issue( @@ -47,7 +50,7 @@ def scan(ctx: ProjectContext) -> list[Issue]: ] cache = CacheManager() - client = OSVClient(cache=cache) + client = OSVClient(cache=cache, read_cache=not getattr(ctx, "no_cache", False)) # Query OSV for all installed packages records = _dedupe_records(client.query_packages(ctx.installed_packages)) @@ -181,7 +184,11 @@ def _record_to_issue(rec: VulnerabilityRecord) -> Issue: severity=sev, title=f"{rec.package} {rec.version} โ€” {id_str}", description=rec.summary or "No description available.", - recommendation=f"pip install --upgrade {rec.package}", + recommendation=( + f'Upgrade to {rec.fixed_in} or later: pip install "{rec.package}>={rec.fixed_in}"' + if rec.fixed_in + else f"No fixed release yet. Track {rec.vuln_id} or pin to a safe version." + ), package=rec.package, extra=rec.to_dict(), ) @@ -193,6 +200,7 @@ def _map_severity(osv_severity: str) -> str: "CRITICAL": Severity.CRITICAL, "HIGH": Severity.CRITICAL, "MEDIUM": Severity.ERROR, + "MODERATE": Severity.ERROR, # GitHub advisories say MODERATE, not MEDIUM "LOW": Severity.WARNING, "UNKNOWN": Severity.WARNING, } diff --git a/pydoctor/security/cvss.py b/pydoctor/security/cvss.py new file mode 100644 index 0000000..9a8a0b7 --- /dev/null +++ b/pydoctor/security/cvss.py @@ -0,0 +1,77 @@ +""" +pydoctor/security/cvss.py +โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +CVSS v3.0 / v3.1 base score calculation. + +OSV records carry CVSS *vectors*, not scores. Earlier versions of PyDoctor +guessed a severity from the vector's attack-vector and privileges fields, +which labelled a 3.1 (Low) and a 9.8 (Critical) vulnerability the same. +This module implements the base score formula from the CVSS v3.1 +specification (section 7.1), which is identical to v3.0 apart from the +round-up function. +""" + +from __future__ import annotations + +import math + +_AV = {"N": 0.85, "A": 0.62, "L": 0.55, "P": 0.2} +_AC = {"L": 0.77, "H": 0.44} +_PR_UNCHANGED = {"N": 0.85, "L": 0.62, "H": 0.27} +_PR_CHANGED = {"N": 0.85, "L": 0.68, "H": 0.5} +_UI = {"N": 0.85, "R": 0.62} +_CIA = {"H": 0.56, "L": 0.22, "N": 0.0} + + +def _roundup(value: float) -> float: + """CVSS v3.1 Roundup: smallest one-decimal number >= value, float-safe.""" + int_input = round(value * 100000) + if int_input % 10000 == 0: + return int_input / 100000.0 + return (math.floor(int_input / 10000) + 1) / 10.0 + + +def base_score(vector: str) -> float | None: + """ + Return the CVSS v3 base score for ``vector``, or None if it isn't a valid v3 vector. + + >>> base_score("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H") + 9.8 + """ + if not vector or not vector.startswith(("CVSS:3.0/", "CVSS:3.1/")): + return None + try: + metrics = dict(part.split(":", 1) for part in vector.split("/")[1:]) + scope_changed = metrics["S"] == "C" + pr_table = _PR_CHANGED if scope_changed else _PR_UNCHANGED + av, ac = _AV[metrics["AV"]], _AC[metrics["AC"]] + pr, ui = pr_table[metrics["PR"]], _UI[metrics["UI"]] + c, i, a = _CIA[metrics["C"]], _CIA[metrics["I"]], _CIA[metrics["A"]] + except (KeyError, ValueError): + return None + + iss = 1 - (1 - c) * (1 - i) * (1 - a) + if scope_changed: + impact = 7.52 * (iss - 0.029) - 3.25 * (iss - 0.02) ** 15 + else: + impact = 6.42 * iss + exploitability = 8.22 * av * ac * pr * ui + + if impact <= 0: + return 0.0 + if scope_changed: + return _roundup(min(1.08 * (impact + exploitability), 10)) + return _roundup(min(impact + exploitability, 10)) + + +def rating(score: float) -> str: + """Qualitative severity rating for a CVSS v3 score.""" + if score >= 9.0: + return "CRITICAL" + if score >= 7.0: + return "HIGH" + if score >= 4.0: + return "MEDIUM" + if score > 0.0: + return "LOW" + return "NONE" diff --git a/pydoctor/security/osv_client.py b/pydoctor/security/osv_client.py index 3250fbd..fc4cbff 100644 --- a/pydoctor/security/osv_client.py +++ b/pydoctor/security/osv_client.py @@ -21,16 +21,26 @@ import hashlib import json import time +from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass, field import requests +from packaging.version import InvalidVersion, Version from pydoctor.cache.cache_manager import CacheManager from pydoctor.config.settings import ( + MAX_WORKERS, OSV_API_URL, OSV_BATCH_SIZE, REQUEST_TIMEOUT, ) +from pydoctor.security.cvss import base_score, rating + +OSV_VULN_URL = "https://api.osv.dev/v1/vulns/{id}" + +# Bump when the parsed record format or severity logic changes, so results +# cached by an older PyDoctor are not reused. +_CACHE_SCHEMA = "v2" # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # Data model @@ -62,6 +72,7 @@ class VulnerabilityRecord: aliases: list[str] = field(default_factory=list) fixed_in: str = "" references: list[str] = field(default_factory=list) + cvss_score: float | None = None def to_dict(self) -> dict: return { @@ -73,6 +84,7 @@ def to_dict(self) -> dict: "aliases": self.aliases, "fixed_in": self.fixed_in, "references": self.references, + "cvss_score": self.cvss_score, } @@ -95,9 +107,12 @@ def __init__( self, cache: CacheManager | None = None, timeout: int = REQUEST_TIMEOUT, + read_cache: bool = True, ) -> None: self._cache = cache or CacheManager() self._timeout = timeout + # False for --no-cache: ignore cached results but still refresh them. + self._read_cache = read_cache self._session = requests.Session() # Packages whose OSV lookup could not be completed (network error, # timeout, or a non-2xx response after all retries). Callers must @@ -149,7 +164,7 @@ def query_packages( def _cache_key(self, name: str, version: str) -> str: """Build a deterministic cache key for a package+version pair.""" - raw = f"osv:{name}:{version}" + raw = f"osv:{_CACHE_SCHEMA}:{name}:{version}" return hashlib.md5(raw.encode()).hexdigest() def _query_batch( # noqa: C901 @@ -168,7 +183,7 @@ def _query_batch( # noqa: C901 # Check cache first for name, version in packages.items(): key = self._cache_key(name, version) - cached = self._cache.get(key) + cached = self._cache.get(key) if self._read_cache else None if cached is not None: records.extend([VulnerabilityRecord(**v) for v in cached]) else: @@ -211,33 +226,51 @@ def _query_batch( # noqa: C901 # Simple exponential backoff: 1s, 2s, 4s... time.sleep(2**attempt) + # The batch endpoint often returns only ids. Fetch the full advisories + # in parallel (one request per unique id), not one at a time. + sparse_ids = { + v["id"] + for result in results + for v in result.get("vulns", []) + if "id" in v and "summary" not in v and "details" not in v + } + full = self._fetch_advisories(sorted(sparse_ids)) + # Parse results โ€” one result entry per queried package (in order) for (name, version), result in zip(to_fetch, results, strict=False): - vulns = result.get("vulns", []) parsed = [] - for v in vulns: - # The batch endpoint sometimes returns sparsely populated records (e.g., just 'id' and 'modified'). - # If crucial fields are missing, fetch the full advisory record. - if "summary" not in v and "details" not in v and "id" in v: - try: - resp = self._session.get( - f"https://api.osv.dev/v1/vulns/{v['id']}", timeout=self._timeout - ) - if resp.status_code == 200: - v = resp.json() - except (requests.RequestException, ValueError): - pass - + for v in result.get("vulns", []): + v = full.get(v.get("id", ""), v) + if v.get("withdrawn"): + continue parsed.append(self._parse_vuln(v, name, version)) records.extend(parsed) # Cache the parsed results (as dicts for JSON-serialisability) key = self._cache_key(name, version) - self._cache.set(key, [p.to_dict() for p in parsed]) + self._cache.set(key, [p.to_dict() for p in parsed], save=False) + self._cache.save() return records + def _fetch_advisories(self, ids: list[str]) -> dict[str, dict]: + """Fetch full OSV records for ``ids`` concurrently; failures are skipped.""" + + def fetch(vuln_id: str) -> tuple[str, dict | None]: + try: + resp = self._session.get(OSV_VULN_URL.format(id=vuln_id), timeout=self._timeout) + if resp.status_code == 200: + return vuln_id, resp.json() + except (requests.RequestException, ValueError): + pass + return vuln_id, None + + if not ids: + return {} + with ThreadPoolExecutor(max_workers=max(1, min(MAX_WORKERS, len(ids)))) as pool: + return {vid: data for vid, data in pool.map(fetch, ids) if data} + def _parse_vuln( self, raw: dict, @@ -266,7 +299,7 @@ def _parse_vuln( refs = [r.get("url", "") for r in raw.get("references", []) if r.get("url")] # Determine severity from database_specific or CVSS data - severity = _extract_severity(raw) + severity, score = _extract_severity(raw) # Find fixed version from affected โ†’ ranges fixed_in = _extract_fixed_version(raw, package, version) @@ -280,6 +313,7 @@ def _parse_vuln( aliases=aliases, fixed_in=fixed_in, references=refs[:5], # cap at 5 references for display + cvss_score=score, ) @@ -288,57 +322,102 @@ def _parse_vuln( # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ -def _extract_severity(raw: dict) -> str: +def _extract_severity(raw: dict) -> tuple[str, float | None]: """ - Extract a human-readable severity level from the OSV vuln JSON. + Return ``(severity_label, cvss_score)`` for an OSV record. - OSV severities live in various places depending on the source database. - We try several paths and default to "UNKNOWN". + Order: the advisory database's own label (GHSA records carry one), then + the CVSS v3 base score computed from the vector. CVSS v4 and v2 vectors + aren't scored; without a database label they are reported as UNKNOWN + rather than guessed. """ - # Try database_specific (common for GHSA) - db_specific = raw.get("database_specific", {}) - if severity := db_specific.get("severity"): - return str(severity).upper() - - # Try CVSS v3 via "severity" array + score = None for sev_entry in raw.get("severity", []): - score_type = sev_entry.get("type", "") - score_str = sev_entry.get("score", "") - if "CVSS" in score_type and score_str: - # score_str is like "CVSS:3.1/AV:N/AC:L/..." - return _cvss_to_label(score_str) - - return "UNKNOWN" - - -def _cvss_to_label(cvss_vector: str) -> str: - """ - Map a CVSS base score extracted from a vector string to a severity label. + if sev_entry.get("type") == "CVSS_V3": + score = base_score(sev_entry.get("score", "")) + if score is not None: + break - This is a rough approximation based on the CVSS v3 severity bands. - """ - # CVSS vectors don't contain the base score inline; use the vector prefix - # qualifiers as a rough indicator (AV:N + AC:L = higher risk) - if "AV:N" in cvss_vector and "PR:N" in cvss_vector: - return "HIGH" - if "AV:N" in cvss_vector: - return "MEDIUM" - return "LOW" + db_specific = raw.get("database_specific") or {} + if label := db_specific.get("severity"): + label = str(label).upper() + return ("MEDIUM" if label == "MODERATE" else label), score + + if score is not None: + return rating(score), score + return "UNKNOWN", None + + +def _parse_version(value: str) -> Version | None: + try: + return Version(value) + except (InvalidVersion, TypeError): + return None + + +def _normalise(name: str) -> str: + return name.lower().replace("_", "-").replace(".", "-") + + +def _range_events(rng: dict) -> list[tuple[Version, str]]: + """Parseable (version, kind) events of one range, sorted by version.""" + events = [] + for ev in rng.get("events", []): + for kind in ("introduced", "fixed", "last_affected"): + if kind in ev: + ver = Version("0") if ev[kind] == "0" else _parse_version(ev[kind]) + if ver is not None: + events.append((ver, kind)) + return sorted(events, key=lambda e: e[0]) + + +def _pairs_from_events(events: list[tuple[Version, str]]) -> list[tuple[Version, Version | None]]: + """Turn sorted events into (introduced, fixed-or-None) intervals.""" + pairs: list[tuple[Version, Version | None]] = [] + start: Version | None = None + for ver, kind in events: + if kind == "introduced": + start = ver if start is None else start + elif start is not None: + pairs.append((start, ver if kind == "fixed" else None)) + start = None + if start is not None: + pairs.append((start, None)) + return pairs + + +def _ranges_for(raw: dict, package: str) -> list[tuple[Version, Version | None]]: + """(introduced, fixed) pairs for ``package`` from ECOSYSTEM ranges.""" + pairs: list[tuple[Version, Version | None]] = [] + for affected in raw.get("affected", []): + pkg_info = affected.get("package", {}) + if pkg_info.get("ecosystem", "").lower() != "pypi": + continue + if pkg_info.get("name") and _normalise(pkg_info["name"]) != _normalise(package): + continue + for rng in affected.get("ranges", []): + if rng.get("type") in ("ECOSYSTEM", "SEMVER"): # GIT ranges use commit hashes + pairs.extend(_pairs_from_events(_range_events(rng))) + return pairs def _extract_fixed_version(raw: dict, package: str, installed: str) -> str: """ - Scan the OSV ``affected[].ranges`` for a ``FIXED`` event version. + Return the first fixed version for the range that contains ``installed``. - Returns the fixed version string or empty string if not found. + An advisory often lists one fix per release line (for example 4.2.17, + 5.0.10 and 5.1.4). Returning the first "fixed" event, as earlier + versions did, pointed Django 5.1.2 users at 4.2.17. If no range contains + the installed version, the lowest fixed version above it is used. + Returns "" when no fix is known. """ - for affected in raw.get("affected", []): - pkg_info = affected.get("package", {}) - if pkg_info.get("ecosystem", "").lower() != "pypi": - continue - # Walk ranges for a FIXED event - for rng in affected.get("ranges", []): - for event in rng.get("events", []): - if "fixed" in event: - return str(event["fixed"]) - return "" + ranges = _ranges_for(raw, package) + fixes = [fixed for _, fixed in ranges if fixed is not None] + current = _parse_version(installed) + if current is None: + return str(min(fixes)) if fixes else "" + for start, fixed in ranges: + if start <= current and (fixed is None or current < fixed): + return str(fixed) if fixed is not None else "" + later = [f for f in fixes if f > current] + return str(min(later)) if later else "" diff --git a/pydoctor/security/secrets.py b/pydoctor/security/secrets.py new file mode 100644 index 0000000..644c4c7 --- /dev/null +++ b/pydoctor/security/secrets.py @@ -0,0 +1,296 @@ +""" +pydoctor/security/secrets.py +โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +Secret detection for the CI/CD guard. + +Earlier versions only looked at ``.py`` files with four patterns, so a +hardcoded Django ``SECRET_KEY``, a Stripe live key or a committed ``.env`` +file were all reported as "secure". This module: + +- scans the files that are (or are about to be) in version control, of any + text type, not just Python; +- uses provider-specific patterns (high confidence) plus a generic + "secret-looking name assigned a high-entropy literal" rule; +- returns the file, line and a redacted preview for every finding; +- honours ``# pydoctor: ignore`` on the same line. +""" + +from __future__ import annotations + +import math +import re +import subprocess +from collections.abc import Iterator +from dataclasses import dataclass +from pathlib import Path + +from pydoctor.utils.file_utils import _should_skip_dir + +MAX_FILE_BYTES = 1_000_000 +IGNORE_MARKER = re.compile(r"pydoctor:\s*ignore", re.I) + +# Files that are never worth scanning for secrets. +_SKIP_SUFFIXES = { + ".lock", ".png", ".jpg", ".jpeg", ".gif", ".ico", ".svg", ".webp", ".pdf", + ".zip", ".gz", ".tar", ".whl", ".so", ".dll", ".dylib", ".pyc", ".woff", + ".woff2", ".ttf", ".eot", ".mp4", ".mp3", ".min.js", ".map", +} # fmt: skip +_SKIP_NAMES = {"package-lock.json", "yarn.lock", "pnpm-lock.yaml", "poetry.lock", "uv.lock"} + +# Environment files that hold real values. Templates are fine to commit. +_ENV_FILE = re.compile(r"^\.env(\..+)?$") +_ENV_TEMPLATE = re.compile(r"\.(example|sample|template|dist|defaults?)$", re.I) + + +@dataclass(frozen=True) +class Rule: + code: str + label: str + pattern: re.Pattern[str] + group: int = 0 # group holding the secret value + high_confidence: bool = True + + +# Provider formats: specific enough that a match is almost always a real key. +PROVIDER_RULES = [ + Rule("AWS_KEY", "AWS access key ID", re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b")), + Rule("GH_TOKEN", "GitHub token", re.compile(r"\bgh[pousr]_[A-Za-z0-9]{36,}\b")), + Rule("GH_TOKEN", "GitHub token", re.compile(r"\bgithub_pat_[A-Za-z0-9_]{50,}\b")), + Rule("PYPI_TOKEN", "PyPI API token", re.compile(r"\bpypi-[A-Za-z0-9_\-]{50,}")), + Rule("STRIPE_KEY", "Stripe live key", re.compile(r"\b[sr]k_live_[A-Za-z0-9]{20,}\b")), + Rule("ANTHROPIC_KEY", "Anthropic API key", re.compile(r"\bsk-ant-[A-Za-z0-9_\-]{20,}")), + Rule( + "OPENAI_KEY", + "OpenAI API key", + re.compile(r"\bsk-(?:proj|svcacct|admin)-[A-Za-z0-9_\-]{20,}|\bsk-[A-Za-z0-9]{48}\b"), + ), + Rule("SLACK_TOKEN", "Slack token", re.compile(r"\bxox[baprs]-[A-Za-z0-9\-]{10,}")), + Rule("GOOGLE_API_KEY", "Google API key", re.compile(r"\bAIza[0-9A-Za-z_\-]{35}\b")), + Rule( + "PRIVATE_KEY", + "Private key", + re.compile(r"-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----"), + ), + Rule( + "DATABASE_URL", + "Database URL with a password", + re.compile( + r"\b(?:postgres(?:ql)?|mysql|mariadb|mongodb(?:\+srv)?|redis|rediss|amqp)" + r"://[^:\s/@'\"]+:([^@\s'\"]+)@([^:/\s'\"]+)" + ), + group=1, + ), + Rule( + "APP_SECRET_KEY", + "SECRET_KEY setting (Django/Flask)", + re.compile(r"^\s*SECRET_KEY\s*=\s*[rbuRBU]?['\"]([^'\"]{20,})['\"]", re.M), + group=1, + ), +] + +# A secret-looking name assigned a literal value. Lower confidence, so the +# name must END with a secret word (MAX_SECRET_FINDINGS doesn't count), the +# value must be a literal that looks random, and documentation is skipped. +_SECRET_NAME = r"[A-Za-z0-9_.\-]*?(?:secret|passw(?:or)?d|pwd|token|api[_\-]?key|apikey|access[_\-]?key|private[_\-]?key)" +_CODE_ASSIGN = re.compile( + rf"""(?i)\b({_SECRET_NAME})["']?\s*(?::=|=>|:|=)\s*[rbuf]?["']([^"'\s]{{8,}})["']""" +) +_CONFIG_ASSIGN = re.compile( + rf"""(?i)^\s*(?:export\s+)?({_SECRET_NAME})\s*[=:]\s*["']?([^"'\s#]{{8,}})""" +) +GENERIC_RULE = Rule("GENERIC_SECRET", "Hardcoded credential", _CODE_ASSIGN, 2, False) + +_DOC_SUFFIXES = {".md", ".rst", ".txt", ".adoc", ".ipynb"} +# Example and documentation code is full of illustrative credentials. +_DOC_DIRS = {"docs", "doc", "docs_src", "examples", "example", "samples", "tutorial", "tutorials"} +_CONFIG_SUFFIXES = {".ini", ".cfg", ".conf", ".properties", ".yml", ".yaml"} +_CONTEXT_RULES = {"APP_SECRET_KEY", "DATABASE_URL"} # too often illustrative in docs + +_PLACEHOLDER = re.compile( + r"(change.?me|example|your[_\-]|xxx|placeholder|dummy|sample|redacted|todo|\.\.\.|โ€ฆ|" + r"<.*>|\$\{|\{\{|%\(|os\.environ|getenv|env\(|config\(|\*\*\*\*|^none$|^null$|" + r"^true$|^false$|^password$|^secret$|not.?set|replace)", + re.I, +) + + +_LOCAL_HOSTS = {"localhost", "127.0.0.1", "0.0.0.0", "db", "database", "postgres", "mysql", "redis"} + + +@dataclass(frozen=True) +class Finding: + code: str + label: str + path: Path + line: int + preview: str + high_confidence: bool + + +def shannon_entropy(value: str) -> float: + if not value: + return 0.0 + counts = {ch: value.count(ch) for ch in set(value)} + return -sum(c / len(value) * math.log2(c / len(value)) for c in counts.values()) + + +def redact(value: str) -> str: + """Show enough to locate the value without printing the secret.""" + value = value.strip() + if len(value) <= 8: + return "****" + return f"{value[:4]}โ€ฆ{value[-2:]} ({len(value)} chars)" + + +def _looks_like_placeholder(value: str) -> bool: + return bool(_PLACEHOLDER.search(value)) or len(set(value)) <= 3 + + +def _looks_random(value: str) -> bool: + """Heuristic for generic matches: mixed letters and digits, not an identifier.""" + if re.fullmatch(r"[A-Z0-9_]+|[a-z_.\-]+|[\w.\-]+\.(?:py|js|ts|json|txt)", value): + return False # NAME_OF_ENV_VAR, plain words, file names + if value.startswith(("/", "./", "http://", "https://")): + return False + has_letter = any(c.isalpha() for c in value) + has_digit = any(c.isdigit() for c in value) + return has_letter and has_digit and shannon_entropy(value) >= 3.0 + + +# โ”€โ”€ File selection โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + +def _git(root: Path, *args: str) -> list[str] | None: + try: + res = subprocess.run( + ["git", *args], cwd=root, capture_output=True, text=True, check=False, timeout=30 + ) + except (OSError, subprocess.SubprocessError): + return None + if res.returncode != 0: + return None + return [p for p in res.stdout.split("\0") if p] + + +def candidate_files(root: Path, fallback: list[Path]) -> tuple[list[Path], set[Path], bool]: + """ + Files to scan, the subset already committed, and whether git was used. + + In a git repository this is every tracked file plus untracked files that + aren't ignored (they're one ``git add`` away from being committed). + Outside git, ``fallback`` (the project's Python files) plus config-like + files found while walking the tree, excluding ``.env`` files, since a + local ``.env`` outside version control is normal. + """ + tracked = _git(root, "ls-files", "-z") + if tracked is not None: + untracked = _git(root, "ls-files", "-z", "--others", "--exclude-standard") or [] + tracked_paths = {root / p for p in tracked} + files = sorted(tracked_paths | {root / p for p in untracked}) + return [f for f in files if f.is_file()], tracked_paths, True + + found: set[Path] = set(fallback) + for path in _walk(root): + if path.suffix in {".py", ".cfg", ".ini", ".toml", ".yml", ".yaml", ".json", ".sh"}: + found.add(path) + return sorted(found), set(), False + + +def _walk(root: Path) -> Iterator[Path]: + try: + entries = list(root.iterdir()) + except OSError: + return + for entry in entries: + if entry.is_dir(): + if not _should_skip_dir(entry) and entry.name != ".git": + yield from _walk(entry) + elif entry.is_file(): + yield entry + + +def is_env_file(path: Path) -> bool: + return bool(_ENV_FILE.match(path.name)) and not _ENV_TEMPLATE.search(path.name) + + +def _readable_text(path: Path) -> str | None: + name = path.name.lower() + if name in _SKIP_NAMES or any(name.endswith(s) for s in _SKIP_SUFFIXES): + return None + try: + if path.stat().st_size > MAX_FILE_BYTES: + return None + data = path.read_bytes() + except OSError: + return None + if b"\0" in data[:8192]: + return None # binary + return data.decode("utf-8", errors="replace") + + +# โ”€โ”€ Scanning โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + +class _Collector: + """Collects findings for one file: one per line, honouring ignore markers.""" + + def __init__(self, path: Path, lines: list[str]) -> None: + self.path, self.lines = path, lines + self.findings: list[Finding] = [] + self.flagged: set[int] = set() + + def add(self, rule: Rule, line_no: int, value: str) -> None: + line = self.lines[line_no - 1] if 0 < line_no <= len(self.lines) else "" + if line_no in self.flagged or IGNORE_MARKER.search(line) or _looks_like_placeholder(value): + return + self.flagged.add(line_no) + self.findings.append( + Finding(rule.code, rule.label, self.path, line_no, redact(value), rule.high_confidence) + ) + + +def _provider_pass(out: _Collector, text: str, is_doc: bool) -> None: + for rule in PROVIDER_RULES: + if is_doc and rule.code in _CONTEXT_RULES: + continue + for m in rule.pattern.finditer(text): + if rule.code == "DATABASE_URL" and m.group(2).lower() in _LOCAL_HOSTS: + continue # local/dev database (docker-compose style); not a leak + out.add(rule, text.count("\n", 0, m.start()) + 1, m.group(rule.group)) + + +def _generic_pass(out: _Collector, is_config: bool) -> None: + for line_no, line in enumerate(out.lines, start=1): + if line_no in out.flagged or line.lstrip().startswith(("#", "//")): + continue + m = _CONFIG_ASSIGN.match(line) if is_config else None + m = m or _CODE_ASSIGN.search(line) + if m and "hash" not in m.group(1).lower() and _looks_random(m.group(2)): + out.add(GENERIC_RULE, line_no, m.group(2)) + + +def scan_text(path: Path, text: str) -> list[Finding]: + """Find secrets in one file's text.""" + suffix = path.suffix.lower() + is_doc = suffix in _DOC_SUFFIXES or bool(_DOC_DIRS.intersection(p.lower() for p in path.parts)) + is_config = path.name.startswith(".env") or suffix in _CONFIG_SUFFIXES + is_workflow = ".github/workflows/" in path.as_posix() or path.name == ".gitlab-ci.yml" + out = _Collector(path, text.splitlines()) + _provider_pass(out, text, is_doc) + # Docs are full of examples; workflows get their own CI_CLEARTEXT_ENV check. + if not (is_doc or is_workflow): + _generic_pass(out, is_config) + return out.findings + + +def scan_files(files: list[Path], skip_content) -> list[Finding]: + """Scan ``files``; ``skip_content(path)`` excludes e.g. test fixtures.""" + findings: list[Finding] = [] + for path in files: + if skip_content(path): + continue + text = _readable_text(path) + if text is None: + continue + findings.extend(scan_text(path, text)) + return findings diff --git a/pydoctor/utils/env_probe.py b/pydoctor/utils/env_probe.py new file mode 100644 index 0000000..59db5b0 --- /dev/null +++ b/pydoctor/utils/env_probe.py @@ -0,0 +1,145 @@ +""" +pydoctor/utils/env_probe.py +โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +Read facts about the *project's* Python environment. + +PyDoctor often runs from a different interpreter than the project it scans +(pipx, ``uv tool``, a global install). Anything that asks PyDoctor's own +``sys`` module, or assumes ``pip`` is installed in the project, then +describes the wrong environment. uv-created environments don't include pip +at all. + +This module runs a small, stdlib-only script inside the project's +interpreter and returns what it reports: version, virtualenv status, +installed distributions with their requirements, marker environment, and +pip version (if pip is present). +""" + +from __future__ import annotations + +import json +import subprocess +import tempfile +from dataclasses import dataclass, field + +# Runs inside the project's interpreter. Must stay stdlib-only and work on +# every Python version PyDoctor supports scanning. +_PROBE_SCRIPT = r""" +import json, os, platform, sys +import importlib.metadata as md + +def _fmt(info): + v = "%d.%d.%d" % (info.major, info.minor, info.micro) + if info.releaselevel != "final": + v += info.releaselevel[0] + str(info.serial) + return v + +out = { + "executable": sys.executable, + "version": list(sys.version_info[:3]), + "prefix": sys.prefix, + "base_prefix": getattr(sys, "base_prefix", sys.prefix), + "markers": { + "implementation_name": sys.implementation.name, + "implementation_version": _fmt(sys.implementation.version), + "os_name": os.name, + "platform_machine": platform.machine(), + "platform_release": platform.release(), + "platform_system": platform.system(), + "platform_version": platform.version(), + "python_full_version": platform.python_version(), + "platform_python_implementation": platform.python_implementation(), + "python_version": ".".join(platform.python_version_tuple()[:2]), + "sys_platform": sys.platform, + }, +} +dists = {} +for d in md.distributions(): + try: + name = d.metadata["Name"] + except Exception: + name = None + if not name or name in dists: + continue + dists[name] = {"version": d.version, "requires": list(d.requires or [])} +out["distributions"] = dists +try: + out["pip"] = md.version("pip") +except Exception: + out["pip"] = None +print(json.dumps(out)) +""" + + +@dataclass +class EnvProbe: + """Facts reported by the project's own interpreter.""" + + executable: str + version: tuple[int, int, int] + prefix: str + base_prefix: str + markers: dict[str, str] = field(default_factory=dict) + distributions: dict[str, dict] = field(default_factory=dict) + pip_version: str | None = None + + @property + def in_virtualenv(self) -> bool: + return self.prefix != self.base_prefix + + @property + def packages(self) -> dict[str, str]: + """Normalised distribution name โ†’ installed version.""" + return {normalise_name(n): d["version"] for n, d in self.distributions.items()} + + +def normalise_name(name: str) -> str: + """PEP 503-style normalisation used throughout PyDoctor.""" + return name.lower().replace("_", "-").replace(".", "-") + + +def probe_environment(python: str, timeout: int = 60) -> tuple[EnvProbe | None, str | None]: + """ + Run the probe in ``python``. + + Returns ``(probe, None)`` on success or ``(None, reason)`` on failure. + The probe runs from an empty temporary directory so files in the + project (for example a local ``json.py``) can't shadow the stdlib. + """ + try: + with tempfile.TemporaryDirectory(prefix="pydoctor-probe-") as cwd: + result = subprocess.run( + [python, "-c", _PROBE_SCRIPT], + capture_output=True, + text=True, + timeout=timeout, + cwd=cwd, + ) + except FileNotFoundError: + return None, f"interpreter not found: {python}" + except subprocess.TimeoutExpired: + return None, f"interpreter did not respond within {timeout}s: {python}" + except OSError as exc: + return None, f"could not run {python}: {exc}" + + if result.returncode != 0: + detail = (result.stderr or "").strip().splitlines() + return None, f"{python} exited with code {result.returncode}" + ( + f": {detail[-1]}" if detail else "" + ) + try: + data = json.loads(result.stdout.strip().splitlines()[-1]) + return ( + EnvProbe( + executable=data["executable"], + version=tuple(data["version"]), + prefix=data["prefix"], + base_prefix=data["base_prefix"], + markers=data.get("markers", {}), + distributions=data.get("distributions", {}), + pip_version=data.get("pip"), + ), + None, + ) + except (ValueError, KeyError, IndexError) as exc: + return None, f"unexpected output from {python}: {exc}" diff --git a/pydoctor/utils/file_utils.py b/pydoctor/utils/file_utils.py index acb3400..5dd2038 100644 --- a/pydoctor/utils/file_utils.py +++ b/pydoctor/utils/file_utils.py @@ -88,14 +88,16 @@ def is_test_file(path: Path, root: Path) -> bool: - Files inside directories named tests, test, or testing """ name = path.name.lower() - if name.startswith("test_") or name == "conftest.py": + if name.startswith("test_") or name == "conftest.py" or name.endswith("_test.py"): + return True + if ".test." in name or ".spec." in name: # JS/TS test files return True try: parts = path.relative_to(root).parts for part in parts: p = part.lower() - if p in ("tests", "test", "testing") or p.startswith("test"): + if p in ("tests", "test", "testing", "__tests__", "fixtures") or p.startswith("test"): return True except ValueError: pass diff --git a/pydoctor/utils/parser_utils.py b/pydoctor/utils/parser_utils.py index 5d7d684..38c32f9 100644 --- a/pydoctor/utils/parser_utils.py +++ b/pydoctor/utils/parser_utils.py @@ -76,17 +76,9 @@ def extract_imports_from_project(python_files: list[Path]) -> set[str]: _MODULE_STRING = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$") -def extract_string_module_refs(python_files: list[Path]) -> set[str]: - """ - Collect top-level names from string constants that look like module paths. - - Frameworks load many dependencies by name rather than by ``import``: - Django's ``INSTALLED_APPS = ["corsheaders"]``, ``MIDDLEWARE = ["whitenoise.middleware..."]`` - and ``"BACKEND": "django_redis.cache.RedisCache"`` are all plain strings. - Callers should only treat a returned name as a dependency reference when it - matches the import name of an installed distribution. - """ - names: set[str] = set() +def extract_string_constants(python_files: list[Path], max_len: int = 200) -> set[str]: + """All short string constants in the project's Python files (stripped).""" + values: set[str] = set() for fpath in python_files: source = read_file_safe(fpath) if source is None: @@ -98,9 +90,27 @@ def extract_string_module_refs(python_files: list[Path]) -> set[str]: for node in ast.walk(tree): if isinstance(node, ast.Constant) and isinstance(node.value, str): value = node.value.strip() - if 0 < len(value) <= 200 and _MODULE_STRING.match(value): - names.add(value.split(".", 1)[0]) - return names + if 0 < len(value) <= max_len: + values.add(value) + return values + + +def module_refs_from_strings(strings: set[str]) -> set[str]: + """ + Top-level names from strings that look like module paths. + + Frameworks load many dependencies by name rather than by ``import``: + Django's ``INSTALLED_APPS = ["corsheaders"]``, ``MIDDLEWARE = ["whitenoise.middleware..."]`` + and ``"BACKEND": "django_redis.cache.RedisCache"`` are all plain strings. + Callers should only treat a returned name as a dependency reference when it + matches the import name of an installed distribution. + """ + return {v.split(".", 1)[0] for v in strings if _MODULE_STRING.match(v)} + + +def extract_string_module_refs(python_files: list[Path]) -> set[str]: + """Backwards-compatible wrapper: module refs found in ``python_files``.""" + return module_refs_from_strings(extract_string_constants(python_files)) # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ diff --git a/pydoctor/utils/pip_utils.py b/pydoctor/utils/pip_utils.py index 8b1fc0a..734d530 100644 --- a/pydoctor/utils/pip_utils.py +++ b/pydoctor/utils/pip_utils.py @@ -43,30 +43,39 @@ def get_installed_packages(python_executable: str | None = None) -> dict[str, st return {} -def get_outdated_packages(python_executable: str | None = None) -> list[dict]: +def get_outdated_packages(python_executable: str | None = None) -> list[dict] | None: """ - Return a list of outdated packages as reported by ``pip list --outdated``. + Return outdated packages as reported by ``pip list --outdated``. - Returns - ------- - list[dict] - Empty list when pip fails or output cannot be parsed. + Returns ``None`` (not an empty list) when pip fails, so callers can tell + "nothing is outdated" apart from "couldn't check". Raises + ``subprocess.TimeoutExpired`` on timeout. """ - import subprocess + result = run_pip_command( + ["list", "--outdated", "--format=json"], python_executable=python_executable, timeout=30 + ) + return _parse_outdated(result) + + +def get_outdated_packages_uv(uv: str, python_executable: str) -> list[dict] | None: + """Same as ``get_outdated_packages`` for environments without pip, using uv.""" + from pydoctor.utils.subprocess_utils import run_command + + result = run_command( + [uv, "pip", "list", "--outdated", "--format", "json", "--python", python_executable], + timeout=60, + ) + return _parse_outdated(result) + +def _parse_outdated(result) -> list[dict] | None: + if result.returncode != 0: + return None try: - result = run_pip_command( - ["list", "--outdated", "--format=json"], python_executable=python_executable, timeout=30 - ) - if result.returncode != 0: - return [] - return json.loads(result.stdout) + data = json.loads(result.stdout or "[]") except json.JSONDecodeError: - return [] - except subprocess.TimeoutExpired: - # We raise TimeoutExpired up so the scanner can report it beautifully as an INFO issue - # rather than just displaying "All packages are up to date" (false positive). - raise + return None + return data if isinstance(data, list) else None # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @@ -228,22 +237,24 @@ def remove_from_requirements_file(req_path: Path, package: str) -> bool: def get_dependency_graph(python_executable: str | None = None) -> list[dict]: """ - Return the dependency tree for the current or specified environment. - Uses ``pipdeptree --json-tree`` if available, otherwise returns []. + Return the dependency tree of the given (or current) environment. + + pipdeptree is a PyDoctor dependency, so it is installed next to PyDoctor, + not necessarily in the project. It is run from PyDoctor's interpreter and + pointed at the project with ``--python``, which also works for + environments without pip (uv). Returns [] if it can't run. """ import subprocess + cmd = [sys.executable, "-m", "pipdeptree", "--json-tree"] + if python_executable and python_executable != sys.executable: + cmd[3:3] = ["--python", python_executable] try: - py = python_executable or sys.executable - result = subprocess.run( - [py, "-m", "pipdeptree", "--json-tree"], - capture_output=True, - text=True, - check=False, - ) + result = subprocess.run(cmd, capture_output=True, text=True, check=False, timeout=120) if result.returncode == 0: - return json.loads(result.stdout) - except (subprocess.SubprocessError, json.JSONDecodeError, ImportError): + data = json.loads(result.stdout) + return data if isinstance(data, list) else [] + except (subprocess.SubprocessError, json.JSONDecodeError, OSError): pass return [] diff --git a/pyproject.toml b/pyproject.toml index 8c2e9ad..ffa8b5b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "pydoctor-cli" -version = "2.1.0" +version = "2.2.0" description = "Premium Python environment diagnostic CLI โ€” your project's personal physician." readme = "README.md" license = { file = "LICENSE" } @@ -62,9 +62,9 @@ dev = [ pydoctor = "pydoctor.cli.main:main" [project.urls] -"Homepage" = "https://pydoctor.vercel.app" +"Homepage" = "https://pydoctor-docs.thally.app" "Repository" = "https://github.com/iamAgbaCoder/pydoctor-cli" -"Documentation" = "https://pydoctor.vercel.app/docs" +"Documentation" = "https://pydoctor-docs.thally.app" "Bug Tracker" = "https://github.com/iamAgbaCoder/pydoctor-cli/issues" "Changelog" = "https://github.com/iamAgbaCoder/pydoctor-cli/releases" diff --git a/tests/test_ci_scanner.py b/tests/test_ci_scanner.py index 70c23d1..b0544f6 100644 --- a/tests/test_ci_scanner.py +++ b/tests/test_ci_scanner.py @@ -1,39 +1,196 @@ +""" +tests/test_ci_scanner.py +โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +Secret and workflow detection. Each "should not flag" case below is a real +line from a popular open-source project that an earlier draft flagged. +""" + +from __future__ import annotations + +import subprocess +from pathlib import Path + +import pytest + from pydoctor.core.project import ProjectContext from pydoctor.scanners.ci_scanner import scan +from pydoctor.security.secrets import scan_text + + +def _codes(issues): + return sorted(i.code for i in issues if i.severity != "ok") + + +def _ctx(root: Path, files: list[Path] | None = None) -> ProjectContext: + return ProjectContext(root=root, python_files=files or []) + + +def _git(root: Path, *args: str) -> None: + subprocess.run(["git", *args], cwd=root, check=True, capture_output=True) + + +# Fake credentials are assembled at runtime, so this file never contains a +# string in a real provider's format. Secret scanners (GitHub push +# protection included) rightly reject such strings even in tests. +FAKE_AWS = "AK" + "IA" + "1234567890ABCDEF" +FAKE_STRIPE = "sk_" + "live_" + "51HxYzAbCdEfGhIjKlMnOpQrStUvWx" +FAKE_OPENAI = "sk-" + "proj-" + "AbCdEf1234567890AbCdEf1234567890" +FAKE_ANTHROPIC = "sk-" + "ant-" + "api03-AbCdEf1234567890AbCdEf" +FAKE_GITHUB = "gh" + "p_" + "a1B2c3D4e5" * 4 +FAKE_KEY_HEADER = "-----BEGIN OPENSSH " + "PRIVATE KEY-----" + + +# โ”€โ”€ Secrets โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def test_scan_for_secrets(tmp_path): - # Create fake project with a secret secret_file = tmp_path / "config.py" - secret_file.write_text('AWS_SECRET_KEY = "AKIA1234567890ABCDEF"') + secret_file.write_text(f'AWS_SECRET_KEY = "{FAKE_AWS}"') + issues = scan(_ctx(tmp_path, [secret_file])) + finding = next(i for i in issues if i.code == "SECRET_EXPOSED_AWS_KEY") + assert finding.severity == "critical" + assert finding.extra["line"] == 1 + assert FAKE_AWS not in finding.description # redacted + + +@pytest.mark.parametrize( + "line,code", + [ + ("SECRET_KEY = 'django-insecure-9x!q@7k#z$2m^p&w*r(t)y_u+i=o-0v'", "APP_SECRET_KEY"), + (f'STRIPE = "{FAKE_STRIPE}"', "STRIPE_KEY"), + (f'KEY = "{FAKE_OPENAI}"', "OPENAI_KEY"), + (f'KEY = "{FAKE_ANTHROPIC}"', "ANTHROPIC_KEY"), + (f'T = "{FAKE_GITHUB}"', "GH_TOKEN"), + ('URL = "postgres://admin:Sup3rS3cret@db.example.com/prod"', "DATABASE_URL"), + (FAKE_KEY_HEADER, "PRIVATE_KEY"), + ('db_password = "Xk82mPq0vL3z"', "GENERIC_SECRET"), + ], +) +def test_detects_common_secrets(tmp_path, line, code): + assert [f.code for f in scan_text(tmp_path / "settings.py", line)] == [code] + + +@pytest.mark.parametrize( + "line", + [ + " if len(findings) > MAX_SECRET_FINDINGS:", # name merely contains SECRET + " sessionSecret: 'THALLY_READER_SESSION_SECRET',", # value is an env var name + " username, password = get_auth_from_url(proxy)", + '__author_email__ = "me@kennethreitz.org"', + "SECRET_KEY = config('SECRET_KEY')", + 'API_KEY = "your-api-key-here"', + 'KEY = "AKIAIOSFODNN7EXAMPLE"', # AWS's documented example key + 'URL = "postgres://postgres:postgres@localhost:5432/app"', # local dev database + '"hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w"', + f'token = "{FAKE_STRIPE}" # pydoctor: ignore', + ], +) +def test_does_not_flag_lookalikes(tmp_path, line): + assert scan_text(tmp_path / "app.py", line) == [] - ctx = ProjectContext(root=tmp_path, python_files=[secret_file]) - issues = scan(ctx) - # Filter out the "OK" issue if it exists (though usually it shouldn't if there are findings) - findings = [i for i in issues if i.severity != "ok"] +def test_documentation_only_reports_provider_keys(tmp_path): + doc = "Set ``SECRET_KEY = '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc'``\n" + doc += 'password = "Xk82mPq0vL3z"\n' + assert scan_text(tmp_path / "docs" / "config.rst", doc) == [] + real = f'STRIPE = "{FAKE_STRIPE}"' + assert [f.code for f in scan_text(tmp_path / "README.md", real)] == ["STRIPE_KEY"] - assert len(findings) >= 1 - assert any("Secret Exposed" in i.title for i in findings) + +def test_env_style_config_values(tmp_path): + text = f"DEBUG=1\nOPENAI_API_KEY={FAKE_OPENAI}\nAPP_TOKEN=9f8e7d6c5b4a3f2e\n" + codes = [f.code for f in scan_text(tmp_path / ".env", text)] + assert codes == ["OPENAI_KEY", "GENERIC_SECRET"] + + +# โ”€โ”€ .env files under git โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + +@pytest.fixture +def repo(tmp_path): + _git(tmp_path, "init", "-q") + return tmp_path + + +def test_committed_env_file_is_flagged(repo): + (repo / ".env").write_text("DEBUG=1\n") + _git(repo, "add", ".env") + assert "CI_ENV_FILE_COMMITTED" in _codes(scan(_ctx(repo))) + + +def test_unignored_env_file_is_a_warning(repo): + (repo / ".env").write_text("DEBUG=1\n") + issues = scan(_ctx(repo)) + finding = next(i for i in issues if i.code == "CI_ENV_FILE_NOT_IGNORED") + assert finding.severity == "warning" + + +def test_ignored_env_template_and_test_fixture_are_fine(repo): + (repo / ".gitignore").write_text(".env\n") + (repo / ".env").write_text(f"STRIPE={FAKE_STRIPE}\n") + (repo / ".env.example").write_text("STRIPE=" + "sk_" + "live_your_key_here\n") + (repo / "tests").mkdir() + (repo / "tests" / ".env").write_text("FOO=bar\n") + _git(repo, "add", ".gitignore", ".env.example") + _git(repo, "add", "-f", "tests/.env") # a committed test fixture + assert _codes(scan(_ctx(repo))) == [] + + +# โ”€โ”€ Workflows โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + +def _workflow(root: Path, text: str) -> None: + wf = root / ".github" / "workflows" + wf.mkdir(parents=True) + (wf / "ci.yml").write_text(text) def test_scan_workflows(tmp_path): - # Create a GitHub action workflow with unpinned version - workflow_dir = tmp_path / ".github" / "workflows" - workflow_dir.mkdir(parents=True) - workflow_file = workflow_dir / "main.yml" - workflow_file.write_text("uses: actions/checkout@main") + _workflow( + tmp_path, " - uses: actions/checkout@main\n - uses: actions/setup-python@v5\n" + ) + issues = [i for i in scan(_ctx(tmp_path)) if i.code == "CI_UNPINNED_ACTION"] + assert len(issues) == 1 and issues[0].extra["line"] == 1 - ctx = ProjectContext(root=tmp_path, python_files=[]) - issues = scan(ctx) - findings = [i for i in issues if i.severity != "ok"] - assert any("Unpinned GitHub Action" in i.title for i in findings) +def test_pwn_request_and_script_injection(tmp_path): + _workflow( + tmp_path, + """on: pull_request_target +permissions: write-all +jobs: + build: + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + - run: | + echo "Building" + echo "${{ github.event.pull_request.title }}" + - name: safe + env: + TITLE: ${{ github.event.pull_request.title }} + run: echo "$TITLE" +""", + ) + codes = _codes(scan(_ctx(tmp_path))) + assert codes == [ + "CI_BROAD_PERMISSIONS", + "CI_PULL_REQUEST_TARGET_CHECKOUT", + "CI_SCRIPT_INJECTION", + ] -def test_scan_clean_project(tmp_path): - ctx = ProjectContext(root=tmp_path, python_files=[]) - issues = scan(ctx) +def test_ci_service_passwords_are_not_flagged(tmp_path): + _workflow( + tmp_path, + "services:\n postgres:\n env:\n POSTGRES_PASSWORD: postgres\n" + " API_TOKEN: 7f3k9q2m8x1v5b6n\n", + ) + assert _codes(scan(_ctx(tmp_path))) == ["CI_CLEARTEXT_ENV"] + +def test_scan_clean_project(tmp_path): + issues = scan(_ctx(tmp_path)) assert len(issues) == 1 assert issues[0].code == "CI_HEALTHY" diff --git a/tests/test_cli_ux.py b/tests/test_cli_ux.py index 5eda743..c7eaca3 100644 --- a/tests/test_cli_ux.py +++ b/tests/test_cli_ux.py @@ -30,9 +30,43 @@ def test_diagnose_prompt_no_venv(tmp_path): with patch("pydoctor.cli.main.ProjectContext.from_path") as mock_from_path: mock_ctx = MagicMock() mock_ctx.in_virtualenv = False + mock_ctx.env_error = None mock_from_path.return_value = mock_ctx - # Test that it asks for global packages when no venv is found - result = runner.invoke(app, ["diagnose", "--path", str(tmp_path)], input="n\n") + # Test that it asks for global packages when no venv is found (interactive run) + with patch("pydoctor.cli.main._is_interactive", return_value=True): + result = runner.invoke(app, ["diagnose", "--path", str(tmp_path)], input="n\n") assert "No virtual environment detected" in result.stdout assert "Cancelled" in result.stdout + + +def test_diagnose_never_prompts_when_not_interactive(tmp_path): + """CI and piped runs must not block on the no-venv prompt.""" + with ( + patch("pydoctor.cli.main.ProjectContext.from_path") as mock_from_path, + patch("pydoctor.cli.main._run_scan") as mock_scan, + patch("pydoctor.cli.main._output"), + patch("pydoctor.cli.main._exit_code", return_value=0), + patch("pydoctor.cli.main.Confirm.ask") as ask, + ): + mock_ctx = MagicMock() + mock_ctx.in_virtualenv = False + mock_ctx.env_error = None + mock_ctx.python_executable = "/usr/bin/python3" + mock_ctx.python_source = "`python3` on PATH" + mock_from_path.return_value = mock_ctx + result = runner.invoke(app, ["diagnose", "--path", str(tmp_path)]) + assert "No virtual environment detected" in result.stdout + ask.assert_not_called() + mock_scan.assert_called_once() + + +def test_github_says_remote_repos_are_not_supported(tmp_path): + with ( + patch("pydoctor.cli.main._run_scan") as scan, + patch("pydoctor.cli.main._output"), + patch("pydoctor.cli.main._exit_code", return_value=0), + ): + result = runner.invoke(app, ["github", "https://github.com/x/y", "--path", str(tmp_path)]) + assert "isn't supported yet" in result.output + scan.assert_called_once() diff --git a/tests/test_env_scanner.py b/tests/test_env_scanner.py index b2fd0a6..18b7369 100644 --- a/tests/test_env_scanner.py +++ b/tests/test_env_scanner.py @@ -83,17 +83,30 @@ def test_no_venv_warning(self, tmp_path): class TestPipVersionCheck: - def test_pip_missing(self): - with patch("pydoctor.scanners.env_scanner.get_pip_version", return_value=None): - issues = env_scanner._check_pip_version() - assert any(i.code == "ENV_PIP_MISSING" for i in issues) - - def test_pip_outdated(self): - with patch("pydoctor.scanners.env_scanner.get_pip_version", return_value="20.0.0"): - issues = env_scanner._check_pip_version() - assert any(i.code == "ENV_PIP_OUTDATED" for i in issues) - - def test_pip_ok(self): - with patch("pydoctor.scanners.env_scanner.get_pip_version", return_value="23.1.0"): - issues = env_scanner._check_pip_version() - assert any(i.code == "ENV_PIP_OK" for i in issues) + """pip is checked in the project environment (ctx.pip_version), not PyDoctor's.""" + + def test_pip_missing_without_uv(self, tmp_path): + ctx = _make_ctx(tmp_path) + ctx.pip_version = None + with patch("shutil.which", return_value=None): + issues = env_scanner._check_pip_version(ctx) + assert [i.code for i in issues] == ["ENV_PIP_MISSING"] + assert issues[0].severity == Severity.WARNING + + def test_pip_absent_in_uv_environment_is_info(self, tmp_path): + ctx = _make_ctx(tmp_path) + ctx.pip_version = None + ctx.is_uv = True + issues = env_scanner._check_pip_version(ctx) + assert [i.code for i in issues] == ["ENV_PIP_ABSENT_UV"] + assert issues[0].severity == Severity.INFO + + def test_pip_outdated(self, tmp_path): + ctx = _make_ctx(tmp_path) + ctx.pip_version = "20.0.0" + assert any(i.code == "ENV_PIP_OUTDATED" for i in env_scanner._check_pip_version(ctx)) + + def test_pip_ok(self, tmp_path): + ctx = _make_ctx(tmp_path) + ctx.pip_version = "23.1.0" + assert any(i.code == "ENV_PIP_OK" for i in env_scanner._check_pip_version(ctx)) diff --git a/tests/test_environment.py b/tests/test_environment.py new file mode 100644 index 0000000..a750c1c --- /dev/null +++ b/tests/test_environment.py @@ -0,0 +1,197 @@ +""" +tests/test_environment.py +โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +The scanned environment must be the project's, and a scan that can't read +it must say so instead of reporting a clean result. +""" + +from __future__ import annotations + +import os +import sys +from pathlib import Path +from unittest.mock import patch + +import pytest + +from pydoctor.config.settings import Severity +from pydoctor.core.analyzer import Analyzer, context_issues +from pydoctor.core.project import ProjectContext +from pydoctor.scanners import dependency_scanner, outdated_package_scanner +from pydoctor.utils.env_probe import probe_environment + +# โ”€โ”€ Probe โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + +def test_probe_reads_the_target_interpreter(): + probe, error = probe_environment(sys.executable) + assert error is None and probe is not None + assert probe.version == tuple(sys.version_info[:3]) + assert "pytest" in probe.packages + assert probe.markers["python_version"] == f"{sys.version_info[0]}.{sys.version_info[1]}" + + +def test_probe_reports_virtualenv_from_the_target_not_from_pydoctor(): + # The test suite runs inside a virtualenv; its base interpreter is not one. + ver = f"{sys.version_info[0]}.{sys.version_info[1]}" + candidates = [ + Path(sys.base_prefix) / "bin" / f"python{ver}", + Path(sys.base_prefix) / "python.exe", + ] + base = next((str(p) for p in candidates if p.exists()), None) + if sys.prefix == sys.base_prefix or not base: + pytest.skip("needs to run inside a virtualenv with a locatable base interpreter") + venv_probe, _ = probe_environment(sys.executable) + base_probe, _ = probe_environment(base) + assert venv_probe is not None and venv_probe.in_virtualenv is True + assert base_probe is not None and base_probe.in_virtualenv is False + + +def test_probe_failure_is_reported_not_swallowed(): + probe, error = probe_environment("/definitely/not/python") + assert probe is None + assert "not found" in error + + +def test_probe_ignores_project_files_that_shadow_the_stdlib(tmp_path, monkeypatch): + (tmp_path / "json.py").write_text("raise SystemExit('shadowed')\n", encoding="utf-8") + monkeypatch.chdir(tmp_path) + probe, error = probe_environment(sys.executable) + assert error is None and probe is not None + + +# โ”€โ”€ Interpreter discovery โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + +def _fake_venv(base: Path) -> Path: + py = base / ("Scripts/python.exe" if os.name == "nt" else "bin/python") + py.parent.mkdir(parents=True) + py.write_text("", encoding="utf-8") + return py + + +def test_explicit_python_wins(tmp_path): + _fake_venv(tmp_path / ".venv") + py, source = ProjectContext._find_project_python(tmp_path, {}, explicit=sys.executable) + assert py == sys.executable and source == "--python option" + + +def test_project_venv_is_found_and_labelled(tmp_path, monkeypatch): + monkeypatch.delenv("VIRTUAL_ENV", raising=False) + expected = _fake_venv(tmp_path / ".venv") + py, source = ProjectContext._find_project_python(tmp_path, {}) + assert py == str(expected) + assert source == ".venv/ in the project" + + +def test_parent_venv_is_labelled_as_parent(tmp_path, monkeypatch): + monkeypatch.delenv("VIRTUAL_ENV", raising=False) + _fake_venv(tmp_path / ".venv") + (tmp_path / "backend").mkdir() + _, source = ProjectContext._find_project_python(tmp_path / "backend", {}) + assert "parent directory" in source + + +def test_sibling_folders_named_like_venvs_are_not_used(tmp_path, monkeypatch): + """2.1.0 accepted ../test, ../dev, ../prod etc. from the parent directory.""" + monkeypatch.delenv("VIRTUAL_ENV", raising=False) + _fake_venv(tmp_path / "test") + (tmp_path / "web").mkdir() + with patch("shutil.which", return_value="/usr/bin/python3"): + py, source = ProjectContext._find_project_python(tmp_path / "web", {}) + assert py == "/usr/bin/python3" + assert "PATH" in source + + +# โ”€โ”€ Failing loudly โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + +def test_unreadable_environment_fails_the_scan(tmp_project): + report = Analyzer(project_path=str(tmp_project), python="/definitely/not/python").run() + codes = [i.code for i in report.issues] + assert "ENV_PACKAGES_UNAVAILABLE" in codes + assert report.has_errors + # No scanner may claim a clean result for an environment it never saw. + for clean in ("SEC_NO_VULNS", "DEP_NO_CONFLICTS", "PKG_ALL_UP_TO_DATE", "UNUSED_NONE_FOUND"): + assert clean not in codes + + +def test_ci_only_scan_does_not_need_the_environment(tmp_project): + report = Analyzer( + project_path=str(tmp_project), scanners=["ci"], python="/definitely/not/python" + ).run() + assert "ENV_PACKAGES_UNAVAILABLE" not in [i.code for i in report.issues] + + +def test_wrong_interpreter_is_flagged(tmp_path): + ctx = ProjectContext( + root=tmp_path, + declared_deps={"django": "", "requests": ""}, + installed_packages={"pip": "24.0"}, + python_source="`python3` on PATH (no project virtualenv found)", + ) + issues = context_issues(ctx, ["security"]) + assert [i.code for i in issues] == ["ENV_DEPS_NOT_INSTALLED"] + assert issues[0].severity == Severity.WARNING + + +# โ”€โ”€ Checks that work without pip โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + +def _ctx_with_dists(tmp_path, dists): + return ProjectContext( + root=tmp_path, + distributions=dists, + installed_packages={k.lower(): v["version"] for k, v in dists.items()}, + marker_env={"python_version": "3.11", "sys_platform": "linux", "os_name": "posix"}, + pip_version=None, + ) + + +def test_metadata_check_finds_conflicts_and_missing_packages(tmp_path): + ctx = _ctx_with_dists( + tmp_path, + { + "requests": { + "version": "2.31.0", + "requires": [ + "urllib3<3,>=1.21.1", + "idna<4,>=2.5", + "PySocks!=1.5.7; extra == 'socks'", + ], + }, + "urllib3": {"version": "3.0.0", "requires": []}, + "legacy": {"version": "1.0", "requires": ["tomli; python_version < '3.11'"]}, + }, + ) + issues = dependency_scanner.scan(ctx) + codes = sorted(i.code for i in issues) + assert codes == ["DEP_MISSING", "DEP_VERSION_CONFLICT"] + missing = next(i for i in issues if i.code == "DEP_MISSING") + assert missing.extra["missing_package"] == "idna" # extras and false markers are skipped + + +def test_outdated_check_failure_is_not_reported_as_up_to_date(tmp_path): + ctx = ProjectContext(root=tmp_path, pip_version="24.0") + with patch.object(outdated_package_scanner, "get_outdated_packages", return_value=None): + issues = outdated_package_scanner.scan(ctx) + assert [i.code for i in issues] == ["PKG_OUTDATED_UNAVAILABLE"] + + +def test_outdated_check_without_pip_or_uv_is_skipped(tmp_path): + ctx = _ctx_with_dists(tmp_path, {"six": {"version": "1.16.0", "requires": []}}) + with patch("shutil.which", return_value=None): + issues = outdated_package_scanner.scan(ctx) + assert [i.code for i in issues] == ["PKG_OUTDATED_UNAVAILABLE"] + + +def test_outdated_check_uses_uv_when_pip_is_absent(tmp_path): + ctx = _ctx_with_dists(tmp_path, {"six": {"version": "1.16.0", "requires": []}}) + rows = [{"name": "six", "version": "1.16.0", "latest_version": "1.17.0"}] + with ( + patch("shutil.which", return_value="/usr/bin/uv"), + patch.object(outdated_package_scanner, "get_outdated_packages_uv", return_value=rows) as uv, + ): + issues = outdated_package_scanner.scan(ctx) + uv.assert_called_once() + assert [i.code for i in issues] == ["PKG_OUTDATED"] diff --git a/tests/test_osv_parsing.py b/tests/test_osv_parsing.py new file mode 100644 index 0000000..b15c30a --- /dev/null +++ b/tests/test_osv_parsing.py @@ -0,0 +1,181 @@ +""" +tests/test_osv_parsing.py +โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +Severity and fix-version extraction from real-shaped OSV records. +""" + +from __future__ import annotations + +import pytest + +from pydoctor.cache.cache_manager import CacheManager +from pydoctor.config.settings import Severity +from pydoctor.scanners.vulnerability_scanner import _map_severity +from pydoctor.security import osv_client +from pydoctor.security.cvss import base_score, rating +from pydoctor.security.osv_client import ( + OSVClient, + _extract_fixed_version, + _extract_severity, +) + +# Reference scores from the FIRST CVSS v3.1 calculator. +CVSS_CASES = [ + ("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", 9.8, "CRITICAL"), + ("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H", 10.0, "CRITICAL"), + ("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", 7.5, "HIGH"), + ("CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", 6.1, "MEDIUM"), + ("CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", 5.5, "MEDIUM"), + ("CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:U/C:N/I:L/A:N", 3.1, "LOW"), + ("CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:N", 0.0, "NONE"), +] + + +@pytest.mark.parametrize("vector,score,label", CVSS_CASES) +def test_cvss_base_score_matches_reference(vector, score, label): + assert base_score(vector) == score + assert rating(score) == label + + +def test_invalid_or_unsupported_vectors_are_not_scored(): + assert base_score("CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N") is None + assert base_score("AV:N/AC:L/Au:N/C:P/I:P/A:P") is None # CVSS v2 + assert base_score("CVSS:3.1/AV:X") is None + + +def test_low_vulnerability_is_no_longer_reported_as_critical(): + """2.1.0 labelled any network/no-privilege vector HIGH, shown as critical.""" + raw = {"severity": [{"type": "CVSS_V3", "score": CVSS_CASES[5][0]}]} + label, score = _extract_severity(raw) + assert (label, score) == ("LOW", 3.1) + assert _map_severity(label) == Severity.WARNING + + +def test_github_moderate_maps_to_medium(): + label, _ = _extract_severity({"database_specific": {"severity": "MODERATE"}}) + assert label == "MEDIUM" + assert _map_severity("MODERATE") == Severity.ERROR + + +def test_cvss_v4_only_is_unknown_not_guessed(): + raw = {"severity": [{"type": "CVSS_V4", "score": "CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N"}]} + assert _extract_severity(raw) == ("UNKNOWN", None) + + +DJANGO_ADVISORY = { + "affected": [ + { + "package": {"ecosystem": "PyPI", "name": "Django"}, + "ranges": [ + { + "type": "ECOSYSTEM", + "events": [ + {"introduced": "5.1"}, + {"fixed": "5.1.4"}, + {"introduced": "0"}, + {"fixed": "4.2.17"}, + {"introduced": "5.0"}, + {"fixed": "5.0.10"}, + ], + }, + {"type": "GIT", "events": [{"introduced": "0"}, {"fixed": "abc123"}]}, + ], + } + ] +} + + +@pytest.mark.parametrize( + "installed,expected", + [("5.1.2", "5.1.4"), ("5.0.3", "5.0.10"), ("4.2.1", "4.2.17"), ("4.2.20", "5.0.10")], +) +def test_fixed_version_comes_from_the_installed_release_line(installed, expected): + assert _extract_fixed_version(DJANGO_ADVISORY, "django", installed) == expected + + +def test_no_fix_in_installed_line_returns_empty(): + raw = { + "affected": [ + { + "package": {"ecosystem": "PyPI", "name": "pkg"}, + "ranges": [{"type": "ECOSYSTEM", "events": [{"introduced": "2.0"}]}], + } + ] + } + assert _extract_fixed_version(raw, "pkg", "2.5") == "" + + +def test_other_packages_in_the_advisory_are_ignored(): + raw = { + "affected": [ + { + "package": {"ecosystem": "PyPI", "name": "other"}, + "ranges": [ + {"type": "ECOSYSTEM", "events": [{"introduced": "0"}, {"fixed": "9.0"}]} + ], + }, + DJANGO_ADVISORY["affected"][0], + ] + } + assert _extract_fixed_version(raw, "django", "5.1.2") == "5.1.4" + + +class _Resp: + def __init__(self, data, status=200): + self._data, self.status_code = data, status + + def raise_for_status(self): + pass + + def json(self): + return self._data + + +def _client(tmp_path, monkeypatch, read_cache=True): + monkeypatch.setattr(osv_client.time, "sleep", lambda _s: None) + return OSVClient(cache=CacheManager(cache_file=tmp_path / "c.json"), read_cache=read_cache) + + +def test_withdrawn_advisories_are_skipped_and_sparse_ones_fetched(tmp_path, monkeypatch): + client = _client(tmp_path, monkeypatch) + batch = {"results": [{"vulns": [{"id": "GHSA-live"}, {"id": "GHSA-gone"}]}]} + full = { + "GHSA-live": { + "id": "GHSA-live", + "summary": "real", + "database_specific": {"severity": "LOW"}, + }, + "GHSA-gone": {"id": "GHSA-gone", "summary": "x", "withdrawn": "2026-01-01T00:00:00Z"}, + } + fetched = [] + monkeypatch.setattr(client._session, "post", lambda *a, **k: _Resp(batch)) + + def get(url, timeout): + vid = url.rsplit("/", 1)[-1] + fetched.append(vid) + return _Resp(full[vid]) + + monkeypatch.setattr(client._session, "get", get) + records = client.query_packages({"pkg": "1.0"}) + assert [r.vuln_id for r in records] == ["GHSA-live"] + assert sorted(fetched) == ["GHSA-gone", "GHSA-live"] + + +def test_no_cache_ignores_cached_results_but_refreshes_them(tmp_path, monkeypatch): + calls = [] + batch = {"results": [{"vulns": []}]} + + def post(*a, **k): + calls.append(1) + return _Resp(batch) + + first = _client(tmp_path, monkeypatch) + monkeypatch.setattr(first._session, "post", post) + first.query_packages({"pkg": "1.0"}) + cached = _client(tmp_path, monkeypatch) + monkeypatch.setattr(cached._session, "post", post) + cached.query_packages({"pkg": "1.0"}) + bypass = _client(tmp_path, monkeypatch, read_cache=False) + monkeypatch.setattr(bypass._session, "post", post) + bypass.query_packages({"pkg": "1.0"}) + assert len(calls) == 2 # first run and the --no-cache run; the middle run hit the cache diff --git a/tests/test_report_output.py b/tests/test_report_output.py new file mode 100644 index 0000000..cc280c3 --- /dev/null +++ b/tests/test_report_output.py @@ -0,0 +1,72 @@ +""" +tests/test_report_output.py +โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +Health score behaviour and JSON output shape. +""" + +from __future__ import annotations + +import io +import json + +from pydoctor.analysis.health_score import calculate_health +from pydoctor.core.report import DiagnosisReport, Issue +from pydoctor.reports.json_formatter import render_json + + +def _vuln(pkg: str, severity: str = "critical", vuln_id: str = "GHSA-x") -> Issue: + return Issue( + "security", + "SEC_VULNERABILITY", + severity, + f"{pkg} advisory", + "summary", + "upgrade", + package=pkg, + extra={"vuln_id": vuln_id, "version": "1.0", "aliases": ["CVE-1"], "fixed_in": "1.1"}, + ) + + +def _report(*issues: Issue) -> DiagnosisReport: + report = DiagnosisReport() + report.extend(list(issues)) + return report + + +def test_many_advisories_for_one_package_cost_one_penalty(): + one = calculate_health(_report(_vuln("pillow"))) + many = calculate_health(_report(*[_vuln("pillow") for _ in range(54)])) + assert one.score == many.score + + +def test_fixing_packages_moves_the_score_in_a_badly_affected_project(): + pkgs = ["pillow", "cryptography", "pyjwt", "urllib3", "sqlparse", "djangorestframework"] + before = calculate_health(_report(*[_vuln(p) for p in pkgs])).score + after = calculate_health(_report(*[_vuln(p) for p in pkgs[3:]])).score + assert after > before + + +def test_any_critical_issue_rules_out_good(): + health = calculate_health(_report(_vuln("pillow"))) + assert health.score <= 69 and health.verdict in ("Needs Attention", "Critical") + + +def test_incomplete_scan_is_labelled_incomplete(): + issue = Issue("security", "SEC_SCAN_INCOMPLETE", "error", "t", "d", "r") + assert calculate_health(_report(issue)).verdict == "Incomplete" + + +def test_json_includes_health(): + out = io.StringIO() + render_json(_report(Issue("outdated", "PKG_OUTDATED", "warning", "t", "d", "r")), stream=out) + data = json.loads(out.getvalue()) + assert set(data["health"]) == {"score", "verdict"} + + +def test_security_json_keeps_advisory_ids(): + out = io.StringIO() + render_json(_report(_vuln("requests", "error", "GHSA-9wx4-h78v-vm56")), stream=out) + entry = json.loads(out.getvalue())["vulnerabilities"][0] + assert entry["advisory"] == "GHSA-9wx4-h78v-vm56" + assert entry["code"] == "SEC_VULNERABILITY" + assert entry["fixed_in"] == "1.1" and entry["aliases"] == ["CVE-1"] diff --git a/tests/test_unused_scanner.py b/tests/test_unused_scanner.py index c5ea22e..10ebded 100644 --- a/tests/test_unused_scanner.py +++ b/tests/test_unused_scanner.py @@ -171,3 +171,22 @@ def test_title_has_no_rich_markup(self, tmp_path): ctx = _make_ctx(tmp_path, py_files=[("main.py", "import os\n")], declared={"pandas": ""}) for issue in unused_package_scanner.scan(ctx): assert "[dim]" not in issue.title and "[/]" not in issue.title + + +class TestBackendDrivers: + """Drivers chosen by a settings string that never names the package.""" + + def test_database_driver_hasher_and_cache_client(self, tmp_path, monkeypatch): + monkeypatch.setattr(unused_package_scanner, "_distribution_map", lambda ctx: {}) + settings = ( + 'DATABASES = {"default": {"ENGINE": "django.db.backends.postgresql"}}\n' + 'PASSWORD_HASHERS = ["django.contrib.auth.hashers.Argon2PasswordHasher"]\n' + 'CELERY_BROKER_URL = "redis://localhost:6379/0"\n' + ) + ctx = _make_ctx( + tmp_path, + py_files=[("settings.py", settings)], + declared={"psycopg2-binary": "", "argon2-cffi": "", "redis": "", "six": ""}, + ) + unused = [i.package for i in unused_package_scanner.scan(ctx) if i.code == "UNUSED_PACKAGE"] + assert unused == ["six"]