diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 458ad9e..9963301 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -3,7 +3,9 @@ name: PyDoctor CLI - CI/CD on: push: branches: [main, release] - tags: ["v*"] + # Release tags only (v2.3.0). The moving major tag (v2) used by the + # GitHub Action must not trigger a PyPI release. + tags: ["v*.*.*"] pull_request: branches: [main, release] @@ -84,7 +86,7 @@ jobs: name: Deploy to Production PyPI needs: test # Run only on pushes to release branch or new semantic tags - if: github.event_name == 'push' && (github.ref == 'refs/heads/release' || startsWith(github.ref, 'refs/tags/v')) + if: github.event_name == 'push' && (github.ref == 'refs/heads/release' || startsWith(github.ref, 'refs/tags/v') && contains(github.ref_name, '.')) runs-on: ubuntu-latest environment: name: production @@ -106,7 +108,7 @@ jobs: github-release: name: GitHub Release needs: [deploy-pypi] - if: startsWith(github.ref, 'refs/tags/v') + if: startsWith(github.ref, 'refs/tags/v') && contains(github.ref_name, '.') runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/pydoctor.yml b/.github/workflows/pydoctor.yml new file mode 100644 index 0000000..fa10102 --- /dev/null +++ b/.github/workflows/pydoctor.yml @@ -0,0 +1,34 @@ +# Runs this repository's own GitHub Action against itself, so every pull +# request exercises the action and shows pydoctor's findings in code scanning. +name: pydoctor (self-scan) + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + scan: + runs-on: ubuntu-latest + permissions: + contents: read + security-events: write + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install project dependencies + run: python -m pip install --upgrade --upgrade-strategy eager -e . + + - name: pydoctor + uses: ./ + with: + version: local + # Report findings in code scanning; the publish workflow is the gate. + fail-on-findings: "false" diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml new file mode 100644 index 0000000..82be3c5 --- /dev/null +++ b/.pre-commit-hooks.yaml @@ -0,0 +1,23 @@ +# pre-commit hooks for pydoctor-cli. See https://pre-commit.com +# +# pydoctor-ci: secrets and workflow checks. Runs in its own environment and +# doesn't need your project's dependencies or network access. +- id: pydoctor-ci + name: pydoctor (secrets and CI/CD guard) + description: Block commits that add secrets, .env files or risky GitHub Actions workflows. + entry: pydoctor check --ci + language: python + pass_filenames: false + always_run: true + stages: [pre-commit, pre-push] + +# pydoctor-check: the full scan, using the pydoctor you installed yourself so +# it scans your project's environment. Needs network access. Best at pre-push. +- id: pydoctor-check + name: pydoctor (full scan) + description: Full pydoctor scan of the project's environment before pushing. + entry: pydoctor check + language: system + pass_filenames: false + always_run: true + stages: [pre-push] diff --git a/README.md b/README.md index 1d9d7e6..829fe45 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,44 @@ Run a comprehensive check-up on your project. pydoctor diagnose ``` +### In CI: GitHub Action + +Findings appear as code-scanning alerts on pull requests, and the job fails on new problems: + +```yaml +permissions: + contents: read + security-events: write + +steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: { python-version: "3.12" } + - run: pip install -r requirements.txt + - uses: iamAgbaCoder/pydoctor-cli@v2 +``` + +Set `ci-only: "true"` to run only the secrets and workflow checks. Any CI system can use `pydoctor check --sarif pydoctor.sarif` directly. + +### Adopting it in an existing project: baselines + +```bash +pydoctor baseline # accept today's issues; commit .pydoctor-baseline.json +pydoctor check # now fails only on new issues +``` + +Problems with the scan itself (unreadable environment, unreachable vulnerability database) are never baselined. + +### pre-commit + +```yaml +repos: + - repo: https://github.com/iamAgbaCoder/pydoctor-cli + rev: v2.3.0 + hooks: + - id: pydoctor-ci # blocks commits that add secrets or risky workflows +``` + ### Automated Fixes Let PyDoctor perform the heavy lifting. It will offer to install missing packages, upgrade outdated ones, and clean up your environment. @@ -85,6 +123,15 @@ pydoctor fix ## Release History +### v2.3.0 +Built for CI: adopt pydoctor in an existing project without a wall of failures, and see findings where you review code. + +- **Baselines:** `pydoctor baseline` records today's issues in `.pydoctor-baseline.json`; scans then fail only on new ones and tell you when baselined issues are fixed. Fingerprints survive unrelated edits (a secret moved down by new lines stays known) and package upgrades. `--ci` updates only the CI-guard entries. `--baseline FILE` / `--no-baseline` on every scan command. Broken scans are never baselined. +- **SARIF output:** `--sarif FILE` on every scan command (SARIF 2.1.0, schema-validated). Vulnerabilities carry their CVSS score as security severity and point at the line that declares the package; secrets and workflow findings point at their file and line. +- **GitHub Action:** `uses: iamAgbaCoder/pydoctor-cli@v2` installs pydoctor in isolation, uploads findings to code scanning, and fails the job on new problems. +- **pre-commit hooks:** `pydoctor-ci` blocks commits that add secrets, `.env` files or risky workflows; `pydoctor-check` runs the full scan at pre-push. +- **Docs links:** every issue links to its page on pydoctor-docs.thally.app (`docs_url` in JSON; shown in the terminal for errors). + ### 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. diff --git a/action.yml b/action.yml new file mode 100644 index 0000000..dc88740 --- /dev/null +++ b/action.yml @@ -0,0 +1,80 @@ +name: "pydoctor" +description: "Scan a Python project for vulnerable, conflicting and unused dependencies, committed secrets and risky workflows." +author: "Favour Bamgboye" +branding: + icon: "activity" + color: "orange" + +inputs: + path: + description: "Project directory to scan." + default: "." + ci-only: + description: "Only run the CI/CD guard (secrets and workflow checks). Doesn't need the project's dependencies installed." + default: "false" + python: + description: "Python interpreter of the project. Default: auto-detect (the setup-python interpreter on PATH)." + default: "" + args: + description: "Extra arguments passed to `pydoctor check`, e.g. `--no-baseline`." + default: "" + version: + description: "pydoctor-cli version to install: an exact version (2.3.0), `local` to install from this action's source, or empty to match the action's tag (v2 → latest 2.x)." + default: "" + sarif-file: + description: "Where to write the SARIF report." + default: "pydoctor.sarif" + upload-sarif: + description: "Upload the SARIF report to GitHub code scanning. Needs `permissions: security-events: write`." + default: "true" + fail-on-findings: + description: "Fail the step when pydoctor exits with code 1 (new error or critical issues, or score below min_health_score)." + default: "true" + +outputs: + exit-code: + description: "pydoctor's exit code (0 clean, 1 findings, 2 usage error)." + value: ${{ steps.scan.outputs.exit-code }} + sarif-file: + description: "Path of the SARIF report." + value: ${{ steps.scan.outputs.sarif-file }} + +runs: + using: "composite" + steps: + - name: Install pydoctor (isolated) + id: install + shell: bash + env: + PYDOCTOR_VERSION: ${{ inputs.version }} + ACTION_REF: ${{ github.action_ref }} + run: bash "$GITHUB_ACTION_PATH/action/install.sh" + + - name: Run pydoctor + id: scan + shell: bash + env: + PYDOCTOR_BIN: ${{ steps.install.outputs.bin }} + INPUT_PATH: ${{ inputs.path }} + INPUT_CI_ONLY: ${{ inputs.ci-only }} + INPUT_PYTHON: ${{ inputs.python }} + INPUT_ARGS: ${{ inputs.args }} + INPUT_SARIF_FILE: ${{ inputs.sarif-file }} + run: bash "$GITHUB_ACTION_PATH/action/scan.sh" + + - name: Upload SARIF to code scanning + if: ${{ always() && inputs.upload-sarif == 'true' && steps.scan.outputs.sarif-written == 'true' }} + continue-on-error: true + uses: github/codeql-action/upload-sarif@v3 + with: + sarif_file: ${{ steps.scan.outputs.sarif-file }} + category: pydoctor + + - name: Fail on findings + if: ${{ inputs.fail-on-findings == 'true' && steps.scan.outputs.exit-code != '0' }} + shell: bash + env: + CODE: ${{ steps.scan.outputs.exit-code }} + run: | + echo "::error title=pydoctor::pydoctor exited with code $CODE. See the scan step for details." + exit "$CODE" diff --git a/action/install.sh b/action/install.sh new file mode 100755 index 0000000..c8d0aca --- /dev/null +++ b/action/install.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# Install pydoctor-cli into its own virtual environment so it can't change, or +# be counted as part of, the project's environment. Prints `bin=` to +# $GITHUB_OUTPUT. +set -euo pipefail + +spec="pydoctor-cli" +version="${PYDOCTOR_VERSION:-}" +ref="${ACTION_REF:-}" + +if [[ "$version" == "local" ]]; then + spec="${GITHUB_ACTION_PATH:?}" +elif [[ -n "$version" ]]; then + spec="pydoctor-cli==${version#v}" +elif [[ "$ref" =~ ^v([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then + spec="pydoctor-cli==${ref#v}" +elif [[ "$ref" =~ ^v([0-9]+)$ ]]; then + major="${BASH_REMATCH[1]}" + spec="pydoctor-cli>=${major},<$((major + 1))" +fi + +if [[ -n "${PYDOCTOR_DRY_RUN:-}" ]]; then + echo "$spec" + exit 0 +fi + +base="${RUNNER_TEMP:-${TMPDIR:-/tmp}}/pydoctor-venv" +# On Windows runners RUNNER_TEMP is a Windows path; use the POSIX form in bash. +if command -v cygpath >/dev/null 2>&1; then + base="$(cygpath -u "$base")" +fi +py="$(command -v python3 || command -v python)" +"$py" -m venv "$base" +if [[ -x "$base/bin/python" ]]; then + venv_py="$base/bin/python"; bin="$base/bin/pydoctor" +else + venv_py="$base/Scripts/python.exe"; bin="$base/Scripts/pydoctor.exe" +fi +"$venv_py" -m pip install --quiet --disable-pip-version-check "$spec" +"$bin" --version +echo "bin=$bin" >> "${GITHUB_OUTPUT:-/dev/null}" diff --git a/action/scan.sh b/action/scan.sh new file mode 100755 index 0000000..65a3d4e --- /dev/null +++ b/action/scan.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# Run `pydoctor check`, write SARIF, and record the exit code without failing, +# so the SARIF upload step still runs. The action's last step fails the job. +set -uo pipefail + +args=(check --path "${INPUT_PATH:-.}" --sarif "${INPUT_SARIF_FILE:-pydoctor.sarif}") +[[ "${INPUT_CI_ONLY:-false}" == "true" ]] && args+=(--ci) +[[ -n "${INPUT_PYTHON:-}" ]] && args+=(--python "$INPUT_PYTHON") +if [[ -n "${INPUT_ARGS:-}" ]]; then + read -r -a extra <<< "$INPUT_ARGS" + args+=("${extra[@]}") +fi + +"${PYDOCTOR_BIN:?}" "${args[@]}" +code=$? + +out="${GITHUB_OUTPUT:-/dev/null}" +echo "exit-code=$code" >> "$out" +echo "sarif-file=${INPUT_SARIF_FILE:-pydoctor.sarif}" >> "$out" +if [[ -f "${INPUT_SARIF_FILE:-pydoctor.sarif}" ]]; then + echo "sarif-written=true" >> "$out" +else + echo "sarif-written=false" >> "$out" +fi +exit 0 diff --git a/pydoctor/__init__.py b/pydoctor/__init__.py index ea99e5d..1d36ff6 100644 --- a/pydoctor/__init__.py +++ b/pydoctor/__init__.py @@ -9,6 +9,6 @@ License: MIT """ -__version__ = "2.2.0" +__version__ = "2.3.0" __author__ = "Favour Bamgboye" __description__ = "Python environment diagnostic CLI — your project's doctor." diff --git a/pydoctor/cli/main.py b/pydoctor/cli/main.py index 53957b1..a77f534 100644 --- a/pydoctor/cli/main.py +++ b/pydoctor/cli/main.py @@ -85,7 +85,7 @@ def version_callback(value: bool): [section]šŸ„ COMMUNITY & SUPPORT[/] [label]Docs:[/][pkg] https://pydoctor-docs.thally.app[/] - [label]Version:[/][info] v2.2.0 (Premium Kernel Edition)[/] + [label]Version:[/][info] v2.3.0 (Premium Kernel Edition)[/] [kernel]Healthy code leads to healthy deployments. Keep your environment sterile.[/] """ @@ -122,6 +122,19 @@ 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.") +_SARIF_ARG = typer.Option( + ..., + "--sarif", + help="Also write findings to this file in SARIF format (for GitHub code scanning).", +) +_BASELINE_ARG = typer.Option( + ..., + "--baseline", + help="Baseline file of accepted issues (default: .pydoctor-baseline.json if present).", +) +_NO_BASELINE_ARG = typer.Option( + ..., "--no-baseline", help="Report every issue, ignoring the baseline." +) _PYTHON_ARG = typer.Option( ..., "--python", @@ -212,6 +225,42 @@ def _output(report: DiagnosisReport, as_json: bool, verbose: bool = False) -> No render_report(report, verbose=verbose) +def _finish( + report: DiagnosisReport, + path: str, + as_json: bool, + verbose: bool, + sarif: Path | None, + baseline: Path | None, + no_baseline: bool, +) -> None: + """Apply the baseline, print the report, write SARIF, and exit with the right code.""" + from pydoctor.core.baseline import BaselineError, apply_baseline, default_path + + if not no_baseline: + path_to_use = baseline or default_path(report) + if baseline is not None and not path_to_use.is_file(): + err_console.print(f"[error]āœ– Baseline file not found: {path_to_use}[/]") + raise typer.Exit(code=2) + if path_to_use.is_file(): + try: + apply_baseline(report, path_to_use, set(report.scanners)) + except BaselineError as exc: + err_console.print(f"[error]āœ– {exc}[/]") + raise typer.Exit(code=2) from exc + + _output(report, as_json=as_json, verbose=verbose) + + if sarif is not None: + from pydoctor.reports.sarif_formatter import write_sarif + + write_sarif(report, sarif) + if not as_json: + console.print(f"[dim_text]SARIF report written to {sarif}[/]") + + raise typer.Exit(code=_exit_code(report, path)) + + def _exit_code(report: DiagnosisReport, path: str = ".") -> int: """ Return a non-zero exit code if: @@ -237,6 +286,9 @@ def _exit_code(report: DiagnosisReport, path: str = ".") -> int: def diagnose( path: Annotated[str, _PATH_ARG] = ".", python: Annotated[str | None, _PYTHON_ARG] = None, + sarif: Annotated[Path | None, _SARIF_ARG] = None, + baseline: Annotated[Path | None, _BASELINE_ARG] = None, + no_baseline: Annotated[bool, _NO_BASELINE_ARG] = False, json: Annotated[bool, _JSON_ARG] = False, verbose: Annotated[bool, _VERBOSE_ARG] = False, no_cache: Annotated[bool, _NO_CACHE_ARG] = False, @@ -268,14 +320,16 @@ def diagnose( python=python, ctx=ctx, ) - _output(report, as_json=json, verbose=verbose) - raise typer.Exit(code=_exit_code(report, path)) + _finish(report, path, json, verbose, sarif, baseline, no_baseline) @app.command(rich_help_panel="CORE COMMANDS") def check( path: Annotated[str, _PATH_ARG] = ".", python: Annotated[str | None, _PYTHON_ARG] = None, + sarif: Annotated[Path | None, _SARIF_ARG] = None, + baseline: Annotated[Path | None, _BASELINE_ARG] = None, + no_baseline: Annotated[bool, _NO_BASELINE_ARG] = False, 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, @@ -284,8 +338,7 @@ def 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)) + _finish(report, path, json, verbose, sarif, baseline, no_baseline) @app.command(rich_help_panel="SECURITY & CI/CD") @@ -319,6 +372,9 @@ 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, + sarif: Annotated[Path | None, _SARIF_ARG] = None, + baseline: Annotated[Path | None, _BASELINE_ARG] = None, + no_baseline: Annotated[bool, _NO_BASELINE_ARG] = False, json: Annotated[bool, _JSON_ARG] = False, verbose: Annotated[bool, _VERBOSE_ARG] = False, ) -> None: @@ -347,8 +403,7 @@ def 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)) + _finish(report, path, json, verbose, sarif, baseline, no_baseline) # --- Individual Targeted Scans --- @@ -358,6 +413,9 @@ def github( def scan_security( path: Annotated[str, _PATH_ARG] = ".", python: Annotated[str | None, _PYTHON_ARG] = None, + sarif: Annotated[Path | None, _SARIF_ARG] = None, + baseline: Annotated[Path | None, _BASELINE_ARG] = None, + no_baseline: Annotated[bool, _NO_BASELINE_ARG] = False, json: Annotated[bool, _JSON_ARG] = False, verbose: Annotated[bool, _VERBOSE_ARG] = False, ) -> None: @@ -370,8 +428,7 @@ def scan_security( command="scan-security", python=python, ) - _output(report, as_json=json, verbose=verbose) - raise typer.Exit(code=_exit_code(report, path)) + _finish(report, path, json, verbose, sarif, baseline, no_baseline) # ────────────────────────────────────────────────────────────── @@ -383,6 +440,9 @@ def scan_security( def scan_unused( path: Annotated[str, _PATH_ARG] = ".", python: Annotated[str | None, _PYTHON_ARG] = None, + sarif: Annotated[Path | None, _SARIF_ARG] = None, + baseline: Annotated[Path | None, _BASELINE_ARG] = None, + no_baseline: Annotated[bool, _NO_BASELINE_ARG] = False, json: Annotated[bool, _JSON_ARG] = False, verbose: Annotated[bool, _VERBOSE_ARG] = False, ) -> None: @@ -395,14 +455,16 @@ def scan_unused( command="scan-unused", python=python, ) - _output(report, as_json=json, verbose=verbose) - raise typer.Exit(code=_exit_code(report, path)) + _finish(report, path, json, verbose, sarif, baseline, no_baseline) @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, + sarif: Annotated[Path | None, _SARIF_ARG] = None, + baseline: Annotated[Path | None, _BASELINE_ARG] = None, + no_baseline: Annotated[bool, _NO_BASELINE_ARG] = False, json: Annotated[bool, _JSON_ARG] = False, verbose: Annotated[bool, _VERBOSE_ARG] = False, ) -> None: @@ -415,14 +477,16 @@ def scan_deps( command="scan-deps", python=python, ) - _output(report, as_json=json, verbose=verbose) - raise typer.Exit(code=_exit_code(report, path)) + _finish(report, path, json, verbose, sarif, baseline, no_baseline) @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, + sarif: Annotated[Path | None, _SARIF_ARG] = None, + baseline: Annotated[Path | None, _BASELINE_ARG] = None, + no_baseline: Annotated[bool, _NO_BASELINE_ARG] = False, json: Annotated[bool, _JSON_ARG] = False, verbose: Annotated[bool, _VERBOSE_ARG] = False, ) -> None: @@ -435,13 +499,56 @@ def check_env( command="check-env", python=python, ) - _output(report, as_json=json, verbose=verbose) - raise typer.Exit(code=_exit_code(report, path)) + _finish(report, path, json, verbose, sarif, baseline, no_baseline) # --- Re-adding fix and other commands --- +@app.command(rich_help_panel="CORE COMMANDS") +def baseline( + path: Annotated[str, _PATH_ARG] = ".", + python: Annotated[str | None, _PYTHON_ARG] = None, + ci: bool = typer.Option( + False, "--ci", help="Only record CI/CD guard findings (keeps the rest of the file)." + ), + output: Annotated[ + Path | None, + typer.Option( + "--output", "-o", help="Where to write it (default: .pydoctor-baseline.json)." + ), + ] = None, +) -> None: + """šŸ“Œ Accept today's issues so CI only fails on new ones.""" + from pydoctor.core.baseline import NEVER_BASELINE, default_path, write_baseline + + report = _run_scan( + scanners=["ci"] if ci else None, path=path, python=python, command="baseline" + ) + target = output or default_path(report) + count = write_baseline(report, target, __version__, set(report.scanners) if ci else None) + console.print( + Panel( + f"[ok]āœ” {count} issue{'s' if count != 1 else ''} recorded in {target}[/]\n\n" + "Commit this file. Scans now hide these issues and fail only on new ones.\n" + "Run `pydoctor baseline` again after fixing issues to shrink it, or scan with " + "--no-baseline to see everything.", + border_style="ok", + ) + ) + + incomplete = [i for i in report.issues if i.code in NEVER_BASELINE] + if incomplete: + for issue in incomplete: + err_console.print(f"[error]āœ– {issue.title}[/]\n {issue.description}") + err_console.print( + "\n[warning]⚠ Part of the scan didn't run, so its issues aren't in the baseline. " + "They will be reported as new once the scan can run. Fix the problems above and " + "run `pydoctor baseline` again.[/]" + ) + raise typer.Exit(code=1) + + @app.command(rich_help_panel="CORE COMMANDS") def fix( packages: Annotated[ diff --git a/pydoctor/core/analyzer.py b/pydoctor/core/analyzer.py index 88eb709..43d0b6e 100644 --- a/pydoctor/core/analyzer.py +++ b/pydoctor/core/analyzer.py @@ -159,6 +159,7 @@ def run(self, on_progress: Callable[[str], None] | None = None) -> DiagnosisRepo 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) + report.scanners = [k for k in self._scanner_keys if k in SCANNER_REGISTRY] scanner_timings: dict[str, float] = {} report.extend(context_issues(ctx, self._scanner_keys)) diff --git a/pydoctor/core/baseline.py b/pydoctor/core/baseline.py new file mode 100644 index 0000000..78921b3 --- /dev/null +++ b/pydoctor/core/baseline.py @@ -0,0 +1,153 @@ +""" +pydoctor/core/baseline.py +────────────────────────── +Baselines: accept today's issues so CI only fails on new ones. + +A project with dozens of existing findings can't turn on a pydoctor CI gate +without it failing on every run. ``pydoctor baseline`` records the current +issues in ``.pydoctor-baseline.json``; later scans hide issues whose +fingerprint is in that file and report how many were hidden. Fixed issues +drop out naturally, and the file can be refreshed at any time. + +Problems with the scan itself (an unreadable environment, an unreachable +vulnerability database, a crashed scanner) are never baselined: accepting +them would turn a broken scan into a passing one. +""" + +from __future__ import annotations + +import datetime +import json +from dataclasses import dataclass, field +from pathlib import Path + +from pydoctor.config.settings import Severity +from pydoctor.core.report import DiagnosisReport, Issue +from pydoctor.reports.fingerprint import fingerprint + +BASELINE_FILE = ".pydoctor-baseline.json" +BASELINE_FORMAT = 1 + +# Never accepted into a baseline. +NEVER_BASELINE = {"ENV_PACKAGES_UNAVAILABLE", "SEC_SCAN_INCOMPLETE", "SCANNER_ERROR"} +_IGNORED_SEVERITIES = {Severity.OK, Severity.INFO} + + +class BaselineError(Exception): + """The baseline file exists but can't be used.""" + + +@dataclass +class BaselineResult: + path: Path + suppressed: int = 0 + stale: int = 0 + suppressed_codes: dict[str, int] = field(default_factory=dict) + + +def _root(report: DiagnosisReport) -> Path: + return Path(report.ctx.root) if report.ctx is not None else Path(report.scan_path) + + +def baselinable(issue: Issue) -> bool: + return issue.severity not in _IGNORED_SEVERITIES and issue.code not in NEVER_BASELINE + + +def default_path(report: DiagnosisReport) -> Path: + return _root(report) / BASELINE_FILE + + +def write_baseline( + report: DiagnosisReport, path: Path, version: str, scanned_categories: set[str] | None = None +) -> int: + """ + Record every baselinable issue in ``report``. Returns how many are in the file. + + When ``scanned_categories`` is given (a partial scan such as + `pydoctor baseline --ci`), entries for categories that weren't scanned are + kept from the existing file instead of being dropped. + """ + root = _root(report) + entries: dict[str, dict] = {} + if scanned_categories is not None and path.is_file(): + try: + previous = json.loads(path.read_text(encoding="utf-8")).get("issues", []) + except (OSError, ValueError): + previous = [] + for e in previous: + if e.get("category") not in scanned_categories and "fingerprint" in e: + entries[e["fingerprint"]] = e + for issue in report.issues: + if not baselinable(issue): + continue + fp = fingerprint(issue, root) + entries[fp] = { + "fingerprint": fp, + "code": issue.code, + "category": issue.category, + "severity": issue.severity, + "title": issue.title, + } + data = { + "format": BASELINE_FORMAT, + "created_at": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"), + "pydoctor_version": version, + "issues": sorted(entries.values(), key=lambda e: (e["code"], e["title"])), + } + path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + return len(entries) + + +def load_fingerprints(path: Path) -> set[str]: + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + raise BaselineError(f"{path} couldn't be read: {exc}") from exc + if not isinstance(data, dict) or data.get("format") != BASELINE_FORMAT: + raise BaselineError( + f"{path} isn't a pydoctor baseline (format {BASELINE_FORMAT}). " + "Recreate it with `pydoctor baseline`." + ) + return {e["fingerprint"] for e in data.get("issues", []) if "fingerprint" in e} + + +def apply_baseline( + report: DiagnosisReport, path: Path, scanned_categories: set[str] +) -> BaselineResult: + """ + Remove issues recorded in the baseline from ``report``. + + ``scanned_categories`` limits stale-entry counting to what this scan + actually checked: `scan-security` can't tell whether a baselined secret + still exists. + """ + known = load_fingerprints(path) + root = _root(report) + result = BaselineResult(path=path) + seen: set[str] = set() + kept: list[Issue] = [] + for issue in report.issues: + fp = fingerprint(issue, root) if baselinable(issue) else None + if fp is not None and fp in known: + seen.add(fp) + result.suppressed += 1 + result.suppressed_codes[issue.code] = result.suppressed_codes.get(issue.code, 0) + 1 + continue + kept.append(issue) + report.issues = kept + + try: + entries = json.loads(path.read_text(encoding="utf-8")).get("issues", []) + except (OSError, ValueError): + entries = [] + result.stale = sum( + 1 + for e in entries + if e.get("fingerprint") not in seen and e.get("category") in scanned_categories + ) + report.scanner_meta["baseline"] = { + "file": str(path), + "suppressed": result.suppressed, + "stale": result.stale, + } + return result diff --git a/pydoctor/core/report.py b/pydoctor/core/report.py index 0b9c125..21abc14 100644 --- a/pydoctor/core/report.py +++ b/pydoctor/core/report.py @@ -60,8 +60,15 @@ def to_dict(self) -> dict: "recommendation": self.recommendation, "package": self.package, "extra": self.extra, + "docs_url": self.docs_url, } + @property + def docs_url(self) -> str: + from pydoctor.reports.docs_links import docs_url + + return docs_url(self) + # ────────────────────────────────────────────────────────────── # DiagnosisReport — aggregated result of all scans @@ -89,6 +96,7 @@ class DiagnosisReport: scanner_meta: dict = field(default_factory=dict) ctx: Any = None command: str | None = None + scanners: list[str] = field(default_factory=list) # scanner keys that ran # ── Convenience helpers ──────────────────────────────────── diff --git a/pydoctor/reports/docs_links.py b/pydoctor/reports/docs_links.py new file mode 100644 index 0000000..b633fb6 --- /dev/null +++ b/pydoctor/reports/docs_links.py @@ -0,0 +1,52 @@ +""" +pydoctor/reports/docs_links.py +─────────────────────────────── +Link every issue to the page of the documentation that explains it. + +Anchors here must exist on https://pydoctor-docs.thally.app. Specific +troubleshooting entries win; otherwise the issue links to the section of +the scanner reference that produced it. +""" + +from __future__ import annotations + +from pydoctor.core.report import Issue + +DOCS_URL = "https://pydoctor-docs.thally.app" + +_BY_CODE: dict[str, str] = { + "ENV_PACKAGES_UNAVAILABLE": "/guides/troubleshooting#packages-unavailable", + "ENV_DEPS_NOT_INSTALLED": "/guides/troubleshooting#wrong-python", + "SEC_SCAN_INCOMPLETE": "/guides/troubleshooting#scan-incomplete", + "CI_ENV_FILE_COMMITTED": "/guides/troubleshooting#env-file-committed", + "CI_ENV_FILE_NOT_IGNORED": "/guides/troubleshooting#env-file-committed", + "CI_PULL_REQUEST_TARGET_CHECKOUT": "/scanners#workflow-checks", + "CI_SCRIPT_INJECTION": "/scanners#workflow-checks", + "CI_BROAD_PERMISSIONS": "/scanners#workflow-checks", + "CI_UNPINNED_ACTION": "/scanners#workflow-checks", + "CI_CLEARTEXT_ENV": "/scanners#workflow-checks", + "SEC_VULNERABILITY": "/scanners#severity", +} + +_BY_PREFIX: dict[str, str] = { + "SECRET_EXPOSED_": "/scanners#secret-rules", +} + +_BY_CATEGORY: dict[str, str] = { + "environment": "/scanners#environment", + "dependencies": "/scanners#dependencies", + "outdated": "/scanners#outdated-packages", + "security": "/scanners#security", + "unused": "/scanners#unused-packages", + "ci": "/scanners#ci-cd", +} + + +def docs_url(issue: Issue) -> str: + """The documentation page for ``issue`` (falls back to the docs home).""" + path = _BY_CODE.get(issue.code) + if path is None: + path = next((p for prefix, p in _BY_PREFIX.items() if issue.code.startswith(prefix)), None) + if path is None: + path = _BY_CATEGORY.get(issue.category, "") + return DOCS_URL + path diff --git a/pydoctor/reports/fingerprint.py b/pydoctor/reports/fingerprint.py new file mode 100644 index 0000000..ff24b03 --- /dev/null +++ b/pydoctor/reports/fingerprint.py @@ -0,0 +1,57 @@ +""" +pydoctor/reports/fingerprint.py +──────────────────────────────── +Stable identities for issues, shared by baselines and SARIF output. + +A fingerprint must stay the same across scans while the problem is the same, +and change when it's a different problem: + +- A vulnerability is identified by package and advisory, not by the + installed version, so it stays "known" until the advisory no longer + applies. +- An outdated package is identified by name only; the latest version changes + all the time. +- File findings (secrets, workflow checks) use the file and a hash of the + line's content, not the line number, so adding lines above them doesn't + turn them into new findings. +""" + +from __future__ import annotations + +import hashlib +from pathlib import Path + +from pydoctor.core.report import Issue + +FINGERPRINT_VERSION = "v1" + + +def _line_hash(root: Path | None, rel: str, line: int | None) -> str: + if root is None or not line: + return "" + try: + lines = (root / rel).read_text(encoding="utf-8", errors="replace").splitlines() + text = lines[line - 1].strip() if 0 < line <= len(lines) else "" + except OSError: + text = "" + return hashlib.sha256(text.encode()).hexdigest()[:16] if text else f"L{line}" + + +def _key(issue: Issue, root: Path | None) -> str: + extra = issue.extra or {} + if issue.code == "SEC_VULNERABILITY": + return f"{issue.package}|{extra.get('vuln_id', issue.title)}" + if "file" in extra: + return f"{extra['file']}|{_line_hash(root, extra['file'], extra.get('line'))}" + if issue.code.startswith("DEP_"): + target = extra.get("missing_package") or extra.get("required_spec") or "" + return f"{issue.package}|{target}" + if issue.package: + return str(issue.package) + return issue.title + + +def fingerprint(issue: Issue, root: Path | None = None) -> str: + """Return a short, stable identifier for ``issue``.""" + raw = f"{FINGERPRINT_VERSION}|{issue.code}|{_key(issue, root)}" + return hashlib.sha256(raw.encode()).hexdigest()[:24] diff --git a/pydoctor/reports/json_formatter.py b/pydoctor/reports/json_formatter.py index 0ec8b29..f15a6f8 100644 --- a/pydoctor/reports/json_formatter.py +++ b/pydoctor/reports/json_formatter.py @@ -103,6 +103,7 @@ def _vuln_entry(issue) -> dict: "severity": issue.severity, "summary": issue.description, "code": issue.code, + "docs_url": issue.docs_url, **( {"unchecked_packages": extra["unchecked_packages"]} if "unchecked_packages" in extra diff --git a/pydoctor/reports/sarif_formatter.py b/pydoctor/reports/sarif_formatter.py new file mode 100644 index 0000000..0618c63 --- /dev/null +++ b/pydoctor/reports/sarif_formatter.py @@ -0,0 +1,187 @@ +""" +pydoctor/reports/sarif_formatter.py +──────────────────────────────────── +SARIF 2.1.0 output, for GitHub code scanning and other SARIF viewers. + +Design choices: + +- Each vulnerability advisory is its own rule (ruleId = GHSA/PYSEC/CVE id), + because code scanning reads ``security-severity`` from the rule, and + advisories under one rule would all share a severity. +- Package findings point at the line that declares the package + (pyproject.toml or requirements*.txt) so they appear on a file; file + findings (secrets, workflows) point at their own file and line. +- Environment findings and problems with the scan itself are left out: they + describe the machine, not the code, and they already fail the run. +- Paths are relative to the git repository root, which is what code scanning + expects even when the scanned project is a subdirectory. +""" + +from __future__ import annotations + +import json +import re +import subprocess +from pathlib import Path + +from pydoctor import __version__ +from pydoctor.core.baseline import NEVER_BASELINE +from pydoctor.core.report import DiagnosisReport, Issue +from pydoctor.reports.docs_links import DOCS_URL, docs_url +from pydoctor.reports.fingerprint import fingerprint + +SARIF_SCHEMA = "https://json.schemastore.org/sarif-2.1.0.json" +_EXCLUDED_CATEGORIES = {"environment"} +_EXCLUDED_CODES = NEVER_BASELINE | {"SECRET_FINDINGS_TRUNCATED"} +_LEVEL = {"critical": "error", "error": "error", "warning": "warning"} +_SECURITY_SEVERITY = {"critical": "9.0", "error": "6.5", "warning": "3.5"} +_MANIFESTS = ("pyproject.toml", "requirements.txt") + + +def _repo_root(project_root: Path) -> Path: + try: + res = subprocess.run( + ["git", "rev-parse", "--show-toplevel"], + cwd=project_root, + capture_output=True, + text=True, + check=False, + timeout=10, + ) + if res.returncode == 0 and res.stdout.strip(): + return Path(res.stdout.strip()).resolve() + except (OSError, subprocess.SubprocessError): + pass + return project_root + + +def _declaration(project_root: Path, package: str) -> tuple[str, int] | None: + """File (relative to the project) and line that declare ``package``.""" + name = re.escape(package).replace(r"\-", "[-_.]").replace(r"\_", "[-_.]") + pattern = re.compile(rf"""^\s*["']?{name}\s*(?:\[[^\]]*\])?\s*([<>=!~^;,"'\s]|$)""", re.I) + candidates = [project_root / m for m in _MANIFESTS] + sorted( + project_root.glob("requirements*.txt") + ) + for path in dict.fromkeys(candidates): + if not path.is_file(): + continue + try: + lines = path.read_text(encoding="utf-8", errors="replace").splitlines() + except OSError: + continue + for no, line in enumerate(lines, start=1): + if pattern.match(line): + return str(path.relative_to(project_root)), no + return None + + +def _first_manifest(project_root: Path) -> str | None: + return next((m for m in _MANIFESTS if (project_root / m).is_file()), None) + + +def _location(issue: Issue, project_root: Path, repo_root: Path) -> dict | None: + extra = issue.extra or {} + if "file" in extra: + rel, line = extra["file"], extra.get("line") or 1 + elif issue.package and (decl := _declaration(project_root, issue.package)): + rel, line = decl + elif manifest := _first_manifest(project_root): + rel, line = manifest, 1 + else: + return None + try: + uri = (project_root / rel).resolve().relative_to(repo_root).as_posix() + except ValueError: + uri = Path(rel).as_posix() + return { + "physicalLocation": { + "artifactLocation": {"uri": uri, "uriBaseId": "%SRCROOT%"}, + "region": {"startLine": int(line)}, + } + } + + +def _rule_id(issue: Issue) -> str: + if issue.code == "SEC_VULNERABILITY": + return str((issue.extra or {}).get("vuln_id") or issue.code) + return issue.code + + +def _rule(issue: Issue, rule_id: str) -> dict: + extra = issue.extra or {} + rule: dict = {"id": rule_id, "properties": {"tags": [issue.category]}} + if issue.code == "SEC_VULNERABILITY": + rule["name"] = "Vulnerability" + rule["shortDescription"] = {"text": f"{rule_id} in {issue.package}"} + rule["fullDescription"] = {"text": issue.description or rule_id} + rule["helpUri"] = f"https://osv.dev/vulnerability/{rule_id}" + rule["help"] = {"text": f"{issue.recommendation}\n\nAdvisory: {rule['helpUri']}"} + score = extra.get("cvss_score") + rule["properties"]["security-severity"] = ( + f"{float(score):.1f}" if score else _SECURITY_SEVERITY.get(issue.severity, "5.0") + ) + rule["properties"]["tags"] += ["security", "vulnerability", "dependency"] + else: + rule["name"] = "".join(p.capitalize() for p in issue.code.lower().split("_")) + rule["shortDescription"] = {"text": issue.code.replace("_", " ").capitalize()} + rule["helpUri"] = docs_url(issue) + rule["help"] = {"text": f"{issue.recommendation}\n\nDocs: {rule['helpUri']}"} + if issue.category in ("ci", "security"): + rule["properties"]["security-severity"] = _SECURITY_SEVERITY.get(issue.severity, "5.0") + rule["properties"]["tags"].append("security") + return rule + + +def build_sarif(report: DiagnosisReport) -> dict: + project_root = ( + Path(report.ctx.root) if report.ctx is not None else Path(report.scan_path) + ).resolve() + repo_root = _repo_root(project_root) + rules: dict[str, dict] = {} + results: list[dict] = [] + + for issue in report.issues: + if ( + issue.severity not in _LEVEL + or issue.category in _EXCLUDED_CATEGORIES + or issue.code in _EXCLUDED_CODES + ): + continue + rule_id = _rule_id(issue) + rules.setdefault(rule_id, _rule(issue, rule_id)) + result: dict = { + "ruleId": rule_id, + "level": _LEVEL[issue.severity], + "message": {"text": f"{issue.title}. {issue.description}".strip()}, + "partialFingerprints": {"pydoctorFingerprint/v1": fingerprint(issue, project_root)}, + "properties": {"pydoctorCode": issue.code, "pydoctorSeverity": issue.severity}, + } + if location := _location(issue, project_root, repo_root): + result["locations"] = [location] + results.append(result) + + return { + "$schema": SARIF_SCHEMA, + "version": "2.1.0", + "runs": [ + { + "tool": { + "driver": { + "name": "pydoctor", + "version": __version__, + "informationUri": DOCS_URL, + "rules": list(rules.values()), + } + }, + "results": results, + } + ], + } + + +def write_sarif(report: DiagnosisReport, path: Path) -> None: + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + json.dumps(build_sarif(report), indent=2, ensure_ascii=False) + "\n", encoding="utf-8" + ) diff --git a/pydoctor/reports/table_formatter.py b/pydoctor/reports/table_formatter.py index 0e76084..149e51a 100644 --- a/pydoctor/reports/table_formatter.py +++ b/pydoctor/reports/table_formatter.py @@ -17,6 +17,7 @@ from pydoctor.analysis.health_score import calculate_health from pydoctor.config.settings import Severity from pydoctor.core.report import DiagnosisReport, Issue +from pydoctor.reports.docs_links import docs_url from pydoctor.reports.terminal_colors import ( ICON_OK, ICON_WARNING, @@ -71,6 +72,7 @@ def render_report(report: DiagnosisReport, verbose: bool = False) -> None: console.print() _render_verdict(report) + _render_baseline_note(report) console.print() _render_recommendations(report, verbose=verbose) @@ -175,6 +177,9 @@ def _render_boxed_category(cat_key: str, issues: list[Issue]) -> None: if i.recommendation: content.append(" Suggestion: ", style="dim_text") content.append(f"{i.recommendation}\n", style="code") + if i.severity in (Severity.ERROR, Severity.CRITICAL): + content.append(" Docs: ", style="dim_text") + content.append(f"{docs_url(i)}\n", style="dim_text") content.append("\n") panel = Panel( @@ -215,6 +220,22 @@ def _render_health_score(report: DiagnosisReport) -> None: console.print(f"[{color}]{bar}[/] [label]{health.score} / 100[/]") +def _render_baseline_note(report: DiagnosisReport) -> None: + info = report.scanner_meta.get("baseline") + if not info: + return + if info.get("suppressed"): + console.print( + f"[dim_text]šŸ“Œ {info['suppressed']} known issue(s) hidden by the baseline " + f"({info['file']}). Use --no-baseline to show them.[/]" + ) + if info.get("stale"): + console.print( + f"[ok]āœ” {info['stale']} baselined issue(s) are fixed. " + "Run `pydoctor baseline` to update the file.[/]" + ) + + def _render_verdict(report: DiagnosisReport) -> None: health = calculate_health(report) console.print("[section]🩺 Doctor's Verdict[/]") diff --git a/pyproject.toml b/pyproject.toml index ffa8b5b..ff114ce 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "pydoctor-cli" -version = "2.2.0" +version = "2.3.0" description = "Premium Python environment diagnostic CLI — your project's personal physician." readme = "README.md" license = { file = "LICENSE" } diff --git a/tests/test_baseline.py b/tests/test_baseline.py new file mode 100644 index 0000000..ae966b6 --- /dev/null +++ b/tests/test_baseline.py @@ -0,0 +1,165 @@ +""" +tests/test_baseline.py +────────────────────── +Baselines hide known issues, survive unrelated edits, and never hide a +broken scan. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from typer.testing import CliRunner + +from pydoctor.cli import main +from pydoctor.core.baseline import BaselineError, apply_baseline, write_baseline +from pydoctor.core.report import DiagnosisReport, Issue +from pydoctor.reports.fingerprint import fingerprint + + +def _vuln(pkg="pillow", vid="GHSA-aaaa", version="12.2.0"): + return Issue( + "security", + "SEC_VULNERABILITY", + "critical", + f"{pkg} {version} — {vid}", + "d", + "r", + package=pkg, + extra={"vuln_id": vid, "version": version}, + ) + + +def _secret(line=1): + return Issue( + "ci", + "SECRET_EXPOSED_STRIPE_KEY", + "critical", + f"Exposed secret (app.py:{line})", + "d", + "r", + extra={"file": "app.py", "line": line}, + ) + + +def _report(root: Path, *issues: Issue, scanners=("security", "ci")) -> DiagnosisReport: + report = DiagnosisReport(scan_path=str(root)) + report.extend(list(issues)) + report.scanners = list(scanners) + return report + + +# ── Fingerprints ─────────────────────────────────────────────── + + +def test_vulnerability_fingerprint_ignores_installed_version(tmp_path): + assert fingerprint(_vuln(version="12.2.0"), tmp_path) == fingerprint( + _vuln(version="12.3.0"), tmp_path + ) + assert fingerprint(_vuln(vid="GHSA-aaaa"), tmp_path) != fingerprint( + _vuln(vid="GHSA-bbbb"), tmp_path + ) + + +def test_file_finding_fingerprint_survives_line_shifts(tmp_path): + (tmp_path / "app.py").write_text("KEY = 'x'\n", encoding="utf-8") + before = fingerprint(_secret(line=1), tmp_path) + (tmp_path / "app.py").write_text("# header\n# more\nKEY = 'x'\n", encoding="utf-8") + assert fingerprint(_secret(line=3), tmp_path) == before + (tmp_path / "app.py").write_text("# header\n# more\nKEY = 'y'\n", encoding="utf-8") + assert fingerprint(_secret(line=3), tmp_path) != before + + +# ── Apply ────────────────────────────────────────────────────── + + +def test_known_issues_are_hidden_and_new_ones_kept(tmp_path): + path = tmp_path / ".pydoctor-baseline.json" + write_baseline(_report(tmp_path, _vuln()), path, "test") + report = _report(tmp_path, _vuln(), _vuln(vid="GHSA-new")) + result = apply_baseline(report, path, {"security"}) + assert [i.extra["vuln_id"] for i in report.issues] == ["GHSA-new"] + assert result.suppressed == 1 and result.stale == 0 + assert report.scanner_meta["baseline"]["suppressed"] == 1 + + +def test_fixed_issues_are_counted_as_stale_only_for_scanned_categories(tmp_path): + (tmp_path / "app.py").write_text("KEY = 'x'\n", encoding="utf-8") + path = tmp_path / ".pydoctor-baseline.json" + write_baseline(_report(tmp_path, _vuln(), _secret()), path, "test") + # A security-only scan finds no vulnerabilities: the vuln is fixed, the + # secret wasn't checked and must not be called fixed. + result = apply_baseline(_report(tmp_path, scanners=["security"]), path, {"security"}) + assert result.stale == 1 + + +@pytest.mark.parametrize( + "code", ["SEC_SCAN_INCOMPLETE", "ENV_PACKAGES_UNAVAILABLE", "SCANNER_ERROR"] +) +def test_broken_scans_are_never_baselined(tmp_path, code): + broken = Issue("security", code, "error", "t", "d", "r") + path = tmp_path / "b.json" + assert write_baseline(_report(tmp_path, broken), path, "test") == 0 + report = _report(tmp_path, broken) + apply_baseline(report, path, {"security"}) + assert report.has_errors + + +def test_info_and_ok_are_not_recorded(tmp_path): + info = Issue("outdated", "PKG_OUTDATED", "info", "t", "d", "r", package="six") + assert write_baseline(_report(tmp_path, info), tmp_path / "b.json", "test") == 0 + + +def test_partial_baseline_keeps_other_categories(tmp_path): + (tmp_path / "app.py").write_text("KEY = 'x'\n", encoding="utf-8") + path = tmp_path / "b.json" + write_baseline(_report(tmp_path, _vuln(), _secret()), path, "test") + count = write_baseline(_report(tmp_path, scanners=["ci"]), path, "test", {"ci"}) + entries = json.loads(path.read_text())["issues"] + assert count == 1 and [e["code"] for e in entries] == ["SEC_VULNERABILITY"] + + +def test_invalid_baseline_file_is_an_error(tmp_path): + path = tmp_path / "b.json" + path.write_text('{"something": "else"}', encoding="utf-8") + with pytest.raises(BaselineError): + apply_baseline(_report(tmp_path), path, {"ci"}) + + +def test_baseline_file_contains_no_secret_values(tmp_path): + secret = _secret() + secret.extra["preview"] = "sk_l…Wx (32 chars)" + (tmp_path / "app.py").write_text("KEY = 'x'\n", encoding="utf-8") + path = tmp_path / "b.json" + write_baseline(_report(tmp_path, secret), path, "test") + assert "preview" not in path.read_text() and "sk_l" not in path.read_text() + + +# ── CLI ──────────────────────────────────────────────────────── + + +def test_cli_exit_code_ignores_baselined_issues(tmp_path, monkeypatch): + (tmp_path / "app.py").write_text("KEY = 'x'\n", encoding="utf-8") + write_baseline(_report(tmp_path, _secret()), tmp_path / ".pydoctor-baseline.json", "test") + monkeypatch.setattr( + main, "_run_scan", lambda **k: _report(tmp_path, _secret(), scanners=["ci"]) + ) + runner = CliRunner() + assert ( + runner.invoke(main.app, ["check", "--ci", "--path", str(tmp_path), "--json"]).exit_code == 0 + ) + result = runner.invoke( + main.app, ["check", "--ci", "--path", str(tmp_path), "--json", "--no-baseline"] + ) + assert result.exit_code == 1 + + +def test_cli_missing_explicit_baseline_is_a_usage_error(tmp_path, monkeypatch): + monkeypatch.setattr(main, "_run_scan", lambda **k: _report(tmp_path, scanners=["ci"])) + result = CliRunner().invoke( + main.app, + ["check", "--ci", "--path", str(tmp_path), "--baseline", str(tmp_path / "nope.json")], + ) + assert result.exit_code == 2 diff --git a/tests/test_github_action.py b/tests/test_github_action.py new file mode 100644 index 0000000..1ca45db --- /dev/null +++ b/tests/test_github_action.py @@ -0,0 +1,86 @@ +""" +tests/test_github_action.py +─────────────────────────── +The composite action's shell scripts: version resolution and exit handling. +""" + +from __future__ import annotations + +import os +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +# These scripts run under GitHub Actions' own bash (Git Bash on Windows +# runners). On a Windows test runner, `bash` on PATH is often WSL, which can't +# read Windows paths, so the scripts are tested on Linux and macOS only. +pytestmark = pytest.mark.skipif( + shutil.which("bash") is None or sys.platform == "win32", + reason="needs a POSIX bash (the action itself runs under Git Bash on Windows)", +) + + +def _install_spec(**env) -> str: + result = subprocess.run( + ["bash", str(ROOT / "action" / "install.sh")], + env={**os.environ, "PYDOCTOR_DRY_RUN": "1", **env}, + capture_output=True, + text=True, + check=True, + ) + return result.stdout.strip() + + +@pytest.mark.parametrize( + "env,expected", + [ + ({"ACTION_REF": "v2"}, "pydoctor-cli>=2,<3"), + ({"ACTION_REF": "v2.3.0"}, "pydoctor-cli==2.3.0"), + ({"ACTION_REF": "main"}, "pydoctor-cli"), + ({"ACTION_REF": "v2", "PYDOCTOR_VERSION": "2.2.0"}, "pydoctor-cli==2.2.0"), + ({"PYDOCTOR_VERSION": "local", "GITHUB_ACTION_PATH": "/x/action"}, "/x/action"), + ], +) +def test_version_resolution(env, expected): + assert _install_spec(**env) == expected + + +def _scan(tmp_path, exit_code: int, write_sarif: bool): + fake = tmp_path / "pydoctor" + sarif = tmp_path / "out.sarif" + body = f'touch "{sarif}"\n' if write_sarif else "" + fake.write_text(f'#!/usr/bin/env bash\necho "$@" > "{tmp_path}/args"\n{body}exit {exit_code}\n') + fake.chmod(0o755) + out = tmp_path / "github_output" + result = subprocess.run( + ["bash", str(ROOT / "action" / "scan.sh")], + env={ + **os.environ, + "PYDOCTOR_BIN": str(fake), + "INPUT_CI_ONLY": "true", + "INPUT_ARGS": "--no-baseline --verbose", + "INPUT_SARIF_FILE": str(sarif), + "GITHUB_OUTPUT": str(out), + }, + capture_output=True, + text=True, + ) + outputs = dict(line.split("=", 1) for line in out.read_text().splitlines()) + return result.returncode, outputs, (tmp_path / "args").read_text().split() + + +def test_findings_are_recorded_without_failing_the_step(tmp_path): + code, outputs, args = _scan(tmp_path, exit_code=1, write_sarif=True) + assert code == 0 # the upload step must still run + assert outputs["exit-code"] == "1" and outputs["sarif-written"] == "true" + assert args[:3] == ["check", "--path", "."] + assert "--ci" in args and args[-2:] == ["--no-baseline", "--verbose"] + + +def test_missing_sarif_is_reported(tmp_path): + _, outputs, _ = _scan(tmp_path, exit_code=2, write_sarif=False) + assert outputs["exit-code"] == "2" and outputs["sarif-written"] == "false" diff --git a/tests/test_sarif.py b/tests/test_sarif.py new file mode 100644 index 0000000..9ef0655 --- /dev/null +++ b/tests/test_sarif.py @@ -0,0 +1,117 @@ +""" +tests/test_sarif.py +─────────────────── +SARIF output shape, locations and rules. +""" + +from __future__ import annotations + +import subprocess +from pathlib import Path + +from pydoctor.core.report import DiagnosisReport, Issue +from pydoctor.reports.docs_links import _BY_CATEGORY, _BY_CODE, docs_url +from pydoctor.reports.sarif_formatter import build_sarif + + +def _report(root: Path, *issues: Issue) -> DiagnosisReport: + report = DiagnosisReport(scan_path=str(root)) + report.extend(list(issues)) + return report + + +def _run(root, *issues): + return build_sarif(_report(root, *issues))["runs"][0] + + +def _vuln(score=7.5): + return Issue( + "security", + "SEC_VULNERABILITY", + "critical", + "requests 2.31.0 — GHSA-x", + "summary", + 'pip install "requests>=2.32.0"', + package="requests", + extra={"vuln_id": "GHSA-x", "cvss_score": score}, + ) + + +def test_vulnerability_points_at_its_declaration(tmp_path): + (tmp_path / "requirements.txt").write_text("flask\nRequests==2.31.0\n", encoding="utf-8") + run = _run(tmp_path, _vuln()) + result = run["results"][0] + loc = result["locations"][0]["physicalLocation"] + assert result["ruleId"] == "GHSA-x" and result["level"] == "error" + assert loc["artifactLocation"]["uri"] == "requirements.txt" + assert loc["region"]["startLine"] == 2 + rule = run["tool"]["driver"]["rules"][0] + assert rule["properties"]["security-severity"] == "7.5" + assert rule["helpUri"] == "https://osv.dev/vulnerability/GHSA-x" + + +def test_paths_are_relative_to_the_repository_root(tmp_path): + subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True) + project = tmp_path / "backend" + project.mkdir() + issue = Issue( + "ci", + "SECRET_EXPOSED_STRIPE_KEY", + "critical", + "t", + "d", + "r", + extra={"file": "app.py", "line": 4}, + ) + result = _run(project, issue)["results"][0] + loc = result["locations"][0]["physicalLocation"] + assert loc["artifactLocation"]["uri"] == "backend/app.py" + assert loc["region"]["startLine"] == 4 + assert result["partialFingerprints"]["pydoctorFingerprint/v1"] + + +def test_environment_info_and_broken_scan_issues_are_left_out(tmp_path): + run = _run( + tmp_path, + Issue("environment", "ENV_NO_VENV", "warning", "t", "d", "r"), + Issue("security", "SEC_SCAN_INCOMPLETE", "error", "t", "d", "r"), + Issue("outdated", "PKG_OUTDATED", "info", "t", "d", "r", package="six"), + Issue("outdated", "PKG_OUTDATED", "warning", "t", "d", "r", package="django"), + ) + assert [r["ruleId"] for r in run["results"]] == ["PKG_OUTDATED"] + + +def test_one_rule_per_code_or_advisory(tmp_path): + run = _run( + tmp_path, _vuln(), _vuln(), Issue("unused", "UNUSED_PACKAGE", "warning", "t", "d", "r") + ) + assert sorted(r["id"] for r in run["tool"]["driver"]["rules"]) == ["GHSA-x", "UNUSED_PACKAGE"] + assert len(run["results"]) == 3 + + +# Anchors that exist on https://pydoctor-docs.thally.app (checked when this test was written). +LIVE_ANCHORS = { + "/scanners": { + "scanned-environment", "environment", "dependencies", "outdated-packages", "security", + "severity", "unused-packages", "ci-cd", "secret-rules", "workflow-checks", + }, + "/guides/troubleshooting": { + "packages-unavailable", "wrong-python", "scan-incomplete", "env-file-committed", + }, +} # fmt: skip + + +def test_docs_links_only_use_known_anchors(): + for path in list(_BY_CODE.values()) + list(_BY_CATEGORY.values()) + ["/scanners#secret-rules"]: + page, anchor = path.split("#") + assert anchor in LIVE_ANCHORS[page], path + + +def test_every_issue_gets_a_docs_link(): + assert ( + docs_url(Issue("x", "UNKNOWN", "warning", "t", "d", "r")) + == "https://pydoctor-docs.thally.app" + ) + secret = Issue("ci", "SECRET_EXPOSED_AWS_KEY", "critical", "t", "d", "r") + assert docs_url(secret).endswith("/scanners#secret-rules") + assert secret.to_dict()["docs_url"] == docs_url(secret)