diff --git a/.github/actions/setup-hatch/action.yml b/.github/actions/setup-hatch/action.yml index 0da5160b..ed59e21f 100644 --- a/.github/actions/setup-hatch/action.yml +++ b/.github/actions/setup-hatch/action.yml @@ -6,8 +6,9 @@ description: >- runs: using: "composite" steps: + # Match the dev extra and build-system backend pins in pyproject.toml. - shell: bash run: | python -m pip install --upgrade pip pip install "virtualenv<20.36" - pip install hatchling==1.27.0 hatch==1.14.0 + pip install hatchling==1.33.0 hatch==1.18.2 diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml index a609193d..1e41e141 100644 --- a/.github/workflows/dependency-review.yml +++ b/.github/workflows/dependency-review.yml @@ -150,7 +150,7 @@ jobs: echo "sha=${{ github.event.pull_request.head.sha }}" } > sfw-artifacts/context.txt - - uses: $/.github/actions/setup-sfw + - uses: ./.github/actions/setup-sfw with: uv: "true" mode: firewall-free @@ -241,7 +241,7 @@ jobs: echo "sha=${{ github.event.pull_request.head.sha }}" } > sfw-artifacts/context.txt - - uses: $/.github/actions/setup-sfw + - uses: ./.github/actions/setup-sfw with: uv: "true" mode: firewall-enterprise @@ -332,7 +332,7 @@ jobs: echo "sha=${{ github.event.pull_request.head.sha }}" } > sfw-artifacts/context.txt - - uses: $/.github/actions/setup-sfw + - uses: ./.github/actions/setup-sfw with: node: "true" mode: firewall-free @@ -393,7 +393,7 @@ jobs: echo "sha=${{ github.event.pull_request.head.sha }}" } > sfw-artifacts/context.txt - - uses: $/.github/actions/setup-sfw + - uses: ./.github/actions/setup-sfw with: node: "true" mode: firewall-enterprise @@ -454,7 +454,7 @@ jobs: echo "sha=${{ github.event.pull_request.head.sha }}" } > sfw-artifacts/context.txt - - uses: $/.github/actions/setup-sfw + - uses: ./.github/actions/setup-sfw with: python: "true" mode: firewall-free @@ -518,7 +518,7 @@ jobs: echo "sha=${{ github.event.pull_request.head.sha }}" } > sfw-artifacts/context.txt - - uses: $/.github/actions/setup-sfw + - uses: ./.github/actions/setup-sfw with: python: "true" mode: firewall-enterprise diff --git a/.github/workflows/docker-stable.yml b/.github/workflows/docker-stable.yml index 4205ed9f..c3c412a9 100644 --- a/.github/workflows/docker-stable.yml +++ b/.github/workflows/docker-stable.yml @@ -20,7 +20,7 @@ jobs: persist-credentials: false - name: Set up Docker publishing - uses: $/.github/actions/setup-docker + uses: ./.github/actions/setup-docker with: # Retagging copies manifests between tags; nothing is built. enable-qemu: "false" diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 00000000..4af0054e --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,42 @@ +name: Lint + +env: + PYTHON_VERSION: "3.12" + +# Report on every PR, including changes outside the Python test paths. +# Required checks need a result even when a PR changes no Python files. +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: lint-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + ruff: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 1 + persist-credentials: false + - name: ๐Ÿ setup python + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: ${{ env.PYTHON_VERSION }} + - name: ๐Ÿ› ๏ธ install deps + run: | + python -m pip install --upgrade pip + pip install uv + uv sync --locked --extra dev + - name: ๐Ÿงน ruff check + run: uv run --locked --extra dev ruff check + - name: ๐ŸŽจ ruff format + run: uv run --locked --extra dev ruff format --check diff --git a/.github/workflows/package-check.yml b/.github/workflows/package-check.yml index c80a0419..a6f946a6 100644 --- a/.github/workflows/package-check.yml +++ b/.github/workflows/package-check.yml @@ -28,7 +28,7 @@ jobs: python-version: "3.12" - name: Install build tooling - uses: $/.github/actions/setup-hatch + uses: ./.github/actions/setup-hatch - name: Install distribution validator run: python -m pip install "twine>=4.0.0" diff --git a/.github/workflows/pr-preview.yml b/.github/workflows/pr-preview.yml index 7b08efff..581e6f32 100644 --- a/.github/workflows/pr-preview.yml +++ b/.github/workflows/pr-preview.yml @@ -93,6 +93,9 @@ jobs: core.setOutput('head_sha', pullRequest.head.sha); build: + # Manual builds execute PR code in the default branch's cache scope. + # Keep this job free of cache restore/save steps. Publishing runs separately + # with write permissions and consumes artifacts without checking out PR code. needs: context runs-on: ubuntu-latest timeout-minutes: 10 @@ -112,7 +115,7 @@ jobs: python-version: "3.12" - name: Install build tooling - uses: $/.github/actions/setup-hatch + uses: ./.github/actions/setup-hatch - name: Install distribution validator run: python -m pip install "twine>=4.0.0" @@ -252,7 +255,7 @@ jobs: path: dist - name: Set up Docker publishing - uses: $/.github/actions/setup-docker + uses: ./.github/actions/setup-docker with: # QEMU is required to build the arm64 layer on an amd64 runner. enable-qemu: "true" diff --git a/.github/workflows/python-tests.yml b/.github/workflows/python-tests.yml index bfde20a3..75041b9e 100644 --- a/.github/workflows/python-tests.yml +++ b/.github/workflows/python-tests.yml @@ -60,26 +60,6 @@ jobs: print('import smoke OK') " - ruff: - runs-on: ubuntu-latest - timeout-minutes: 10 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - fetch-depth: 1 - persist-credentials: false - - name: ๐Ÿ setup python - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - with: - python-version: ${{ env.PYTHON_VERSION }} - - name: ๐Ÿ› ๏ธ install deps - run: | - python -m pip install --upgrade pip - pip install uv - uv sync --extra dev - - name: ๐Ÿงน run ruff - run: uv run ruff check - unsupported-python-install: runs-on: ubuntu-latest timeout-minutes: 10 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6c3c5076..0dbfdaac 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -20,7 +20,7 @@ jobs: python-version: '3.13' - name: Install build tooling - uses: $/.github/actions/setup-hatch + uses: ./.github/actions/setup-hatch - name: Get Version id: version @@ -28,7 +28,7 @@ jobs: REF_NAME: ${{ github.ref_name }} run: | RAW_VERSION=$(hatch version) - echo "VERSION=$RAW_VERSION" >> $GITHUB_ENV + echo "VERSION=$RAW_VERSION" >> "$GITHUB_ENV" if [ "v$RAW_VERSION" != "$REF_NAME" ]; then echo "Error: Git tag ($REF_NAME) does not match hatch version (v$RAW_VERSION)" exit 1 @@ -39,12 +39,12 @@ jobs: env: VERSION: ${{ env.VERSION }} run: | - if curl -s -f https://pypi.org/pypi/socketsecurity/$VERSION/json > /dev/null; then + if curl -s -f "https://pypi.org/pypi/socketsecurity/$VERSION/json" > /dev/null; then echo "Version ${VERSION} already exists on PyPI" - echo "pypi_exists=true" >> $GITHUB_OUTPUT + echo "pypi_exists=true" >> "$GITHUB_OUTPUT" else echo "Version ${VERSION} not found on PyPI - proceeding with PyPI deployment" - echo "pypi_exists=false" >> $GITHUB_OUTPUT + echo "pypi_exists=false" >> "$GITHUB_OUTPUT" fi - name: Check Docker image existence @@ -54,9 +54,9 @@ jobs: run: | if curl -s -f "https://hub.docker.com/v2/repositories/socketdev/cli/tags/${VERSION}" > /dev/null; then echo "Docker image socketdev/cli:${VERSION} already exists" - echo "docker_exists=true" >> $GITHUB_OUTPUT + echo "docker_exists=true" >> "$GITHUB_OUTPUT" else - echo "docker_exists=false" >> $GITHUB_OUTPUT + echo "docker_exists=false" >> "$GITHUB_OUTPUT" fi - name: Build package @@ -70,7 +70,7 @@ jobs: uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 - name: Set up Docker publishing - uses: $/.github/actions/setup-docker + uses: ./.github/actions/setup-docker with: dockerhub-username: ${{ secrets.DOCKERHUB_USERNAME }} dockerhub-token: ${{ secrets.DOCKERHUB_TOKEN }} diff --git a/.github/workflows/version-check.yml b/.github/workflows/version-check.yml index ae187338..2c45fbdb 100644 --- a/.github/workflows/version-check.yml +++ b/.github/workflows/version-check.yml @@ -29,106 +29,7 @@ jobs: python -m pip install --upgrade pip pip install packaging - # Get version from current PR - PR_VERSION=$(grep -o "__version__.*" socketsecurity/__init__.py | awk '{print $3}' | tr -d "'") - echo "PR_VERSION=$PR_VERSION" >> $GITHUB_ENV - - # Get version from main branch - MAIN_VERSION=$(git show origin/main:socketsecurity/__init__.py | grep -o "__version__.*" | awk '{print $3}' | tr -d "'") - echo "MAIN_VERSION=$MAIN_VERSION" >> $GITHUB_ENV - - export PR_VERSION - export MAIN_VERSION - - # Compare against the latest published PyPI release. - python3 <<'PY' - import json - import os - import subprocess - import tomllib - import urllib.request - from packaging import version - - pr_ver = version.parse(os.environ["PR_VERSION"]) - main_ver = version.parse(os.environ["MAIN_VERSION"]) - - with open("pyproject.toml", "rb") as fh: - pyproject_ver = version.parse(tomllib.load(fh)["project"]["version"]) - - # The version is two hand-maintained literals with nothing deriving one - # from the other: pyproject.toml is what actually gets published, and - # socketsecurity/__init__.py is what the CLI reports as its User-Agent. - # Every comparison below reads only __init__.py, so bumping that alone - # would pass this job and then publish under the old number -- caught - # late, by twine rejecting an existing file, after the merge. Require - # the two to agree before comparing anything. (uv.lock carries a third - # copy, but uv derives it and `uv lock --locked` in python-tests - # already fails when it drifts.) - if pr_ver != pyproject_ver: - print( - f"โŒ Version mismatch inside the PR: pyproject.toml is " - f"{pyproject_ver}, socketsecurity/__init__.py is {pr_ver}. " - f"Bump both." - ) - raise SystemExit(1) - - with urllib.request.urlopen("https://pypi.org/pypi/socketsecurity/json") as response: - pypi_data = json.load(response) - - published_versions = [] - for raw in pypi_data.get("releases", {}).keys(): - parsed = version.parse(raw) - if not parsed.is_prerelease and not parsed.is_devrelease: - published_versions.append(parsed) - - pypi_ver = max(published_versions) if published_versions else version.parse("0.0.0") - - # The only hard requirement is that the version is ahead of what is - # actually released. Treating main's version as a second floor breaks - # the legitimate case where several PRs share one unreleased release: - # the first bumps main to the new version and the rest ride it without - # bumping again, which is what keeps them under a single changelog - # header. Main is therefore only a floor when this PR moves the - # version -- a change to it must go forwards, never backwards. - if pr_ver <= pypi_ver: - print( - f"โŒ Version {pr_ver} is already published on PyPI " - f"(latest release: {pypi_ver}). Bump it." - ) - raise SystemExit(1) - - # Releases are immutable: once a v release is published, its tag can't - # be moved or reused, even when that release failed and nothing reached PyPI. - # PyPI alone misses that, so a burned tag would only surface when the release - # run fails after the merge. - tag = f"v{os.environ['PR_VERSION']}" - if subprocess.run( - ["git", "rev-parse", "--quiet", "--verify", f"refs/tags/{tag}"], - capture_output=True, - ).returncode == 0: - print( - f"โŒ Tag {tag} already exists, so {pr_ver} can never be released " - f"(latest PyPI release: {pypi_ver}). Bump to a version with no tag." - ) - raise SystemExit(1) - - if pr_ver < main_ver: - print( - f"โŒ Version moves backwards: main is {main_ver}, PR is {pr_ver}." - ) - raise SystemExit(1) - - if pr_ver == main_ver: - print( - f"โœ… Riding main's unreleased {pr_ver} " - f"(latest PyPI release: {pypi_ver})." - ) - else: - print( - f"โœ… Version properly incremented. " - f"Main: {main_ver}, PyPI: {pypi_ver}, PR: {pr_ver}" - ) - PY + python3 .hooks/check_version.py - name: Require uv.lock update when pyproject changes run: | diff --git a/.hooks/check_version.py b/.hooks/check_version.py new file mode 100644 index 00000000..4b2be5c1 --- /dev/null +++ b/.hooks/check_version.py @@ -0,0 +1,88 @@ +"""Validate release versions for pull requests that change packaged files.""" + +import json +import os +import re +import subprocess +import tomllib +import urllib.request +from pathlib import Path + +from packaging.version import Version + + +def read_version(source: str) -> Version: + match = re.search(r"^__version__\s*=\s*['\"]([^'\"]+)['\"]", source, re.MULTILINE) + if not match: + raise ValueError("No __version__ declaration found") + return Version(match.group(1)) + + +def latest_pypi_version() -> Version: + with urllib.request.urlopen("https://pypi.org/pypi/socketsecurity/json") as response: + releases = json.load(response).get("releases", {}) + versions = (Version(raw) for raw in releases) + return max((v for v in versions if not v.is_prerelease and not v.is_devrelease), default=Version("0.0.0")) + + +def main() -> int: + pr_ver = read_version(Path("socketsecurity/__init__.py").read_text()) + main_ver = read_version( + subprocess.check_output(["git", "show", "origin/main:socketsecurity/__init__.py"], text=True) + ) + changed_paths = subprocess.check_output( + ["git", "diff", "--name-only", "origin/main...HEAD"], text=True + ).splitlines() + enforced = any( + name.startswith("socketsecurity/") or name in {"pyproject.toml", "uv.lock"} for name in changed_paths + ) + + if github_env := os.environ.get("GITHUB_ENV"): + with open(github_env, "a", encoding="utf-8") as env_file: + env_file.write(f"PR_VERSION={pr_ver}\nMAIN_VERSION={main_ver}\n") + + def reject(message: str) -> int: + print(message) + if enforced: + return 1 + print("โ„น๏ธ Not enforced: this PR changes no packaged files, so it ships nothing that needs a new version.") + return 0 + + with open("pyproject.toml", "rb") as project_file: + pyproject_ver = Version(tomllib.load(project_file)["project"]["version"]) + if pr_ver != pyproject_ver: + return reject( + f"โŒ Version mismatch inside the PR: pyproject.toml is {pyproject_ver}, " + f"socketsecurity/__init__.py is {pr_ver}. Bump both." + ) + + pypi_ver = latest_pypi_version() + if pr_ver <= pypi_ver: + return reject(f"โŒ Version {pr_ver} is already published on PyPI (latest release: {pypi_ver}). Bump it.") + + # Published release tags are immutable, even if publication to PyPI fails. + tag = f"v{pr_ver}" + if ( + subprocess.run( + ["git", "rev-parse", "--quiet", "--verify", f"refs/tags/{tag}"], capture_output=True, check=False + ).returncode + == 0 + ): + return reject( + f"โŒ Tag {tag} already exists, so {pr_ver} can never be released " + f"(latest PyPI release: {pypi_ver}). Bump to a version with no tag." + ) + + if pr_ver < main_ver: + return reject(f"โŒ Version moves backwards: main is {main_ver}, PR is {pr_ver}.") + + # Multiple pull requests may share main's unreleased version. + if pr_ver == main_ver: + print(f"โœ… Riding main's unreleased {pr_ver} (latest PyPI release: {pypi_ver}).") + else: + print(f"โœ… Version properly incremented. Main: {main_ver}, PyPI: {pypi_ver}, PR: {pr_ver}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.hooks/sync_version.py b/.hooks/sync_version.py old mode 100644 new mode 100755 index 51835c3f..50d191fe --- a/.hooks/sync_version.py +++ b/.hooks/sync_version.py @@ -16,6 +16,7 @@ PYPI_PROD_API = "https://pypi.org/pypi/socketsecurity/json" PYPI_TEST_API = "https://test.pypi.org/pypi/socketsecurity/json" + def read_version_from_init(path: pathlib.Path) -> str: content = path.read_text() match = VERSION_PATTERN.search(content) @@ -24,6 +25,7 @@ def read_version_from_init(path: pathlib.Path) -> str: sys.exit(1) return match.group(1) + def read_version_from_git(path: str) -> str: try: output = subprocess.check_output(["git", "show", f"HEAD:{path}"], text=True) @@ -34,6 +36,7 @@ def read_version_from_git(path: str) -> str: except subprocess.CalledProcessError: return None + def bump_patch_version(version: str) -> str: if ".dev" in version: version = version.split(".dev")[0] @@ -41,6 +44,7 @@ def bump_patch_version(version: str) -> str: parts[-1] = str(int(parts[-1]) + 1) return ".".join(parts) + def parse_stable_version(version: str): if not STABLE_VERSION_PATTERN.fullmatch(version): return None @@ -72,6 +76,7 @@ def fetch_latest_stable_pypi_version(): return None return max(stable_versions) + def find_next_available_dev_version(base_version: str) -> str: existing_versions = fetch_existing_versions(PYPI_TEST_API) for i in range(1, 100): @@ -94,12 +99,13 @@ def find_next_stable_patch_version(current_version: str) -> str: next_parts = (base_parts[0], base_parts[1], base_parts[2] + 1) return format_stable_version(next_parts) + def inject_version(version: str): print(f"๐Ÿ” Updating version to: {version}") # Update __init__.py init_content = INIT_FILE.read_text() - new_init_content = VERSION_PATTERN.sub(f"__version__ = '{version}'", init_content) + new_init_content = VERSION_PATTERN.sub(f'__version__ = "{version}"', init_content) INIT_FILE.write_text(new_init_content) # Update pyproject.toml @@ -190,16 +196,21 @@ def main(): inject_version(new_version) uv_lock_changed = run_uv_lock() lock_hint = " and uv.lock" if uv_lock_changed else "" - print(f"โš ๏ธ Version {current_version} is already published on PyPI โ€” auto-bumped to {new_version}. Please git add{lock_hint} + commit again.") + print( + f"โš ๏ธ Version {current_version} is already published on PyPI โ€” auto-bumped to {new_version}. Please git add{lock_hint} + commit again." + ) sys.exit(1) uv_lock_changed = run_uv_lock() if uv_lock_changed: - print("โš ๏ธ Version already bumped, but uv.lock was out of date and has been updated. Please git add uv.lock + commit again.") + print( + "โš ๏ธ Version already bumped, but uv.lock was out of date and has been updated. Please git add uv.lock + commit again." + ) sys.exit(1) print("โœ… Version already bumped and uv.lock is up to date โ€” proceeding.") sys.exit(0) + if __name__ == "__main__": main() diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index d201e7f5..bacb47be 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -6,4 +6,19 @@ repos: entry: python .hooks/sync_version.py language: python always_run: true - pass_filenames: false \ No newline at end of file + pass_filenames: false + + # Use the project's locked Ruff version, shared with CI and make lint. + - id: ruff-check + name: ruff check + entry: uv run --locked --extra dev ruff check --force-exclude --fix + language: system + types_or: [python, pyi] + require_serial: true + + - id: ruff-format + name: ruff format + entry: uv run --locked --extra dev ruff format --force-exclude + language: system + types_or: [python, pyi] + require_serial: true diff --git a/CHANGELOG.md b/CHANGELOG.md index 018a314a..0c08eb62 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,25 @@ # Changelog +## 2.15.11 + +### Fixed + +- Configuration debug output masks credential fields and integration URL paths, + including nested plugin settings and Slack webhook lists. Slack configuration + environment contents are reported only as set or unset. +- The ignore-command authorization policy remains visible in configuration + debug output so comment-handling decisions can be diagnosed. +- Alert timestamps retain their leading and trailing characters when the + optional timezone suffix is removed. +- Slack, Teams, Jira, webhook, and GitLab commit-status requests use a 30-second + timeout so an unresponsive endpoint cannot hold a scan open indefinitely. +- Jira request failures are logged without interrupting report file creation or + changing the scan's exit code. +- Manifest upload validation also runs under `python -O`. +- Duplicate SBOM package diagnostics use debug logging, keeping stdout available + for machine-readable reports. +- Configuration warnings and errors use the CLI's configured logger. + ## 2.15.10 ### Added diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ed9ee2b0..a359169f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -11,9 +11,16 @@ dependencies: uv sync --all-extras ``` +Install the git hooks once per clone: + +```bash +make hooks +``` + Before opening a pull request, run: ```bash +make lint make test uv run hatch build uv run python -m twine check dist/* @@ -22,6 +29,58 @@ uv run python -m twine check dist/* To develop against a local SDK checkout, set `SOCKET_SDK_PATH` if it is not at `../socketdev`, then run `make first-time-local-setup`. +## Linting + +Ruff reads the rule set from `pyproject.toml`. Its version is pinned in the +project's `dev` extra and resolved in `uv.lock` for local commands, pre-commit, +and CI. + +- `make lint` checks linting and formatting across the repository. +- `make lint-fix` applies safe lint fixes; `make format` formats Python files. +- The pre-commit hooks fix and format the files in a commit. When they modify a + file, review and stage the edits before committing again. +- The `Lint` workflow checks the whole repository on every pull request and + every push to `main`, including `.hooks/`, benchmarks, and end-to-end tooling. + It has no path filter, so it can report on every pull request when configured + as a required check. + +The formatter uses a line length of 120. `E501` and `W291`/`W293` are not +selected: whitespace inside strings can affect help text, logs, and rendered +Markdown. In particular, trailing double-spaces in pull request comment strings +are Markdown hard line breaks. + +### One trap worth knowing + +Never run `ruff check --select --fix` with `RUF100` in the select. +With a narrow select, RUF100 considers every `# noqa` for a *non-selected* rule +to be unused and deletes it -- silently stripping the complexity suppressions +across the repository. Run `make lint-fix`, which uses the full configured rule +set, instead of hand-rolling a `--select`. + +### Complexity limits + +Two rules bound how large a single function may get: + +| Rule | Limit | What it measures | +| --- | --- | --- | +| `C901` | 12 | Cyclomatic complexity: independent paths through a function. | +| `PLR0913` | 8 | Arguments in a function definition. | + +Functions that already exceed these limits carry an explicit +`# noqa: C901` / `# noqa: PLR0913` on their `def` line. Treat these as a refactoring backlog: + +- **Do not add a new suppression.** If a function you are writing trips the + limit, split it. +- **Suppressions clean themselves up.** `RUF100` fails the build on a `# noqa` + that no longer applies, so refactoring a function back under the limit forces + the marker to be removed. + +To see what is left: + +```bash +grep -rn 'noqa: C901\|noqa: PLR0913' socketsecurity/ tests/ +``` + ## Pull request validation The `Package Check` workflow runs automatically for pull requests. It builds @@ -29,6 +88,21 @@ and validates the distributions, smoke-tests the wheel, and uploads the distributions as workflow artifacts. It does not publish a package or Docker image. +## Build tooling and release notes + +Keep the Hatch and Hatchling pins in `.github/actions/setup-hatch/action.yml` +aligned with the `dev` extra and build backend in `pyproject.toml`. + +The `Version Check` workflow enforces release-version checks for changes to +`socketsecurity/`, `pyproject.toml`, or `uv.lock`. A pull request can share +`main`'s unreleased version. CI and documentation changes alone do not require +a package version bump. Version extraction accepts single- and double-quoted +`__version__` declarations. + +Keep changelog entries short and focused on observable CLI, dashboard, or scan +log behavior. Document contributor setup and CI policies in this guide, and +describe workflow implementation changes in the pull request description. + ## Publishing pull request previews Preview publication is intentionally opt-in. Only request previews for code diff --git a/Makefile b/Makefile index c0fb1b01..b6fb52ee 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: setup sync clean test lint update-lock local-dev first-time-setup dev-setup sync-all first-time-local-setup +.PHONY: setup sync clean test lint lint-fix format format-check hooks update-lock local-dev first-time-setup dev-setup sync-all first-time-local-setup # Environment variable for local SDK path (optional) SOCKET_SDK_PATH ?= ../socketdev @@ -57,6 +57,20 @@ clean: test: uv run pytest +# Installs the git pre-commit hooks (ruff + version sync). +hooks: + uv run --locked --extra dev pre-commit install + +# Run the same Ruff checks as the Lint workflow. lint: - uv run ruff check . - uv run ruff format --check . \ No newline at end of file + uv run --locked --extra dev ruff check + uv run --locked --extra dev ruff format --check + +lint-fix: + uv run --locked --extra dev ruff check --fix + +format: + uv run --locked --extra dev ruff format + +format-check: + uv run --locked --extra dev ruff format --check diff --git a/benchmarks/manifest_discovery.py b/benchmarks/manifest_discovery.py old mode 100644 new mode 100755 index abc0e8bb..81412728 --- a/benchmarks/manifest_discovery.py +++ b/benchmarks/manifest_discovery.py @@ -47,8 +47,8 @@ def legacy_discover(root: Path) -> set[str]: insensitive = Core.to_case_insensitive_regex(pattern) for candidate in root.rglob(insensitive): if candidate.is_file() and not Core.is_excluded( - str(candidate), - excluded_dirs, + str(candidate), + excluded_dirs, ): results.add(candidate.as_posix()) return results @@ -85,10 +85,7 @@ def main() -> None: ) if legacy_results != new_results: - raise SystemExit( - "Manifest result mismatch: " - f"legacy={len(legacy_results)}, single_pass={len(new_results)}" - ) + raise SystemExit(f"Manifest result mismatch: legacy={len(legacy_results)}, single_pass={len(new_results)}") speedup = legacy_seconds / new_seconds if new_seconds else float("inf") print(f"Manifests: {len(new_results)}") diff --git a/pyproject.toml b/pyproject.toml index 062b5a9d..34d95abc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "hatchling.build" [project] name = "socketsecurity" -version = "2.15.10" +version = "2.15.11" requires-python = ">= 3.11" license = {"file" = "LICENSE"} dependencies = [ @@ -85,7 +85,9 @@ show_missing = true skip_empty = true [tool.ruff] -# Exclude a variety of commonly ignored directories. +# The formatter owns physical layout. E501 and W291/W293 are unselected: +# whitespace inside help text, log messages, and Markdown strings is content. +line-length = 120 exclude = [ ".bzr", ".direnv", @@ -116,25 +118,104 @@ exclude = [ ] [tool.ruff.lint] -# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default. -# Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or -# McCabe complexity (`C901`) by default. select = [ - "E4", "E7", "E9", "F", # Current rules - "I", # isort - "F401", # Unused imports - "F403", # Star imports - "F405", # Star imports undefined - "F821", # Undefined names + # --- Baseline correctness ------------------------------------------- + "E4", # pycodestyle: import formatting + "E7", # pycodestyle: statement-level errors + "E9", # pycodestyle: syntax/IO errors + "W605", # invalid escape sequence in a string literal + "F", # Pyflakes: undefined names, unused imports, star imports + "I", # isort: deterministic import order + "PLE", # Pylint errors: unambiguous bugs, never style + + # --- Complexity guardrails ------------------------------------------ + "C901", # McCabe cyclomatic complexity + "PLR0913", # too many arguments in a function definition + + # --- Correctness checks -------------------------------------------- + "ASYNC", # blocking calls inside async functions + "B", # bugbear: loop-variable capture, missing `raise ... from` + "C4", # comprehension misuse + "DTZ", # naive datetimes: scan timestamps must be tz-aware + "EXE", # shebang / executable-bit mismatches in a packaged wheel + "FLY", # static str.join() that should be an f-string + "FURB", # modern-Python refactors + "ICN", # conventional import aliases + "INT", # gettext f-string traps + "LOG", # logging misuse + "PERF", # avoidable per-iteration work + "PIE", # dead code and redundant constructs + "PLW", # Pylint warnings: unchecked subprocess, loop-var rebinding + "RET", # unreachable or redundant return flow + "RSE", # raise Exception() -- not raise Exception + "RUF", # Ruff-native checks (incl. RUF100, see below) + "S", # bandit: request timeouts, unsafe subprocess, weak randomness + "SIM", # simplifiable branches and context managers + "SLOT", # __slots__ on subclasses of str/tuple/namedtuple + "T10", # leftover breakpoint()/pdb.set_trace() reaching a release + "T20", # stray print(): stdout is a contract for a CLI, not a debug log + "TID", # relative imports + "UP", # pyupgrade follows requires-python + "YTT", # incorrect sys.version comparisons + + # Individually selected because their siblings are style opinions + # (PLR2004 magic values, PLC0415 deliberate lazy imports, TRY003 + # message length) that would cost more than they catch here. + "PLR1714", # repeated equality comparison -> `in` + "PLR1722", # `exit()` -> `sys.exit()`: `exit` only exists when `site` ran + "PLR1730", # if-statement that should be min()/max() + "PLR5501", # else-if that should be elif + "TRY201", # `raise` instead of re-raising the bound name + + # --- Keeping the suppressions honest -------------------------------- + "PGH", # no blanket `# noqa` / `# type: ignore` -- codes required + "RUF100", # unused `# noqa` -- makes the grandfather list self-cleaning +] + +ignore = [ + # Keep expected failures readable without requiring tracebacks. + "TRY400", + "TRY401", + "SIM108", # retain comments on if/else branches + "PERF401", # retain readable loops for multi-line dictionary construction + "S603", # git and Coana use argument lists; shell=True remains checked + "S607", # git, node, and other tools intentionally resolve through PATH ] # Allow fix for all enabled rules (when `--fix`) is provided. fixable = ["ALL"] unfixable = [] +# The information glyph is deliberate UI in the PR-comment markup. +allowed-confusables = ["โ„น"] + # Allow unused variables when underscore-prefixed. dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$" +[tool.ruff.lint.mccabe] +# Existing over-limit functions have explicit suppressions. Split new functions +# that exceed the limit; RUF100 rejects suppressions that become unnecessary. +max-complexity = 12 + +[tool.ruff.lint.pylint] +# Allow ordinary CLI constructors while bounding argument-heavy interfaces. +max-args = 8 + +[tool.ruff.lint.per-file-ignores] +# Tests use assertions, placeholder credentials, and fixed fixture paths. +"tests/**" = [ + "S101", # asserts are the point + "S105", # throwaway credentials in fixtures + "S106", + "S108", # fixed temp paths in fixtures + "T201", # diagnostic prints; pytest captures stdout anyway + "RUF012", # ClassVar annotations on test-local constants are noise +] + +# Developer tooling, not shipped in the wheel. stdout is their entire interface. +".hooks/**" = ["T201", "S310"] # fetches a hardcoded PyPI JSON endpoint +"benchmarks/**" = ["T201"] + [tool.ruff.lint.isort] known-first-party = ["socketsecurity"] diff --git a/scripts/build_container.sh b/scripts/build_container.sh index 2e078d40..f60e8d38 100755 --- a/scripts/build_container.sh +++ b/scripts/build_container.sh @@ -1,5 +1,5 @@ #!/bin/sh -VERSION=$(grep -o "__version__.*" socketsecurity/__init__.py | awk '{print $3}' | tr -d "'") +VERSION=$(grep -E '^__version__[[:space:]]*=' socketsecurity/__init__.py | awk '{print $3}' | tr -d "\"'") ENABLE_PYPI_BUILD=$1 STABLE_VERSION=$2 diff --git a/scripts/build_container_flexible.sh b/scripts/build_container_flexible.sh index 4ecbc7ad..01d220d9 100644 --- a/scripts/build_container_flexible.sh +++ b/scripts/build_container_flexible.sh @@ -1,5 +1,5 @@ #!/bin/sh -VERSION=$(grep -o "__version__.*" socketsecurity/__init__.py | awk '{print $3}' | tr -d "'") +VERSION=$(grep -E '^__version__[[:space:]]*=' socketsecurity/__init__.py | awk '{print $3}' | tr -d "\"'") ENABLE_PYPI_BUILD=$1 STABLE_VERSION=$2 GO_VERSION=${GO_VERSION:-"1.21"} diff --git a/scripts/deploy-test-pypi.sh b/scripts/deploy-test-pypi.sh index 408cc92e..0152acb3 100755 --- a/scripts/deploy-test-pypi.sh +++ b/scripts/deploy-test-pypi.sh @@ -4,7 +4,7 @@ # Get version from __init__.py INIT_FILE="socketsecurity/__init__.py" -ORIGINAL_VERSION=$(grep -o "__version__.*" $INIT_FILE | awk '{print $3}' | tr -d "'") +ORIGINAL_VERSION=$(grep -E '^__version__[[:space:]]*=' $INIT_FILE | awk '{print $3}' | tr -d "\"'") BACKUP_FILE="${INIT_FILE}.bak" # Get existing versions from TestPyPI @@ -37,7 +37,7 @@ echo "Deploying version ${VERSION} to Test PyPI" cp $INIT_FILE $BACKUP_FILE # Update version in __init__.py -sed -i.tmp "s/__version__ = '${ORIGINAL_VERSION}'/__version__ = '${VERSION}'/" $INIT_FILE +sed -i.tmp -E "s/__version__ = ['\"]${ORIGINAL_VERSION}['\"]/__version__ = \"${VERSION}\"/" $INIT_FILE rm "${INIT_FILE}.tmp" # Build and upload to test PyPI diff --git a/session.md b/session.md index 5707e679..186c9406 100644 --- a/session.md +++ b/session.md @@ -66,7 +66,7 @@ Keep all existing webhook functionality unchanged. ```python { "channel": "channel-name", # or "C1234567890" - "blocks": blocks + "blocks": blocks, } ``` - Headers: `{"Authorization": f"Bearer {bot_token}", "Content-Type": "application/json"}` diff --git a/socketsecurity/__init__.py b/socketsecurity/__init__.py index 967132e7..9b544bd3 100644 --- a/socketsecurity/__init__.py +++ b/socketsecurity/__init__.py @@ -1,4 +1,4 @@ -__author__ = 'socket.dev' -__version__ = '2.15.10' -USER_AGENT_NAME = 'socket-python-cli' -USER_AGENT = f'{USER_AGENT_NAME}/{__version__}' +__author__ = "socket.dev" +__version__ = "2.15.11" +USER_AGENT_NAME = "socket-python-cli" +USER_AGENT = f"{USER_AGENT_NAME}/{__version__}" diff --git a/socketsecurity/config.py b/socketsecurity/config.py index 7edb65e1..f690dfc6 100644 --- a/socketsecurity/config.py +++ b/socketsecurity/config.py @@ -5,19 +5,23 @@ import sys import tomllib from dataclasses import asdict, dataclass, field -from typing import List, NoReturn, Optional +from typing import NoReturn from socketdev import INTEGRATION_TYPES, IntegrationType from socketsecurity import __version__ from socketsecurity.exit_codes import EXIT_USAGE +from socketsecurity.redaction import redact_mapping + +log = logging.getLogger("socketcli") def _usage_error(message: str) -> NoReturn: """Log an invalid flag or config value and exit like an argparse usage error.""" - logging.error(message) + log.error(message) sys.exit(EXIT_USAGE) + def get_plugin_config_from_env(prefix: str) -> dict: config_str = os.getenv(f"{prefix}_CONFIG_JSON", "{}") try: @@ -37,13 +41,13 @@ def get_plugin_config_from_env(prefix: str) -> dict: COMMIT_MESSAGE_TRUNCATION_MARKER = "..." -def truncate_commit_message(commit_message: Optional[str]) -> Optional[str]: +def truncate_commit_message(commit_message: str | None) -> str | None: """Cap commit_message to a length the full-scan request line can carry.""" if commit_message and len(commit_message) > MAX_COMMIT_MESSAGE_LENGTH: # INFO, not DEBUG: the scan keeps the truncated value, so for a CI job that does # not pass --enable-debug this line is the only explanation of why the message in # the dashboard is clipped. - logging.info( + log.info( f"commit_message truncated from {len(commit_message)} to " f"{MAX_COMMIT_MESSAGE_LENGTH} characters to stay within API request size limits" ) @@ -91,7 +95,7 @@ def load_cli_config_file(config_path: str) -> dict: return data -def parse_files(value) -> List[str]: +def parse_files(value) -> list[str]: """Read CLI/config file lists before credentials or scan setup are evaluated.""" if isinstance(value, str): encoded = value.strip() @@ -110,7 +114,8 @@ def parse_files(value) -> List[str]: _usage_error("--files must be a JSON array of nonempty file paths") return value -def normalize_exclude_paths(value) -> Optional[List[str]]: + +def normalize_exclude_paths(value) -> list[str] | None: """Normalize a --exclude-paths value into a clean list of patterns. Accepts a comma-separated string (CLI) or a list/tuple (e.g. a JSON/TOML --config file @@ -128,7 +133,7 @@ def normalize_exclude_paths(value) -> Optional[List[str]]: return cleaned or None -def validate_exclude_paths(patterns: List[str]) -> None: +def validate_exclude_paths(patterns: list[str]) -> None: """Validate --exclude-paths patterns (mirrors Node's assertValidExcludePaths). Patterns are scan-root-relative globs. Reject the cases coana's --exclude-dirs / fast-glob @@ -153,40 +158,40 @@ def validate_exclude_paths(patterns: List[str]) -> None: @dataclass class PluginConfig: enabled: bool = False - levels: List[str] = None - config: Optional[dict] = None + levels: list[str] = None + config: dict | None = None @dataclass class CliConfig: api_token: str - repo: Optional[str] + repo: str | None branch: str = "" - committers: Optional[List[str]] = None + committers: list[str] | None = None pr_number: str = "0" pr_number_explicit: bool = False - commit_message: Optional[str] = None + commit_message: str | None = None default_branch: bool = False target_path: str = "./" scm: str = "api" - sbom_file: Optional[str] = None + sbom_file: str | None = None commit_sha: str = "" - base_scan_id: Optional[str] = None - base_commit_sha: Optional[str] = None + base_scan_id: str | None = None + base_commit_sha: str | None = None generate_license: bool = False enable_debug: bool = False allow_unverified: bool = False enable_json: bool = False - json_file: Optional[str] = None + json_file: str | None = None enable_sarif: bool = False - sarif_file: Optional[str] = None + sarif_file: str | None = None sarif_scope: str = "diff" sarif_grouping: str = "instance" sarif_reachability: str = "all" enable_gitlab_security: bool = False - gitlab_security_file: Optional[str] = None - summary_file: Optional[str] = None - report_link_file: Optional[str] = None + gitlab_security_file: str | None = None + summary_file: str | None = None + report_link_file: str | None = None disable_overview: bool = False disable_security_issue: bool = False files: str = None @@ -196,46 +201,46 @@ class CliConfig: ignore_authorization: str = "enforce" # Tri-state log-upload preference: True = --upload-logs, False = --no-upload-logs, # None = neither (server-side override decides). - upload_logs: Optional[bool] = None + upload_logs: bool | None = None strict_blocking: bool = False integration_type: IntegrationType = "api" - integration_org_slug: Optional[str] = None + integration_org_slug: str | None = None pending_head: bool = False enable_diff: bool = False - timeout: Optional[int] = 1200 + timeout: int | None = 1200 exit_code_on_api_error: int = 3 exclude_license_details: bool = False include_module_folders: bool = False repo_is_public: bool = False - excluded_ecosystems: list[str] = field(default_factory=lambda: []) - exclude_paths: Optional[List[str]] = None - included_dirs: List[str] = field(default_factory=lambda: []) + excluded_ecosystems: list[str] = field(default_factory=list) + exclude_paths: list[str] | None = None + included_dirs: list[str] = field(default_factory=list) version: str = __version__ jira_plugin: PluginConfig = field(default_factory=PluginConfig) slack_plugin: PluginConfig = field(default_factory=PluginConfig) - slack_webhook: Optional[str] = None + slack_webhook: str | None = None license_file_name: str = "license_output.json" - save_submitted_files_list: Optional[str] = None - save_manifest_tar: Optional[str] = None - sub_paths: List[str] = field(default_factory=list) - workspace_name: Optional[str] = None - workspace: Optional[str] = None + save_submitted_files_list: str | None = None + save_manifest_tar: str | None = None + sub_paths: list[str] = field(default_factory=list) + workspace_name: str | None = None + workspace: str | None = None # Web URL of the scanned repository, resolved at runtime; see resolve_repository_url. - repository_url: Optional[str] = None + repository_url: str | None = None # Reachability Flags reach: bool = False - reach_version: Optional[str] = None - reach_analysis_memory_limit: Optional[str] = None - reach_analysis_timeout: Optional[str] = None + reach_version: str | None = None + reach_analysis_memory_limit: str | None = None + reach_analysis_timeout: str | None = None reach_disable_analytics: bool = False reach_detailed_analysis_log_file: bool = False - reach_ecosystems: Optional[List[str]] = None - reach_exclude_paths: Optional[List[str]] = None + reach_ecosystems: list[str] | None = None + reach_exclude_paths: list[str] | None = None reach_skip_cache: bool = False - reach_min_severity: Optional[str] = None - reach_output_file: Optional[str] = None - reach_concurrency: Optional[int] = None - reach_additional_params: Optional[List[str]] = None + reach_min_severity: str | None = None + reach_output_file: str | None = None + reach_concurrency: int | None = None + reach_additional_params: list[str] | None = None only_facts_file: bool = False reach_use_only_pregenerated_sboms: bool = False reach_continue_on_analysis_errors: bool = False @@ -249,7 +254,7 @@ class CliConfig: enable_commit_status: bool = False legal: bool = False legal_format: str = "socket" - config_file: Optional[str] = None + config_file: str | None = None def __post_init__(self): # Capped on construction so that every source of commit_message -- the @@ -258,14 +263,14 @@ def __post_init__(self): self.commit_message = truncate_commit_message(self.commit_message) @classmethod - def from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig': + def from_args(cls, args_list: list[str] | None = None) -> "CliConfig": try: return cls._from_args(args_list) except (TypeError, ValueError, AttributeError) as error: _usage_error(f"Invalid CLI configuration: {error}") @classmethod - def _from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig': + def _from_args(cls, args_list: list[str] | None = None) -> "CliConfig": # noqa: C901 parser = create_argument_parser() pre_parser = argparse.ArgumentParser(add_help=False) @@ -291,7 +296,9 @@ def _from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig': if value is None: continue option = action.option_strings[0] if action.option_strings else action.dest - if isinstance(action, (argparse._StoreTrueAction, argparse._StoreFalseAction)) and not isinstance(value, bool): + if isinstance(action, (argparse._StoreTrueAction, argparse._StoreFalseAction)) and not isinstance( + value, bool + ): parser.error(f"{option} must be a boolean") if action.type is int and (not isinstance(value, int) or isinstance(value, bool)): parser.error(f"{option} must be an integer") @@ -305,26 +312,22 @@ def _from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig': integration_type = getattr(args, "integration", "api") pr_number = getattr(args, "pr_number", "0") - if ( - not integration_explicit and - integration_type == "api" and - args.scm in ("github", "gitlab") - ): + if not integration_explicit and integration_type == "api" and args.scm in ("github", "gitlab"): integration_type = args.scm if args.reach_exclude_paths: - logging.warning( + log.warning( "--reach-exclude-paths is deprecated; use --exclude-paths instead. " "It is still honored and unioned with --exclude-paths." ) # Get API token from env or args (check multiple env var names) api_token = ( - os.getenv("SOCKET_SECURITY_API_KEY") or - os.getenv("SOCKET_SECURITY_API_TOKEN") or - os.getenv("SOCKET_API_KEY") or - os.getenv("SOCKET_API_TOKEN") or - args.api_token + os.getenv("SOCKET_SECURITY_API_KEY") + or os.getenv("SOCKET_SECURITY_API_TOKEN") + or os.getenv("SOCKET_API_KEY") + or os.getenv("SOCKET_API_TOKEN") + or args.api_token ) # --sarif-file implies --enable-sarif @@ -337,119 +340,119 @@ def _from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig': commit_message = commit_message[1:-1] config_args = { - 'api_token': api_token, - 'repo': args.repo, - 'branch': args.branch, - 'committers': args.committers, - 'pr_number': pr_number, - 'pr_number_explicit': pr_number_explicit, - 'commit_message': commit_message, - 'default_branch': args.default_branch, - 'target_path': os.path.expanduser(args.target_path), - 'scm': args.scm, - 'sbom_file': args.sbom_file, - 'commit_sha': args.commit_sha, - 'base_scan_id': args.base_scan_id, - 'base_commit_sha': args.base_commit_sha, - 'generate_license': args.generate_license, - 'enable_debug': args.enable_debug, - 'enable_diff': args.enable_diff, - 'allow_unverified': args.allow_unverified, - 'enable_json': args.enable_json, - 'json_file': args.json_file, - 'enable_sarif': args.enable_sarif, - 'sarif_file': args.sarif_file, - 'sarif_scope': args.sarif_scope, - 'sarif_grouping': args.sarif_grouping, - 'sarif_reachability': args.sarif_reachability, - 'enable_gitlab_security': args.enable_gitlab_security, - 'gitlab_security_file': args.gitlab_security_file, - 'summary_file': args.summary_file, - 'report_link_file': args.report_link_file, - 'disable_overview': args.disable_overview, - 'disable_security_issue': args.disable_security_issue, - 'files': args.files, - 'ignore_commit_files': args.ignore_commit_files, - 'disable_blocking': args.disable_blocking, - 'disable_ignore': args.disable_ignore, - 'ignore_authorization': args.ignore_authorization, - 'upload_logs': args.upload_logs, - 'strict_blocking': args.strict_blocking, - 'integration_type': integration_type, - 'pending_head': args.pending_head, - 'timeout': args.timeout, - 'exit_code_on_api_error': args.exit_code_on_api_error, - 'exclude_license_details': args.exclude_license_details, - 'include_module_folders': args.include_module_folders, - 'repo_is_public': args.repo_is_public, + "api_token": api_token, + "repo": args.repo, + "branch": args.branch, + "committers": args.committers, + "pr_number": pr_number, + "pr_number_explicit": pr_number_explicit, + "commit_message": commit_message, + "default_branch": args.default_branch, + "target_path": os.path.expanduser(args.target_path), + "scm": args.scm, + "sbom_file": args.sbom_file, + "commit_sha": args.commit_sha, + "base_scan_id": args.base_scan_id, + "base_commit_sha": args.base_commit_sha, + "generate_license": args.generate_license, + "enable_debug": args.enable_debug, + "enable_diff": args.enable_diff, + "allow_unverified": args.allow_unverified, + "enable_json": args.enable_json, + "json_file": args.json_file, + "enable_sarif": args.enable_sarif, + "sarif_file": args.sarif_file, + "sarif_scope": args.sarif_scope, + "sarif_grouping": args.sarif_grouping, + "sarif_reachability": args.sarif_reachability, + "enable_gitlab_security": args.enable_gitlab_security, + "gitlab_security_file": args.gitlab_security_file, + "summary_file": args.summary_file, + "report_link_file": args.report_link_file, + "disable_overview": args.disable_overview, + "disable_security_issue": args.disable_security_issue, + "files": args.files, + "ignore_commit_files": args.ignore_commit_files, + "disable_blocking": args.disable_blocking, + "disable_ignore": args.disable_ignore, + "ignore_authorization": args.ignore_authorization, + "upload_logs": args.upload_logs, + "strict_blocking": args.strict_blocking, + "integration_type": integration_type, + "pending_head": args.pending_head, + "timeout": args.timeout, + "exit_code_on_api_error": args.exit_code_on_api_error, + "exclude_license_details": args.exclude_license_details, + "include_module_folders": args.include_module_folders, + "repo_is_public": args.repo_is_public, "excluded_ecosystems": args.excluded_ecosystems, - 'license_file_name': args.license_file_name, - 'save_submitted_files_list': args.save_submitted_files_list, - 'save_manifest_tar': args.save_manifest_tar, - 'sub_paths': args.sub_paths or [], - 'workspace_name': args.workspace_name, - 'workspace': args.workspace, - 'slack_webhook': args.slack_webhook, - 'reach': args.reach, - 'reach_version': args.reach_version, - 'reach_analysis_timeout': args.reach_analysis_timeout, - 'reach_analysis_memory_limit': args.reach_analysis_memory_limit, - 'reach_disable_analytics': args.reach_disable_analytics, - 'reach_detailed_analysis_log_file': args.reach_detailed_analysis_log_file, - 'reach_ecosystems': args.reach_ecosystems.split(',') if args.reach_ecosystems else None, - 'reach_exclude_paths': args.reach_exclude_paths.split(',') if args.reach_exclude_paths else None, - 'exclude_paths': normalize_exclude_paths(args.exclude_paths), - 'included_dirs': normalize_exclude_paths(args.include_dirs) or [], - 'reach_skip_cache': args.reach_skip_cache, - 'reach_min_severity': args.reach_min_severity, - 'reach_output_file': args.reach_output_file, - 'reach_concurrency': args.reach_concurrency, - 'reach_additional_params': args.reach_additional_params, - 'only_facts_file': args.only_facts_file, - 'reach_use_only_pregenerated_sboms': args.reach_use_only_pregenerated_sboms, - 'reach_continue_on_analysis_errors': args.reach_continue_on_analysis_errors, - 'reach_continue_on_install_errors': args.reach_continue_on_install_errors, - 'reach_continue_on_missing_lock_files': args.reach_continue_on_missing_lock_files, - 'reach_continue_on_no_source_files': args.reach_continue_on_no_source_files, - 'reach_debug': args.reach_debug, - 'reach_disable_external_tool_checks': args.reach_disable_external_tool_checks, - 'reach_disable_dependency_downloads': args.reach_disable_dependency_downloads, - 'max_purl_batch_size': args.max_purl_batch_size, - 'enable_commit_status': args.enable_commit_status, - 'legal': args.legal or args.legal_format == "fossa", - 'legal_format': args.legal_format, - 'config_file': args.config_file, - 'version': __version__ + "license_file_name": args.license_file_name, + "save_submitted_files_list": args.save_submitted_files_list, + "save_manifest_tar": args.save_manifest_tar, + "sub_paths": args.sub_paths or [], + "workspace_name": args.workspace_name, + "workspace": args.workspace, + "slack_webhook": args.slack_webhook, + "reach": args.reach, + "reach_version": args.reach_version, + "reach_analysis_timeout": args.reach_analysis_timeout, + "reach_analysis_memory_limit": args.reach_analysis_memory_limit, + "reach_disable_analytics": args.reach_disable_analytics, + "reach_detailed_analysis_log_file": args.reach_detailed_analysis_log_file, + "reach_ecosystems": args.reach_ecosystems.split(",") if args.reach_ecosystems else None, + "reach_exclude_paths": args.reach_exclude_paths.split(",") if args.reach_exclude_paths else None, + "exclude_paths": normalize_exclude_paths(args.exclude_paths), + "included_dirs": normalize_exclude_paths(args.include_dirs) or [], + "reach_skip_cache": args.reach_skip_cache, + "reach_min_severity": args.reach_min_severity, + "reach_output_file": args.reach_output_file, + "reach_concurrency": args.reach_concurrency, + "reach_additional_params": args.reach_additional_params, + "only_facts_file": args.only_facts_file, + "reach_use_only_pregenerated_sboms": args.reach_use_only_pregenerated_sboms, + "reach_continue_on_analysis_errors": args.reach_continue_on_analysis_errors, + "reach_continue_on_install_errors": args.reach_continue_on_install_errors, + "reach_continue_on_missing_lock_files": args.reach_continue_on_missing_lock_files, + "reach_continue_on_no_source_files": args.reach_continue_on_no_source_files, + "reach_debug": args.reach_debug, + "reach_disable_external_tool_checks": args.reach_disable_external_tool_checks, + "reach_disable_dependency_downloads": args.reach_disable_dependency_downloads, + "max_purl_batch_size": args.max_purl_batch_size, + "enable_commit_status": args.enable_commit_status, + "legal": args.legal or args.legal_format == "fossa", + "legal_format": args.legal_format, + "config_file": args.config_file, + "version": __version__, } - if config_args['legal']: - config_args['generate_license'] = True - if not config_args['json_file']: - config_args['json_file'] = "socket-report.json" - if not config_args['summary_file']: - config_args['summary_file'] = "socket-summary.txt" - if not config_args['report_link_file']: - config_args['report_link_file'] = "socket-report-link.txt" - if not config_args['sbom_file']: - config_args['sbom_file'] = "socket-sbom.json" - if config_args['license_file_name'] == "license_output.json": - config_args['license_file_name'] = "socket-license.json" - - if config_args['legal_format'] == "fossa": + if config_args["legal"]: + config_args["generate_license"] = True + if not config_args["json_file"]: + config_args["json_file"] = "socket-report.json" + if not config_args["summary_file"]: + config_args["summary_file"] = "socket-summary.txt" + if not config_args["report_link_file"]: + config_args["report_link_file"] = "socket-report-link.txt" + if not config_args["sbom_file"]: + config_args["sbom_file"] = "socket-sbom.json" + if config_args["license_file_name"] == "license_output.json": + config_args["license_file_name"] = "socket-license.json" + + if config_args["legal_format"] == "fossa": if not args.json_file: - config_args['json_file'] = "fossa-analyze.json" + config_args["json_file"] = "fossa-analyze.json" if not args.summary_file: - config_args['summary_file'] = "fossa-test.txt" + config_args["summary_file"] = "fossa-test.txt" if not args.report_link_file: - config_args['report_link_file'] = "fossa-link.txt" + config_args["report_link_file"] = "fossa-link.txt" if not args.license_file_name: # argparse always provides a default, so this branch is defensive only - config_args['license_file_name'] = "fossa-sbom.json" + config_args["license_file_name"] = "fossa-sbom.json" elif args.license_file_name == "license_output.json": - config_args['license_file_name'] = "fossa-sbom.json" + config_args["license_file_name"] = "fossa-sbom.json" if not args.sbom_file: # FOSSA's "SBOM" artifact is the attribution payload; suppress the extra Socket-only SBOM file by default. - config_args['sbom_file'] = None + config_args["sbom_file"] = None excluded_ecosystems = config_args["excluded_ecosystems"] if isinstance(excluded_ecosystems, list): config_args["excluded_ecosystems"] = excluded_ecosystems @@ -468,22 +471,24 @@ def _from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig': slack_config = get_plugin_config_from_env("SOCKET_SLACK") if args.slack_webhook: slack_config["url"] = args.slack_webhook - - config_args.update({ - "jira_plugin": PluginConfig( - enabled=os.getenv("SOCKET_JIRA_ENABLED", "false").lower() == "true", - levels=os.getenv("SOCKET_JIRA_LEVELS", "block,warn").split(","), - config=get_plugin_config_from_env("SOCKET_JIRA") - ), - "slack_plugin": PluginConfig( - enabled=bool(slack_config) or bool(args.slack_webhook), - levels=os.getenv("SOCKET_SLACK_LEVELS", "block,warn").split(","), - config=slack_config - ) - }) + + config_args.update( + { + "jira_plugin": PluginConfig( + enabled=os.getenv("SOCKET_JIRA_ENABLED", "false").lower() == "true", + levels=os.getenv("SOCKET_JIRA_LEVELS", "block,warn").split(","), + config=get_plugin_config_from_env("SOCKET_JIRA"), + ), + "slack_plugin": PluginConfig( + enabled=bool(slack_config) or bool(args.slack_webhook), + levels=os.getenv("SOCKET_SLACK_LEVELS", "block,warn").split(","), + config=slack_config, + ), + } + ) if args.owner: - config_args['integration_org_slug'] = args.owner + config_args["integration_org_slug"] = args.owner # Validate that sub_paths and workspace_name are used together if args.sub_paths and not args.workspace_name: @@ -501,7 +506,7 @@ def _from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig': ) if args.pending_head: - logging.warning( + log.warning( "--pending-head is deprecated and has no effect. A scan becomes the head scan " "when it runs on the default branch; use --default-branch to mark it as such." ) @@ -545,37 +550,38 @@ def _from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig': def to_dict(self) -> dict: return asdict(self) + def to_redacted_dict(self) -> dict: + """Return the configuration with credential fields masked for logging.""" + return redact_mapping(asdict(self)) + + def create_argument_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog="socketcli", description="Scan dependencies and report security alerts. In diff mode, blocking findings exit 1; " - "warnings alone exit 0. Invalid flags or configuration exit 2, infrastructure " - "failures exit 3 by default, and Ctrl+C exits 130." + "warnings alone exit 0. Invalid flags or configuration exit 2, infrastructure " + "failures exit 3 by default, and Ctrl+C exits 130.", ) # Authentication - auth_group = parser.add_argument_group('Authentication') + auth_group = parser.add_argument_group("Authentication") auth_group.add_argument( "--config", dest="config_file", metavar="", - help="Path to JSON/TOML file with default CLI options. CLI flags take precedence." + help="Path to JSON/TOML file with default CLI options. CLI flags take precedence.", ) auth_group.add_argument( "--api-token", dest="api_token", metavar="", help="Socket Security API token (can also be set via SOCKET_SECURITY_API_TOKEN env var)", - required=False - ) - auth_group.add_argument( - "--api_token", - dest="api_token", - help=argparse.SUPPRESS + required=False, ) + auth_group.add_argument("--api_token", dest="api_token", help=argparse.SUPPRESS) # Repository info - repo_group = parser.add_argument_group('Repository') + repo_group = parser.add_argument_group("Repository") repo_group.add_argument( "--repo", metavar="", @@ -583,28 +589,23 @@ def create_argument_parser() -> argparse.ArgumentParser: "Repository slug in Socket, without the owner (e.g. my-repo, not my-org/my-repo). " "Defaults to the git remote's repository name. Use --workspace for the owner." ), - required=False + required=False, ) repo_group.add_argument( "--workspace", metavar="", help="The workspace in the Socket Organization that the repository is in to associate with the full scan.", - required=False + required=False, ) repo_group.add_argument( "--repo-is-public", dest="repo_is_public", action="store_true", - help="If set it will flag a new repository creation as public. Defaults to false." - ) - repo_group.add_argument( - "--branch", - metavar="", - help="Branch name", - default="" + help="If set it will flag a new repository creation as public. Defaults to false.", ) + repo_group.add_argument("--branch", metavar="", help="Branch name", default="") - integration_group = parser.add_argument_group('Integration') + integration_group = parser.add_argument_group("Integration") integration_group.add_argument( "--integration", choices=INTEGRATION_TYPES, @@ -614,17 +615,17 @@ def create_argument_parser() -> argparse.ArgumentParser: "Defaults to api; --scm github/gitlab implies the matching integration " "when this option is omitted" ), - default=argparse.SUPPRESS + default=argparse.SUPPRESS, ) integration_group.add_argument( "--owner", metavar="", help="Name of the integration owner, defaults to the socket organization slug", - required=False + required=False, ) # Pull Request and Commit info - pr_group = parser.add_argument_group('Pull Request and Commit') + pr_group = parser.add_argument_group("Pull Request and Commit") pr_group.add_argument( "--pr-number", dest="pr_number", @@ -633,42 +634,15 @@ def create_argument_parser() -> argparse.ArgumentParser: "Pull request number. Auto-detected in supported CI environments when omitted; " "pass 0 explicitly to disable detection" ), - default=argparse.SUPPRESS - ) - pr_group.add_argument( - "--pr_number", - dest="pr_number", - help=argparse.SUPPRESS, - default=argparse.SUPPRESS - ) - pr_group.add_argument( - "--commit-message", - dest="commit_message", - metavar="", - help="Commit message" - ) - pr_group.add_argument( - "--commit_message", - dest="commit_message", - help=argparse.SUPPRESS - ) - pr_group.add_argument( - "--commit-sha", - dest="commit_sha", - metavar="", - default="", - help="Commit SHA" + default=argparse.SUPPRESS, ) + pr_group.add_argument("--pr_number", dest="pr_number", help=argparse.SUPPRESS, default=argparse.SUPPRESS) + pr_group.add_argument("--commit-message", dest="commit_message", metavar="", help="Commit message") + pr_group.add_argument("--commit_message", dest="commit_message", help=argparse.SUPPRESS) + pr_group.add_argument("--commit-sha", dest="commit_sha", metavar="", default="", help="Commit SHA") + pr_group.add_argument("--commit_sha", dest="commit_sha", help=argparse.SUPPRESS) pr_group.add_argument( - "--commit_sha", - dest="commit_sha", - help=argparse.SUPPRESS - ) - pr_group.add_argument( - "--committers", - metavar="", - help="Committer for the commit (comma separated)", - nargs="*" + "--committers", metavar="", help="Committer for the commit (comma separated)", nargs="*" ) base_scan_group = pr_group.add_mutually_exclusive_group() base_scan_group.add_argument( @@ -677,7 +651,7 @@ def create_argument_parser() -> argparse.ArgumentParser: metavar="", default=None, help="Full scan ID to diff the new scan against, overriding the repository's " - "head scan as the baseline. Mutually exclusive with --base-commit-sha." + "head scan as the baseline. Mutually exclusive with --base-commit-sha.", ) base_scan_group.add_argument( "--base-commit-sha", @@ -685,82 +659,60 @@ def create_argument_parser() -> argparse.ArgumentParser: metavar="", default=None, help="Commit SHA to diff the new scan against, overriding the repository's head " - "scan as the baseline. The CLI uses the most recent matching full scan, or " - "the nearest scanned first-parent ancestor within 100 local commits when " - "the commit itself was not scanned. Also sets the range changed-file " - "detection reads, so a manifest changed anywhere between this commit and " - "HEAD is seen. Mutually exclusive with --base-scan-id." + "scan as the baseline. The CLI uses the most recent matching full scan, or " + "the nearest scanned first-parent ancestor within 100 local commits when " + "the commit itself was not scanned. Also sets the range changed-file " + "detection reads, so a manifest changed anywhere between this commit and " + "HEAD is seen. Mutually exclusive with --base-scan-id.", ) # Path and File options - path_group = parser.add_argument_group('Path and File') + path_group = parser.add_argument_group("Path and File") path_group.add_argument( - "--target-path", - dest="target_path", - metavar="", - default="./", - help="Target path for analysis" - ) - path_group.add_argument( - "--target_path", - dest="target_path", - help=argparse.SUPPRESS - ) - path_group.add_argument( - "--sbom-file", - dest="sbom_file", - metavar="", - help="SBOM file path" - ) - path_group.add_argument( - "--sbom_file", - dest="sbom_file", - help=argparse.SUPPRESS + "--target-path", dest="target_path", metavar="", default="./", help="Target path for analysis" ) + path_group.add_argument("--target_path", dest="target_path", help=argparse.SUPPRESS) + path_group.add_argument("--sbom-file", dest="sbom_file", metavar="", help="SBOM file path") + path_group.add_argument("--sbom_file", dest="sbom_file", help=argparse.SUPPRESS) path_group.add_argument( "--license-file-name", dest="license_file_name", default="license_output.json", metavar="", - help="SBOM file path" + help="SBOM file path", ) path_group.add_argument( "--save-submitted-files-list", dest="save_submitted_files_list", metavar="", - help="Save list of submitted file names to JSON file for debugging purposes" + help="Save list of submitted file names to JSON file for debugging purposes", ) path_group.add_argument( "--save-manifest-tar", dest="save_manifest_tar", metavar="", - help="Save all manifest files to a compressed tar.gz archive with original directory structure" - ) - path_group.add_argument( - "--files", - metavar="", - default="[]", - help="Files to analyze (JSON array string)" + help="Save all manifest files to a compressed tar.gz archive with original directory structure", ) + path_group.add_argument("--files", metavar="", default="[]", help="Files to analyze (JSON array string)") path_group.add_argument( "--sub-path", dest="sub_paths", metavar="", action="append", - help="Sub-path within target-path for manifest file scanning (can be specified multiple times). All sub-paths will be combined into a single workspace scan while preserving git context from target-path" + help="Sub-path within target-path for manifest file scanning (can be specified multiple times). All sub-paths will be combined into a single workspace scan while preserving git context from target-path", ) path_group.add_argument( "--workspace-name", - dest="workspace_name", + dest="workspace_name", metavar="", - help="Workspace name suffix to append to repository name (repo-name-workspace_name)" + help="Workspace name suffix to append to repository name (repo-name-workspace_name)", ) path_group.add_argument( "--excluded-ecosystems", default="[]", dest="excluded_ecosystems", - help="List of ecosystems to exclude from analysis (JSON array string)" + help="List of ecosystems to exclude from analysis (JSON array string)", ) path_group.add_argument( @@ -768,8 +720,8 @@ def create_argument_parser() -> argparse.ArgumentParser: dest="exclude_paths", metavar="", help="Comma-separated paths/globs to exclude from BOTH manifest discovery and " - "reachability analysis (e.g. 'tests/**,packages/legacy,*.spec.ts'). " - "Supersedes --reach-exclude-paths." + "reachability analysis (e.g. 'tests/**,packages/legacy,*.spec.ts'). " + "Supersedes --reach-exclude-paths.", ) path_group.add_argument( @@ -777,33 +729,20 @@ def create_argument_parser() -> argparse.ArgumentParser: dest="include_dirs", metavar="", help="Comma-separated directory names that are excluded from manifest discovery by " - "default but should be scanned (e.g. 'build,dist'). Names are matched against any " - "path segment, mirroring the default exclude list. Defaults excluded: " - "node_modules, bower_components, jspm_packages, __pycache__, .venv, venv, build, " - "dist, .tox, .mypy_cache, .pytest_cache, *.egg-info, vendor." + "default but should be scanned (e.g. 'build,dist'). Names are matched against any " + "path segment, mirroring the default exclude list. Defaults excluded: " + "node_modules, bower_components, jspm_packages, __pycache__, .venv, venv, build, " + "dist, .tox, .mypy_cache, .pytest_cache, *.egg-info, vendor.", ) # Branch and Scan Configuration - config_group = parser.add_argument_group('Branch and Scan Configuration') - config_group.add_argument( - "--default-branch", - dest="default_branch", - action="store_true", - help="Make this branch the default branch" - ) + config_group = parser.add_argument_group("Branch and Scan Configuration") config_group.add_argument( - "--default_branch", - dest="default_branch", - action="store_true", - help=argparse.SUPPRESS + "--default-branch", dest="default_branch", action="store_true", help="Make this branch the default branch" ) + config_group.add_argument("--default_branch", dest="default_branch", action="store_true", help=argparse.SUPPRESS) # Deprecated no-op, still accepted so existing pipelines don't fail to parse. - config_group.add_argument( - "--pending-head", - dest="pending_head", - action="store_true", - help=argparse.SUPPRESS - ) + config_group.add_argument("--pending-head", dest="pending_head", action="store_true", help=argparse.SUPPRESS) config_group.add_argument( "--ignore-authorization", dest="ignore_authorization", @@ -815,122 +754,84 @@ def create_argument_parser() -> argparse.ArgumentParser: "a warning when the provider cannot report the commenter's access. " "'strict' rejects the command in that case instead. " "'off' honors a command from any commenter." - ) - ) - config_group.add_argument( - "--pending_head", - dest="pending_head", - action="store_true", - help=argparse.SUPPRESS + ), ) + config_group.add_argument("--pending_head", dest="pending_head", action="store_true", help=argparse.SUPPRESS) # Output Configuration - output_group = parser.add_argument_group('Output Configuration') + output_group = parser.add_argument_group("Output Configuration") output_group.add_argument( - "--generate-license", - dest="generate_license", - action="store_true", - help="Generate license information" + "--generate-license", dest="generate_license", action="store_true", help="Generate license information" ) output_group.add_argument( - "--generate_license", - dest="generate_license", - action="store_true", - help=argparse.SUPPRESS + "--generate_license", dest="generate_license", action="store_true", help=argparse.SUPPRESS ) + output_group.add_argument("--enable-debug", dest="enable_debug", action="store_true", help="Enable debug logging") + output_group.add_argument("--enable_debug", dest="enable_debug", action="store_true", help=argparse.SUPPRESS) + output_group.add_argument("--enable-json", dest="enable_json", action="store_true", help="Output in JSON format") output_group.add_argument( - "--enable-debug", - dest="enable_debug", - action="store_true", - help="Enable debug logging" - ) - output_group.add_argument( - "--enable_debug", - dest="enable_debug", - action="store_true", - help=argparse.SUPPRESS - ) - output_group.add_argument( - "--enable-json", - dest="enable_json", - action="store_true", - help="Output in JSON format" - ) - output_group.add_argument( - "--json-file", - dest="json_file", - metavar="", - help="Output file path for JSON report" + "--json-file", dest="json_file", metavar="", help="Output file path for JSON report" ) output_group.add_argument( "--enable-sarif", dest="enable_sarif", action="store_true", - help="Enable SARIF output of results instead of table or JSON format" + help="Enable SARIF output of results instead of table or JSON format", ) output_group.add_argument( "--sarif-file", dest="sarif_file", metavar="", default=None, - help="Output file path for SARIF report (implies --enable-sarif)" + help="Output file path for SARIF report (implies --enable-sarif)", ) output_group.add_argument( "--sarif-scope", dest="sarif_scope", choices=["diff", "full"], default="diff", - help="Scope SARIF output to diff alerts (default) or full reachability facts data (requires --reach)" + help="Scope SARIF output to diff alerts (default) or full reachability facts data (requires --reach)", ) output_group.add_argument( "--sarif-grouping", dest="sarif_grouping", choices=["instance", "alert"], default="instance", - help="SARIF result grouping mode: instance (default) or alert (full scope only)" + help="SARIF result grouping mode: instance (default) or alert (full scope only)", ) output_group.add_argument( "--sarif-reachability", dest="sarif_reachability", choices=["all", "reachable", "potentially", "reachable-or-potentially"], default="all", - help="Reachability filter for SARIF output (requires --reach when not 'all')" + help="Reachability filter for SARIF output (requires --reach when not 'all')", ) output_group.add_argument( "--enable-gitlab-security", dest="enable_gitlab_security", action="store_true", - help="Enable GitLab Security Dashboard output format (Dependency Scanning report)" + help="Enable GitLab Security Dashboard output format (Dependency Scanning report)", ) output_group.add_argument( "--gitlab-security-file", dest="gitlab_security_file", metavar="", default="gl-dependency-scanning-report.json", - help="Output file path for GitLab Security report (default: gl-dependency-scanning-report.json)" + help="Output file path for GitLab Security report (default: gl-dependency-scanning-report.json)", ) output_group.add_argument( - "--summary-file", - dest="summary_file", - metavar="", - help="Output file path for a plain-text summary report" + "--summary-file", dest="summary_file", metavar="", help="Output file path for a plain-text summary report" ) output_group.add_argument( "--report-link-file", dest="report_link_file", metavar="", - help="Output file path for the Socket report link" + help="Output file path for the Socket report link", ) output_group.add_argument( - "--disable-overview", - dest="disable_overview", - action="store_true", - help="Disable overview output" + "--disable-overview", dest="disable_overview", action="store_true", help="Disable overview output" ) output_group.add_argument( - "--disable_overview", - dest="disable_overview", - action="store_true", - help=argparse.SUPPRESS + "--disable_overview", dest="disable_overview", action="store_true", help=argparse.SUPPRESS ) output_group.add_argument( "--exclude-license-details", @@ -941,63 +842,54 @@ def create_argument_parser() -> argparse.ArgumentParser: "As of 2.4.0 the internal diff request always omits license details " "(they were unused there and bloated large-repo responses), so this " "flag now only affects the report link, not diff performance." - ) + ), ) output_group.add_argument( "--max-purl-batch-size", dest="max_purl_batch_size", type=int, default=5000, - help="Maximum batch size for PURL endpoint calls when generating license info (default: 5000, min: 1, max: 9999)" + help="Maximum batch size for PURL endpoint calls when generating license info (default: 5000, min: 1, max: 9999)", ) output_group.add_argument( "--disable-security-issue", dest="disable_security_issue", action="store_true", - help="Disable security issue checks" + help="Disable security issue checks", ) output_group.add_argument( - "--disable_security_issue", - dest="disable_security_issue", - action="store_true", - help=argparse.SUPPRESS + "--disable_security_issue", dest="disable_security_issue", action="store_true", help=argparse.SUPPRESS ) output_group.add_argument( "--enable-commit-status", dest="enable_commit_status", action="store_true", - help="Report scan result as a commit status on GitLab (requires GitLab SCM)" + help="Report scan result as a commit status on GitLab (requires GitLab SCM)", ) output_group.add_argument( - "--enable_commit_status", - dest="enable_commit_status", - action="store_true", - help=argparse.SUPPRESS + "--enable_commit_status", dest="enable_commit_status", action="store_true", help=argparse.SUPPRESS ) # Plugin Configuration - plugin_group = parser.add_argument_group('Plugin Configuration') + plugin_group = parser.add_argument_group("Plugin Configuration") plugin_group.add_argument( "--slack-webhook", dest="slack_webhook", metavar="", - help="Slack webhook URL for notifications (automatically enables Slack plugin)" + help="Slack webhook URL for notifications (automatically enables Slack plugin)", ) # Advanced Configuration - advanced_group = parser.add_argument_group('Advanced Configuration') + advanced_group = parser.add_argument_group("Advanced Configuration") advanced_group.add_argument( "--ignore-commit-files", dest="ignore_commit_files", action="store_true", - help="Compare against the baseline regardless of which files changed, scanning every manifest in the target path" + help="Compare against the baseline regardless of which files changed, scanning every manifest in the target path", ) advanced_group.add_argument( - "--ignore_commit_files", - dest="ignore_commit_files", - action="store_true", - help=argparse.SUPPRESS + "--ignore_commit_files", dest="ignore_commit_files", action="store_true", help=argparse.SUPPRESS ) advanced_group.add_argument( "--disable-blocking", @@ -1010,24 +902,16 @@ def create_argument_parser() -> argparse.ArgumentParser: ), ) advanced_group.add_argument( - "--disable_blocking", - dest="disable_blocking", - action="store_true", - help=argparse.SUPPRESS + "--disable_blocking", dest="disable_blocking", action="store_true", help=argparse.SUPPRESS ) advanced_group.add_argument( "--disable-ignore", dest="disable_ignore", action="store_true", help="Disable support for @SocketSecurity ignore commands in PR comments. " - "Alerts cannot be suppressed via comments when this flag is set." - ) - advanced_group.add_argument( - "--disable_ignore", - dest="disable_ignore", - action="store_true", - help=argparse.SUPPRESS + "Alerts cannot be suppressed via comments when this flag is set.", ) + advanced_group.add_argument("--disable_ignore", dest="disable_ignore", action="store_true", help=argparse.SUPPRESS) log_upload_group = advanced_group.add_mutually_exclusive_group() log_upload_group.add_argument( "--upload-logs", @@ -1035,9 +919,9 @@ def create_argument_parser() -> argparse.ArgumentParser: action="store_const", const=True, help="Upload the CLI's log output to the Socket backend for this run. " - "When set, the CLI registers the run with share_logs=true and streams " - "its log records in 5s batches. Default off. Mutually exclusive with " - "--no-upload-logs." + "When set, the CLI registers the run with share_logs=true and streams " + "its log records in 5s batches. Default off. Mutually exclusive with " + "--no-upload-logs.", ) log_upload_group.add_argument( "--no-upload-logs", @@ -1045,34 +929,29 @@ def create_argument_parser() -> argparse.ArgumentParser: action="store_const", const=False, help="Explicitly opt out of uploading CLI logs to the Socket backend, even " - "when an org-level override would otherwise enable it. Mutually " - "exclusive with --upload-logs." + "when an org-level override would otherwise enable it. Mutually " + "exclusive with --upload-logs.", ) advanced_group.add_argument( "--strict-blocking", dest="strict_blocking", action="store_true", help="Fail on new and existing Block findings. Compare even when no manifest changed. " - "With --scm, branch pipelines without PR/MR context run non-blocking full scans." + "With --scm, branch pipelines without PR/MR context run non-blocking full scans.", ) advanced_group.add_argument( "--enable-diff", dest="enable_diff", action="store_true", - help="Enable diff mode even when using --integration api (forces diff mode without SCM integration)" - ) - advanced_group.add_argument( - "--scm", - metavar="", - default="api", - help="Source control management type" + help="Enable diff mode even when using --integration api (forces diff mode without SCM integration)", ) + advanced_group.add_argument("--scm", metavar="", default="api", help="Source control management type") advanced_group.add_argument( "--timeout", type=int, metavar="", help="Timeout in seconds for API requests (must be greater than zero)", - required=False + required=False, ) advanced_group.add_argument( "--exit-code-on-api-error", @@ -1089,25 +968,20 @@ def create_argument_parser() -> argparse.ArgumentParser: "CI -- e.g. set to a Buildkite soft_fail code. NOTE: --disable-blocking " "overrides this flag but never suppresses usage errors; do not " "combine the two if you want the custom code to take effect." - ) + ), ) advanced_group.add_argument( - "--allow-unverified", - action="store_true", - help="Disable SSL certificate verification for API requests" + "--allow-unverified", action="store_true", help="Disable SSL certificate verification for API requests" ) advanced_group.add_argument( - "--legal", - dest="legal", - action="store_true", - help="Enable legal/compliance-friendly defaults and file outputs" + "--legal", dest="legal", action="store_true", help="Enable legal/compliance-friendly defaults and file outputs" ) advanced_group.add_argument( "--legal-format", dest="legal_format", choices=["socket", "fossa"], default="socket", - help="Select the legal artifact format. 'socket' keeps Socket-native outputs; 'fossa' emits compatibility-shaped JSON artifacts." + help="Select the legal artifact format. 'socket' keeps Socket-native outputs; 'fossa' emits compatibility-shaped JSON artifacts.", ) config_group.add_argument( "--include-module-folders", @@ -1115,189 +989,172 @@ def create_argument_parser() -> argparse.ArgumentParser: action="store_true", default=False, help="Include manifests found under node_modules, bower_components, and jspm_packages. " - "Use a CycloneDX SBOM to inventory installed packages. " - "See https://github.com/SocketDev/socket-python-cli/blob/main/docs/troubleshooting.md" + "Use a CycloneDX SBOM to inventory installed packages. " + "See https://github.com/SocketDev/socket-python-cli/blob/main/docs/troubleshooting.md", ) # Reachability Configuration - reachability_group = parser.add_argument_group('Reachability Analysis') - reachability_group.add_argument( - "--reach", - dest="reach", - action="store_true", - help="Enable reachability analysis" - ) + reachability_group = parser.add_argument_group("Reachability Analysis") + reachability_group.add_argument("--reach", dest="reach", action="store_true", help="Enable reachability analysis") reachability_group.add_argument( "--reach-version", dest="reach_version", metavar="", help="Version of the Coana CLI to use. Defaults to the version pinned to this CLI " - "release; pass 'latest' to always use the newest published version (opt-in " - "auto-update), or an explicit version (e.g. '1.2.3') to pin it." + "release; pass 'latest' to always use the newest published version (opt-in " + "auto-update), or an explicit version (e.g. '1.2.3') to pin it.", ) reachability_group.add_argument( "--reach-analysis-timeout", dest="reach_analysis_timeout", metavar="", - help="Set the timeout for each reachability analysis run, e.g. 90s, 10m or 1h. (default: 10m)" + help="Set the timeout for each reachability analysis run, e.g. 90s, 10m or 1h. (default: 10m)", ) # Backwards-compatible alias for the pre-alignment name. Kept working, hidden from help. - reachability_group.add_argument( - "--reach-timeout", - dest="reach_analysis_timeout", - help=argparse.SUPPRESS - ) + reachability_group.add_argument("--reach-timeout", dest="reach_analysis_timeout", help=argparse.SUPPRESS) reachability_group.add_argument( "--reach-analysis-memory-limit", dest="reach_analysis_memory_limit", metavar="", - help="Set the memory limit for each reachability analysis run, e.g. 512MB or 8GB. (default: 8GB)" + help="Set the memory limit for each reachability analysis run, e.g. 512MB or 8GB. (default: 8GB)", ) # Backwards-compatible alias for the pre-alignment name. Kept working, hidden from help. - reachability_group.add_argument( - "--reach-memory-limit", - dest="reach_analysis_memory_limit", - help=argparse.SUPPRESS - ) + reachability_group.add_argument("--reach-memory-limit", dest="reach_analysis_memory_limit", help=argparse.SUPPRESS) reachability_group.add_argument( "--reach-ecosystems", dest="reach_ecosystems", metavar="", - help="Ecosystems to analyze for reachability (comma-separated, e.g., 'npm,pypi')" + help="Ecosystems to analyze for reachability (comma-separated, e.g., 'npm,pypi')", ) reachability_group.add_argument( "--reach-exclude-paths", dest="reach_exclude_paths", metavar="", help="[DEPRECATED: use --exclude-paths] Paths to exclude from reachability analysis " - "(comma-separated). Still honored and unioned with --exclude-paths." + "(comma-separated). Still honored and unioned with --exclude-paths.", ) reachability_group.add_argument( "--reach-min-severity", dest="reach_min_severity", metavar="", - help="Minimum severity level for reachability analysis (info, low, moderate, high, critical)" + help="Minimum severity level for reachability analysis (info, low, moderate, high, critical)", ) reachability_group.add_argument( "--reach-skip-cache", dest="reach_skip_cache", action="store_true", - help="Skip cache usage for reachability analysis" + help="Skip cache usage for reachability analysis", ) reachability_group.add_argument( "--reach-disable-analytics", dest="reach_disable_analytics", action="store_true", - help="Disable analytics sharing for reachability analysis" + help="Disable analytics sharing for reachability analysis", ) reachability_group.add_argument( "--reach-disable-analysis-splitting", dest="reach_disable_analysis_splitting", action="store_true", - help=argparse.SUPPRESS # Deprecated, kept for backwards compatibility (no-op) + help=argparse.SUPPRESS, # Deprecated, kept for backwards compatibility (no-op) ) reachability_group.add_argument( "--reach-enable-analysis-splitting", dest="reach_enable_analysis_splitting", action="store_true", - help=argparse.SUPPRESS # Deprecated, kept for backwards compatibility (no-op) + help=argparse.SUPPRESS, # Deprecated, kept for backwards compatibility (no-op) ) reachability_group.add_argument( "--reach-detailed-analysis-log-file", dest="reach_detailed_analysis_log_file", action="store_true", - help="Create a detailed analysis log file for reachability analysis. The output path is written to stdout" + help="Create a detailed analysis log file for reachability analysis. The output path is written to stdout", ) reachability_group.add_argument( "--reach-lazy-mode", dest="reach_lazy_mode", action="store_true", - help=argparse.SUPPRESS # Deprecated, kept for backwards compatibility (no-op) + help=argparse.SUPPRESS, # Deprecated, kept for backwards compatibility (no-op) ) reachability_group.add_argument( "--reach-output-file", dest="reach_output_file", metavar="", default=".socket.facts.json", - help="Output file path for reachability analysis results (default: .socket.facts.json)" + help="Output file path for reachability analysis results (default: .socket.facts.json)", ) reachability_group.add_argument( "--reach-concurrency", dest="reach_concurrency", type=int, metavar="", - help="Concurrency level for reachability analysis (must be >= 1; defaults to the coana CLI's own default, currently 1)" + help="Concurrency level for reachability analysis (must be >= 1; defaults to the coana CLI's own default, currently 1)", ) reachability_group.add_argument( "--reach-additional-params", dest="reach_additional_params", - nargs='+', + nargs="+", metavar="", - help="Additional parameters to pass to the coana CLI (e.g., --reach-additional-params --other-param value --another-param value2)" + help="Additional parameters to pass to the coana CLI (e.g., --reach-additional-params --other-param value --another-param value2)", ) reachability_group.add_argument( "--only-facts-file", dest="only_facts_file", action="store_true", - help="Submit only the .socket.facts.json file when creating full scan (requires --reach)" + help="Submit only the .socket.facts.json file when creating full scan (requires --reach)", ) reachability_group.add_argument( "--reach-use-only-pregenerated-sboms", dest="reach_use_only_pregenerated_sboms", action="store_true", - help="When using this option, the scan is created based only on pre-generated CDX and SPDX files in your project. (requires --reach)" + help="When using this option, the scan is created based only on pre-generated CDX and SPDX files in your project. (requires --reach)", ) reachability_group.add_argument( "--reach-continue-on-analysis-errors", dest="reach_continue_on_analysis_errors", action="store_true", - help=argparse.SUPPRESS + help=argparse.SUPPRESS, ) reachability_group.add_argument( "--reach-continue-on-install-errors", dest="reach_continue_on_install_errors", action="store_true", - help=argparse.SUPPRESS + help=argparse.SUPPRESS, ) reachability_group.add_argument( "--reach-continue-on-missing-lock-files", dest="reach_continue_on_missing_lock_files", action="store_true", - help=argparse.SUPPRESS + help=argparse.SUPPRESS, ) reachability_group.add_argument( "--reach-continue-on-no-source-files", dest="reach_continue_on_no_source_files", action="store_true", - help=argparse.SUPPRESS + help=argparse.SUPPRESS, ) reachability_group.add_argument( "--reach-debug", dest="reach_debug", action="store_true", help="Enable debug output for the reachability analysis (passes --debug to the coana CLI). " - "Independent of the global --enable-debug flag." + "Independent of the global --enable-debug flag.", ) reachability_group.add_argument( "--reach-disable-external-tool-checks", dest="reach_disable_external_tool_checks", action="store_true", help="Disable coana's external tool availability checks during reachability analysis " - "(passes --disable-external-tool-checks to the coana CLI)." + "(passes --disable-external-tool-checks to the coana CLI).", ) reachability_group.add_argument( "--reach-disable-dependency-downloads", dest="reach_disable_dependency_downloads", action="store_true", help="Only analyze dependencies that are already installed (e.g. in the project's .venv, " - "vendor directory or module cache); missing ones count as install failures " - "(passes --disable-dependency-downloads to the coana CLI)." + "vendor directory or module cache); missing ones count as install failures " + "(passes --disable-dependency-downloads to the coana CLI).", ) - parser.add_argument( - '--version', - action='version', - version=f'%(prog)s {__version__}' - ) + parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}") return parser diff --git a/socketsecurity/core/__init__.py b/socketsecurity/core/__init__.py index 9fc1ec3f..d2022dec 100644 --- a/socketsecurity/core/__init__.py +++ b/socketsecurity/core/__init__.py @@ -1,4 +1,5 @@ import atexit +import contextlib import copy import fnmatch import importlib @@ -11,19 +12,10 @@ import tarfile import tempfile import time +from collections.abc import Iterable, Iterator from dataclasses import asdict from pathlib import PurePath -from typing import ( - TYPE_CHECKING, - Dict, - Iterable, - Iterator, - List, - NamedTuple, - Optional, - Set, - Tuple, -) +from typing import TYPE_CHECKING, ClassVar, NamedTuple, Optional if TYPE_CHECKING: from socketsecurity.config import CliConfig @@ -51,10 +43,10 @@ __all__ = [ + "USER_AGENT", "Core", - "log", "__version__", - "USER_AGENT", + "log", ] version = __version__ @@ -154,7 +146,7 @@ # Temp dirs holding placeholder facts files (see Core.empty_head_scan_file). Call sites unlink # the file itself once the upload finishes; the now-empty directory is removed at process exit # so a run that raises mid-scan doesn't leak one. -_PLACEHOLDER_FACTS_DIRS: List[str] = [] +_PLACEHOLDER_FACTS_DIRS: list[str] = [] @atexit.register @@ -188,10 +180,10 @@ class ManifestPatterns(NamedTuple): flat as the API's pattern list grows. """ - literal_basenames: Set[str] - basename_globs: List[str] - path_globs: List[str] - candidate_basenames: Set[str] + literal_basenames: set[str] + basename_globs: list[str] + path_globs: list[str] + candidate_basenames: set[str] candidate_basename_regex: Optional["re.Pattern"] @property @@ -203,31 +195,28 @@ def is_empty(self) -> bool: class Core: """Main class for interacting with Socket Security API and processing scan results.""" - ALERT_TYPE_TO_CAPABILITY = { + ALERT_TYPE_TO_CAPABILITY: ClassVar[dict[str, str]] = { "envVars": "Environment Variables", "networkAccess": "Network Access", "filesystemAccess": "File System Access", "shellAccess": "Shell Access", "usesEval": "Uses Eval", - "unsafe": "Unsafe" + "unsafe": "Unsafe", } config: SocketConfig sdk: socketdev - cli_config: Optional['CliConfig'] + cli_config: Optional["CliConfig"] - def __init__(self, config: SocketConfig, sdk: socketdev, cli_config: Optional['CliConfig'] = None) -> None: + def __init__(self, config: SocketConfig, sdk: socketdev, cli_config: Optional["CliConfig"] = None) -> None: """Initialize Core with configuration and SDK instance.""" self.config = config self.sdk = sdk self.cli_config = cli_config - self._supported_patterns: Optional[Dict] = None + self._supported_patterns: dict | None = None org_start_time = time.perf_counter() self.set_org_vars() - log.info( - "Organization initialization completed in " - f"{time.perf_counter() - org_start_time:.2f}s" - ) + log.info(f"Organization initialization completed in {time.perf_counter() - org_start_time:.2f}s") def set_org_vars(self) -> None: """Sets the main shared configuration variables for organization access.""" @@ -240,17 +229,17 @@ def set_org_vars(self) -> None: self.config.full_scan_path = f"{base_path}/full-scans" self.config.repository_path = f"{base_path}/repos" - def get_org_id_slug(self) -> Tuple[str, str]: + def get_org_id_slug(self) -> tuple[str, str]: """Gets the Org ID and Org Slug for the API Token.""" response = self.sdk.org.get(use_types=True) - organizations: Dict[str, Organization] = response.get("organizations", {}) + organizations: dict[str, Organization] = response.get("organizations", {}) if len(organizations) == 1: org_id = next(iter(organizations)) - return org_id, organizations[org_id]['slug'] + return org_id, organizations[org_id]["slug"] return None, None - def get_sbom_data(self, full_scan_id: str) -> Dict[str, SocketArtifact]: + def get_sbom_data(self, full_scan_id: str) -> dict[str, SocketArtifact]: """Returns SBOM artifacts for a full scan keyed by artifact ID.""" response = self.sdk.fullscans.stream(self.config.org_slug, full_scan_id, use_types=True) if not response.success: @@ -258,9 +247,7 @@ def get_sbom_data(self, full_scan_id: str) -> Dict[str, SocketArtifact]: # API error (exit code 3 by default) rather than empty reports. log.error(f"Failed to get SBOM data for full-scan {full_scan_id}") log.error(response.message) - raise APIFailure( - f"Failed to get SBOM data for full-scan {full_scan_id}: {response.message}" - ) + raise APIFailure(f"Failed to get SBOM data for full-scan {full_scan_id}: {response.message}") if not hasattr(response, "artifacts") or not response.artifacts: return {} artifacts = { @@ -271,7 +258,7 @@ def get_sbom_data(self, full_scan_id: str) -> Dict[str, SocketArtifact]: Core.warn_if_invalid_facts_marker(len(artifacts) != len(response.artifacts)) return artifacts - def get_sbom_data_list(self, artifacts_dict: Dict[str, SocketArtifact]) -> list[SocketArtifact]: + def get_sbom_data_list(self, artifacts_dict: dict[str, SocketArtifact]) -> list[SocketArtifact]: """Converts artifacts dictionary to a list.""" return list(artifacts_dict.values()) @@ -329,34 +316,35 @@ def create_sbom_output(self, diff: Diff) -> dict: return {} @staticmethod - def expand_brace_pattern(pattern: str) -> List[str]: + def expand_brace_pattern(pattern: str) -> list[str]: """ Recursively expands brace expressions (e.g., {a,b,c}) into separate patterns, supporting nested braces. """ - def recursive_expand(pat: str) -> List[str]: + + def recursive_expand(pat: str) -> list[str]: stack = [] for i, c in enumerate(pat): - if c == '{': + if c == "{": stack.append(i) - elif c == '}' and stack: + elif c == "}" and stack: start = stack.pop() if not stack: # Found the outermost pair before = pat[:start] - after = pat[i+1:] - inner = pat[start+1:i] + after = pat[i + 1 :] + inner = pat[start + 1 : i] # Split on commas not inside nested braces options = [] depth = 0 last = 0 for j, ch in enumerate(inner): - if ch == '{': + if ch == "{": depth += 1 - elif ch == '}': + elif ch == "}": depth -= 1 - elif ch == ',' and depth == 0: + elif ch == "," and depth == 0: options.append(inner[last:j]) - last = j+1 + last = j + 1 options.append(inner[last:]) results = [] for opt in options: @@ -364,15 +352,13 @@ def recursive_expand(pat: str) -> List[str]: results.extend(recursive_expand(expanded)) return results return [pat] + return recursive_expand(pattern) @staticmethod - def is_excluded(file_path: str, excluded_dirs: Set[str]) -> bool: + def is_excluded(file_path: str, excluded_dirs: set[str]) -> bool: parts = os.path.normpath(file_path).split(os.sep) - for part in parts: - if part in excluded_dirs: - return True - return False + return any(part in excluded_dirs for part in parts) @staticmethod def _exclude_glob_to_regex(pattern: str) -> str: @@ -393,10 +379,10 @@ def _exclude_glob_to_regex(pattern: str) -> str: out.append("(?:[^/]+/)*") # '**/' -> zero or more path segments i += 3 else: - out.append(".*") # '**' at end / before non-slash -> any, incl '/' + out.append(".*") # '**' at end / before non-slash -> any, incl '/' i += 2 else: - out.append("[^/]*") # '*' -> within a single path segment + out.append("[^/]*") # '*' -> within a single path segment i += 1 elif c == "?": out.append("[^/]") @@ -408,14 +394,14 @@ def _exclude_glob_to_regex(pattern: str) -> str: return "".join(out) @staticmethod - def compile_exclude_paths(patterns: Optional[List[str]]) -> List["re.Pattern"]: + def compile_exclude_paths(patterns: list[str] | None) -> list["re.Pattern"]: """Compile --exclude-paths globs into anchored regexes (compiled once per scan). Each pattern ``P`` is expanded the way Node feeds fast-glob's ``ignore``: ``P`` (a file- or dir-shaped exact match) plus ``P/**`` (its subtree), unless ``P`` already ends with ``/**``. Validation of the patterns happens earlier, in CliConfig.from_args. """ - compiled: List["re.Pattern"] = [] + compiled: list[re.Pattern] = [] for raw in patterns or []: p = (raw or "").strip().replace("\\", "/").rstrip("/") if not p: @@ -425,17 +411,17 @@ def compile_exclude_paths(patterns: Optional[List[str]]) -> List["re.Pattern"]: return compiled @staticmethod - def path_matches_exclude_regexes(rel_path: str, regexes: List["re.Pattern"]) -> bool: + def path_matches_exclude_regexes(rel_path: str, regexes: list["re.Pattern"]) -> bool: rp = rel_path.replace(os.sep, "/").replace("\\", "/") return any(r.match(rp) for r in regexes) @staticmethod - def matches_exclude_paths(file_path: str, base_path: str, patterns: List[str]) -> bool: + def matches_exclude_paths(file_path: str, base_path: str, patterns: list[str]) -> bool: """Convenience matcher (compiles patterns per call); used in tests/ad-hoc checks.""" rel_path = os.path.relpath(file_path, base_path).replace(os.sep, "/") return Core.path_matches_exclude_regexes(rel_path, Core.compile_exclude_paths(patterns)) - def save_submitted_files_list(self, files: List[str], output_path: str) -> None: + def save_submitted_files_list(self, files: list[str], output_path: str) -> None: """ Save the list of submitted file names to a JSON file for debugging. @@ -447,7 +433,7 @@ def save_submitted_files_list(self, files: List[str], output_path: str) -> None: # Calculate total size of all files total_size_bytes = 0 valid_files = [] - + for file_path in files: try: if os.path.exists(file_path) and os.path.isfile(file_path): @@ -460,33 +446,35 @@ def save_submitted_files_list(self, files: List[str], output_path: str) -> None: except OSError as e: log.warning(f"Error accessing file {file_path}: {e}") valid_files.append(file_path) # Still include in list for debugging - + # Convert bytes to human-readable format def format_bytes(bytes_value): """Convert bytes to human readable format""" - for unit in ['B', 'KB', 'MB', 'GB']: + for unit in ["B", "KB", "MB", "GB"]: if bytes_value < 1024.0: return f"{bytes_value:.2f} {unit}" bytes_value /= 1024.0 return f"{bytes_value:.2f} TB" - + file_data = { "timestamp": time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime()), "total_files": len(valid_files), "total_size_bytes": total_size_bytes, "total_size_human": format_bytes(total_size_bytes), - "files": sorted(valid_files) + "files": sorted(valid_files), } - - with open(output_path, 'w', encoding='utf-8') as f: + + with open(output_path, "w", encoding="utf-8") as f: json.dump(file_data, f, indent=2, ensure_ascii=False) - - log.info(f"Saved list of {len(valid_files)} submitted files ({file_data['total_size_human']}) to: {output_path}") - + + log.info( + f"Saved list of {len(valid_files)} submitted files ({file_data['total_size_human']}) to: {output_path}" + ) + except Exception as e: log.error(f"Failed to save submitted files list to {output_path}: {e}") - def save_manifest_tar(self, files: List[str], output_path: str, base_dir: str) -> None: + def save_manifest_tar(self, files: list[str], output_path: str, base_dir: str) -> None: """ Save all manifest files to a compressed tar.gz archive with original directory structure. @@ -504,7 +492,7 @@ def save_manifest_tar(self, files: List[str], output_path: str, base_dir: str) - log.info(f"Creating manifest tar.gz file: {output_path}") log.debug(f"Base directory: {base_dir}") - with tarfile.open(output_path, 'w:gz') as tar: + with tarfile.open(output_path, "w:gz") as tar: for file_path in files: if not os.path.exists(file_path): log.warning(f"File not found, skipping: {file_path}") @@ -521,33 +509,33 @@ def save_manifest_tar(self, files: List[str], output_path: str, base_dir: str) - log.warning(f"File outside base dir, using basename: {file_path} -> {arcname}") # Normalize archive name to use forward slashes - arcname = arcname.replace(os.sep, '/') + arcname = arcname.replace(os.sep, "/") log.debug(f"Adding to tar: {file_path} -> {arcname}") tar.add(file_path, arcname=arcname) # Get tar file size for logging tar_size = os.path.getsize(output_path) - + def format_bytes(bytes_value): """Convert bytes to human readable format""" - for unit in ['B', 'KB', 'MB', 'GB']: + for unit in ["B", "KB", "MB", "GB"]: if bytes_value < 1024.0: return f"{bytes_value:.2f} {unit}" bytes_value /= 1024.0 return f"{bytes_value:.2f} TB" tar_size_human = format_bytes(tar_size) - log.info(f"Successfully created tar.gz with {len(files)} files ({tar_size_human}, {tar_size:,} bytes): {output_path}") + log.info( + f"Successfully created tar.gz with {len(files)} files ({tar_size_human}, {tar_size:,} bytes): {output_path}" + ) except Exception as e: log.error(f"Failed to save manifest tar.gz to {output_path}: {e}") @staticmethod def _prepare_manifest_patterns( - patterns: Dict, - ecosystems: Optional[List[str]], - excluded_ecosystems: List[str] + patterns: dict, ecosystems: list[str] | None, excluded_ecosystems: list[str] ) -> "ManifestPatterns": """Prepare case-folded manifest patterns for a single filesystem walk. @@ -559,9 +547,9 @@ def _prepare_manifest_patterns( """ included_ecosystems = set(ecosystems) if ecosystems is not None else None excluded = set(excluded_ecosystems) - literal_basenames: Set[str] = set() - basename_globs: Set[str] = set() - path_globs: Set[str] = set() + literal_basenames: set[str] = set() + basename_globs: set[str] = set() + path_globs: set[str] = set() for ecosystem, ecosystem_patterns in patterns.items(): if included_ecosystems is not None and ecosystem not in included_ecosystems: @@ -603,7 +591,7 @@ def _prepare_manifest_patterns( ) @staticmethod - def _compile_basename_globs(globs: Set[str]) -> Optional["re.Pattern"]: + def _compile_basename_globs(globs: set[str]) -> Optional["re.Pattern"]: """Compile basename globs into a single alternation, or None if there are none. fnmatch.translate anchors the tail with ``\\Z`` and re.match anchors the head, @@ -611,9 +599,7 @@ def _compile_basename_globs(globs: Set[str]) -> Optional["re.Pattern"]: """ if not globs: return None - return re.compile( - "|".join(f"(?:{fnmatch.translate(glob)})" for glob in sorted(globs)) - ) + return re.compile("|".join(f"(?:{fnmatch.translate(glob)})" for glob in sorted(globs))) @staticmethod def _basename_could_match(normalized_name: str, patterns: "ManifestPatterns") -> bool: @@ -645,11 +631,11 @@ def _matches_manifest_pattern(relative_path: str, patterns: "ManifestPatterns") return any(candidate.match(pattern) for pattern in patterns.path_globs) @staticmethod - def _matches_excluded_directory(directory_name: str, excluded_dirs: Set[str]) -> bool: + def _matches_excluded_directory(directory_name: str, excluded_dirs: set[str]) -> bool: """Match configured directory exclusions, including entries such as ``*.egg-info``.""" return any(fnmatch.fnmatchcase(directory_name, pattern) for pattern in excluded_dirs) - def find_files(self, path: str, ecosystems: Optional[List[str]] = None) -> List[str]: + def find_files(self, path: str, ecosystems: list[str] | None = None) -> list[str]: # noqa: C901 """ Finds supported manifest files in the given path. @@ -662,7 +648,7 @@ def find_files(self, path: str, ecosystems: Optional[List[str]] = None) -> List[ """ log.debug("Starting manifest discovery") start_time = time.perf_counter() - files: Set[str] = set() + files: set[str] = set() # Unified --exclude-paths: filter discovered manifests by the same paths/globs that are # forwarded to coana's --exclude-dirs. Only consulted when the user supplied the flag. @@ -702,18 +688,18 @@ def handle_walk_error(error: OSError) -> None: log.debug(f"Unable to inspect path during manifest discovery: {error}") for current_root, directory_names, file_names in os.walk( - path, - topdown=True, - followlinks=False, - onerror=handle_walk_error, + path, + topdown=True, + followlinks=False, + onerror=handle_walk_error, ): directories_visited += 1 kept_directories = [] for directory_name in directory_names: if directory_name == ".git" or Core._matches_excluded_directory( - directory_name, - excluded_dirs, + directory_name, + excluded_dirs, ): directories_pruned += 1 continue @@ -742,8 +728,8 @@ def handle_walk_error(error: OSError) -> None: if not Core._matches_manifest_pattern(relative_path, manifest_patterns): continue if exclude_regexes and Core.path_matches_exclude_regexes( - relative_path, - exclude_regexes, + relative_path, + exclude_regexes, ): continue if os.path.isfile(file_path): @@ -767,8 +753,12 @@ def handle_walk_error(error: OSError) -> None: ulimit_check = check_file_count_against_ulimit(file_count) if ulimit_check["can_check"]: if ulimit_check["would_exceed"]: - log.debug(f"Found {file_count} manifest files, which may exceed the file descriptor limit (ulimit -n = {ulimit_check['soft_limit']})") - log.debug(f"Available file descriptors: {ulimit_check['available_fds']} (after {ulimit_check['buffer_size']} buffer)") + log.debug( + f"Found {file_count} manifest files, which may exceed the file descriptor limit (ulimit -n = {ulimit_check['soft_limit']})" + ) + log.debug( + f"Available file descriptors: {ulimit_check['available_fds']} (after {ulimit_check['buffer_size']} buffer)" + ) log.debug(f"Recommendation: {ulimit_check['recommendation']}") log.debug("This may cause 'Too many open files' errors during processing") else: @@ -778,7 +768,7 @@ def handle_walk_error(error: OSError) -> None: return file_list - def find_sbom_files(self, path: str) -> List[str]: + def find_sbom_files(self, path: str) -> list[str]: """ Finds only pre-generated SBOM files (CDX and SPDX) in the given path. @@ -792,10 +782,10 @@ def find_sbom_files(self, path: str) -> List[str]: List of found CDX and SPDX file paths. """ log.debug("Starting Find SBOM Files (CDX and SPDX only)") - sbom_ecosystems = ['cdx', 'spdx'] + sbom_ecosystems = ["cdx", "spdx"] return self.find_files(path, ecosystems=sbom_ecosystems) - def get_supported_patterns(self) -> Dict: + def get_supported_patterns(self) -> dict: """ Gets supported file patterns from the Socket API. @@ -827,10 +817,7 @@ def get_supported_patterns(self) -> Dict: if source == "api": self._supported_patterns = patterns elapsed = time.perf_counter() - start_time - log.info( - "Supported manifest patterns loaded in " - f"{elapsed:.2f}s: source={source}, ecosystems={len(patterns)}" - ) + log.info(f"Supported manifest patterns loaded in {elapsed:.2f}s: source={source}, ecosystems={len(patterns)}") return patterns def has_manifest_files(self, files: list) -> bool: @@ -850,10 +837,11 @@ def has_manifest_files(self, files: list) -> bool: log.error(f"Error getting supported patterns from API: {e}") log.warning("Falling back to local patterns") from .utils import socket_globs as fallback_patterns + patterns = fallback_patterns # Normalize all file paths for matching - norm_files = [f.replace('\\', '/').lstrip('./') for f in files] + norm_files = [f.replace("\\", "/").lstrip("./") for f in files] for ecosystem in patterns: ecosystem_patterns = patterns[ecosystem] @@ -869,17 +857,17 @@ def has_manifest_files(self, files: list) -> bool: return True # Also try with **/ prefix to match files in subdirectories # (e.g. "src/requirements.txt" matching "*requirements.txt") - if '/' not in exp_pat and PurePath(file).match(f"**/{exp_pat}"): + if "/" not in exp_pat and PurePath(file).match(f"**/{exp_pat}"): return True return False def check_file_count_limit(self, file_count: int) -> dict: """ Check if the given file count would exceed the system's file descriptor limit. - + Args: file_count: Number of files to check - + Returns: Dictionary with check results including recommendations """ @@ -899,10 +887,10 @@ def to_case_insensitive_regex(input_string: str) -> str: Example: "pipfile" -> "[Pp][Ii][Pp][Ff][Ii][Ll][Ee]" """ - return ''.join(f'[{char.lower()}{char.upper()}]' if char.isalpha() else char for char in input_string) + return "".join(f"[{char.lower()}{char.upper()}]" if char.isalpha() else char for char in input_string) @staticmethod - def empty_head_scan_file() -> List[str]: + def empty_head_scan_file() -> list[str]: """ Creates a temporary placeholder manifest for scans with no manifest files. @@ -921,11 +909,11 @@ def empty_head_scan_file() -> List[str]: """ # Own directory per call so concurrent runs can't clobber each other's placeholder; # the basename must stay exactly SOCKET_FACTS_FILENAME to pass the API's validator. - temp_dir = tempfile.mkdtemp(prefix='socket_baseline_') + temp_dir = tempfile.mkdtemp(prefix="socket_baseline_") _PLACEHOLDER_FACTS_DIRS.append(temp_dir) temp_path = os.path.join(temp_dir, SOCKET_FACTS_FILENAME) - with open(temp_path, 'w') as f: + with open(temp_path, "w") as f: f.write(SOCKET_FACTS_EMPTY_DOCUMENT) log.debug(f"Created temporary placeholder facts file for baseline scan: {temp_path}") @@ -955,10 +943,10 @@ def finalize_tier1_scan(self, full_scan_id: str, facts_file_path: str) -> bool: log.debug(f"Facts file not found: {facts_file_path}") return False - with open(facts_file_path, 'r') as f: + with open(facts_file_path) as f: facts = json.load(f) - tier1_scan_id = facts.get('tier1ReachabilityScanId') + tier1_scan_id = facts.get("tier1ReachabilityScanId") if not tier1_scan_id: log.debug(f"No tier1ReachabilityScanId found in {facts_file_path}") return False @@ -966,12 +954,12 @@ def finalize_tier1_scan(self, full_scan_id: str, facts_file_path: str) -> bool: tier1_scan_id = tier1_scan_id.strip() log.debug(f"Found tier1ReachabilityScanId: {tier1_scan_id}") - except (json.JSONDecodeError, IOError) as e: + except (OSError, json.JSONDecodeError) as e: log.debug(f"Failed to read tier1ReachabilityScanId from {facts_file_path}: {e}") return False # Call the SDK to finalize the full application reachability scan, retrying transient failures with backoff. - last_error: Optional[Exception] = None + last_error: Exception | None = None for attempt in range(1, TIER1_FINALIZE_MAX_ATTEMPTS + 1): try: success = self.sdk.fullscans.finalize_tier1( @@ -980,7 +968,9 @@ def finalize_tier1_scan(self, full_scan_id: str, facts_file_path: str) -> bool: ) if success: - log.debug(f"Successfully finalized full application reachability scan {tier1_scan_id} for full scan {full_scan_id}") + log.debug( + f"Successfully finalized full application reachability scan {tier1_scan_id} for full scan {full_scan_id}" + ) return True log.debug( @@ -1051,14 +1041,12 @@ def _compress_facts_file(source_path: str) -> str: # Don't leave a half-written .br behind for the caller to miss (it only tracks # the path for cleanup once this returns). Remove it, then re-raise so the caller # falls back to uploading the plain file. - try: + with contextlib.suppress(OSError): os.unlink(target_path) - except OSError: - pass raise return target_path - def _compress_facts_files_for_upload(self, files: List[str]) -> Tuple[List[str], List[str]]: + def _compress_facts_files_for_upload(self, files: list[str]) -> tuple[list[str], list[str]]: """Replace any ``.socket.facts.json`` upload entry with a brotli-compressed ``.br`` sibling. The Socket full-scan endpoint transparently decompresses a multipart part named @@ -1078,8 +1066,8 @@ def _compress_facts_files_for_upload(self, files: List[str]) -> Tuple[List[str], list to upload and ``temp_paths`` are compressed files the caller must delete once the upload completes. """ - upload_files: List[str] = [] - temp_paths: List[str] = [] + upload_files: list[str] = [] + temp_paths: list[str] = [] for file_path in files: try: if ( @@ -1098,13 +1086,13 @@ def _compress_facts_files_for_upload(self, files: List[str]) -> Tuple[List[str], continue except Exception as e: # Never let compression break an upload: fall back to the plain file. - log.warning( - f"Failed to brotli-compress facts file {file_path}, uploading uncompressed: {e}" - ) + log.warning(f"Failed to brotli-compress facts file {file_path}, uploading uncompressed: {e}") upload_files.append(file_path) return upload_files, temp_paths - def create_full_scan(self, files: List[str], params: FullScanParams, base_paths: Optional[List[str]] = None) -> FullScan: + def create_full_scan( + self, files: list[str], params: FullScanParams, base_paths: list[str] | None = None + ) -> FullScan: """ Creates a new full scan via the Socket API. @@ -1134,7 +1122,14 @@ def create_full_scan(self, files: List[str], params: FullScanParams, base_paths: # below) outlive every attempt. for attempt, backoff_seconds in enumerate(FULL_SCAN_UPLOAD_BACKOFF_SCHEDULE_SECONDS, start=1): try: - res = self.sdk.fullscans.post(upload_files, params, use_types=True, use_lazy_loading=True, max_open_files=50, base_paths=base_paths) + res = self.sdk.fullscans.post( + upload_files, + params, + use_types=True, + use_lazy_loading=True, + max_open_files=50, + base_paths=base_paths, + ) break except APIFailure as error: if error.status_code in REQUEST_TOO_LARGE_STATUS_CODES: @@ -1150,13 +1145,12 @@ def create_full_scan(self, files: List[str], params: FullScanParams, base_paths: "--commit-message or shorten other scan metadata." ) raise APIFailure( - f"Full scan request rejected as too large (HTTP {error.status_code}). " - f"{guidance}\n{error}", + f"Full scan request rejected as too large (HTTP {error.status_code}). {guidance}\n{error}", status_code=error.status_code, ) from error if backoff_seconds is None or not error.is_transient_error(): raise - wait_seconds = backoff_seconds + random.uniform( + wait_seconds = backoff_seconds + random.uniform( # noqa: S311 0, FULL_SCAN_UPLOAD_BACKOFF_JITTER_SECONDS ) # SDK error messages can span many lines (path + response headers); the @@ -1186,11 +1180,10 @@ def create_full_scan(self, files: List[str], params: FullScanParams, base_paths: # Finalize full application reachability scan if reachability analysis was enabled if self.cli_config and self.cli_config.reach: - facts_file_path = os.path.join( - self.cli_config.target_path or ".", - self.cli_config.reach_output_file + facts_file_path = os.path.join(self.cli_config.target_path or ".", self.cli_config.reach_output_file) + log.debug( + f"Reachability analysis enabled, finalizing full application reachability scan for full scan {full_scan.id}" ) - log.debug(f"Reachability analysis enabled, finalizing full application reachability scan for full scan {full_scan.id}") try: success = self.finalize_tier1_scan(full_scan.id, facts_file_path) if success: @@ -1204,18 +1197,17 @@ def create_full_scan(self, files: List[str], params: FullScanParams, base_paths: @staticmethod def _log_scan_configuration( - paths: List[str], - params: FullScanParams, - files: List[str], - manifest_source: str, - base_paths: Optional[List[str]] = None, + paths: list[str], + params: FullScanParams, + files: list[str], + manifest_source: str, + base_paths: list[str] | None = None, ) -> None: """Log aggregate scan inputs without exposing submitted manifest paths.""" base_path = base_paths[0] if base_paths else (paths[0] if paths else ".") absolute_base_path = os.path.abspath(base_path) relative_roots = [ - os.path.relpath(os.path.abspath(path), absolute_base_path).replace("\\", "/") - for path in paths + os.path.relpath(os.path.abspath(path), absolute_base_path).replace("\\", "/") for path in paths ] or ["."] log.info( "Scan configuration: " @@ -1226,15 +1218,15 @@ def _log_scan_configuration( f"manifests={len(files)} manifest_source={manifest_source}" ) - def create_full_scan_with_report_url( - self, - paths: List[str], - params: FullScanParams, - no_change: bool = False, - save_files_list_path: Optional[str] = None, - save_manifest_tar_path: Optional[str] = None, - base_paths: Optional[List[str]] = None, - explicit_files: Optional[List[str]] = None + def create_full_scan_with_report_url( # noqa: C901 + self, + paths: list[str], + params: FullScanParams, + no_change: bool = False, + save_files_list_path: str | None = None, + save_manifest_tar_path: str | None = None, + base_paths: list[str] | None = None, + explicit_files: list[str] | None = None, ) -> Diff: """Create a new full scan and return with html_report_url. @@ -1251,11 +1243,7 @@ def create_full_scan_with_report_url( Dict with full scan data including html_report_url """ log.debug(f"starting create_full_scan_with_report_url with no_change: {no_change}") - diff = Diff( - id="NO_SCAN_RAN", - report_url="", - diff_url="" - ) + diff = Diff(id="NO_SCAN_RAN", report_url="", diff_url="") if no_change: return diff @@ -1276,15 +1264,15 @@ def create_full_scan_with_report_url( manifest_source="provided" if explicit_files is not None else "discovered", base_paths=base_paths, ) - + # Save submitted files list if requested if save_files_list_path and all_files: self.save_submitted_files_list(all_files, save_files_list_path) - + # Save manifest tar.gz if requested (use first path as base) if save_manifest_tar_path and all_files and paths: self.save_manifest_tar(all_files, save_manifest_tar_path, paths[0]) - + # If no supported files found, create empty scan if not all_files: log.info("No supported manifest files found - creating empty scan") @@ -1295,7 +1283,7 @@ def create_full_scan_with_report_url( new_full_scan = self.create_full_scan(empty_files, params, base_paths=base_paths) new_scan_end = time.time() log.info(f"Total time to create empty full scan: {new_scan_end - new_scan_start:.2f}") - + # Clean up the temporary empty file for temp_file in empty_files: try: @@ -1303,14 +1291,12 @@ def create_full_scan_with_report_url( log.debug(f"Cleaned up temporary file: {temp_file}") except OSError as e: log.warning(f"Failed to clean up temporary file {temp_file}: {e}") - except Exception as e: + except Exception: # Clean up temp files even if scan creation fails for temp_file in empty_files: - try: + with contextlib.suppress(OSError): os.unlink(temp_file) - except OSError: - pass - raise e + raise else: try: # Create new scan @@ -1329,13 +1315,8 @@ def create_full_scan_with_report_url( diff.id = new_full_scan.id diff.is_full_scan = True - needs_alerts = ( - self.cli_config is not None - and ( - self.cli_config.enable_gitlab_security - or self.cli_config.enable_json - or self.cli_config.enable_sarif - ) + needs_alerts = self.cli_config is not None and ( + self.cli_config.enable_gitlab_security or self.cli_config.enable_json or self.cli_config.enable_sarif ) # --generate-license (and --legal-format fossa, which it gates) enumerates # diff.packages rather than the alert list, so a full scan has to carry the @@ -1343,9 +1324,7 @@ def create_full_scan_with_report_url( # this, an SCM branch pipeline writes an attribution file with zero packages. # Keep in sync with _requires_unchanged_artifacts, which lists the same # consumers for the comparison path. - needs_license_artifacts = ( - self.cli_config is not None and self.cli_config.generate_license - ) + needs_license_artifacts = self.cli_config is not None and self.cli_config.generate_license if needs_alerts or needs_license_artifacts: log.info("Output format requires SBOM data, fetching it for the full scan") @@ -1358,12 +1337,10 @@ def create_full_scan_with_report_url( diff.packages = packages if needs_alerts: - all_alerts_collection: Dict[str, List[Issue]] = {} - for package_id, package in packages.items(): + all_alerts_collection: dict[str, list[Issue]] = {} + for package in packages.values(): self.add_package_alerts_to_collection( - package=package, - alerts_collection=all_alerts_collection, - packages=packages + package=package, alerts_collection=all_alerts_collection, packages=packages ) findings = Core._consolidate_reportable_alerts( @@ -1374,8 +1351,7 @@ def create_full_scan_with_report_url( sbom_end = time.time() log.info( - f"Fetched {len(packages)} packages and {len(diff.new_alerts)} alerts " - f"in {sbom_end - sbom_start:.2f}s" + f"Fetched {len(packages)} packages and {len(diff.new_alerts)} alerts in {sbom_end - sbom_start:.2f}s" ) else: diff.packages = {} @@ -1396,9 +1372,7 @@ def _add_license_details(self, packages: dict[str, Package]) -> dict[str, Packag qualified_name = package.name if package.namespace: qualified_name = f"{package.namespace.strip('/')}/{qualified_name}" - packages_by_purl[ - f"{package.type}/{qualified_name}@{package.version}" - ] = package + packages_by_purl[f"{package.type}/{qualified_name}@{package.version}"] = package self.get_license_text_via_purl( packages_by_purl, batch_size=batch_size, @@ -1437,7 +1411,7 @@ def create_packages_dict(self, sbom_artifacts: list[SocketArtifact]) -> dict[str for artifact in sbom_artifacts: package = Package.from_socket_artifact(asdict(artifact)) if package.id in packages: - print("Duplicate package?") + log.debug(f"Duplicate package in SBOM artifacts: {package.id}") else: package.license_text = self.get_package_license_text(package) packages[package.id] = package @@ -1491,9 +1465,8 @@ def get_package_license_text(self, package: Package) -> str: return "" license_raw = package.license - data = self.sdk.licensemetadata.post([license_raw], {'includetext': 'true'}) - license_str = data[0].get('text') if data and len(data) == 1 else "" - return license_str + data = self.sdk.licensemetadata.post([license_raw], {"includetext": "true"}) + return data[0].get("text") if data and len(data) == 1 else "" def get_repo_info(self, repo_slug: str, default_branch: str = "socket-default-branch") -> RepositoryInfo: """ @@ -1538,23 +1511,21 @@ def get_repo_info(self, repo_slug: str, default_branch: str = "socket-default-br raise InfrastructureError(f"Failed to get repository {repo_slug}{status}: {reason}") from lookup_error log.warning(f"Failed to get repository {repo_slug}, attempting to create it") try: - create_response = self.sdk.repos.post( self.config.org_slug, name=repo_slug, default_branch=default_branch, - visibility=self.config.repo_visibility + visibility=self.config.repo_visibility, ) # Check if the response is empty (failure) or has content (success) if not create_response: log.error("Failed to create repository: empty response") raise Exception("Failed to create repository: empty response") - else: - response = self.sdk.repos.repo(self.config.org_slug, repo_slug, use_types=True) - if not response.success: - raise APIFailure(response.message or "Repository lookup failed", status_code=response.status) - return response.data + response = self.sdk.repos.repo(self.config.org_slug, repo_slug, use_types=True) + if not response.success: + raise APIFailure(response.message or "Repository lookup failed", status_code=response.status) + return response.data except APIFailure as e: status = f" (HTTP {e.status_code})" if e.status_code else "" @@ -1569,11 +1540,11 @@ def get_repo_info(self, repo_slug: str, default_branch: str = "socket-default-br return response.data def get_head_scan_for_repo( - self, - repo_slug: str, - workspace: Optional[str] = None, - scan_type: Optional[str] = None, - ) -> Optional[str]: + self, + repo_slug: str, + workspace: str | None = None, + scan_type: str | None = None, + ) -> str | None: """ Gets the head scan ID for a repository. @@ -1610,14 +1581,14 @@ def get_head_scan_for_repo( if scan_type: query_params["scan_type"] = Core.query_param_value(scan_type) for results in self._full_scan_result_pages( - query_params, - f"Failed to list matching full scans for repo {repo_slug}", + query_params, + f"Failed to list matching full scans for repo {repo_slug}", ): scan_id = Core.newest_persisted_scan_id(results) if scan_id: return scan_id return None - return repo_info.head_full_scan_id if repo_info.head_full_scan_id else None + return repo_info.head_full_scan_id or None @staticmethod def query_param_value(value): @@ -1631,7 +1602,7 @@ def query_param_value(value): return getattr(value, "value", value) @staticmethod - def newest_persisted_scan_id(results: List[dict]) -> Optional[str]: + def newest_persisted_scan_id(results: list[dict]) -> str | None: """ Returns the newest scan ID from a full scan listing, skipping temporary scans. @@ -1656,10 +1627,10 @@ def newest_persisted_scan_id(results: List[dict]) -> Optional[str]: return None def _full_scan_result_pages( - self, - query_params: dict, - failure_message: str, - ) -> Iterator[List[dict]]: + self, + query_params: dict, + failure_message: str, + ) -> Iterator[list[dict]]: """Yields successful full-scan listing pages and rejects failed lookups.""" request_params = dict(query_params) seen_pages = {str(request_params.get("page", 1))} @@ -1681,13 +1652,11 @@ def _full_scan_result_pages( page_key = str(next_page) if page_key in seen_pages: - raise APIFailure( - f"{failure_message}: full-scan pagination repeated page {next_page}" - ) + raise APIFailure(f"{failure_message}: full-scan pagination repeated page {next_page}") seen_pages.add(page_key) request_params = {**query_params, "page": next_page} - def first_parent_commits(self, start_commit_sha: str, max_count: int) -> List[str]: + def first_parent_commits(self, start_commit_sha: str, max_count: int) -> list[str]: """ Lists a commit and its first-parent ancestors, newest first. @@ -1719,12 +1688,12 @@ def first_parent_commits(self, start_commit_sha: str, max_count: int) -> List[st return [line.strip() for line in output.splitlines() if line.strip()] def find_baseline_scan_for_ancestor( - self, - repo_slug: str, - commit_sha: str, - workspace: Optional[str] = None, - scan_type: Optional[str] = None, - ) -> Tuple[Optional[str], Optional[str], int]: + self, + repo_slug: str, + commit_sha: str, + workspace: str | None = None, + scan_type: str | None = None, + ) -> tuple[str | None, str | None, int]: """ Finds the nearest ancestor of a commit that does have a full scan. @@ -1766,8 +1735,8 @@ def find_baseline_scan_for_ancestor( scans_by_commit = {} ancestor_set = set(ancestors) for results in self._full_scan_result_pages( - query_params, - f"Failed to list ancestor full scans for repo {repo_slug}", + query_params, + f"Failed to list ancestor full scans for repo {repo_slug}", ): for result in results: if not isinstance(result, dict) or result.get("tmp"): @@ -1775,11 +1744,7 @@ def find_baseline_scan_for_ancestor( result_commit = result.get("commit_hash") scan_id = result.get("id") # Newest first, so the first scan seen for a commit is the one to keep. - if ( - result_commit in ancestor_set - and scan_id - and result_commit not in scans_by_commit - ): + if result_commit in ancestor_set and scan_id and result_commit not in scans_by_commit: scans_by_commit[result_commit] = scan_id if not scans_by_commit: @@ -1792,12 +1757,8 @@ def find_baseline_scan_for_ancestor( return None, None, 0 def get_full_scan_id_by_commit( - self, - repo_slug: str, - commit_sha: str, - workspace: Optional[str] = None, - scan_type: Optional[str] = None - ) -> Optional[str]: + self, repo_slug: str, commit_sha: str, workspace: str | None = None, scan_type: str | None = None + ) -> str | None: """ Finds the most recent full scan for a repository + commit SHA. @@ -1827,15 +1788,15 @@ def get_full_scan_id_by_commit( query_params["scan_type"] = Core.query_param_value(scan_type) for results in self._full_scan_result_pages( - query_params, - f"Failed to list full scans for commit {commit_sha} in repo {repo_slug}", + query_params, + f"Failed to list full scans for commit {commit_sha} in repo {repo_slug}", ): scan_id = Core.newest_persisted_scan_id(results) if scan_id: return scan_id return None - def resolve_base_full_scan_id(self, params: FullScanParams) -> Optional[str]: + def resolve_base_full_scan_id(self, params: FullScanParams) -> str | None: """ Resolves the baseline full scan ID to diff a new scan against. @@ -1851,10 +1812,7 @@ def resolve_base_full_scan_id(self, params: FullScanParams) -> Optional[str]: has no head scan yet (caller creates an empty baseline scan). """ if self.cli_config and self.cli_config.base_scan_id: - log.info( - "Baseline selected: source=explicit-scan " - f"scan_id={json.dumps(self.cli_config.base_scan_id)}" - ) + log.info(f"Baseline selected: source=explicit-scan scan_id={json.dumps(self.cli_config.base_scan_id)}") return self.cli_config.base_scan_id if self.cli_config and self.cli_config.base_commit_sha: @@ -1915,10 +1873,7 @@ def resolve_base_full_scan_id(self, params: FullScanParams) -> Optional[str]: f"Failed to resolve the matching head scan for repo {params.repo}: {error}" ) from error if scan_id: - log.info( - "Baseline selected: source=repository-head " - f"scan_id={json.dumps(scan_id)}" - ) + log.info(f"Baseline selected: source=repository-head scan_id={json.dumps(scan_id)}") return scan_id @staticmethod @@ -1932,41 +1887,41 @@ def update_package_values(pkg: Package) -> Package: def get_license_text_via_purl(self, packages: dict[str, Package], batch_size: int = 5000) -> dict: """Get license attribution and details via PURL endpoint in batches. - + Args: packages: Dictionary of packages to get license info for batch_size: Maximum number of packages to process per API call (1-9999) - + Returns: Updated packages dictionary with licenseAttrib and licenseDetails populated """ # Validate batch size batch_size = max(1, min(9999, batch_size)) - + # Build list of all components all_components = [] for purl in packages: full_purl = f"pkg:/{purl}" all_components.append({"purl": full_purl}) - + # Process in batches total_components = len(all_components) log.debug(f"Processing {total_components} packages in batches of {batch_size}") - + for i in range(0, total_components, batch_size): - batch_components = all_components[i:i + batch_size] + batch_components = all_components[i : i + batch_size] batch_num = (i // batch_size) + 1 total_batches = (total_components + batch_size - 1) // batch_size log.debug(f"Processing batch {batch_num}/{total_batches} ({len(batch_components)} packages)") - + results = self.sdk.purl.post( license=True, components=batch_components, org_slug=self.config.org_slug, licenseattrib=True, - licensedetails=True + licensedetails=True, ) - + purl_packages = [] for result in results: ecosystem = result["type"] @@ -1981,14 +1936,11 @@ def get_license_text_via_purl(self, packages: dict[str, Package], batch_size: in if purl not in purl_packages and purl in packages: packages[purl].licenseAttrib = licenseAttrib packages[purl].licenseDetails = licenseDetails - + return packages - def get_diff_scan_artifacts( - self, - head_full_scan_id: str, - new_full_scan_id: str, - external_href: Optional[str] = None + def get_diff_scan_artifacts( # noqa: C901 + self, head_full_scan_id: str, new_full_scan_id: str, external_href: str | None = None ) -> DiffArtifacts: """Compare two full scans via the diff-scans endpoints, polling for the result. @@ -2059,8 +2011,7 @@ def get_diff_scan_artifacts( diff_scan_id = diff_scan.get("id") if not diff_scan_id: raise Exception( - "Error creating or resolving diff scan: " - f"unexpected response: {str(response_summary)[:500]}" + f"Error creating or resolving diff scan: unexpected response: {str(response_summary)[:500]}" ) # Logged at INFO, not debug: this is the only identifier that ties a slow or # failed comparison in a CI log back to a server-side diff scan, and it is @@ -2147,8 +2098,7 @@ def get_diff_scan_artifacts( break if time.monotonic() >= deadline: raise Exception( - f"Timed out waiting for diff scan {diff_scan_id} after " - f"{DIFF_SCAN_POLL_TIMEOUT_SECONDS:.0f} seconds" + f"Timed out waiting for diff scan {diff_scan_id} after {DIFF_SCAN_POLL_TIMEOUT_SECONDS:.0f} seconds" ) log.debug(f"Diff scan {diff_scan_id} still processing, polling again in {interval:.0f}s") time.sleep(interval) @@ -2190,13 +2140,13 @@ def _requires_unchanged_artifacts(self) -> bool: or getattr(config, "legal_format", "socket") == "fossa" ) - def get_added_and_removed_packages( - self, - head_full_scan_id: str, - new_full_scan_id: str, - include_license_details: bool = False, - external_href: Optional[str] = None - ) -> Tuple[Dict[str, Package], Dict[str, Package], Dict[str, Package]]: + def get_added_and_removed_packages( # noqa: C901 + self, + head_full_scan_id: str, + new_full_scan_id: str, + include_license_details: bool = False, + external_href: str | None = None, + ) -> tuple[dict[str, Package], dict[str, Package], dict[str, Package]]: """ Get packages that were added and removed between scans. @@ -2255,29 +2205,25 @@ def get_added_and_removed_packages( f"Diff scan comparison failed with {type(error).__name__}({error_summary}), " "falling back to the streaming scan comparison" ) - log.info( - "Diff comparison mode: requested=diff-scan effective=streaming " - f"reason={type(error).__name__}" - ) + log.info(f"Diff comparison mode: requested=diff-scan effective=streaming reason={type(error).__name__}") if diff_artifacts is None: try: - diff_artifacts = ( - self.sdk.fullscans.stream_diff( - self.config.org_slug, - head_full_scan_id, - new_full_scan_id, - use_types=True, - include_license_details=str(include_license_details).lower() - ).data.artifacts - ) + diff_artifacts = self.sdk.fullscans.stream_diff( + self.config.org_slug, + head_full_scan_id, + new_full_scan_id, + use_types=True, + include_license_details=str(include_license_details).lower(), + ).data.artifacts except APIFailure as e: log.error(f"API Error: {e}") # API failures are mapped to the configured infrastructure exit code by cli(). raise except Exception as e: import traceback - log.error(f"Error getting diff report: {str(e)}") + + log.error(f"Error getting diff report: {e!s}") log.error(f"Stack trace:\n{traceback.format_exc()}") raise @@ -2288,7 +2234,7 @@ def get_added_and_removed_packages( # Drop it from every bucket before the counts below, which should describe what the # CLI actually reports on. marker_found = False - buckets: Dict[str, List] = {} + buckets: dict[str, list] = {} for name in ("added", "removed", "unchanged", "replaced", "updated"): bucket = getattr(diff_artifacts, name) buckets[name] = [a for a in bucket if not Core.is_invalid_facts_marker(a)] @@ -2303,9 +2249,9 @@ def get_added_and_removed_packages( removed_artifacts = buckets["removed"] + buckets["replaced"] unchanged_artifacts = buckets["unchanged"] - added_packages: Dict[str, Package] = {} - removed_packages: Dict[str, Package] = {} - packages: Dict[str, Package] = {} + added_packages: dict[str, Package] = {} + removed_packages: dict[str, Package] = {} + packages: dict[str, Package] = {} for artifact in added_artifacts: try: pkg = Package.from_diff_artifact(asdict(artifact)) @@ -2348,19 +2294,19 @@ def get_added_and_removed_packages( packages = self.get_license_text_via_purl(packages, batch_size=batch_size) else: log.debug("Skipping PURL endpoint call (--generate-license not set)") - + return added_packages, removed_packages, packages - def create_new_diff( - self, - paths: List[str], - params: FullScanParams, - no_change: bool = False, - save_files_list_path: Optional[str] = None, - save_manifest_tar_path: Optional[str] = None, - base_paths: Optional[List[str]] = None, - explicit_files: Optional[List[str]] = None, - external_href: Optional[str] = None + def create_new_diff( # noqa: C901 + self, + paths: list[str], + params: FullScanParams, + no_change: bool = False, + save_files_list_path: str | None = None, + save_manifest_tar_path: str | None = None, + base_paths: list[str] | None = None, + explicit_files: list[str] | None = None, + external_href: str | None = None, ) -> Diff: """Create a new diff using the Socket SDK. @@ -2396,15 +2342,15 @@ def create_new_diff( manifest_source="provided" if explicit_files is not None else "discovered", base_paths=base_paths, ) - + # Save submitted files list if requested if save_files_list_path and all_files: self.save_submitted_files_list(all_files, save_files_list_path) - + # Save manifest tar.gz if requested (use first path as base) if save_manifest_tar_path and all_files and paths: self.save_manifest_tar(all_files, save_manifest_tar_path, paths[0]) - + # If no supported files found, create empty scan for comparison scan_files = all_files if not all_files: @@ -2420,23 +2366,20 @@ def create_new_diff( if head_full_scan_id is None: log.info("No previous scan found - creating empty baseline scan") new_params = copy.deepcopy(params.__dict__) - new_params.pop('include_license_details') + new_params.pop("include_license_details") tmp_params = FullScanParams(**new_params) tmp_params.include_license_details = params.include_license_details tmp_params.tmp = True tmp_params.set_as_pending_head = False tmp_params.make_default_branch = False - + # Create baseline scan with empty file empty_files = Core.empty_head_scan_file() try: head_full_scan = self.create_full_scan(empty_files, tmp_params, base_paths=base_paths) head_full_scan_id = head_full_scan.id - log.info( - "Baseline selected: source=empty " - f"scan_id={json.dumps(head_full_scan_id)}" - ) - + log.info(f"Baseline selected: source=empty scan_id={json.dumps(head_full_scan_id)}") + # Clean up the temporary empty file for temp_file in empty_files: try: @@ -2444,20 +2387,18 @@ def create_new_diff( log.debug(f"Cleaned up temporary file: {temp_file}") except OSError as e: log.warning(f"Failed to clean up temporary file {temp_file}: {e}") - except Exception as e: + except Exception: # Clean up temp files even if scan creation fails for temp_file in empty_files: - try: + with contextlib.suppress(OSError): os.unlink(temp_file) - except OSError: - pass - raise e + raise # Create new scan temp_files_to_cleanup = [] if not all_files: # We're using empty scan files temp_files_to_cleanup = scan_files - + try: new_scan_start = time.time() new_full_scan = self.create_full_scan(scan_files, params, base_paths=base_paths) @@ -2467,22 +2408,19 @@ def create_new_diff( log.error(f"API Error: {e}") # Clean up temp files if any for temp_file in temp_files_to_cleanup: - try: + with contextlib.suppress(OSError): os.unlink(temp_file) - except OSError: - pass # API failures are mapped to the configured infrastructure exit code by cli(). raise except Exception as e: import traceback - log.error(f"Error creating new full scan: {str(e)}") + + log.error(f"Error creating new full scan: {e!s}") log.error(f"Stack trace:\n{traceback.format_exc()}") # Clean up temp files if any for temp_file in temp_files_to_cleanup: - try: + with contextlib.suppress(OSError): os.unlink(temp_file) - except OSError: - pass raise finally: # Clean up temporary empty files if they were created @@ -2502,11 +2440,7 @@ def create_new_diff( # the response and risks the truncation crash on large repos. The # user flag still controls the dashboard report URL below; it just no # longer gates this internal diff payload. - ( - added_packages, - removed_packages, - packages - ) = self.get_added_and_removed_packages( + (added_packages, removed_packages, packages) = self.get_added_and_removed_packages( head_full_scan_id, new_full_scan.id, include_license_details=False, @@ -2522,7 +2456,8 @@ def create_new_diff( for package in bucket.values() } existing_changed_packages = { - package_id: copy.copy(package) for package_id, package in added_packages.items() + package_id: copy.copy(package) + for package_id, package in added_packages.items() if package.diffType == "updated" or Core._package_identity(package.type, package.namespace, package.name, "")[:3] in baseline_names } @@ -2579,10 +2514,10 @@ def _requires_unchanged_alerts(self) -> bool: def add_existing_alerts_from_full_scan( self, - unchanged_packages: Dict[str, Package], + unchanged_packages: dict[str, Package], full_scan_id: str, *, - changed_packages: Optional[Dict[str, Package]] = None, + changed_packages: dict[str, Package] | None = None, ) -> None: """Load alerts for unchanged and optionally changed packages from the new full scan. @@ -2605,24 +2540,24 @@ def add_existing_alerts_from_full_scan( package_kind = "current" if changed_packages else "unchanged" start = time.time() - by_id: Dict[str, List[dict]] = {} - by_identity: Dict[Tuple[str, str, str, str], List[dict]] = {} + by_id: dict[str, list[dict]] = {} + by_identity: dict[tuple[str, str, str, str], list[dict]] = {} for artifact in self.get_sbom_data(full_scan_id).values(): data = asdict(artifact) alerts = data.get("alerts") or [] by_id[data["id"]] = alerts - by_identity[Core._package_identity( - data["type"], data.get("namespace"), data["name"], data["version"] - )] = alerts + by_identity[Core._package_identity(data["type"], data.get("namespace"), data["name"], data["version"])] = ( + alerts + ) matched = 0 alert_count = 0 for package in packages_to_load.values(): alerts = by_id.get(package.id) if alerts is None: - alerts = by_identity.get(Core._package_identity( - package.type, package.namespace, package.name, package.version - )) + alerts = by_identity.get( + Core._package_identity(package.type, package.namespace, package.name, package.version) + ) if alerts is None: continue package.alerts = alerts @@ -2640,7 +2575,7 @@ def add_existing_alerts_from_full_scan( ) @staticmethod - def _package_identity(package_type, namespace, name, version) -> Tuple[str, str, str, str]: + def _package_identity(package_type, namespace, name, version) -> tuple[str, str, str, str]: return ( str(Package.normalize_type(package_type) or ""), (namespace or "").strip("/"), @@ -2650,10 +2585,10 @@ def _package_identity(package_type, namespace, name, version) -> Tuple[str, str, @staticmethod def get_unchanged_packages( - packages: Dict[str, Package], - added_packages: Dict[str, Package], - removed_packages: Dict[str, Package], - ) -> Dict[str, Package]: + packages: dict[str, Package], + added_packages: dict[str, Package], + removed_packages: dict[str, Package], + ) -> dict[str, Package]: """Return the packages in ``packages`` that were neither added nor removed. ``packages`` is keyed by ``type/purl`` while the added and removed dicts are @@ -2662,18 +2597,17 @@ def get_unchanged_packages( ``get_source_data`` expects when it resolves ``topLevelAncestors``. """ return { - pkg.id: pkg for pkg in packages.values() - if pkg.id not in added_packages and pkg.id not in removed_packages + pkg.id: pkg for pkg in packages.values() if pkg.id not in added_packages and pkg.id not in removed_packages } def create_diff_report( self, - added_packages: Dict[str, Package], - removed_packages: Dict[str, Package], - unchanged_packages: Optional[Dict[str, Package]] = None, + added_packages: dict[str, Package], + removed_packages: dict[str, Package], + unchanged_packages: dict[str, Package] | None = None, direct_only: bool = True, *, - existing_changed_packages: Optional[Dict[str, Package]] = None, + existing_changed_packages: dict[str, Package] | None = None, ) -> Diff: """ Creates a diff report comparing two sets of packages. @@ -2697,9 +2631,9 @@ def create_diff_report( """ diff = Diff() - alerts_in_added_packages: Dict[str, List[Issue]] = {} - alerts_in_removed_packages: Dict[str, List[Issue]] = {} - alerts_in_unchanged_packages: Dict[str, List[Issue]] = {} + alerts_in_added_packages: dict[str, list[Issue]] = {} + alerts_in_removed_packages: dict[str, list[Issue]] = {} + alerts_in_unchanged_packages: dict[str, list[Issue]] = {} current_packages = {**(unchanged_packages or {}), **added_packages} seen_packages = { @@ -2720,9 +2654,7 @@ def create_diff_report( seen_packages[change_type].add(base_purl) self.add_package_alerts_to_collection( - package=package, - alerts_collection=alerts_in_added_packages, - packages=added_packages + package=package, alerts_collection=alerts_in_added_packages, packages=added_packages ) for package_id, package in removed_packages.items(): @@ -2736,9 +2668,7 @@ def create_diff_report( seen_packages[change_type].add(base_purl) self.add_package_alerts_to_collection( - package=package, - alerts_collection=alerts_in_removed_packages, - packages=removed_packages + package=package, alerts_collection=alerts_in_removed_packages, packages=removed_packages ) # Process unchanged packages for --strict-blocking support @@ -2749,21 +2679,14 @@ def create_diff_report( continue self.add_package_alerts_to_collection( - package=package, - alerts_collection=alerts_in_unchanged_packages, - packages=unchanged_packages + package=package, alerts_collection=alerts_in_unchanged_packages, packages=unchanged_packages ) - diff.new_alerts = Core.get_new_alerts( - alerts_in_added_packages, - alerts_in_removed_packages - ) + diff.new_alerts = Core.get_new_alerts(alerts_in_added_packages, alerts_in_removed_packages) - diff.unchanged_alerts = Core.get_unchanged_alerts( - alerts_in_unchanged_packages - ) + diff.unchanged_alerts = Core.get_unchanged_alerts(alerts_in_unchanged_packages) if existing_changed_packages: - current_changed_alerts: Dict[str, List[Issue]] = {} + current_changed_alerts: dict[str, list[Issue]] = {} for package in existing_changed_packages.values(): self.add_package_alerts_to_collection( package=package, @@ -2780,9 +2703,7 @@ def create_diff_report( diff.unchanged_alerts = list(current_findings.values()) # Get removed alerts (for completeness) - diff.removed_alerts = Core.get_removed_alerts( - alerts_in_removed_packages - ) + diff.removed_alerts = Core.get_removed_alerts(alerts_in_removed_packages) diff.new_capabilities = Core.get_capabilities_for_added_packages(added_packages) @@ -2807,7 +2728,7 @@ def create_purl(self, package_id: str, packages: dict[str, Package]) -> Purl: """ package = packages[package_id] introduced_by = Core.get_source_data(package, packages) - purl = Purl( + return Purl( id=package.id, name=package.name, version=package.version, @@ -2819,10 +2740,8 @@ def create_purl(self, package_id: str, packages: dict[str, Package]) -> Purl: transitives=package.transitives, url=package.url, purl=package.purl, - scores=package.score + scores=package.score, ) - return purl - @staticmethod def get_source_data(package: Package, packages: dict) -> list: @@ -2858,9 +2777,7 @@ def get_source_data(package: Package, packages: dict) -> list: if top_package: manifests = "" ancestor_name = ( - f"{top_package.namespace}/{top_package.name}" - if top_package.namespace - else top_package.name + f"{top_package.namespace}/{top_package.name}" if top_package.namespace else top_package.name ) top_purl = f"{top_package.type}/{ancestor_name}@{top_package.version}" if hasattr(top_package, "manifestFiles") and top_package.manifestFiles: @@ -2889,12 +2806,10 @@ def add_purl_capabilities(diff: Diff) -> None: for attribute in ("new_packages", "updated_packages"): packages = [] for purl in getattr(diff, attribute): + updated = purl if purl.id in diff.new_capabilities: - purl = Purl( - **{**purl.__dict__, - "capabilities": diff.new_capabilities[purl.id]} - ) - packages.append(purl) + updated = Purl(**{**purl.__dict__, "capabilities": diff.new_capabilities[purl.id]}) + packages.append(updated) setattr(diff, attribute, packages) def add_package_alerts_to_collection(self, package: Package, alerts_collection: dict, packages: dict) -> dict: @@ -2909,12 +2824,9 @@ def add_package_alerts_to_collection(self, package: Package, alerts_collection: Returns: Updated alerts collection dictionary """ - default_props = type('EmptyProps', (), { - 'description': "", - 'title': "", - 'suggestion': "", - 'nextStepTitle': "" - })() + default_props = type( + "EmptyProps", (), {"description": "", "title": "", "suggestion": "", "nextStepTitle": ""} + )() for alert_item in package.alerts: alert = Alert(**alert_item) @@ -2933,7 +2845,7 @@ def add_package_alerts_to_collection(self, package: Package, alerts_collection: title = "License Policy Violation" if not title: title = _humanize_alert_type(alert.type) - + issue_alert = Issue( pkg_type=package.type, pkg_name=package.name, @@ -2951,12 +2863,12 @@ def add_package_alerts_to_collection(self, package: Package, alerts_collection: manifest_files=package.manifestFiles or [], direct=bool(package.direct), purl=package.purl, - url=package.url + url=package.url, ) # Use action from API (from security policy, label policy, triage, etc.) - if 'action' in alert_item and alert_item['action']: - action = alert_item['action'] + if alert_item.get("action"): + action = alert_item["action"] setattr(issue_alert, action, True) if issue_alert.key not in alerts_collection: @@ -2981,12 +2893,12 @@ def save_file(file_name: str, content: str) -> None: try: with open(file_name, "w") as f: f.write(content) - except IOError as e: + except OSError as e: log.error(f"Failed to save file {file_name}: {e}") raise @staticmethod - def get_capabilities_for_added_packages(added_packages: Dict[str, Package]) -> Dict[str, List[str]]: + def get_capabilities_for_added_packages(added_packages: dict[str, Package]) -> dict[str, list[str]]: """ Maps added packages to their capabilities based on their alerts. @@ -2996,7 +2908,7 @@ def get_capabilities_for_added_packages(added_packages: Dict[str, Package]) -> D Returns: Dictionary mapping package IDs to their capability lists """ - capabilities: Dict[str, List[str]] = {} + capabilities: dict[str, list[str]] = {} for package_id, package in added_packages.items(): for alert in package.alerts: @@ -3012,10 +2924,10 @@ def get_capabilities_for_added_packages(added_packages: Dict[str, Package]) -> D @staticmethod def get_new_alerts( - added_package_alerts: Dict[str, List[Issue]], - removed_package_alerts: Dict[str, List[Issue]], - ignore_readded: bool = True - ) -> List[Issue]: + added_package_alerts: dict[str, list[Issue]], + removed_package_alerts: dict[str, list[Issue]], + ignore_readded: bool = True, + ) -> list[Issue]: """ Find alerts that are new or changed between added and removed packages. @@ -3036,9 +2948,7 @@ def get_new_alerts( return list(findings.values()) @staticmethod - def get_unchanged_alerts( - unchanged_package_alerts: Dict[str, List[Issue]] - ) -> List[Issue]: + def get_unchanged_alerts(unchanged_package_alerts: dict[str, list[Issue]]) -> list[Issue]: """ Extract all alerts from unchanged packages that are errors or warnings. @@ -3057,9 +2967,9 @@ def get_unchanged_alerts( return list(findings.values()) @staticmethod - def _consolidate_reportable_alerts(alerts: Iterable[Issue]) -> Dict[Tuple[str, str, str, str], Issue]: + def _consolidate_reportable_alerts(alerts: Iterable[Issue]) -> dict[tuple[str, str, str, str], Issue]: """Keep the strongest reportable action for each finding across manifests and scan results.""" - findings: Dict[Tuple[str, str, str, str], Issue] = {} + findings: dict[tuple[str, str, str, str], Issue] = {} for alert in alerts: if alert.error or alert.warn: key = alert.consolidation_key() @@ -3069,9 +2979,7 @@ def _consolidate_reportable_alerts(alerts: Iterable[Issue]) -> Dict[Tuple[str, s return findings @staticmethod - def get_removed_alerts( - removed_package_alerts: Dict[str, List[Issue]] - ) -> List[Issue]: + def get_removed_alerts(removed_package_alerts: dict[str, list[Issue]]) -> list[Issue]: """ Extract all alerts from removed packages. @@ -3083,7 +2991,7 @@ def get_removed_alerts( Returns: List of all alerts from removed packages """ - alerts: List[Issue] = [] + alerts: list[Issue] = [] consolidated_alerts = set() for alert_key in removed_package_alerts: diff --git a/socketsecurity/core/alert_selection.py b/socketsecurity/core/alert_selection.py index d775b17b..e382307f 100644 --- a/socketsecurity/core/alert_selection.py +++ b/socketsecurity/core/alert_selection.py @@ -1,6 +1,6 @@ import logging from pathlib import Path -from typing import Any, Dict, List, Optional, Set, Tuple +from typing import Any from socketsecurity.core.classes import Diff, Issue from socketsecurity.core.helper.socket_facts_loader import ( @@ -11,7 +11,7 @@ from socketsecurity.core.messages import Messages -def select_diff_alerts(diff: Diff, strict_blocking: bool = False) -> List[Issue]: +def select_diff_alerts(diff: Diff, strict_blocking: bool = False) -> list[Issue]: """Select diff alerts for output rendering. In strict blocking mode, include unchanged alerts so rendered output aligns @@ -29,13 +29,13 @@ def select_diff_alerts(diff: Diff, strict_blocking: bool = False) -> List[Issue] return selected -def _alert_identity(alert: Issue) -> Optional[Tuple[str, str, str, str]]: +def _alert_identity(alert: Issue) -> tuple[str, str, str, str] | None: if not (getattr(alert, "purl", "") or ""): return None return alert.consolidation_key() -def clone_diff_with_selected_alerts(diff: Diff, selected_alerts: List[Issue]) -> Diff: +def clone_diff_with_selected_alerts(diff: Diff, selected_alerts: list[Issue]) -> Diff: """Clone a diff object while replacing new_alerts with selected alerts.""" selected_diff = Diff( new_alerts=selected_alerts, @@ -55,9 +55,9 @@ def clone_diff_with_selected_alerts(diff: Diff, selected_alerts: List[Issue]) -> def load_components_with_alerts( - target_path: Optional[str], - reach_output_file: Optional[str], -) -> Optional[List[Dict[str, Any]]]: + target_path: str | None, + reach_output_file: str | None, +) -> list[dict[str, Any]] | None: facts_file = reach_output_file or ".socket.facts.json" facts_file_path = str(Path(target_path or ".") / facts_file) facts_data = load_socket_facts(facts_file_path) @@ -72,9 +72,7 @@ def _normalize_purl(purl: str) -> str: if not purl: return "" normalized = purl.strip().lower().replace("%40", "@") - if normalized.startswith("pkg:"): - normalized = normalized[4:] - return normalized + return normalized.removeprefix("pkg:") def _normalize_vuln_id(vuln_id: str) -> str: @@ -83,7 +81,7 @@ def _normalize_vuln_id(vuln_id: str) -> str: return vuln_id.strip().upper() -def _normalize_pkg_key(pkg_type: str, pkg_name: str, pkg_version: str) -> Tuple[str, str, str]: +def _normalize_pkg_key(pkg_type: str, pkg_name: str, pkg_version: str) -> tuple[str, str, str]: return ( (pkg_type or "").strip().lower(), (pkg_name or "").strip().lower(), @@ -91,8 +89,8 @@ def _normalize_pkg_key(pkg_type: str, pkg_name: str, pkg_version: str) -> Tuple[ ) -def _extract_issue_vuln_ids(issue: Issue) -> Set[str]: - ids: Set[str] = set() +def _extract_issue_vuln_ids(issue: Issue) -> set[str]: + ids: set[str] = set() props = getattr(issue, "props", None) or {} for key in ("ghsaId", "ghsa_id", "cveId", "cve_id"): value = props.get(key) @@ -107,7 +105,7 @@ def _is_potentially_reachable(reachability: str, undeterminable: bool = False) - return normalized in potential_states or undeterminable -def _matches_selector(states: Set[str], selector: str) -> bool: +def _matches_selector(states: set[str], selector: str) -> bool: selected = (selector or "all").strip().lower() if selected == "all": return True @@ -122,14 +120,37 @@ def _matches_selector(states: Set[str], selector: str) -> bool: return True +def _index_reachability( + container: dict[Any, dict[str, set[str]]], + key: Any, + vuln_ids: set[str], + reachability: str, +) -> None: + if key not in container: + container[key] = {} + vuln_key = next(iter(vuln_ids)) if len(vuln_ids) == 1 else "*" + if vuln_key not in container[key]: + container[key][vuln_key] = set() + container[key][vuln_key].add(reachability) + if vuln_ids and vuln_key == "*": + for vuln_id in vuln_ids: + if vuln_id not in container[key]: + container[key][vuln_id] = set() + container[key][vuln_id].add(reachability) + if not vuln_ids: + if "*" not in container[key]: + container[key]["*"] = set() + container[key]["*"].add(reachability) + + def _build_reachability_index( - components_with_alerts: Optional[List[Dict[str, Any]]], -) -> Optional[Tuple[Dict[str, Dict[str, Set[str]]], Dict[Tuple[str, str, str], Dict[str, Set[str]]]]]: + components_with_alerts: list[dict[str, Any]] | None, +) -> tuple[dict[str, dict[str, set[str]]], dict[tuple[str, str, str], dict[str, set[str]]]] | None: if not components_with_alerts: return None - by_purl: Dict[str, Dict[str, Set[str]]] = {} - by_pkg: Dict[Tuple[str, str, str], Dict[str, Set[str]]] = {} + by_purl: dict[str, dict[str, set[str]]] = {} + by_pkg: dict[tuple[str, str, str], dict[str, set[str]]] = {} for component in components_with_alerts: component_alerts = component.get("alerts", []) @@ -138,7 +159,7 @@ def _build_reachability_index( namespace = (component.get("namespace") or "").strip() name = (component.get("name") or component.get("id") or "").strip() - pkg_names: Set[str] = {name} + pkg_names: set[str] = {name} if namespace: pkg_names.add(f"{namespace}/{name}") @@ -152,39 +173,22 @@ def _build_reachability_index( vuln_ids = {v for v in vuln_ids if v} purl = _normalize_purl(props.get("purl", "")) - def _add(container: Dict[Any, Dict[str, Set[str]]], key: Any) -> None: - if key not in container: - container[key] = {} - vuln_key = next(iter(vuln_ids)) if len(vuln_ids) == 1 else "*" - if vuln_key not in container[key]: - container[key][vuln_key] = set() - container[key][vuln_key].add(reachability) - if vuln_ids and vuln_key == "*": - for vuln_id in vuln_ids: - if vuln_id not in container[key]: - container[key][vuln_id] = set() - container[key][vuln_id].add(reachability) - if not vuln_ids: - if "*" not in container[key]: - container[key]["*"] = set() - container[key]["*"].add(reachability) - if purl: - _add(by_purl, purl) + _index_reachability(by_purl, purl, vuln_ids, reachability) for pkg_name in pkg_names: pkg_key = _normalize_pkg_key(pkg_type, pkg_name, pkg_version) - _add(by_pkg, pkg_key) + _index_reachability(by_pkg, pkg_key, vuln_ids, reachability) return by_purl, by_pkg def _alert_reachability_states( alert: Issue, - by_purl: Dict[str, Dict[str, Set[str]]], - by_pkg: Dict[Tuple[str, str, str], Dict[str, Set[str]]], -) -> Set[str]: - states: Set[str] = set() + by_purl: dict[str, dict[str, set[str]]], + by_pkg: dict[tuple[str, str, str], dict[str, set[str]]], +) -> set[str]: + states: set[str] = set() alert_ids = _extract_issue_vuln_ids(alert) alert_purl = _normalize_purl(getattr(alert, "purl", "")) pkg_key = _normalize_pkg_key( @@ -193,8 +197,8 @@ def _alert_reachability_states( getattr(alert, "pkg_version", ""), ) - def _collect(index: Dict[Any, Dict[str, Set[str]]], key: Any) -> Set[str]: - found: Set[str] = set() + def _collect(index: dict[Any, dict[str, set[str]]], key: Any) -> set[str]: + found: set[str] = set() mapping = index.get(key, {}) if not mapping: return found @@ -218,13 +222,13 @@ def _collect(index: Dict[Any, Dict[str, Set[str]]], key: Any) -> Set[str]: def filter_alerts_by_reachability( - alerts: List[Issue], + alerts: list[Issue], selector: str, - target_path: Optional[str], - reach_output_file: Optional[str], - logger: Optional[logging.Logger] = None, + target_path: str | None, + reach_output_file: str | None, + logger: logging.Logger | None = None, fallback_to_blocking_for_reachable: bool = True, -) -> List[Issue]: +) -> list[Issue]: """ Filter issue alerts by reachability selector using .socket.facts.json data. @@ -245,7 +249,7 @@ def filter_alerts_by_reachability( return [] by_purl, by_pkg = reachability_index - filtered: List[Issue] = [] + filtered: list[Issue] = [] for alert in alerts: states = _alert_reachability_states(alert, by_purl, by_pkg) if _matches_selector(states, normalized_selector): diff --git a/socketsecurity/core/classes.py b/socketsecurity/core/classes.py index bdea4b41..d9e5b3b8 100644 --- a/socketsecurity/core/classes.py +++ b/socketsecurity/core/classes.py @@ -1,7 +1,7 @@ import json import logging from dataclasses import dataclass, field -from typing import Dict, List, Optional, Tuple, TypedDict +from typing import TypedDict from socketdev.fullscans import ( FullScanMetadata, @@ -25,22 +25,23 @@ ADVISORY_ID_PROPS = ("ghsaId", "ghsa_id", "cveId", "cve_id", "cve") __all__ = [ - "Report", - "Score", - "Package", - "Issue", - "YamlFile", "Alert", - "FullScan", - "Repository", + "Comment", "Diff", + "FullScan", + "Issue", + "Package", "Purl", - "Comment" + "Report", + "Repository", + "Score", + "YamlFile", ] + class Report: """Represents a Socket Security scan report for a repository.""" - + branch: str commit: str id: str @@ -59,20 +60,20 @@ def __init__(self, **kwargs): setattr(self, key, value) if not hasattr(self, "processed"): self.processed = False - if hasattr(self, "pull_requests"): - if self.pull_requests is not None: - self.pull_requests = json.loads(str(self.pull_requests)) + if hasattr(self, "pull_requests") and self.pull_requests is not None: + self.pull_requests = json.loads(str(self.pull_requests)) def __str__(self): return json.dumps(self.__dict__) + class Score: """ Represents Socket Security scores for a package or repository. - + All scores are normalized to 0-100 range, converting from 0-1 if needed. """ - + supplyChain: float quality: float maintenance: float @@ -96,7 +97,7 @@ def __str__(self): def to_dict(self) -> dict: """ Convert Score object to dictionary with default values. - + Returns: Dictionary containing all score values, defaulting to 0 if not set """ @@ -106,44 +107,47 @@ def to_dict(self) -> dict: "maintenance": self.maintenance if hasattr(self, "maintenance") else 0, "license": self.license if hasattr(self, "license") else 0, "overall": self.overall if hasattr(self, "overall") else 0, - "vulnerability": self.vulnerability if hasattr(self, "vulnerability") else 0 + "vulnerability": self.vulnerability if hasattr(self, "vulnerability") else 0, } + class AlertCounts(TypedDict): """Type definition for counting alerts by severity level.""" + critical: int high: int middle: int low: int + @dataclass(kw_only=True) -class Package(): +class Package: """ Represents a package detected in a Socket Security scan. - + Inherits from SocketArtifactLink to maintain connection to dependency tree. Adds additional fields for package-specific information. """ - + # Common properties from both artifact types type: str name: str version: str - release: Optional[str] = None - diffType: Optional[str] = None + release: str | None = None + diffType: str | None = None id: str - author: List[str] = field(default_factory=list) + author: list[str] = field(default_factory=list) score: SocketScore - alerts: List[SocketAlert] - size: Optional[int] = None - license: Optional[str] = None - namespace: Optional[str] = None - topLevelAncestors: Optional[List[str]] = None - direct: Optional[bool] = False - manifestFiles: Optional[List[SocketManifestReference]] = None - dependencies: Optional[List[str]] = None - artifact: Optional[SocketArtifactLink] = None - + alerts: list[SocketAlert] + size: int | None = None + license: str | None = None + namespace: str | None = None + topLevelAncestors: list[str] | None = None + direct: bool | None = False + manifestFiles: list[SocketManifestReference] | None = None + dependencies: list[str] | None = None + artifact: SocketArtifactLink | None = None + # Package-specific fields license_text: str = "" purl: str = "" @@ -151,9 +155,8 @@ class Package(): url: str = "" # Artifact-specific fields - licenseDetails: Optional[list] = None - licenseAttrib: Optional[List] = None - + licenseDetails: list | None = None + licenseAttrib: list | None = None @staticmethod def normalize_type(package_type) -> str: @@ -166,7 +169,7 @@ def normalize_type(package_type) -> str: return getattr(package_type, "value", package_type) @staticmethod - def socket_url(package_type, namespace: Optional[str], name: str, version: str) -> str: + def socket_url(package_type, namespace: str | None, name: str, version: str) -> str: """ Builds the socket.dev package overview URL for a package. @@ -196,10 +199,10 @@ def socket_url(package_type, namespace: Optional[str], name: str, version: str) def from_socket_artifact(cls, data: dict) -> "Package": """ Create a Package from a SocketArtifact dictionary. - + Args: data: Dictionary containing SocketArtifact data - + Returns: New Package instance """ @@ -227,20 +230,20 @@ def from_socket_artifact(cls, data: dict) -> "Package": artifact=data.get("artifact"), purl=purl, url=url, - namespace=namespace or None + namespace=namespace or None, ) @classmethod def from_diff_artifact(cls, data: dict) -> "Package": """ Create a Package from a DiffArtifact dictionary. - + Args: data: Dictionary containing DiffArtifact data - + Returns: New Package instance - + Raises: ValueError: If reference data cannot be found in DiffArtifact """ @@ -294,12 +297,13 @@ def from_diff_artifact(cls, data: dict) -> "Package": manifestFiles=ref.get("manifestFiles", []), dependencies=ref.get("dependencies"), artifact=ref.get("artifact"), - namespace=data.get('namespace', None), + namespace=data.get("namespace"), release=ref.get("release", None), diffType=ref.get("diffType", diff_type), ) -class Issue: + +class Issue: # noqa: PLW1641 pkg_type: str pkg_name: str pkg_version: str @@ -328,13 +332,13 @@ class Issue: manifest_files: list direct: bool - def __init__(self, **kwargs): + def __init__(self, **kwargs): # noqa: C901 if kwargs: for key, value in kwargs.items(): setattr(self, key, value) if hasattr(self, "created_at"): - self.created_at = self.created_at.strip(" (Coordinated Universal Time)") + self.created_at = self.created_at.removesuffix(" (Coordinated Universal Time)") if not hasattr(self, "manifest_files"): self.manifest_files = [] if not hasattr(self, "direct"): @@ -347,7 +351,7 @@ def __init__(self, **kwargs): self.introduced_by = [] else: for item in self.introduced_by: - pkg, manifest = item + _pkg, manifest = item self.manifests += f"{manifest};" self.manifests = self.manifests.rstrip(";") if not hasattr(self, "error"): @@ -382,7 +386,7 @@ def advisory_id(self) -> str: return value.strip().upper() return "" - def consolidation_key(self) -> Tuple[str, str, str, str]: + def consolidation_key(self) -> tuple[str, str, str, str]: """Identity used to collapse repeat sightings of one finding into one alert. The same alert arrives once per manifest that pulls the package in, so the @@ -412,10 +416,10 @@ def __ne__(self, other): class YamlFile: """ Represents a YAML configuration file with associated alerts. - + Stores metadata about the file and any security alerts found during scanning. """ - + path: str name: str team: list @@ -439,19 +443,17 @@ def __str__(self): issue: Issue issue = self.alerts[issue_key]["issue"] manifests = self.alerts[issue_key]["manifests"] - new_alert = { - "issue": json.loads(str(issue)), - "manifests": manifests - } + new_alert = {"issue": json.loads(str(issue)), "manifests": manifests} alerts[issue_key] = new_alert dump_object = self dump_object.alerts = alerts return json.dumps(dump_object.__dict__) + class Alert: """Represents a security alert with its type, severity, and associated properties.""" - + key: str type: str severity: str @@ -472,10 +474,10 @@ def __str__(self): class FullScan(FullScanMetadata): """ Represents a complete Socket Security scan of a repository. - + Inherits from FullScanMetadata and adds fields for SBOM artifacts and package data. """ - + sbom_artifacts: list[SocketArtifact] packages: dict[str, Package] @@ -492,7 +494,7 @@ def __str__(self): class Repository: """Represents a source code repository with its metadata and scan results.""" - + id: str created_at: str updated_at: str @@ -512,13 +514,14 @@ def __init__(self, **kwargs): def __str__(self): return json.dumps(self.__dict__) + class Purl: """ Represents a Package URL (PURL) with extended metadata. - + Includes package identification, authorship, and dependency information. """ - + id: str name: str version: str @@ -528,7 +531,7 @@ class Purl: size: int transitives: int introduced_by: list - capabilities: List[str] + capabilities: list[str] is_new: bool author_url: str url: str @@ -553,11 +556,11 @@ def __init__(self, **kwargs): def generate_author_data(authors: list, ecosystem: str) -> str: """ Creates markdown-formatted links to author profiles. - + Args: authors: List of author names ecosystem: Package ecosystem (npm, pypi, etc.) - + Returns: Comma-separated string of markdown links to author profiles """ @@ -565,8 +568,7 @@ def generate_author_data(authors: list, ecosystem: str) -> str: for author in authors: author_url = f"https://socket.dev/{ecosystem}/user/{author}" authors_str += f"[{author}]({author_url})," - authors_str = authors_str.rstrip(",") - return authors_str + return authors_str.rstrip(",") def __str__(self): return json.dumps(self.__dict__) @@ -574,7 +576,7 @@ def __str__(self): def to_dict(self) -> dict: """ Convert Purl object to a dictionary representation. - + Returns: Dictionary containing all Purl attributes """ @@ -592,23 +594,23 @@ def to_dict(self) -> dict: "is_new": self.is_new, "author_url": self.author_url, "url": self.url, - "purl": self.purl + "purl": self.purl, } class Diff: """ Represents differences between two Socket Security scans. - + Tracks changes in packages, capabilities, and security alerts between scans. """ - + new_packages: list[Purl] updated_packages: list[Purl] removed_packages: list[Purl] replaced_packages: list[Purl] packages: dict[str, Package] - new_capabilities: Dict[str, List[str]] + new_capabilities: dict[str, list[str]] new_alerts: list[Issue] unchanged_alerts: list[Issue] removed_alerts: list[Issue] @@ -620,7 +622,7 @@ class Diff: is_full_scan: bool alerts_fetched: bool - def __init__(self, **kwargs): + def __init__(self, **kwargs): # noqa: C901 if kwargs: for key, value in kwargs.items(): setattr(self, key, value) @@ -651,7 +653,7 @@ def __str__(self): def to_dict(self) -> dict: """ Convert Diff object to a dictionary representation. - + Returns: Dictionary containing all Diff attributes with nested objects converted """ @@ -662,18 +664,23 @@ def to_dict(self) -> dict: "removed_packages": [p.to_dict() for p in self.removed_packages], "replaced_packages": [p.to_dict() for p in self.replaced_packages], "new_alerts": [alert.__dict__ for alert in self.new_alerts], - "unchanged_alerts": [alert.__dict__ for alert in self.unchanged_alerts] if hasattr(self, "unchanged_alerts") else [], - "removed_alerts": [alert.__dict__ for alert in self.removed_alerts] if hasattr(self, "removed_alerts") else [], + "unchanged_alerts": [alert.__dict__ for alert in self.unchanged_alerts] + if hasattr(self, "unchanged_alerts") + else [], + "removed_alerts": [alert.__dict__ for alert in self.removed_alerts] + if hasattr(self, "removed_alerts") + else [], "id": self.id, "sbom": self.sbom if hasattr(self, "sbom") else [], "packages": {k: v.to_dict() for k, v in self.packages.items()} if hasattr(self, "packages") else {}, "report_url": self.report_url if hasattr(self, "report_url") else None, - "diff_url": self.diff_url if hasattr(self, "diff_url") else None + "diff_url": self.diff_url if hasattr(self, "diff_url") else None, } + class Comment: """Represents a GitHub comment with its metadata and content.""" - + url: str html_url: str issue_url: str diff --git a/socketsecurity/core/cli_client.py b/socketsecurity/core/cli_client.py index afa13470..3fd3365d 100644 --- a/socketsecurity/core/cli_client.py +++ b/socketsecurity/core/cli_client.py @@ -1,7 +1,6 @@ import base64 import json import logging -from typing import Dict, List, Optional, Union import requests @@ -12,6 +11,7 @@ logger = logging.getLogger("socketdev") + class CliClient: def __init__(self, config: SocketConfig): self.config = config @@ -19,23 +19,23 @@ def __init__(self, config: SocketConfig): @staticmethod def _encode_key(token: str) -> str: - return base64.b64encode(f"{token}:".encode()).decode('ascii') + return base64.b64encode(f"{token}:".encode()).decode("ascii") def request( self, path: str, method: str = "GET", - headers: Optional[Dict] = None, - payload: Optional[Union[Dict, str]] = None, - files: Optional[List] = None, - base_url: Optional[str] = None + headers: dict | None = None, + payload: dict | str | None = None, + files: list | None = None, + base_url: str | None = None, ) -> requests.Response: url = f"{base_url or self.config.api_url}/{path}" default_headers = { - 'Authorization': f"Basic {self._encoded_key}", - 'User-Agent': USER_AGENT, - "accept": "application/json" + "Authorization": f"Basic {self._encoded_key}", + "User-Agent": USER_AGENT, + "accept": "application/json", } headers = headers or default_headers @@ -48,7 +48,7 @@ def request( data=payload, files=files, timeout=self.config.timeout, - verify=not self.config.allow_unverified_ssl + verify=not self.config.allow_unverified_ssl, ) response.raise_for_status() @@ -66,7 +66,7 @@ def request( raise APIFailure(f"Request failed: {detail}", status_code=status_code) from e @staticmethod - def _server_error_message(response: Optional[requests.Response]) -> Optional[str]: + def _server_error_message(response: requests.Response | None) -> str | None: """The explanation the Socket API gives in its ``{"error": {"message": ...}}`` body.""" if response is None: return None @@ -76,17 +76,17 @@ def _server_error_message(response: Optional[requests.Response]) -> Optional[str return None return message if isinstance(message, str) and message else None - def post_telemetry_events(self, org_slug: str, events: List[Dict]) -> None: + def post_telemetry_events(self, org_slug: str, events: list[dict]) -> None: """Post telemetry events one at a time to the v0 telemetry API. Fire-and-forget โ€” logs errors but never raises.""" logger.debug(f"Sending {len(events)} telemetry event(s) to v0/orgs/{org_slug}/telemetry") for i, event in enumerate(events): try: - logger.debug(f"Telemetry event {i+1}/{len(events)}: {json.dumps(event)}") + logger.debug(f"Telemetry event {i + 1}/{len(events)}: {json.dumps(event)}") resp = self.request( path=f"orgs/{org_slug}/telemetry", method="POST", payload=json.dumps(event), ) - logger.debug(f"Telemetry event {i+1}/{len(events)} sent: status={resp.status_code}") + logger.debug(f"Telemetry event {i + 1}/{len(events)} sent: status={resp.status_code}") except Exception as e: - logger.warning(f"Failed to send telemetry event {i+1}/{len(events)}: {e}") + logger.warning(f"Failed to send telemetry event {i + 1}/{len(events)}: {e}") diff --git a/socketsecurity/core/cli_run.py b/socketsecurity/core/cli_run.py index cea3bfb4..234eda5e 100644 --- a/socketsecurity/core/cli_run.py +++ b/socketsecurity/core/cli_run.py @@ -17,7 +17,6 @@ import json import logging -from typing import Optional from .cli_client import CliClient @@ -27,8 +26,8 @@ def register_cli_run( client: CliClient, client_version: str, - upload_logs: Optional[bool], -) -> Optional[str]: + upload_logs: bool | None, +) -> str | None: """Register a CLI run with the backend. `upload_logs` is the user's tri-state preference (True / False / None); @@ -43,11 +42,13 @@ def register_cli_run( resp = client.request( path="python-cli-runs", method="POST", - payload=json.dumps({ - "client_version": client_version, - "share_logs": upload_logs is True, - "decline_logs": upload_logs is False, - }), + payload=json.dumps( + { + "client_version": client_version, + "share_logs": upload_logs is True, + "decline_logs": upload_logs is False, + } + ), ) body = resp.json() if not body.get("log_streaming_enabled"): @@ -67,7 +68,7 @@ def finalize_cli_run( client: CliClient, run_id: str, status: str = "success", - report_run_id: Optional[str] = None, + report_run_id: str | None = None, ) -> None: try: client.request( diff --git a/socketsecurity/core/exceptions.py b/socketsecurity/core/exceptions.py index b2112ee0..4f9621fa 100644 --- a/socketsecurity/core/exceptions.py +++ b/socketsecurity/core/exceptions.py @@ -1,23 +1,21 @@ from socketdev.exceptions import APIFailure as SdkAPIFailure __all__ = [ - "APIFailure", - "APIKeyMissing", "APIAccessDenied", + "APICloudflareError", + "APIFailure", "APIInsufficientQuota", + "APIKeyMissing", "APIResourceNotFound", - "APICloudflareError" ] class APICloudflareError(Exception): """Raised when there is an error using the API related to cloudflare""" - pass class APIKeyMissing(Exception): """Raised when the api key is not passed and the headers are empty""" - pass class APIFailure(SdkAPIFailure): @@ -28,23 +26,19 @@ class APIFailure(SdkAPIFailure): ``except APIFailure`` importing the SDK's -- which every handler in socketsecurity.core does -- and would not carry the SDK class's status code. """ - pass class APIAccessDenied(Exception): """Raised when access is denied to the API""" - pass class APIInsufficientQuota(Exception): """Raised when access is denied to the API""" - pass class APIResourceNotFound(Exception): """Raised when access is denied to the API""" - pass + class RequestTimeoutExceeded(Exception): """Raised when access is denied to the API""" - pass diff --git a/socketsecurity/core/git_interface.py b/socketsecurity/core/git_interface.py index 98dc4121..964d606f 100644 --- a/socketsecurity/core/git_interface.py +++ b/socketsecurity/core/git_interface.py @@ -19,7 +19,7 @@ class Git: path: str base_commit_sha: str | None - def __init__(self, path: str, base_commit_sha: str | None = None): + def __init__(self, path: str, base_commit_sha: str | None = None): # noqa: C901 """ Reads the repository state a scan is built from. @@ -36,14 +36,13 @@ def __init__(self, path: str, base_commit_sha: str | None = None): self._default_branch_name: str | None = None self.ensure_safe_directory(path) self.repo = Repo(path) - assert self.repo self.head = self.repo.head - + # Use CI environment SHA if available, otherwise fall back to current HEAD commit - github_sha = os.getenv('GITHUB_SHA') - gitlab_sha = os.getenv('CI_COMMIT_SHA') - bitbucket_sha = os.getenv('BITBUCKET_COMMIT') - buildkite_sha = os.getenv('BUILDKITE_COMMIT') + github_sha = os.getenv("GITHUB_SHA") + gitlab_sha = os.getenv("CI_COMMIT_SHA") + bitbucket_sha = os.getenv("BITBUCKET_COMMIT") + buildkite_sha = os.getenv("BUILDKITE_COMMIT") ci_commits = ( ("BUILDKITE_COMMIT", buildkite_sha), ("GITHUB_SHA", github_sha), @@ -54,7 +53,7 @@ def __init__(self, path: str, base_commit_sha: str | None = None): ((source, sha) for source, sha in ci_commits if sha), (None, None), ) - + if ci_sha: try: self.commit = self.repo.commit(ci_sha) @@ -62,54 +61,54 @@ def __init__(self, path: str, base_commit_sha: str | None = None): except Exception as error: log.debug(f"Failed to get commit from CI environment: {error}") # Use the actual current HEAD commit, not the head reference's commit - self.commit = self.repo.commit('HEAD') + self.commit = self.repo.commit("HEAD") log.debug(f"Using current HEAD commit: {self.commit.hexsha}") else: # Use the actual current HEAD commit, not the head reference's commit - self.commit = self.repo.commit('HEAD') + self.commit = self.repo.commit("HEAD") log.debug(f"Using current HEAD commit: {self.commit.hexsha}") - + log.debug(f"Final commit being used: {self.commit.hexsha}") log.debug(f"Commit author: {self.commit.author.name} <{self.commit.author.email}>") log.debug(f"Commit committer: {self.commit.committer.name} <{self.commit.committer.email}>") - + # Extract repository name from git remote, with fallback to default self.remote_url: str | None = None try: remote_url = self.repo.remotes.origin.url self.remote_url = remote_url - self.repo_name = remote_url.split('.git')[0].split('/')[-1] + self.repo_name = remote_url.split(".git")[0].split("/")[-1] log.debug(f"Repository name detected from git remote: {self.repo_name}") except Exception as error: log.debug(f"Failed to get repository name from git remote: {error}") self.repo_name = "socket-default-repo" log.debug(f"Using default repository name: {self.repo_name}") - + # Branch detection with priority: CI Variables -> Git Properties -> Default # Note: CLI arguments are handled in socketcli.py and take highest priority - + # First, try CI environment variables (most accurate in CI environments) ci_branch = None - + # GitLab CI variables - gitlab_branch = os.getenv('CI_COMMIT_BRANCH') or os.getenv('CI_MERGE_REQUEST_SOURCE_BRANCH_NAME') - + gitlab_branch = os.getenv("CI_COMMIT_BRANCH") or os.getenv("CI_MERGE_REQUEST_SOURCE_BRANCH_NAME") + # GitHub Actions variables - github_ref = os.getenv('GITHUB_REF') # e.g., 'refs/heads/main' + github_ref = os.getenv("GITHUB_REF") # e.g., 'refs/heads/main' github_branch = None - if github_ref and github_ref.startswith('refs/heads/'): - github_branch = github_ref.replace('refs/heads/', '') - + if github_ref and github_ref.startswith("refs/heads/"): + github_branch = github_ref.replace("refs/heads/", "") + # Bitbucket Pipelines variables - bitbucket_branch = os.getenv('BITBUCKET_BRANCH') + bitbucket_branch = os.getenv("BITBUCKET_BRANCH") # Buildkite branch (the source branch for pull-request builds) - buildkite_branch = os.getenv('BUILDKITE_BRANCH') - + buildkite_branch = os.getenv("BUILDKITE_BRANCH") + # Prefer the native environment when Buildkite is driving the job. This # also avoids requiring Buildkite users to emulate GitHub Actions vars. ci_branch = buildkite_branch or gitlab_branch or github_branch or bitbucket_branch - + if ci_branch: self.branch = ci_branch if buildkite_branch: @@ -128,34 +127,34 @@ def __init__(self, path: str, base_commit_sha: str | None = None): log.debug(f"Branch detected from git reference: {self.branch}") except Exception as error: log.debug(f"Failed to get branch from git reference: {error}") - + # Fallback: try to detect branch from git commands (works in detached HEAD) git_detected_branch = None try: # Try git name-rev first (most reliable for detached HEAD) - result = self.repo.git.name_rev('--name-only', 'HEAD') - if result and result != 'undefined': + result = self.repo.git.name_rev("--name-only", "HEAD") + if result and result != "undefined": # Strip name-rev suffix operators (~N, ^N, or combinations # like master~3^2). These characters are forbidden in git # ref names, so cutting at the first occurrence can never # truncate a real branch name. - result = re.split(r'[~^]', result, maxsplit=1)[0] + result = re.split(r"[~^]", result, maxsplit=1)[0] # Clean up the result (remove any prefixes like 'remotes/origin/') - git_detected_branch = result.split('/')[-1] + git_detected_branch = result.split("/")[-1] log.debug(f"Branch detected from git name-rev: {git_detected_branch}") except Exception as git_error: log.debug(f"git name-rev failed: {git_error}") - + if not git_detected_branch: try: # Fallback: try git describe --all --exact-match - result = self.repo.git.describe('--all', '--exact-match', 'HEAD') - if result and result.startswith('heads/'): - git_detected_branch = result.replace('heads/', '') + result = self.repo.git.describe("--all", "--exact-match", "HEAD") + if result and result.startswith("heads/"): + git_detected_branch = result.replace("heads/", "") log.debug(f"Branch detected from git describe: {git_detected_branch}") except Exception as git_error: log.debug(f"git describe failed: {git_error}") - + if git_detected_branch: self.branch = git_detected_branch log.debug(f"Branch detected from git commands: {self.branch}") @@ -175,15 +174,15 @@ def __init__(self, path: str, base_commit_sha: str | None = None): detected = False detection_source = "single-commit" - github_base_ref = os.getenv('GITHUB_BASE_REF') - github_head_ref = os.getenv('GITHUB_HEAD_REF') - github_event_name = os.getenv('GITHUB_EVENT_NAME') - github_before_sha = os.getenv('GITHUB_EVENT_BEFORE') # previous commit for push - github_sha = os.getenv('GITHUB_SHA') # current commit + github_base_ref = os.getenv("GITHUB_BASE_REF") + github_head_ref = os.getenv("GITHUB_HEAD_REF") + github_event_name = os.getenv("GITHUB_EVENT_NAME") + github_before_sha = os.getenv("GITHUB_EVENT_BEFORE") # previous commit for push + github_sha = os.getenv("GITHUB_SHA") # current commit - buildkite_pr = os.getenv('BUILDKITE_PULL_REQUEST') - buildkite_base_ref = os.getenv('BUILDKITE_PULL_REQUEST_BASE_BRANCH') - buildkite_head_ref = os.getenv('BUILDKITE_BRANCH') + buildkite_pr = os.getenv("BUILDKITE_PULL_REQUEST") + buildkite_base_ref = os.getenv("BUILDKITE_PULL_REQUEST_BASE_BRANCH") + buildkite_head_ref = os.getenv("BUILDKITE_BRANCH") # An explicitly supplied base commit states the comparison range outright, # so it is honored before any inference from CI environment variables. @@ -214,7 +213,7 @@ def __init__(self, path: str, base_commit_sha: str | None = None): ) if detected: detection_source = "buildkite-pr" - elif github_event_name == 'pull_request' and github_base_ref: + elif github_event_name == "pull_request" and github_base_ref: detected = self._detect_pull_request_changes( provider="GitHub", base_ref=github_base_ref, @@ -223,16 +222,16 @@ def __init__(self, path: str, base_commit_sha: str | None = None): if detected: detection_source = "github-pr" # Commits to default branch (push events) - elif github_event_name == 'push' and github_before_sha and github_sha: + elif github_event_name == "push" and github_before_sha and github_sha: try: - diff_files = self.repo.git.diff('--name-only', f'{github_before_sha}..{github_sha}') + diff_files = self.repo.git.diff("--name-only", f"{github_before_sha}..{github_sha}") self.show_files = diff_files.splitlines() log.debug(f"Changed files detected via git diff (GitHub push): {self.show_files}") detected = True detection_source = "github-push" except Exception as error: log.debug(f"Failed to get changed files via git diff (GitHub push): {error}") - elif github_event_name == 'push': + elif github_event_name == "push": try: self.show_files = self.repo.git.show(self.commit, name_only=True, format="%n").splitlines() log.debug(f"Changed files detected via git show (GitHub push fallback): {self.show_files}") @@ -242,8 +241,8 @@ def __init__(self, path: str, base_commit_sha: str | None = None): log.debug(f"Failed to get changed files via git show (GitHub push fallback): {error}") # GitLab CI Merge Request context if not detected: - gitlab_target = os.getenv('CI_MERGE_REQUEST_TARGET_BRANCH_NAME') - gitlab_source = os.getenv('CI_MERGE_REQUEST_SOURCE_BRANCH_NAME') + gitlab_target = os.getenv("CI_MERGE_REQUEST_TARGET_BRANCH_NAME") + gitlab_source = os.getenv("CI_MERGE_REQUEST_SOURCE_BRANCH_NAME") if gitlab_target and gitlab_source: detected = self._detect_pull_request_changes( provider="GitLab", @@ -254,9 +253,9 @@ def __init__(self, path: str, base_commit_sha: str | None = None): detection_source = "gitlab-mr" # Bitbucket Pipelines PR context if not detected: - bitbucket_pr_id = os.getenv('BITBUCKET_PR_ID') - bitbucket_source = os.getenv('BITBUCKET_BRANCH') - bitbucket_dest = os.getenv('BITBUCKET_PR_DESTINATION_BRANCH') + bitbucket_pr_id = os.getenv("BITBUCKET_PR_ID") + bitbucket_source = os.getenv("BITBUCKET_BRANCH") + bitbucket_dest = os.getenv("BITBUCKET_PR_DESTINATION_BRANCH") # BITBUCKET_BRANCH is the source branch in PR builds if bitbucket_pr_id and bitbucket_source and bitbucket_dest: detected = self._detect_pull_request_changes( @@ -298,14 +297,11 @@ def __init__(self, path: str, base_commit_sha: str | None = None): f"{time.perf_counter() - changed_files_start:.2f}s: " f"source={detection_source}, files={len(self.changed_files)}" ) - + # Determine if this commit is on the default branch # This considers both GitHub Actions detached HEAD and regular branch situations self.is_default_branch = self._is_commit_and_branch_default() - log.info( - "Git initialization completed in " - f"{time.perf_counter() - initialization_start:.2f}s" - ) + log.info(f"Git initialization completed in {time.perf_counter() - initialization_start:.2f}s") @staticmethod def _is_buildkite_pull_request(pull_request: str | None) -> bool: @@ -324,8 +320,8 @@ def _resolve_ref(self, ref: str | None) -> str | None: for candidate in candidates: try: return self.repo.commit(candidate).hexsha - except Exception: - continue + except Exception as error: + log.debug(f"Could not resolve git ref {candidate}: {error}") return None def _fetch_ref(self, ref: str, reason: str) -> str | None: @@ -354,11 +350,11 @@ def _fetch_ref(self, ref: str, reason: str) -> str | None: return None def _detect_pull_request_changes( - self, - provider: str, - base_ref: str, - head_ref: str | None, - use_merge_base: bool = True, + self, + provider: str, + base_ref: str, + head_ref: str | None, + use_merge_base: bool = True, ) -> bool: """Detect a base-to-head range locally, fetching only refs needed to complete it.""" base_commit = self._resolve_ref(base_ref) @@ -374,19 +370,20 @@ def _detect_pull_request_changes( try: diff_files = self.repo.git.diff("--name-only", diff_range) self.show_files = diff_files.splitlines() - log.debug( - f"Changed files detected via local git diff ({provider}): {self.show_files}" - ) + log.debug(f"Changed files detected via local git diff ({provider}): {self.show_files}") return True except Exception as local_error: log.debug(f"Local {provider} pull-request diff failed: {local_error}") # A shallow checkout can contain both tips but not their merge base. In # that case refresh only the two relevant branch histories and retry. - base_commit = self._fetch_ref( - base_ref, - f"{provider} pull-request history incomplete", - ) or base_commit + base_commit = ( + self._fetch_ref( + base_ref, + f"{provider} pull-request history incomplete", + ) + or base_commit + ) if head_ref: self._fetch_ref( head_ref, @@ -399,45 +396,40 @@ def _detect_pull_request_changes( f"{base_commit}{range_separator}{head_commit}", ) self.show_files = diff_files.splitlines() - log.debug( - f"Changed files detected after targeted fetch ({provider}): {self.show_files}" - ) + log.debug(f"Changed files detected after targeted fetch ({provider}): {self.show_files}") return True except Exception as retry_error: log.debug(f"Targeted {provider} pull-request diff failed: {retry_error}") return False - def _is_commit_and_branch_default(self) -> bool: + def _is_commit_and_branch_default(self) -> bool: # noqa: C901 """ Check if both the commit is on the default branch AND we're processing the default branch. This handles GitHub Actions detached HEAD state properly. - + Returns: True if commit is on default branch and we're processing the default branch """ try: - github_ref = os.getenv('GITHUB_REF') # e.g., 'refs/heads/main' or 'refs/pull/123/merge' - gitlab_branch = os.getenv('CI_COMMIT_BRANCH') - gitlab_mr_branch = os.getenv('CI_MERGE_REQUEST_SOURCE_BRANCH_NAME') - bitbucket_branch = os.getenv('BITBUCKET_BRANCH') - bitbucket_pr = os.getenv('BITBUCKET_PR_ID') - buildkite_branch = os.getenv('BUILDKITE_BRANCH') - buildkite_pr = os.getenv('BUILDKITE_PULL_REQUEST') + github_ref = os.getenv("GITHUB_REF") # e.g., 'refs/heads/main' or 'refs/pull/123/merge' + gitlab_branch = os.getenv("CI_COMMIT_BRANCH") + gitlab_mr_branch = os.getenv("CI_MERGE_REQUEST_SOURCE_BRANCH_NAME") + bitbucket_branch = os.getenv("BITBUCKET_BRANCH") + bitbucket_pr = os.getenv("BITBUCKET_PR_ID") + buildkite_branch = os.getenv("BUILDKITE_BRANCH") + buildkite_pr = os.getenv("BUILDKITE_PULL_REQUEST") # PR and non-branch builds cannot become the default branch head. # Decide that locally before default-branch lookup contacts origin. if buildkite_branch: if self._is_buildkite_pull_request(buildkite_pr): - log.debug( - f"Processing Buildkite pull request from branch: {buildkite_branch}, " - "not default branch" - ) + log.debug(f"Processing Buildkite pull request from branch: {buildkite_branch}, not default branch") return False elif github_ref: - if github_ref.startswith('refs/pull/'): + if github_ref.startswith("refs/pull/"): log.debug("Processing a pull request, not default branch") return False - if not github_ref.startswith('refs/heads/'): + if not github_ref.startswith("refs/heads/"): log.debug(f"Non-branch ref: {github_ref}, not default branch") return False elif gitlab_branch or gitlab_mr_branch: @@ -458,51 +450,53 @@ def _is_commit_and_branch_default(self) -> bool: default_branch_name = self.get_default_branch_name() is_default = buildkite_branch == default_branch_name log.debug( - f"Buildkite branch: {buildkite_branch}, Default: {default_branch_name}, " - f"Is default: {is_default}" + f"Buildkite branch: {buildkite_branch}, Default: {default_branch_name}, Is default: {is_default}" ) return is_default # Handle GitHub Actions - elif github_ref: + if github_ref: log.debug(f"GitHub ref: {github_ref}") - branch_from_ref = github_ref.removeprefix('refs/heads/') + branch_from_ref = github_ref.removeprefix("refs/heads/") default_branch_name = self.get_default_branch_name() is_default = branch_from_ref == default_branch_name - log.debug(f"Branch from GITHUB_REF: {branch_from_ref}, Default: {default_branch_name}, Is default: {is_default}") + log.debug( + f"Branch from GITHUB_REF: {branch_from_ref}, Default: {default_branch_name}, Is default: {is_default}" + ) return is_default - + # Handle GitLab CI - elif gitlab_branch or gitlab_mr_branch: + if gitlab_branch or gitlab_mr_branch: current_branch = gitlab_mr_branch or gitlab_branch default_branch_name = self.get_default_branch_name() is_default = current_branch == default_branch_name log.debug(f"GitLab branch: {current_branch}, Default: {default_branch_name}, Is default: {is_default}") return is_default - + # Handle Bitbucket Pipelines - elif bitbucket_branch: + if bitbucket_branch: default_branch_name = self.get_default_branch_name() is_default = bitbucket_branch == default_branch_name - log.debug(f"Bitbucket branch: {bitbucket_branch}, Default: {default_branch_name}, Is default: {is_default}") + log.debug( + f"Bitbucket branch: {bitbucket_branch}, Default: {default_branch_name}, Is default: {is_default}" + ) return is_default - else: - # Not in GitHub Actions, use local development logic - # For local development, we consider it "default branch" if: - # 1. Currently on the default branch, OR - # 2. The commit is reachable from the default branch (part of default branch history) - - is_on_default = self.is_on_default_branch() - if is_on_default: - log.debug("Currently on default branch locally") - return True - - # Even if on feature branch, if commit is on default branch, consider it default - # This handles cases where feature branch was created from or merged to default - is_commit_default = self.is_commit_on_default_branch() - log.debug(f"Not on default branch locally, but commit is on default branch: {is_commit_default}") - return is_commit_default - + # Not in GitHub Actions, use local development logic + # For local development, we consider it "default branch" if: + # 1. Currently on the default branch, OR + # 2. The commit is reachable from the default branch (part of default branch history) + + is_on_default = self.is_on_default_branch() + if is_on_default: + log.debug("Currently on default branch locally") + return True + + # Even if on feature branch, if commit is on default branch, consider it default + # This handles cases where feature branch was created from or merged to default + is_commit_default = self.is_commit_on_default_branch() + log.debug(f"Not on default branch locally, but commit is on default branch: {is_commit_default}") + return is_commit_default + except Exception as error: log.debug(f"Error determining if commit and branch are default: {error}") return False @@ -511,7 +505,7 @@ def _is_commit_and_branch_default(self) -> bool: def commit_str(self) -> str: """Return commit SHA as a string""" return self.commit.hexsha - + def get_formatted_committer(self) -> str: """ Get the committer in the preferred order: @@ -520,63 +514,63 @@ def get_formatted_committer(self) -> str: 3. Git username (extracted from email patterns like GitHub noreply) 4. Git email address 5. Git author name (fallback) - + Returns: Formatted committer string """ # Check for CI/CD environment usernames first # GitHub Actions - github_actor = os.getenv('GITHUB_ACTOR') + github_actor = os.getenv("GITHUB_ACTOR") if github_actor: log.debug(f"Using GitHub actor as committer: {github_actor}") return github_actor - + # GitLab CI - gitlab_user_login = os.getenv('GITLAB_USER_LOGIN') + gitlab_user_login = os.getenv("GITLAB_USER_LOGIN") if gitlab_user_login: log.debug(f"Using GitLab user login as committer: {gitlab_user_login}") return gitlab_user_login - + # Bitbucket Pipelines - bitbucket_step_triggerer_uuid = os.getenv('BITBUCKET_STEP_TRIGGERER_UUID') + bitbucket_step_triggerer_uuid = os.getenv("BITBUCKET_STEP_TRIGGERER_UUID") if bitbucket_step_triggerer_uuid: log.debug(f"Using Bitbucket step triggerer as committer: {bitbucket_step_triggerer_uuid}") return bitbucket_step_triggerer_uuid - + # Fall back to commit author/committer details # Priority 3: Try to extract git username from email patterns first if self.author and self.author.email and self.author.email.strip(): email = self.author.email.strip() - + # If it's a GitHub noreply email, try to extract username - if email.endswith('@users.noreply.github.com'): + if email.endswith("@users.noreply.github.com"): # Pattern: number+username@users.noreply.github.com - email_parts = email.split('@')[0] - if '+' in email_parts: - username = email_parts.split('+')[1] + email_parts = email.split("@")[0] + if "+" in email_parts: + username = email_parts.split("+")[1] log.debug(f"Extracted GitHub username from noreply email: {username}") return username - + # Priority 4: Use email if available if self.author and self.author.email and self.author.email.strip(): email = self.author.email.strip() log.debug(f"Using commit author email as committer: {email}") return email - + # Priority 5: Fall back to author name as last resort if self.author and self.author.name and self.author.name.strip(): name = self.author.name.strip() log.debug(f"Using commit author name as fallback committer: {name}") return name - + # Ultimate fallback log.debug("Using fallback committer: unknown") return "unknown" - + def _is_merge_commit(self) -> bool: """ Check if the current commit is a merge commit. - + Returns: True if this is a merge commit (has multiple parents), False otherwise """ @@ -588,14 +582,14 @@ def _is_merge_commit(self) -> bool: except Exception as error: log.debug(f"Error checking if commit is merge commit: {error}") return False - + def _detect_merge_commit_changes(self) -> bool: """ Detect changed files in a merge commit using git diff with parent. - + This method handles the case where git show --name-only doesn't work for merge commits (expected Git behavior). - + Returns: True if detection was successful, False otherwise """ @@ -603,15 +597,15 @@ def _detect_merge_commit_changes(self) -> bool: if not self._is_merge_commit(): log.debug("Not a merge commit, skipping merge commit detection") return False - + # For merge commits, we need to diff against a parent # We'll use the first parent (typically the target branch) if not self.commit.parents: log.debug("Merge commit has no parents - cannot perform merge-aware diff") return False - + parent_commit = self.commit.parents[0] - + # Verify parent commit is accessible try: parent_sha = parent_commit.hexsha @@ -620,26 +614,28 @@ def _detect_merge_commit_changes(self) -> bool: except Exception as parent_error: log.error(f"Cannot resolve parent commit {parent_sha}: {parent_error}") return False - + # Use git diff to show changes from parent to merge commit - diff_range = f'{parent_sha}..{self.commit.hexsha}' + diff_range = f"{parent_sha}..{self.commit.hexsha}" log.debug(f"Attempting merge commit diff: git diff --name-only {diff_range}") - - diff_files = self.repo.git.diff('--name-only', diff_range) + + diff_files = self.repo.git.diff("--name-only", diff_range) self.show_files = diff_files.splitlines() - + log.debug(f"Changed files detected via git diff (merge commit): {self.show_files}") - log.info(f"Changed file detection: method=merge-diff, source=merge-commit-fallback, files={len(self.show_files)}") + log.info( + f"Changed file detection: method=merge-diff, source=merge-commit-fallback, files={len(self.show_files)}" + ) return True - + except Exception as error: log.debug(f"Failed to detect merge commit changes: {error}") return False - + def get_default_branch_name(self) -> str: """ Get the default branch name from the remote origin. - + Returns: Default branch name (e.g., 'main', 'master') """ @@ -648,7 +644,7 @@ def get_default_branch_name(self) -> str: return self._default_branch_name def _detect_default_branch_name(self) -> str: - for variable in ('CI_DEFAULT_BRANCH', 'BUILDKITE_PIPELINE_DEFAULT_BRANCH'): + for variable in ("CI_DEFAULT_BRANCH", "BUILDKITE_PIPELINE_DEFAULT_BRANCH"): default_branch = os.getenv(variable) if default_branch: log.debug(f"Default branch detected from {variable}: {default_branch}") @@ -662,10 +658,7 @@ def _detect_default_branch_name(self) -> str: log.debug(f"Could not determine default branch from origin/HEAD: {error}") # CI checkouts such as actions/checkout fetch a single branch and leave no origin/HEAD. - default_branch = ( - self._default_branch_from_github_event() - or self._default_branch_from_remote() - ) + default_branch = self._default_branch_from_github_event() or self._default_branch_from_remote() if default_branch: return default_branch @@ -673,17 +666,17 @@ def _detect_default_branch_name(self) -> str: remote_refs = {str(ref) for ref in self.repo.remotes.origin.refs} except Exception: remote_refs = set() - for branch_name in ['main', 'master']: - if f'origin/{branch_name}' in remote_refs: + for branch_name in ["main", "master"]: + if f"origin/{branch_name}" in remote_refs: log.debug(f"Using fallback default branch: {branch_name}") return branch_name log.debug("Using final fallback default branch: main") - return 'main' + return "main" @staticmethod def _default_branch_from_github_event() -> str | None: - event_path = os.getenv('GITHUB_EVENT_PATH') + event_path = os.getenv("GITHUB_EVENT_PATH") if not event_path: return None try: @@ -717,10 +710,7 @@ def _default_branch_from_remote(self) -> str | None: output, _ = process.communicate(timeout=REMOTE_HEAD_TIMEOUT_SECONDS) except subprocess.TimeoutExpired: self._kill_process_tree(process) - log.debug( - f"Querying origin for its default branch timed out after " - f"{REMOTE_HEAD_TIMEOUT_SECONDS}s" - ) + log.debug(f"Querying origin for its default branch timed out after {REMOTE_HEAD_TIMEOUT_SECONDS}s") return None if process.returncode != 0: log.debug(f"Querying origin for its default branch exited with {process.returncode}") @@ -741,6 +731,7 @@ def _kill_process_tree(process: subprocess.Popen) -> None: stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10, + check=False, ) else: os.killpg(process.pid, signal.SIGKILL) @@ -753,17 +744,17 @@ def _kill_process_tree(process: subprocess.Popen) -> None: process.wait(timeout=5) except subprocess.TimeoutExpired: log.debug("git ls-remote did not exit after being killed") - + def is_commit_on_default_branch(self) -> bool: """ Check if the current commit is reachable from the default branch. - + Returns: True if current commit is on the default branch, False otherwise """ try: default_branch = self.get_default_branch_name() - + # Get the default branch's HEAD commit try: # Try remote branch first @@ -772,31 +763,31 @@ def is_commit_on_default_branch(self) -> bool: except Exception: # Fallback to local branch try: - default_branch_ref = self.repo.heads[default_branch] + default_branch_ref = self.repo.heads[default_branch] default_branch_commit = default_branch_ref.commit except Exception: log.debug(f"Could not find default branch '{default_branch}' locally or remotely") return False - + # Check if current commit is the same as default branch HEAD if self.commit.hexsha == default_branch_commit.hexsha: log.debug("Current commit is the HEAD of the default branch") return True - + # Check if current commit is an ancestor of the default branch HEAD # This means the commit is reachable from the default branch is_ancestor = self.repo.is_ancestor(self.commit, default_branch_commit) log.debug(f"Current commit is ancestor of default branch: {is_ancestor}") return is_ancestor - + except Exception as error: log.debug(f"Error checking if commit is on default branch: {error}") return False - + def is_on_default_branch(self) -> bool: """ Check if we're currently on the default branch (not just if commit is reachable). - + Returns: True if currently on the default branch, False otherwise """ @@ -805,14 +796,16 @@ def is_on_default_branch(self) -> bool: if self.repo.head.is_detached: log.debug("In detached HEAD state, not on any branch") return False - + current_branch_name = self.repo.active_branch.name default_branch_name = self.get_default_branch_name() - + is_default = current_branch_name == default_branch_name - log.debug(f"Current branch: {current_branch_name}, Default branch: {default_branch_name}, Is default: {is_default}") + log.debug( + f"Current branch: {current_branch_name}, Default branch: {default_branch_name}, Is default: {is_default}" + ) return is_default - + except Exception as error: log.debug(f"Error checking if on default branch: {error}") return False @@ -820,18 +813,20 @@ def is_on_default_branch(self) -> bool: @staticmethod def ensure_safe_directory(path: str) -> None: # Ensure the repo is marked as safe for git (prevents SHA empty/dubious ownership errors) - try : + try: import subprocess + abs_path = os.path.abspath(path) # Get all safe directories - result = subprocess.run([ - "git", "config", "--global", "--get-all", "safe.directory" - ], capture_output=True, text=True) + result = subprocess.run( + ["git", "config", "--global", "--get-all", "safe.directory"], + capture_output=True, + text=True, + check=False, + ) safe_dirs = result.stdout.splitlines() if result.returncode == 0 else [] if abs_path not in safe_dirs: - subprocess.run([ - "git", "config", "--global", "--add", "safe.directory", abs_path - ], check=True) + subprocess.run(["git", "config", "--global", "--add", "safe.directory", abs_path], check=True) log.debug(f"Added {abs_path} to git safe.directory config.") else: log.debug(f"{abs_path} already present in git safe.directory config.") diff --git a/socketsecurity/core/git_remote.py b/socketsecurity/core/git_remote.py index eb5b9c02..637a4b25 100644 --- a/socketsecurity/core/git_remote.py +++ b/socketsecurity/core/git_remote.py @@ -5,8 +5,8 @@ GitHub comment adapter and pull request context resolution need to recover the slug from it, so the parsing lives here rather than in either caller. """ + import re -from typing import Optional, Tuple from urllib.parse import urlparse # git@host:owner/repo - the scp-like syntax urlparse cannot handle. The negative @@ -14,7 +14,7 @@ _SCP_LIKE_REMOTE = re.compile(r"^(?:[^@/]+@)?([^:/]+):(?!//)(.+)$") -def parse_git_remote(value: Optional[str]) -> Tuple[Optional[str], Optional[str]]: +def parse_git_remote(value: str | None) -> tuple[str | None, str | None]: """Split a git remote URL into its host and its repository path. Returns ``(host, path)``, or ``(None, None)`` when the value is not a usable @@ -26,8 +26,7 @@ def parse_git_remote(value: Optional[str]) -> Tuple[Optional[str], Optional[str] if not value: return None, None url = value.strip().rstrip("/") - if url.endswith(".git"): - url = url[:-4] + url = url.removesuffix(".git") match = _SCP_LIKE_REMOTE.match(url) if match: diff --git a/socketsecurity/core/helper/__init__.py b/socketsecurity/core/helper/__init__.py index 224f3cc7..0d8306d1 100644 --- a/socketsecurity/core/helper/__init__.py +++ b/socketsecurity/core/helper/__init__.py @@ -12,52 +12,45 @@ def parse_gfm_section(html_content): Parse a GitHub-Flavored Markdown section containing a table and surrounding content. Returns a dict with "before_html", "columns", "rows_html", and "after_html". """ - html = markdown.markdown(html_content, extensions=['extra']) + html = markdown.markdown(html_content, extensions=["extra"]) soup = BeautifulSoup(html, "html.parser") - table = soup.find('table') + table = soup.find("table") if not table: # If no table, treat entire content as before_html - return {"before_html": html, "columns": [], "rows_html": [], "after_html": ''} + return {"before_html": html, "columns": [], "rows_html": [], "after_html": ""} # Collect HTML before the table before_parts = [str(elem) for elem in table.find_previous_siblings()] - before_html = ''.join(reversed(before_parts)) + before_html = "".join(reversed(before_parts)) # Collect HTML after the table after_parts = [str(elem) for elem in table.find_next_siblings()] - after_html = ''.join(after_parts) + after_html = "".join(after_parts) # Extract table headers - headers = [th.get_text(strip=True) for th in table.find_all('th')] + headers = [th.get_text(strip=True) for th in table.find_all("th")] # Extract table rows (skip header) rows_html = [] - for tr in table.find_all('tr')[1:]: - cells = [str(td) for td in tr.find_all('td')] + for tr in table.find_all("tr")[1:]: + cells = [str(td) for td in tr.find_all("td")] rows_html.append(cells) - return { - "before_html": before_html, - "columns": headers, - "rows_html": rows_html, - "after_html": after_html - } + return {"before_html": before_html, "columns": headers, "rows_html": rows_html, "after_html": after_html} @staticmethod def parse_cell(html_td): """Convert a table cell HTML into plain text or a dict for links/images.""" soup = BeautifulSoup(html_td, "html.parser") - a = soup.find('a') + a = soup.find("a") if a: - cell = {"url": a.get('href', '')} - img = a.find('img') + cell = {"url": a.get("href", "")} + img = a.find("img") if img: - cell.update({ - "img_src": img.get('src', ''), - "title": img.get('title', ''), - "link_text": a.get_text(strip=True) - }) + cell.update( + {"img_src": img.get("src", ""), "title": img.get("title", ""), "link_text": a.get_text(strip=True)} + ) else: cell["link_text"] = a.get_text(strip=True) return cell @@ -72,7 +65,7 @@ def parse_html_parts(html_fragment): - {"link": "url", "text": "..."} - {"img_src": "url", "alt": "...", "title": "..."} """ - soup = BeautifulSoup(html_fragment, 'html.parser') + soup = BeautifulSoup(html_fragment, "html.parser") parts = [] def handle_element(elem): @@ -81,16 +74,14 @@ def handle_element(elem): if text and not all(ch in string.punctuation for ch in text): parts.append({"text": text}) elif isinstance(elem, Tag): - if elem.name == 'a': - href = elem.get('href', '') + if elem.name == "a": + href = elem.get("href", "") txt = elem.get_text(strip=True) parts.append({"link": href, "text": txt}) - elif elem.name == 'img': - parts.append({ - "img_src": elem.get('src', ''), - "alt": elem.get('alt', ''), - "title": elem.get('title', '') - }) + elif elem.name == "img": + parts.append( + {"img_src": elem.get("src", ""), "alt": elem.get("alt", ""), "title": elem.get("title", "")} + ) else: # Recurse into children for nested tags for child in elem.children: @@ -109,13 +100,13 @@ def section_to_json(section_result): """ # Build JSON rows for the table table_rows = [] - cols = section_result.get('columns', []) - for row_html in section_result.get('rows_html', []): + cols = section_result.get("columns", []) + for row_html in section_result.get("rows_html", []): cells = [Helper.parse_cell(cell_html) for cell_html in row_html] - table_rows.append(dict(zip(cols, cells))) + table_rows.append(dict(zip(cols, cells, strict=False))) return { - "before": Helper.parse_html_parts(section_result.get('before_html', '')), + "before": Helper.parse_html_parts(section_result.get("before_html", "")), "table": table_rows, - "after": Helper.parse_html_parts(section_result.get('after_html', '')) - } \ No newline at end of file + "after": Helper.parse_html_parts(section_result.get("after_html", "")), + } diff --git a/socketsecurity/core/helper/socket_facts_loader.py b/socketsecurity/core/helper/socket_facts_loader.py index 26c1ae25..b49943d2 100644 --- a/socketsecurity/core/helper/socket_facts_loader.py +++ b/socketsecurity/core/helper/socket_facts_loader.py @@ -4,30 +4,30 @@ import logging from copy import deepcopy from pathlib import Path -from typing import Any, Dict, List, Optional +from typing import Any logger = logging.getLogger(__name__) -def load_socket_facts(file_path: str = ".socket.facts.json") -> Optional[Dict[str, Any]]: +def load_socket_facts(file_path: str = ".socket.facts.json") -> dict[str, Any] | None: """ Load a .socket.facts.json file into a dictionary. - + The .socket.facts.json file is generated by the Socket CLI reachability analysis - and contains component dependency information, vulnerability data, and + and contains component dependency information, vulnerability data, and reachability analysis results. - + Args: file_path: Path to the .socket.facts.json file. Defaults to ".socket.facts.json" in the current directory. - + Returns: Dict containing the parsed JSON data with keys like: - components: List of dependency components with vulnerabilities and reachability info - tier1ReachabilityScanId: The scan ID for this reachability analysis - + Returns None if the file doesn't exist or cannot be parsed. - + Example structure: { "components": [ @@ -48,31 +48,31 @@ def load_socket_facts(file_path: str = ".socket.facts.json") -> Optional[Dict[st } """ facts_path = Path(file_path) - + if not facts_path.exists(): logger.warning(f"Socket facts file not found: {file_path}") return None - + try: - with facts_path.open('r', encoding='utf-8') as f: + with facts_path.open("r", encoding="utf-8") as f: data = json.load(f) - + logger.debug(f"Successfully loaded socket facts from {file_path}") - + # Validate expected structure if not isinstance(data, dict): logger.warning(f"Socket facts file has unexpected format: expected dict, got {type(data)}") return None - - if 'components' not in data: + + if "components" not in data: logger.warning("Socket facts file missing 'components' key") - + return data - + except json.JSONDecodeError as e: logger.error(f"Failed to parse JSON from {file_path}: {e}") return None - except IOError as e: + except OSError as e: logger.error(f"Failed to read {file_path}: {e}") return None except Exception as e: @@ -80,293 +80,280 @@ def load_socket_facts(file_path: str = ".socket.facts.json") -> Optional[Dict[st return None -def get_components_with_vulnerabilities(facts_data: Dict[str, Any]) -> list: +def get_components_with_vulnerabilities(facts_data: dict[str, Any]) -> list: """ Extract components that have vulnerabilities from socket facts data. - + Note: The .socket.facts.json file contains 'vulnerabilities' and 'reachability' data separately. This function returns components that have vulnerabilities defined. - + Args: facts_data: Dictionary loaded from .socket.facts.json - + Returns: List of component dictionaries that have vulnerabilities """ - if not facts_data or 'components' not in facts_data: + if not facts_data or "components" not in facts_data: return [] - - components = facts_data.get('components', []) - components_with_vulns = [ - comp for comp in components - if comp.get('vulnerabilities') and len(comp.get('vulnerabilities', [])) > 0 - ] - - return components_with_vulns + components = facts_data.get("components", []) + return [comp for comp in components if comp.get("vulnerabilities") and len(comp.get("vulnerabilities", [])) > 0] -def get_scan_id(facts_data: Dict[str, Any]) -> Optional[str]: + +def get_scan_id(facts_data: dict[str, Any]) -> str | None: """ Extract the tier1ReachabilityScanId from socket facts data. - + Args: facts_data: Dictionary loaded from .socket.facts.json - + Returns: The scan ID string if present, None otherwise """ if not facts_data: return None - - scan_id = facts_data.get('tier1ReachabilityScanId') + + scan_id = facts_data.get("tier1ReachabilityScanId") return scan_id.strip() if scan_id else None -def _make_purl(component: Dict[str, Any]) -> str: +def _make_purl(component: dict[str, Any]) -> str: """Construct a package URL (purl) from a component entry.""" - pkg_type = component.get('type', '') - namespace = component.get('namespace', '') - name = component.get('name') or component.get('id', '') - version = component.get('version', '') - + pkg_type = component.get("type", "") + namespace = component.get("namespace", "") + name = component.get("name") or component.get("id", "") + version = component.get("version", "") + if not name: - return '' - + return "" + if namespace: # Percent-encode @ in namespace for purl spec compliance - ns_encoded = namespace.replace('@', '%40') + ns_encoded = namespace.replace("@", "%40") purl = f"pkg:{pkg_type}/{ns_encoded}/{name}" else: purl = f"pkg:{pkg_type}/{name}" - + if version: purl = f"{purl}@{version}" - + return purl -def _determine_reachability(vulnerability: Dict[str, Any], component: Dict[str, Any]) -> Dict[str, Any]: +def _determine_reachability(vulnerability: dict[str, Any], component: dict[str, Any]) -> dict[str, Any]: # noqa: C901 """ Determine the reachability state for a vulnerability on a component. - + Args: vulnerability: Vulnerability dict from component's vulnerabilities array component: Component dict containing reachability data - + Returns: Dict with keys: - type: 'reachable', 'unreachable', 'unknown', 'error', or 'not_applicable' - undeterminableReachability: bool - trace: list of formatted trace strings """ - result = { - 'type': 'unknown', - 'undeterminableReachability': False, - 'trace': [] - } - - vuln_id = vulnerability.get('ghsaId') or vulnerability.get('cveId') + result = {"type": "unknown", "undeterminableReachability": False, "trace": []} + + vuln_id = vulnerability.get("ghsaId") or vulnerability.get("cveId") if not vuln_id: return result - + # Check for undeterminable reachability in the vulnerability data - reach_data = vulnerability.get('reachabilityData') or {} - if reach_data.get('undeterminableReachability'): - result['undeterminableReachability'] = True - result['type'] = 'unknown' - + reach_data = vulnerability.get("reachabilityData") or {} + if reach_data.get("undeterminableReachability"): + result["undeterminableReachability"] = True + result["type"] = "unknown" + # Find matching reachability entry in component - reachability_list = component.get('reachability', []) + reachability_list = component.get("reachability", []) matched_reach = None - + for reach_entry in reachability_list: - if reach_entry.get('ghsa_id') == vuln_id: + if reach_entry.get("ghsa_id") == vuln_id: matched_reach = reach_entry break - + if not matched_reach: # No reachability data found for this vulnerability - if result['undeterminableReachability']: + if result["undeterminableReachability"]: return result # Check if this vulnerability applies to this component version - if 'reachabilityData' in vulnerability: + if "reachabilityData" in vulnerability: # Has reachability data structure but no match - might not apply - result['type'] = 'not_applicable' + result["type"] = "not_applicable" return result - + # Process reachability matches - reach_items = matched_reach.get('reachability', []) + reach_items = matched_reach.get("reachability", []) if not reach_items: return result - + # Take the first reachability entry (usually most relevant) reach_info = reach_items[0] - reach_type = reach_info.get('type', 'unknown') - result['type'] = reach_type - + reach_type = reach_info.get("type", "unknown") + result["type"] = reach_type + # Build trace for reachable vulnerabilities - if reach_type == 'reachable': - matches = reach_info.get('matches', []) + if reach_type == "reachable": + matches = reach_info.get("matches", []) for match_group in matches: if not match_group: continue - + for i, frame in enumerate(match_group): - pkg = frame.get('package', '') - src_loc = frame.get('sourceLocation', {}) - filename = src_loc.get('filename', '') - start = src_loc.get('start', {}) - line = start.get('line') - col = start.get('column') - end = src_loc.get('end', {}) - end_line = end.get('line') - end_col = end.get('column') - + pkg = frame.get("package", "") + src_loc = frame.get("sourceLocation", {}) + filename = src_loc.get("filename", "") + start = src_loc.get("start", {}) + line = start.get("line") + col = start.get("column") + end = src_loc.get("end", {}) + end_line = end.get("line") + end_col = end.get("column") + if i == 0: # First frame - use filename as primary if filename: loc = filename if line is not None: if end_line is not None and end_line != line: - loc = f"{filename} {line}:{col if col else ''}-{end_line}:{end_col if end_col else ''}" + loc = f"{filename} {line}:{col or ''}-{end_line}:{end_col or ''}" else: - loc = f"{filename} {line}:{col if col else ''}" - result['trace'].append(loc) - else: - # Subsequent frames - show package/module reference - if pkg or filename: - entry = pkg if pkg else filename - if line is not None: - entry = f" -> {entry} {line}:{col if col else ''}" - else: - entry = f" -> {entry}" - result['trace'].append(entry) - + loc = f"{filename} {line}:{col or ''}" + result["trace"].append(loc) + # Subsequent frames - show package/module reference + elif pkg or filename: + entry = pkg or filename + entry = f" -> {entry} {line}:{col or ''}" if line is not None else f" -> {entry}" + result["trace"].append(entry) + # Add final line showing the vulnerable component - comp_name = component.get('name') or component.get('id') - comp_ver = component.get('version') + comp_name = component.get("name") or component.get("id") + comp_ver = component.get("version") if comp_name: final_line = f" -> {comp_name}@{comp_ver}" if comp_ver else f" -> {comp_name}" - result['trace'].append(final_line) - + result["trace"].append(final_line) + return result -def convert_to_alerts(components: List[Dict[str, Any]]) -> List[Dict[str, Any]]: +def convert_to_alerts(components: list[dict[str, Any]]) -> list[dict[str, Any]]: # noqa: C901 """ Convert components with vulnerabilities into components with alerts. - - This function processes the raw .socket.facts.json format (with 'vulnerabilities' - and 'reachability' arrays) and converts them into an 'alerts' format suitable + + This function processes the raw .socket.facts.json format (with 'vulnerabilities' + and 'reachability' arrays) and converts them into an 'alerts' format suitable for formatters and notifications. - + Args: components: List of component dicts from .socket.facts.json - + Returns: List of component dicts with 'alerts' field added (original components unchanged) """ components_with_alerts = [] - + for comp in components: - vulns = comp.get('vulnerabilities', []) + vulns = comp.get("vulnerabilities", []) if not vulns: continue - + alerts = [] for vuln in vulns: - vuln_id = vuln.get('ghsaId') or vuln.get('cveId') or 'Unknown' - + vuln_id = vuln.get("ghsaId") or vuln.get("cveId") or "Unknown" + # Extract severity - sev_val = vuln.get('severity', '') - severity = 'unknown' - + sev_val = vuln.get("severity", "") + severity = "unknown" + # Handle both numeric and string severities try: if isinstance(sev_val, (int, float)): score = float(sev_val) if score >= 9.0: - severity = 'critical' + severity = "critical" elif score >= 7.0: - severity = 'high' + severity = "high" elif score >= 4.0: - severity = 'medium' + severity = "medium" else: - severity = 'low' + severity = "low" elif isinstance(sev_val, str): # Try to parse as number first - if sev_val.replace('.', '', 1).isdigit(): + if sev_val.replace(".", "", 1).isdigit(): score = float(sev_val) if score >= 9.0: - severity = 'critical' + severity = "critical" elif score >= 7.0: - severity = 'high' + severity = "high" elif score >= 4.0: - severity = 'medium' + severity = "medium" else: - severity = 'low' + severity = "low" else: # Use as-is if it's a string severity severity = sev_val.lower() except (ValueError, TypeError): - severity = 'unknown' - + severity = "unknown" + # Determine reachability reach_info = _determine_reachability(vuln, comp) - + # Skip vulnerabilities that don't apply to this component version - if reach_info.get('type') == 'not_applicable': + if reach_info.get("type") == "not_applicable": continue - + # Build alert purl = _make_purl(comp) - trace_str = '\n'.join(reach_info.get('trace', [])) - reach_type = reach_info.get('type', 'unknown') - + trace_str = "\n".join(reach_info.get("trace", [])) + reach_type = reach_info.get("type", "unknown") + # Map reachability to severity (reachable = critical, unknown/error = high, unreachable = low) final_severity = severity - if reach_type == 'reachable': - final_severity = 'critical' - elif reach_type in ('unknown', 'error') or reach_info.get('undeterminableReachability'): - final_severity = 'high' - elif reach_type == 'unreachable': - final_severity = 'low' - + if reach_type == "reachable": + final_severity = "critical" + elif reach_type in ("unknown", "error") or reach_info.get("undeterminableReachability"): + final_severity = "high" + elif reach_type == "unreachable": + final_severity = "low" + alert = { - 'title': vuln_id, - 'severity': final_severity, - 'type': 'vulnerability', - 'category': 'vulnerability', - 'props': { - 'cveId': vuln.get('cveId'), - 'ghsaId': vuln.get('ghsaId'), - 'range': vuln.get('range'), - 'purl': purl, - 'reachability': reach_type, - 'undeterminableReachability': reach_info.get('undeterminableReachability', False), - 'trace': trace_str, - 'severity': final_severity, - 'original_severity': severity, - } + "title": vuln_id, + "severity": final_severity, + "type": "vulnerability", + "category": "vulnerability", + "props": { + "cveId": vuln.get("cveId"), + "ghsaId": vuln.get("ghsaId"), + "range": vuln.get("range"), + "purl": purl, + "reachability": reach_type, + "undeterminableReachability": reach_info.get("undeterminableReachability", False), + "trace": trace_str, + "severity": final_severity, + "original_severity": severity, + }, } alerts.append(alert) - + if alerts: # Create a copy with alerts added comp_with_alerts = deepcopy(comp) - comp_with_alerts['alerts'] = alerts + comp_with_alerts["alerts"] = alerts components_with_alerts.append(comp_with_alerts) - + return components_with_alerts -def get_component_count(facts_data: Dict[str, Any]) -> Dict[str, int]: +def get_component_count(facts_data: dict[str, Any]) -> dict[str, int]: """ Get statistics about components in the socket facts data. - + Args: facts_data: Dictionary loaded from .socket.facts.json - + Returns: Dictionary with counts: - total: Total number of components @@ -374,14 +361,14 @@ def get_component_count(facts_data: Dict[str, Any]) -> Dict[str, int]: - direct: Direct dependencies - dev: Development dependencies """ - if not facts_data or 'components' not in facts_data: - return {'total': 0, 'with_vulnerabilities': 0, 'direct': 0, 'dev': 0} - - components = facts_data.get('components', []) - + if not facts_data or "components" not in facts_data: + return {"total": 0, "with_vulnerabilities": 0, "direct": 0, "dev": 0} + + components = facts_data.get("components", []) + return { - 'total': len(components), - 'with_vulnerabilities': len([c for c in components if c.get('vulnerabilities')]), - 'direct': len([c for c in components if c.get('direct')]), - 'dev': len([c for c in components if c.get('dev')]) + "total": len(components), + "with_vulnerabilities": len([c for c in components if c.get("vulnerabilities")]), + "direct": len([c for c in components if c.get("direct")]), + "dev": len([c for c in components if c.get("dev")]), } diff --git a/socketsecurity/core/lazy_file_loader.py b/socketsecurity/core/lazy_file_loader.py index a5bfa15a..fd1fd3cf 100644 --- a/socketsecurity/core/lazy_file_loader.py +++ b/socketsecurity/core/lazy_file_loader.py @@ -1,8 +1,8 @@ """ Lazy file loading utilities for efficient manifest file processing. """ + import logging -from typing import List, Tuple log = logging.getLogger("socketdev") @@ -11,50 +11,50 @@ class LazyFileLoader: """ A file-like object that only opens the actual file when needed for reading. This prevents keeping too many file descriptors open simultaneously. - + This class implements the standard file-like interface that requests library expects for multipart uploads, making it a drop-in replacement for regular file objects. """ - + def __init__(self, file_path: str, name: str): self.file_path = file_path self.name = name self._file = None self._closed = False self._position = 0 - + def _ensure_open(self): """Ensure the file is open and seek to the correct position.""" if self._closed: raise ValueError("I/O operation on closed file.") - + if self._file is None: - self._file = open(self.file_path, 'rb') + self._file = open(self.file_path, "rb") # noqa: SIM115 log.debug(f"Opened file for reading: {self.file_path}") # Seek to the current position if we've been reading before if self._position > 0: self._file.seek(self._position) - + def read(self, size: int = -1): """Read from the file, opening it if needed.""" self._ensure_open() data = self._file.read(size) self._position = self._file.tell() return data - + def readline(self, size: int = -1): """Read a line from the file.""" self._ensure_open() data = self._file.readline(size) self._position = self._file.tell() return data - + def seek(self, offset: int, whence: int = 0): """Seek to a position in the file.""" if self._closed: raise ValueError("I/O operation on closed file.") - + # Calculate new position for tracking if whence == 0: # SEEK_SET self._position = offset @@ -66,24 +66,23 @@ def seek(self, offset: int, whence: int = 0): result = self._file.seek(offset, whence) self._position = self._file.tell() return result - + # If file is already open, seek it too if self._file is not None: - result = self._file.seek(self._position) - return result - + return self._file.seek(self._position) + return self._position - + def tell(self): """Return current file position.""" if self._closed: raise ValueError("I/O operation on closed file.") - + if self._file is not None: self._position = self._file.tell() - + return self._position - + def close(self): """Close the file if it was opened.""" if self._file is not None: @@ -91,40 +90,40 @@ def close(self): log.debug(f"Closed file: {self.file_path}") self._file = None self._closed = True - + def __enter__(self): return self - + def __exit__(self, exc_type, exc_val, exc_tb): self.close() - + @property def closed(self): """Check if the file is closed.""" return self._closed - - @property + + @property def mode(self): """Return the file mode.""" - return 'rb' - + return "rb" + def readable(self): """Return whether the file is readable.""" return not self._closed - + def writable(self): """Return whether the file is writable.""" return False - + def seekable(self): """Return whether the file supports seeking.""" return True -def load_files_for_sending_lazy(files: List[str], workspace: str) -> List[Tuple[str, Tuple[str, LazyFileLoader]]]: +def load_files_for_sending_lazy(files: list[str], workspace: str) -> list[tuple[str, tuple[str, LazyFileLoader]]]: """ Prepares files for sending to the Socket API using lazy loading. - + This version doesn't open all files immediately, instead it creates LazyFileLoader objects that only open files when they're actually read. This prevents "Too many open files" errors when dealing with large numbers @@ -141,14 +140,11 @@ def load_files_for_sending_lazy(files: List[str], workspace: str) -> List[Tuple[ send_files = [] if "\\" in workspace: workspace = workspace.replace("\\", "/") - + for file_path in files: - _, name = file_path.rsplit("/", 1) + _, _name = file_path.rsplit("/", 1) - if file_path.startswith(workspace): - key = file_path[len(workspace):] - else: - key = file_path + key = file_path.removeprefix(workspace) key = key.lstrip("/") key = key.lstrip("./") diff --git a/socketsecurity/core/log_uploader.py b/socketsecurity/core/log_uploader.py index de57df42..adf6785b 100644 --- a/socketsecurity/core/log_uploader.py +++ b/socketsecurity/core/log_uploader.py @@ -17,8 +17,7 @@ import json import logging import threading -from datetime import datetime, timezone -from typing import Optional +from datetime import UTC, datetime from .cli_client import CliClient @@ -28,7 +27,7 @@ def _now_str() -> str: - return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] + return datetime.now(UTC).strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] class BatchedLogUploader: @@ -44,7 +43,7 @@ def __init__( self._buf: list = [] self._lock = threading.Lock() self._stop = threading.Event() - self._thread: Optional[threading.Thread] = None + self._thread: threading.Thread | None = None def add(self, entry: dict) -> None: with self._lock: @@ -102,11 +101,13 @@ def emit(self, record: logging.LogRecord) -> None: if getattr(_FLUSH_GUARD, "active", False): return try: - self._uploader.add({ - "timestamp": _now_str(), - "level": logging.getLevelName(record.levelno), - "message": self.format(record), - "context": self._context, - }) + self._uploader.add( + { + "timestamp": _now_str(), + "level": logging.getLevelName(record.levelno), + "message": self.format(record), + "context": self._context, + } + ) except Exception: self.handleError(record) diff --git a/socketsecurity/core/logging.py b/socketsecurity/core/logging.py index 9e61dae0..1e1978c6 100644 --- a/socketsecurity/core/logging.py +++ b/socketsecurity/core/logging.py @@ -5,7 +5,7 @@ def initialize_logging( level: int = logging.INFO, format: str = "%(asctime)s: %(message)s", socket_logger_name: str = "socketdev", - cli_logger_name: str = "socketcli" + cli_logger_name: str = "socketcli", ) -> tuple[logging.Logger, logging.Logger]: """Initialize logging for Socket Security @@ -24,9 +24,9 @@ def initialize_logging( cli_logger = logging.getLogger(cli_logger_name) cli_logger.setLevel(level) - return socket_logger, cli_logger + def set_debug_mode(enable: bool = False) -> None: """Toggle debug logging across all loggers""" level = logging.DEBUG if enable else logging.INFO diff --git a/socketsecurity/core/messages.py b/socketsecurity/core/messages.py index 3b475dee..5971f06e 100644 --- a/socketsecurity/core/messages.py +++ b/socketsecurity/core/messages.py @@ -2,9 +2,10 @@ import logging import re import uuid -from datetime import datetime, timezone +from datetime import UTC, datetime from html import escape from pathlib import Path +from typing import ClassVar from mdutils import MdUtils from prettytable import PrettyTable @@ -13,8 +14,8 @@ log = logging.getLogger("socketcli") -class Messages: +class Messages: @staticmethod def get_patched_version(alert: Issue) -> str: """Return the first patched version exposed by an alert, if any.""" @@ -44,7 +45,7 @@ def map_severity_to_sarif(severity: str) -> str: def get_manifest_file_url(diff: Diff, manifest_path: str, config=None) -> str: """ Generate proper URL for manifest file based on the repository type and diff URL. - + :param diff: Diff object containing diff_url and report_url :param manifest_path: Path to the manifest file (can contain multiple files separated by ';') :param config: Configuration object to determine SCM type @@ -52,56 +53,52 @@ def get_manifest_file_url(diff: Diff, manifest_path: str, config=None) -> str: """ if not manifest_path: return "" - + # Handle multiple manifest files separated by ';' - use the first one - first_manifest = manifest_path.split(';')[0] if ';' in manifest_path else manifest_path - + first_manifest = manifest_path.split(";")[0] if ";" in manifest_path else manifest_path + # Clean up the manifest path - remove build agent paths and normalize clean_path = first_manifest - + # Remove common build agent path prefixes prefixes_to_remove = [ - 'opt/buildagent/work/', - '/opt/buildagent/work/', - 'home/runner/work/', - '/home/runner/work/', + "opt/buildagent/work/", + "/opt/buildagent/work/", + "home/runner/work/", + "/home/runner/work/", ] - + for prefix in prefixes_to_remove: if clean_path.startswith(prefix): # Find the part after the build ID (usually a hash) - parts = clean_path[len(prefix):].split('/', 2) + parts = clean_path[len(prefix) :].split("/", 2) if len(parts) >= 3: clean_path = parts[2] # Take everything after build ID and repo name break - + # Remove leading slashes - clean_path = clean_path.lstrip('/') - - # diff.diff_url points at Socket, not the SCM, so only config decides. - scm_type = "api" - if config and hasattr(config, 'scm'): - scm_type = config.scm.lower() - - # Generate URL based on SCM type using config information - # NEVER use diff.diff_url for SCM URLs - those are Socket URLs for "View report" links - repository_url = getattr(config, 'repository_url', None) if config else None + clean_path = clean_path.lstrip("/") + + # Socket report URLs carry no source-control information. + scm_type = (getattr(config, "scm", None) or "api").lower() + + repository_url = getattr(config, "repository_url", None) if config else None if repository_url and scm_type in ("github", "gitlab", "bitbucket"): - branch = getattr(config, 'branch', None) or 'main' + branch = getattr(config, "branch", None) or "main" blob_path = {"github": "blob", "gitlab": "-/blob", "bitbucket": "src"}[scm_type] return f"{repository_url}/{blob_path}/{branch}/{clean_path}" # Fallback to Socket file view for API or unknown repository types - if hasattr(diff, 'report_url') and diff.report_url: + if hasattr(diff, "report_url") and diff.report_url: # Strip leading slash and URL encode for Socket dashboard - socket_path = clean_path.lstrip('/') - encoded_path = socket_path.replace('/', '%2F') + socket_path = clean_path.lstrip("/") + encoded_path = socket_path.replace("/", "%2F") return f"{diff.report_url}?tab=files&file={encoded_path}" - + return "" @staticmethod - def find_line_in_file(packagename: str, packageversion: str, manifest_file: str) -> tuple: + def find_line_in_file(packagename: str, packageversion: str, manifest_file: str) -> tuple: # noqa: C901 """ Finds the line number and snippet of code for the given package/version in a manifest file. Returns a 2-tuple: (line_number, snippet_or_message). @@ -118,25 +115,19 @@ def find_line_in_file(packagename: str, packageversion: str, manifest_file: str) if file_type in ["package-lock.json", "Pipfile.lock", "composer.lock"]: try: - with open(manifest_file, "r", encoding="utf-8") as f: + with open(manifest_file, encoding="utf-8") as f: raw_text = f.read() log.debug("Read %d characters from %s", len(raw_text), manifest_file) data = json.loads(raw_text) - packages_dict = ( - data.get("packages") - or data.get("default") - or data.get("dependencies") - or {} - ) + packages_dict = data.get("packages") or data.get("default") or data.get("dependencies") or {} log.debug("Found package keys in %s: %s", manifest_file, list(packages_dict.keys())) found_key = None found_info = None for key, value in packages_dict.items(): - if key.endswith(packagename) and "version" in value: - if value["version"] == packageversion: - found_key = key - found_info = value - break + if key.endswith(packagename) and value.get("version") == packageversion: + found_key = key + found_info = value + break if found_key and found_info: needle_key = f'"{found_key}":' lines = raw_text.splitlines() @@ -146,45 +137,44 @@ def find_line_in_file(packagename: str, packageversion: str, manifest_file: str) log.debug("Found match at line %d in %s: %s", i, manifest_file, line.strip()) return i, line.strip() return 1, f'"{found_key}": {found_info}' - else: - return 1, f"{packagename} {packageversion} (not found in {manifest_file})" + return 1, f"{packagename} {packageversion} (not found in {manifest_file})" except (FileNotFoundError, json.JSONDecodeError) as e: log.error("Error reading %s: %s", manifest_file, e) return 1, f"Error reading {manifest_file}" # For pnpm-lock.yaml, use a special regex pattern. if file_type.lower() == "pnpm-lock.yaml": - searchstring = rf'^\s*/{re.escape(packagename)}/{re.escape(packageversion)}:' + searchstring = rf"^\s*/{re.escape(packagename)}/{re.escape(packageversion)}:" else: search_patterns = { - "package.json": rf'"{packagename}":\s*"[\^~]?{re.escape(packageversion)}"', - "yarn.lock": rf'{packagename}@{packageversion}', - "requirements.txt": rf'^{re.escape(packagename)}\s*(?:==|===|!=|>=|<=|~=|\s+)?\s*{re.escape(packageversion)}(?:\s*;.*)?$', - "pyproject.toml": rf'{packagename}\s*=\s*"{re.escape(packageversion)}"', - "Pipfile": rf'"{packagename}"\s*=\s*"{re.escape(packageversion)}"', - "go.mod": rf'require\s+{re.escape(packagename)}\s+{re.escape(packageversion)}', - "go.sum": rf'{re.escape(packagename)}\s+{re.escape(packageversion)}', - "pom.xml": rf'{re.escape(packagename)}\s*{re.escape(packageversion)}', - "build.gradle": rf'implementation\s+"{re.escape(packagename)}:{re.escape(packageversion)}"', - "Gemfile": rf'gem\s+"{re.escape(packagename)}",\s*"{re.escape(packageversion)}"', - "Gemfile.lock": rf'\s+{re.escape(packagename)}\s+\({re.escape(packageversion)}\)', - ".csproj": rf'', - ".fsproj": rf'', - "paket.dependencies": rf'nuget\s+{re.escape(packagename)}\s+{re.escape(packageversion)}', - "Cargo.toml": rf'{re.escape(packagename)}\s*=\s*"{re.escape(packageversion)}"', - "build.sbt": rf'"{re.escape(packagename)}"\s*%\s*"{re.escape(packageversion)}"', - "Podfile": rf'pod\s+"{re.escape(packagename)}",\s*"{re.escape(packageversion)}"', - "Package.swift": rf'\.package\(name:\s*"{re.escape(packagename)}",\s*url:\s*".*?",\s*version:\s*"{re.escape(packageversion)}"\)', - "mix.exs": rf'\{{:{re.escape(packagename)},\s*"{re.escape(packageversion)}"\}}', - "composer.json": rf'"{re.escape(packagename)}":\s*"{re.escape(packageversion)}"', - "conanfile.txt": rf'{re.escape(packagename)}/{re.escape(packageversion)}', - "vcpkg.json": rf'"{re.escape(packagename)}":\s*"{re.escape(packageversion)}"', + "package.json": rf'"{packagename}":\s*"[\^~]?{re.escape(packageversion)}"', + "yarn.lock": rf"{packagename}@{packageversion}", + "requirements.txt": rf"^{re.escape(packagename)}\s*(?:==|===|!=|>=|<=|~=|\s+)?\s*{re.escape(packageversion)}(?:\s*;.*)?$", + "pyproject.toml": rf'{packagename}\s*=\s*"{re.escape(packageversion)}"', + "Pipfile": rf'"{packagename}"\s*=\s*"{re.escape(packageversion)}"', + "go.mod": rf"require\s+{re.escape(packagename)}\s+{re.escape(packageversion)}", + "go.sum": rf"{re.escape(packagename)}\s+{re.escape(packageversion)}", + "pom.xml": rf"{re.escape(packagename)}\s*{re.escape(packageversion)}", + "build.gradle": rf'implementation\s+"{re.escape(packagename)}:{re.escape(packageversion)}"', + "Gemfile": rf'gem\s+"{re.escape(packagename)}",\s*"{re.escape(packageversion)}"', + "Gemfile.lock": rf"\s+{re.escape(packagename)}\s+\({re.escape(packageversion)}\)", + ".csproj": rf'', + ".fsproj": rf'', + "paket.dependencies": rf"nuget\s+{re.escape(packagename)}\s+{re.escape(packageversion)}", + "Cargo.toml": rf'{re.escape(packagename)}\s*=\s*"{re.escape(packageversion)}"', + "build.sbt": rf'"{re.escape(packagename)}"\s*%\s*"{re.escape(packageversion)}"', + "Podfile": rf'pod\s+"{re.escape(packagename)}",\s*"{re.escape(packageversion)}"', + "Package.swift": rf'\.package\(name:\s*"{re.escape(packagename)}",\s*url:\s*".*?",\s*version:\s*"{re.escape(packageversion)}"\)', + "mix.exs": rf'\{{:{re.escape(packagename)},\s*"{re.escape(packageversion)}"\}}', + "composer.json": rf'"{re.escape(packagename)}":\s*"{re.escape(packageversion)}"', + "conanfile.txt": rf"{re.escape(packagename)}/{re.escape(packageversion)}", + "vcpkg.json": rf'"{re.escape(packagename)}":\s*"{re.escape(packageversion)}"', } - searchstring = search_patterns.get(file_type, rf'{re.escape(packagename)}.*{re.escape(packageversion)}') + searchstring = search_patterns.get(file_type, rf"{re.escape(packagename)}.*{re.escape(packageversion)}") log.debug("Using search pattern for %s: %s", file_type, searchstring) try: - with open(manifest_file, 'r', encoding="utf-8") as file: + with open(manifest_file, encoding="utf-8") as file: lines = [line.rstrip("\n") for line in file] log.debug("Total lines in %s: %d", manifest_file, len(lines)) for line_number, line_content in enumerate(lines, start=1): @@ -230,7 +220,7 @@ def get_manifest_type_url(manifest_file: str, pkg_name: str, pkg_version: str) - return f"https://socket.dev/{url_prefix}/package/{pkg_name}/alerts/{pkg_version}" @staticmethod - def create_security_comment_sarif(diff) -> dict: + def create_security_comment_sarif(diff) -> dict: # noqa: C901 """ Render each alert at its known manifest locations and identify advisory rules by advisory ID. """ @@ -242,16 +232,14 @@ def create_security_comment_sarif(diff) -> dict: sarif_data = { "$schema": "https://json.schemastore.org/sarif-2.1.0.json", "version": "2.1.0", - "runs": [{ - "tool": { - "driver": { - "name": "Socket Security", - "informationUri": "https://socket.dev", - "rules": [] - } - }, - "results": [] - }] + "runs": [ + { + "tool": { + "driver": {"name": "Socket Security", "informationUri": "https://socket.dev", "rules": []} + }, + "results": [], + } + ], } rules_map = {} @@ -266,7 +254,12 @@ def create_security_comment_sarif(diff) -> dict: base_rule_id = f"{base_rule_id} {advisory_id}" severity = alert.severity - log.debug("Alert %s - introduced_by: %s, manifests: %s", base_rule_id, alert.introduced_by, getattr(alert, 'manifests', None)) + log.debug( + "Alert %s - introduced_by: %s, manifests: %s", + base_rule_id, + alert.introduced_by, + getattr(alert, "manifests", None), + ) manifest_files = [] if alert.introduced_by and isinstance(alert.introduced_by, list): for entry in alert.introduced_by: @@ -275,11 +268,12 @@ def create_security_comment_sarif(diff) -> dict: manifest_files.extend(files) elif isinstance(entry, str): manifest_files.extend([m.strip() for m in entry.split(";") if m.strip()]) - elif hasattr(alert, 'manifests') and alert.manifests: + elif hasattr(alert, "manifests") and alert.manifests: manifest_files = [mf.strip() for mf in alert.manifests.split(";") if mf.strip()] if not manifest_files: manifest_files = [ - entry["file"] for entry in getattr(alert, "manifest_files", []) + entry["file"] + for entry in getattr(alert, "manifest_files", []) if isinstance(entry, dict) and entry.get("file") ] @@ -295,30 +289,31 @@ def create_security_comment_sarif(diff) -> dict: log.debug("Alert %s - Processing manifest file: %s", base_rule_id, mf) socket_url = Messages.get_manifest_type_url(mf, pkg_name, pkg_version) line_number, line_content = Messages.find_line_in_file(pkg_name, pkg_version, mf) - if line_number < 1: - line_number = 1 + line_number = max(line_number, 1) log.debug("Alert %s: Manifest %s, line %d: %s", base_rule_id, mf, line_number, line_content) # Create a unique rule id and name by appending the manifest file. unique_rule_id = f"{base_rule_id} ({mf})" rule_name = f"Alert {base_rule_id} ({mf})" props = {} - if hasattr(alert, 'props') and alert.props: + if hasattr(alert, "props") and alert.props: props = alert.props - suggestion = '' - if hasattr(alert, 'suggestion'): + suggestion = "" + if hasattr(alert, "suggestion"): suggestion = alert.suggestion - alert_title = '' - if hasattr(alert, 'title'): + alert_title = "" + if hasattr(alert, "title"): alert_title = alert.title - description = '' - if hasattr(alert, 'description'): + description = "" + if hasattr(alert, "description"): description = alert.description - short_desc = (f"{props.get('note', '')}

Suggested Action:
{suggestion}" - f"
{socket_url}") + short_desc = ( + f"{props.get('note', '')}

Suggested Action:
{suggestion}" + f'
{socket_url}' + ) if advisory_id: short_desc = f"{advisory_id}
{short_desc}" - full_desc = "{} - {}".format(alert_title, description.replace('\r\n', '
')) + full_desc = "{} - {}".format(alert_title, description.replace("\r\n", "
")) if unique_rule_id not in rules_map: rules_map[unique_rule_id] = { @@ -327,23 +322,23 @@ def create_security_comment_sarif(diff) -> dict: "shortDescription": {"text": rule_name}, "fullDescription": {"text": full_desc}, "helpUri": socket_url, - "defaultConfiguration": { - "level": Messages.map_severity_to_sarif(severity) - }, + "defaultConfiguration": {"level": Messages.map_severity_to_sarif(severity)}, } result_obj = { "ruleId": unique_rule_id, "message": {"text": short_desc}, - "locations": [{ - "physicalLocation": { - "artifactLocation": {"uri": mf}, - "region": { - "startLine": line_number, - "snippet": {"text": line_content}, - }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": {"uri": mf}, + "region": { + "startLine": line_number, + "snippet": {"text": line_content}, + }, + } } - }] + ], } results_list.append(result_obj) @@ -377,7 +372,7 @@ def _matches_reachability_filter(reachability: str, selector: str, undeterminabl return True @staticmethod - def create_security_comment_sarif_from_facts( + def create_security_comment_sarif_from_facts( # noqa: C901 components_with_alerts: list, reachability_filter: str = "all", grouping: str = "instance", @@ -393,16 +388,14 @@ def create_security_comment_sarif_from_facts( sarif_data = { "$schema": "https://json.schemastore.org/sarif-2.1.0.json", "version": "2.1.0", - "runs": [{ - "tool": { - "driver": { - "name": "Socket Security", - "informationUri": "https://socket.dev", - "rules": [] - } - }, - "results": [] - }] + "runs": [ + { + "tool": { + "driver": {"name": "Socket Security", "informationUri": "https://socket.dev", "rules": []} + }, + "results": [], + } + ], } rules_map = {} @@ -451,9 +444,8 @@ def create_security_comment_sarif_from_facts( else: rule_id = f"{comp_name}=={comp_version}:{vuln_id}" rule_name = f"Reachability alert {vuln_id} in {comp_name}@{comp_version}" - socket_url = ( - props.get("url") - or Messages.get_manifest_type_url(manifest_uris[0], comp_name, comp_version) + socket_url = props.get("url") or Messages.get_manifest_type_url( + manifest_uris[0], comp_name, comp_version ) if rule_id not in rules_map: @@ -463,15 +455,13 @@ def create_security_comment_sarif_from_facts( "shortDescription": {"text": rule_name}, "fullDescription": {"text": alert.get("title", rule_name)}, "helpUri": socket_url, - "defaultConfiguration": { - "level": Messages.map_severity_to_sarif(severity) - }, + "defaultConfiguration": {"level": Messages.map_severity_to_sarif(severity)}, } message = ( f"Reachability: {reachability}. " f"Suggested Action:
{props.get('range', '')}" - f"
{socket_url}" + f'
{socket_url}' ) if grouping == "alert": @@ -482,15 +472,14 @@ def create_security_comment_sarif_from_facts( grouped_results[alert_key] = { "ruleId": rule_id, "message": {"text": message}, - "locations": [{ - "physicalLocation": { - "artifactLocation": {"uri": first_uri}, - "region": { - "startLine": 1, - "snippet": {"text": f"{comp_name}@{comp_version}"} - }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": {"uri": first_uri}, + "region": {"startLine": 1, "snippet": {"text": f"{comp_name}@{comp_version}"}}, + } } - }], + ], "properties": { "reachability": reachability, "reachabilityStates": [reachability], @@ -501,7 +490,7 @@ def create_security_comment_sarif_from_facts( "cveId": props.get("cveId"), "source": "socket-facts", "socketAlertKey": alert_key, - } + }, } else: states = set(existing["properties"].get("reachabilityStates", [])) @@ -522,26 +511,30 @@ def create_security_comment_sarif_from_facts( existing["properties"]["purls"] = sorted(purls) else: for uri in manifest_uris: - results_list.append({ - "ruleId": rule_id, - "message": {"text": message}, - "locations": [{ - "physicalLocation": { - "artifactLocation": {"uri": uri}, - "region": { - "startLine": 1, - "snippet": {"text": f"{comp_name}@{comp_version}"} - }, - } - }], - "properties": { - "reachability": reachability, - "purl": props.get("purl"), - "ghsaId": props.get("ghsaId"), - "cveId": props.get("cveId"), - "source": "socket-facts" + results_list.append( + { + "ruleId": rule_id, + "message": {"text": message}, + "locations": [ + { + "physicalLocation": { + "artifactLocation": {"uri": uri}, + "region": { + "startLine": 1, + "snippet": {"text": f"{comp_name}@{comp_version}"}, + }, + } + } + ], + "properties": { + "reachability": reachability, + "purl": props.get("purl"), + "ghsaId": props.get("ghsaId"), + "cveId": props.get("cveId"), + "source": "socket-facts", + }, } - }) + ) if grouping == "alert": for grouped in grouped_results.values(): @@ -565,12 +558,7 @@ def create_security_comment_json(diff: Diff) -> dict: if alert.error: scan_failed = True break - output = { - "scan_failed": scan_failed, - "new_alerts": [], - "full_scan_id": diff.id, - "diff_url": diff.diff_url - } + output = {"scan_failed": scan_failed, "new_alerts": [], "full_scan_id": diff.id, "diff_url": diff.diff_url} for alert in diff.new_alerts: alert: Issue output["new_alerts"].append(json.loads(str(alert))) @@ -628,7 +616,7 @@ def generate_uuid_from_alert_gitlab(alert: Issue) -> str: ) # Generate UUID5 (deterministic) from namespace and unique string - namespace = uuid.UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8') # DNS namespace + namespace = uuid.UUID("6ba7b810-9dad-11d1-80b4-00c04fd430c8") # DNS namespace return str(uuid.uuid5(namespace, unique_str)) @staticmethod @@ -670,20 +658,17 @@ def extract_identifiers_gitlab(alert: Issue) -> list: values = [values] elif not isinstance(values, (list, tuple)): continue - for value in values: - if not isinstance(value, str) or not value.strip(): + for raw_value in values: + if not isinstance(raw_value, str) or not raw_value.strip(): continue - value = value.strip() + value = raw_value.strip() identifier_key = (identifier_type, value.upper()) if identifier_key in seen: continue seen.add(identifier_key) - identifiers.append({ - "type": identifier_type, - "name": value, - "value": value, - "url": f"{url_prefix}{value}" - }) + identifiers.append( + {"type": identifier_type, "name": value, "value": value, "url": f"{url_prefix}{value}"} + ) return identifiers @@ -716,19 +701,15 @@ def extract_location_gitlab(alert: Issue) -> dict: manifest_file = candidate break - location = { + return { "file": manifest_file or "unknown", "dependency": { - "package": { - "name": alert.pkg_name - }, + "package": {"name": alert.pkg_name}, "version": alert.pkg_version, - "direct": bool(getattr(alert, "direct", False)) - } + "direct": bool(getattr(alert, "direct", False)), + }, } - return location - @staticmethod def create_security_comment_gitlab(diff: Diff) -> dict: """ @@ -752,30 +733,26 @@ def create_security_comment_gitlab(diff: Diff) -> dict: "id": "socket-security", "name": "Socket Security", "version": __version__, - "vendor": { - "name": "Socket" - } + "vendor": {"name": "Socket"}, }, "scanner": { "id": "socket-cli", "name": "Socket CLI", "version": __version__, - "vendor": { - "name": "Socket" - } + "vendor": {"name": "Socket"}, }, "type": "dependency_scanning", - "start_time": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S"), - "end_time": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S"), - "status": "success" + "start_time": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%S"), + "end_time": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%S"), + "status": "success", }, "vulnerabilities": [], - "dependency_files": [] + "dependency_files": [], } dep_files_map: dict = {} - all_alerts = list(diff.new_alerts) + list(getattr(diff, 'unchanged_alerts', [])) + all_alerts = list(diff.new_alerts) + list(getattr(diff, "unchanged_alerts", [])) seen_ids = set() for alert in all_alerts: vulnerability_id = Messages.generate_uuid_from_alert_gitlab(alert) @@ -786,16 +763,16 @@ def create_security_comment_gitlab(diff: Diff) -> dict: vulnerability = { "id": vulnerability_id, "category": "dependency_scanning", - "name": alert.title if hasattr(alert, 'title') else f"{alert.type} in {alert.pkg_name}", + "name": alert.title if hasattr(alert, "title") else f"{alert.type} in {alert.pkg_name}", "message": f"{alert.pkg_name}@{alert.pkg_version}: {alert.title if hasattr(alert, 'title') else alert.type}", - "description": alert.description if hasattr(alert, 'description') and alert.description else "", + "description": alert.description if hasattr(alert, "description") and alert.description else "", "severity": Messages.map_socket_severity_to_gitlab(alert.severity), "identifiers": Messages.extract_identifiers_gitlab(alert), - "links": [{"url": alert.url}] if hasattr(alert, 'url') and alert.url else [], - "location": Messages.extract_location_gitlab(alert) + "links": [{"url": alert.url}] if hasattr(alert, "url") and alert.url else [], + "location": Messages.extract_location_gitlab(alert), } - if hasattr(alert, 'suggestion') and alert.suggestion: + if hasattr(alert, "suggestion") and alert.suggestion: vulnerability["solution"] = alert.suggestion gitlab_report["vulnerabilities"].append(vulnerability) @@ -803,18 +780,13 @@ def create_security_comment_gitlab(diff: Diff) -> dict: file_path = vulnerability["location"]["file"] if file_path != "unknown": pkg_manager = Messages._pkg_type_to_package_manager( - alert.pkg_type if hasattr(alert, 'pkg_type') else "" + alert.pkg_type if hasattr(alert, "pkg_type") else "" ) if file_path not in dep_files_map: - dep_files_map[file_path] = { - "path": file_path, - "package_manager": pkg_manager, - "dependencies": [] - } - dep_files_map[file_path]["dependencies"].append({ - "package": {"name": alert.pkg_name}, - "version": alert.pkg_version - }) + dep_files_map[file_path] = {"path": file_path, "package_manager": pkg_manager, "dependencies": []} + dep_files_map[file_path]["dependencies"].append( + {"package": {"name": alert.pkg_name}, "version": alert.pkg_version} + ) gitlab_report["dependency_files"] = list(dep_files_map.values()) @@ -876,7 +848,7 @@ def introduced_by_html(alert: Issue) -> str: if not ancestors: return "" - shown = ancestors[:Messages.INTRODUCED_BY_LIMIT] + shown = ancestors[: Messages.INTRODUCED_BY_LIMIT] names = ", ".join(f"{Messages.html_text(name)}" for name in shown) hidden = len(ancestors) - len(shown) if hidden: @@ -978,10 +950,10 @@ def license_group_row(alerts: list, diff: Diff, config, show_ignore: bool) -> st row = "" action = "Block" if any(alert.error for alert in alerts) else "Warn" first_alert = alerts[0] - + # Use orange diamond for license policy violations license_icon = "๐Ÿ”ถ" - + package = f"{first_alert.package_name_with_namespace()}@{first_alert.pkg_version}" license_label = Messages.html_text(package) license_marker = Messages.alert_package_marker(first_alert, package) @@ -990,7 +962,7 @@ def license_group_row(alerts: list, diff: Diff, config, show_ignore: bool) -> st license_findings = [] for alert in alerts: license_findings.append(alert.title) - + row += f""" @@ -1004,17 +976,20 @@ def license_group_row(alerts: list, diff: Diff, config, show_ignore: bool) -> st """ for finding in license_findings: row += f"
  • {Messages.html_text(finding)}
  • \n" - - + # Generate proper manifest URL for license violations license_manifest_url = Messages.get_manifest_file_url(diff, first_alert.manifests, config) license_ignore_html = ( - f"

    Mark the package as acceptable risk: To ignore findings for this package version in this pull request, reply with " - f"@SocketSecurity ignore {Messages.html_text(first_alert.pkg_type)}/{license_label}. " - f"You can also ignore all packages with @SocketSecurity ignore-all. " - f"To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

    " - ) if show_ignore else "" + ( + f"

    Mark the package as acceptable risk: To ignore findings for this package version in this pull request, reply with " + f"@SocketSecurity ignore {Messages.html_text(first_alert.pkg_type)}/{license_label}. " + f"You can also ignore all packages with @SocketSecurity ignore-all. " + f"To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

    " + ) + if show_ignore + else "" + ) row += f"""

    From: Manifest File

    {Messages.introduced_by_html(first_alert)} @@ -1039,9 +1014,9 @@ def security_alert_row(alert: Issue, diff: Diff, config, show_ignore: bool) -> s details_open = "" patched_version = Messages.get_patched_version(alert) patched_version_html = ( - "

    Patched version: " - f"{Messages.html_text(patched_version)}

    " - if patched_version else "" + f"

    Patched version: {Messages.html_text(patched_version)}

    " + if patched_version + else "" ) # Generate proper manifest URL manifest_url = Messages.get_manifest_file_url(diff, alert.manifests, config) @@ -1050,11 +1025,15 @@ def security_alert_row(alert: Issue, diff: Diff, config, show_ignore: bool) -> s pkg_marker = Messages.alert_package_marker(alert, package) alert_title = Messages.alert_title_with_advisory(alert) ignore_html = ( - f"

    Mark as acceptable risk: To ignore this alert only in this pull request, reply with:
    " - f"@SocketSecurity ignore {Messages.html_text(alert.pkg_type)}/{pkg_label}
    " - f"Or ignore all future alerts with:
    " - f"@SocketSecurity ignore-all

    " - ) if show_ignore else "" + ( + f"

    Mark as acceptable risk: To ignore this alert only in this pull request, reply with:
    " + f"@SocketSecurity ignore {Messages.html_text(alert.pkg_type)}/{pkg_label}
    " + f"Or ignore all future alerts with:
    " + f"@SocketSecurity ignore-all

    " + ) + if show_ignore + else "" + ) return f""" @@ -1147,7 +1126,10 @@ def security_comment_template(diff: Diff, config=None) -> str: # Reserve the full table structure and the largest possible omission notices # before adding rows, so a large new section cannot displace the footer. reserved = ( - new_header, new_footer, existing_header, existing_footer, + new_header, + new_footer, + existing_header, + existing_footer, Messages.omitted_comment_alerts("new", len(new_alerts)), Messages.omitted_comment_alerts("existing", len(existing_alerts)), ) @@ -1168,9 +1150,13 @@ def security_comment_template(diff: Diff, config=None) -> str: existing_groups, diff, config, budget - len(new_rows.encode()) ) return Messages.normalize_comment_html( - new_header + new_rows + new_footer + new_header + + new_rows + + new_footer + Messages.omitted_comment_alerts("new", len(new_alerts) - new_count) - + existing_header + existing_rows + existing_footer + + existing_header + + existing_rows + + existing_footer + Messages.omitted_comment_alerts("existing", len(existing_alerts) - existing_count) + report_link ) @@ -1184,10 +1170,7 @@ def security_comment_template(diff: Diff, config=None) -> str: def omitted_comment_alerts(section: str, count: int) -> str: if not count: return "" - marker = ( - Messages.NEW_ALERTS_TRUNCATED_MARKER if section == "new" - else Messages.EXISTING_ALERTS_TRUNCATED_MARKER - ) + marker = Messages.NEW_ALERTS_TRUNCATED_MARKER if section == "new" else Messages.EXISTING_ALERTS_TRUNCATED_MARKER return ( f"\n{marker}\n\n{count} more {section} alert(s) are not shown here " "to keep this comment within GitHub's size limit.\n" @@ -1205,10 +1188,7 @@ def existing_alerts_effect(existing_alerts: list, config) -> str: return "None has a **Block** action, so they don't fail the run." if getattr(config, "disable_blocking", False): verb = "has" if blocking == 1 else "have" - return ( - f"{blocking} {verb} a **Block** action but don't fail the run, " - "because `--disable-blocking` is set." - ) + return f"{blocking} {verb} a **Block** action but don't fail the run, because `--disable-blocking` is set." return f"`--strict-blocking` fails the run on the {blocking} with a **Block** action." @staticmethod @@ -1222,7 +1202,8 @@ def existing_comment_alerts(diff: Diff, config) -> list: return [] new_keys = {alert.consolidation_key() for alert in getattr(diff, "new_alerts", []) or []} return [ - alert for alert in getattr(diff, "unchanged_alerts", []) or [] + alert + for alert in getattr(diff, "unchanged_alerts", []) or [] if (alert.error or alert.warn) and alert.consolidation_key() not in new_keys ] @@ -1280,7 +1261,6 @@ def get_severity_icon(severity: str) -> str: } return severity_map.get(severity.lower(), "https://github-app-statics.socket.dev/severity-0.svg") - @staticmethod def create_next_steps(md: MdUtils, next_steps: dict): """ @@ -1360,48 +1340,25 @@ def create_security_alert_table(diff: Diff, md: MdUtils) -> tuple[MdUtils, list, :param md: MdUtils - Main markdown variable :return: """ - alert_table = [ - "Alert", - "Package", - "Introduced by", - "Manifest File", - "CI" - ] + alert_table = ["Alert", "Package", "Introduced by", "Manifest File", "CI"] num_of_alert_columns = len(alert_table) next_steps = {} ignore_commands = [] for alert in diff.new_alerts: alert: Issue if alert.next_step_title not in next_steps: - next_steps[alert.next_step_title] = [ - alert.description, - alert.suggestion - ] + next_steps[alert.next_step_title] = [alert.description, alert.suggestion] ignore = f"`SocketSecurity ignore {alert.purl}`" if ignore not in ignore_commands: ignore_commands.append(ignore) manifest_str, source_str = Messages.create_sources(alert) purl_url = f"[{alert.purl}]({alert.url})" - if alert.error: - emoji = ':no_entry_sign:' - else: - emoji = ':warning:' - row = [ - alert.title, - purl_url, - source_str, - manifest_str, - emoji - ] + emoji = ":no_entry_sign:" if alert.error else ":warning:" + row = [alert.title, purl_url, source_str, manifest_str, emoji] if row not in alert_table: alert_table.extend(row) num_of_alert_rows = len(diff.new_alerts) + 1 - md.new_table( - columns=num_of_alert_columns, - rows=num_of_alert_rows, - text=alert_table, - text_align="left" - ) + md.new_table(columns=num_of_alert_columns, rows=num_of_alert_rows, text=alert_table, text_align="left") return md, ignore_commands, next_steps @staticmethod @@ -1414,7 +1371,9 @@ def dependency_overview_template(diff: Diff) -> str: md = MdUtils(file_name="markdown_overview_temp.md") md.new_line("") md.new_header(level=1, title="Socket Security: Dependency Overview") - md.new_line("Review the following changes in direct dependencies. Learn more about [socket.dev](https://socket.dev)") + md.new_line( + "Review the following changes in direct dependencies. Learn more about [socket.dev](https://socket.dev)" + ) md.new_line() md = Messages.create_added_table(diff, md) md.create_md_file() @@ -1427,7 +1386,9 @@ def short_dependency_overview_comment(diff: Diff) -> MdUtils: md = MdUtils(file_name="markdown_overview_temp.md") md.new_line("") md.new_header(level=1, title="Socket Security: Dependency Overview") - md.new_line("Review the following changes in direct dependencies. Learn more about [socket.dev](https://socket.dev)") + md.new_line( + "Review the following changes in direct dependencies. Learn more about [socket.dev](https://socket.dev)" + ) md.new_line() md.new_line("The amount of dependency changes were to long for this comment. Please check out the full report") md.new_line(f"To view more information about this report checkout the [Full Report]({diff.diff_url})") @@ -1453,7 +1414,7 @@ def create_remove_line(diff: Diff, md: MdUtils) -> MdUtils: # Change types the shared badge host publishes an image for. Removed and # replaced have no artwork, so they fall back to a bold text label rather than # rendering a broken image; added and updated render the available badges. - DIFF_BADGES = { + DIFF_BADGES: ClassVar[dict[str, str]] = { "Added": "diff-added.svg", "Updated": "diff-updated.svg", } @@ -1466,6 +1427,27 @@ def get_diff_badge(change: str, package_url: str) -> str: return f"**{change}**" return f"[![{change}](https://github-app-statics.socket.dev/{badge})]({package_url})" + @staticmethod + def _score_to_badge(score: float, url: str) -> str: + score_percent = int(score * 100) # Convert to integer percentage + return f"[![{score_percent}](https://github-app-statics.socket.dev/score-{score_percent}.svg)]({url})" + + @staticmethod + def _get_score_for_badge(package: Purl, score_name: str) -> float: + scores = getattr(package, "scores", None) + if isinstance(scores, dict): + raw_score = scores.get(score_name) + else: + raw_score = getattr(scores, score_name, None) if scores is not None else None + + if raw_score is None: + return 1.0 + + score = float(raw_score) + if score > 1: + score = score / 100 + return max(0.0, min(score, 1.0)) + @staticmethod def create_added_table(diff: Diff, md: MdUtils) -> MdUtils: """ @@ -1482,7 +1464,7 @@ def create_added_table(diff: Diff, md: MdUtils) -> MdUtils: "Vulnerability", "Quality", "Maintenance", - "License" + "License", ] num_of_overview_columns = len(overview_table) @@ -1500,32 +1482,16 @@ def create_added_table(diff: Diff, md: MdUtils) -> MdUtils: package_url = f"[{package.purl}]({package.url})" diff_badge = Messages.get_diff_badge(change, package.url) - # Scores dynamically converted to badge URLs and linked - def score_to_badge(score): - score_percent = int(score * 100) # Convert to integer percentage - return f"[![{score_percent}](https://github-app-statics.socket.dev/score-{score_percent}.svg)]({package.url})" - - def get_score_for_badge(score_name: str) -> float: - scores = getattr(package, "scores", None) - if isinstance(scores, dict): - raw_score = scores.get(score_name) - else: - raw_score = getattr(scores, score_name, None) if scores is not None else None - - if raw_score is None: - return 1.0 - - score = float(raw_score) - if score > 1: - score = score / 100 - return max(0.0, min(score, 1.0)) - - # Generate badges for each score type - supply_chain_risk_badge = score_to_badge(get_score_for_badge("supplyChain")) - vulnerability_badge = score_to_badge(get_score_for_badge("vulnerability")) - quality_badge = score_to_badge(get_score_for_badge("quality")) - maintenance_badge = score_to_badge(get_score_for_badge("maintenance")) - license_badge = score_to_badge(get_score_for_badge("license")) + ( + supply_chain_risk_badge, + vulnerability_badge, + quality_badge, + maintenance_badge, + license_badge, + ) = ( + Messages._score_to_badge(Messages._get_score_for_badge(package, name), package.url) + for name in ("supplyChain", "vulnerability", "quality", "maintenance", "license") + ) # Add the row for this package row = [ @@ -1535,7 +1501,7 @@ def get_score_for_badge(score_name: str) -> float: vulnerability_badge, quality_badge, maintenance_badge, - license_badge + license_badge, ] overview_table.extend(row) count += 1 @@ -1545,10 +1511,7 @@ def get_score_for_badge(score_name: str) -> float: # Generate Markdown table md.new_table( - columns=num_of_overview_columns, - rows=num_of_overview_rows, - text=overview_table, - text_align="center" + columns=num_of_overview_columns, rows=num_of_overview_rows, text=overview_table, text_align="center" ) return md @@ -1559,8 +1522,7 @@ def create_purl_link(details: Purl) -> str: :param details: Purl - Details about the package needed to create the URLs :return: """ - package_url = f"[{details.purl}]({details.url})" - return package_url + return f"[{details.purl}]({details.url})" @staticmethod def create_console_security_alert_table(diff: Diff) -> PrettyTable: @@ -1570,15 +1532,7 @@ def create_console_security_alert_table(diff: Diff) -> PrettyTable: :return: """ alert_table = PrettyTable( - [ - "Alert", - "Package", - "Patched Version", - "url", - "Introduced by", - "Manifest File", - "CI Status" - ] + ["Alert", "Package", "Patched Version", "url", "Introduced by", "Manifest File", "CI Status"] ) for alert in diff.new_alerts: alert: Issue @@ -1598,7 +1552,7 @@ def create_console_security_alert_table(diff: Diff) -> PrettyTable: alert.url, source_str, manifest_str, - state + state, ] alert_table.add_row(row) return alert_table diff --git a/socketsecurity/core/pull_request.py b/socketsecurity/core/pull_request.py index 1804dd6d..7a6127e2 100644 --- a/socketsecurity/core/pull_request.py +++ b/socketsecurity/core/pull_request.py @@ -1,6 +1,6 @@ import re +from collections.abc import Mapping from dataclasses import dataclass -from typing import Mapping, Optional from urllib.parse import urlparse from socketsecurity.core.git_remote import parse_git_remote @@ -9,7 +9,7 @@ @dataclass(frozen=True) class PullRequestContext: number: int = 0 - url: Optional[str] = None + url: str | None = None def parse_pull_request_number(value) -> int: @@ -24,10 +24,10 @@ def parse_pull_request_number(value) -> int: parsed = int(value) except (TypeError, ValueError): return 0 - return parsed if parsed > 0 else 0 + return max(0, parsed) -def _http_url(value: Optional[str]) -> Optional[str]: +def _http_url(value: str | None) -> str | None: """Return ``value`` if it is an http(s) URL with a host, else ``None``. Every URL fragment read out of the CI environment goes through here before it @@ -42,12 +42,11 @@ def _http_url(value: Optional[str]) -> Optional[str]: return url if parsed.scheme in ("http", "https") and parsed.netloc else None -def _repository_url(value: Optional[str]) -> Optional[str]: +def _repository_url(value: str | None) -> str | None: if not value: return None url = value.strip().rstrip("/") - if url.endswith(".git"): - url = url[:-4] + url = url.removesuffix(".git") return _http_url(url) @@ -59,9 +58,7 @@ def _github_number(env: Mapping[str, str]) -> int: return parse_pull_request_number(match.group(1)) if match else 0 -def _github_repository_url( - repo: Optional[str], env: Mapping[str, str], remote_url: Optional[str] = None -) -> Optional[str]: +def _github_repository_url(repo: str | None, env: Mapping[str, str], remote_url: str | None = None) -> str | None: remote_host, remote_path = parse_git_remote(env.get("BUILDKITE_REPO") or remote_url) # config.repo is only ever a bare repository name, so it cannot produce a # slug on its own; it is kept last for callers that pass a full owner/repo. @@ -76,25 +73,18 @@ def _github_repository_url( return f"{server}/{repository.strip('/')}" -def _gitlab_project_url( - repo: Optional[str], env: Mapping[str, str], remote_url: Optional[str] = None -) -> Optional[str]: +def _gitlab_project_url(repo: str | None, env: Mapping[str, str], remote_url: str | None = None) -> str | None: project_url = _repository_url(env.get("CI_PROJECT_URL")) if not project_url: remote_host, remote_path = parse_git_remote(env.get("BUILDKITE_REPO") or remote_url) project_path = env.get("CI_PROJECT_PATH") or remote_path or repo - server = ( - _http_url(env.get("CI_SERVER_URL")) - or (_http_url(f"https://{remote_host}") if remote_host else None) - ) + server = _http_url(env.get("CI_SERVER_URL")) or (_http_url(f"https://{remote_host}") if remote_host else None) if server and project_path and "/" in project_path: project_url = f"{server}/{project_path.strip('/')}" return project_url -def _bitbucket_repository_url( - repo: Optional[str], env: Mapping[str, str], remote_url: Optional[str] = None -) -> Optional[str]: +def _bitbucket_repository_url(repo: str | None, env: Mapping[str, str], remote_url: str | None = None) -> str | None: remote_host, remote_path = parse_git_remote(remote_url) repository = env.get("BITBUCKET_REPO_FULL_NAME") or remote_path or repo if not repository or "/" not in repository: @@ -108,11 +98,11 @@ def _bitbucket_repository_url( def resolve_repository_url( - scm: Optional[str], - repo: Optional[str] = None, - env: Optional[Mapping[str, str]] = None, - remote_url: Optional[str] = None, -) -> Optional[str]: + scm: str | None, + repo: str | None = None, + env: Mapping[str, str] | None = None, + remote_url: str | None = None, +) -> str | None: """Return the web URL of the scanned repository, such as ``https://github.com/owner/repo``. The CI environment wins, then the checkout's ``origin`` remote. ``None`` means the @@ -130,7 +120,7 @@ def resolve_repository_url( return None -def repository_owner(repository_url: Optional[str]) -> str: +def repository_owner(repository_url: str | None) -> str: """Return everything before the repository name in ``repository_url``'s path. That is the owner on GitHub and Bitbucket, and the full group path on GitLab, @@ -142,20 +132,19 @@ def repository_owner(repository_url: Optional[str]) -> str: return path.rsplit("/", 1)[0] if "/" in path else "" -def _github_url(number: int, repo: Optional[str], env: Mapping[str, str]) -> Optional[str]: +def _github_url(number: int, repo: str | None, env: Mapping[str, str]) -> str | None: repository_url = _github_repository_url(repo, env) return f"{repository_url}/pull/{number}" if repository_url else None -def _gitlab_url(number: int, repo: Optional[str], env: Mapping[str, str]) -> Optional[str]: +def _gitlab_url(number: int, repo: str | None, env: Mapping[str, str]) -> str | None: project_url = _gitlab_project_url(repo, env) return f"{project_url}/-/merge_requests/{number}" if project_url else None -def _azure_url(number: int, env: Mapping[str, str], github_pr: bool) -> Optional[str]: +def _azure_url(number: int, env: Mapping[str, str], github_pr: bool) -> str | None: repository_url = _repository_url( - env.get("BUILD_REPOSITORY_URI") or - env.get("SYSTEM_PULLREQUEST_SOURCEREPOSITORYURI") + env.get("BUILD_REPOSITORY_URI") or env.get("SYSTEM_PULLREQUEST_SOURCEREPOSITORYURI") ) if not repository_url: return None @@ -167,10 +156,10 @@ def _azure_url(number: int, env: Mapping[str, str], github_pr: bool) -> Optional def resolve_pull_request_context( integration_type: str, configured_number, - repo: Optional[str], + repo: str | None, *, configured_explicit: bool = False, - env: Optional[Mapping[str, str]] = None, + env: Mapping[str, str] | None = None, ) -> PullRequestContext: """Resolve PR metadata without making provider API calls. @@ -187,10 +176,9 @@ def resolve_pull_request_context( elif provider == "gitlab": number = parse_pull_request_number(environment.get("CI_MERGE_REQUEST_IID")) elif provider == "azure": - number = ( - parse_pull_request_number(environment.get("SYSTEM_PULLREQUEST_PULLREQUESTNUMBER")) or - parse_pull_request_number(environment.get("SYSTEM_PULLREQUEST_PULLREQUESTID")) - ) + number = parse_pull_request_number( + environment.get("SYSTEM_PULLREQUEST_PULLREQUESTNUMBER") + ) or parse_pull_request_number(environment.get("SYSTEM_PULLREQUEST_PULLREQUESTID")) if not number: return PullRequestContext() diff --git a/socketsecurity/core/resource_utils.py b/socketsecurity/core/resource_utils.py index dc78c1b8..86757d9c 100644 --- a/socketsecurity/core/resource_utils.py +++ b/socketsecurity/core/resource_utils.py @@ -1,12 +1,14 @@ """ System resource utilities for the Socket Security CLI. """ + import logging # The resource module is only available on Unix-like systems resource_available = False try: import resource + resource_available = True except ImportError: # On Windows, the resource module is not available @@ -51,7 +53,7 @@ def check_file_count_against_ulimit(file_count, buffer_size=100): return { "can_check": False, "error": "Could not determine file descriptor limit", - "safe_to_process": True # Assume safe if we can't check + "safe_to_process": True, # Assume safe if we can't check } available_fds = soft_limit - buffer_size @@ -66,5 +68,7 @@ def check_file_count_against_ulimit(file_count, buffer_size=100): "would_exceed": would_exceed, "safe_to_process": not would_exceed, "buffer_size": buffer_size, - "recommendation": "Consider processing files in batches or increasing ulimit" if would_exceed else "Safe to process all files" + "recommendation": "Consider processing files in batches or increasing ulimit" + if would_exceed + else "Safe to process all files", } diff --git a/socketsecurity/core/scm/base.py b/socketsecurity/core/scm/base.py index 715f6de5..b67ae2d1 100644 --- a/socketsecurity/core/scm/base.py +++ b/socketsecurity/core/scm/base.py @@ -1,7 +1,7 @@ from abc import ABC, abstractmethod -from typing import Dict -from ..classes import Comment +from socketsecurity.core.classes import Comment + from .client import ScmClient @@ -12,26 +12,22 @@ def __init__(self, client: ScmClient): @abstractmethod def check_event_type(self) -> str: """Determine the type of event (push, pr, comment)""" - pass @abstractmethod def add_socket_comments( self, security_comment: str, overview_comment: str, - comments: Dict[str, Comment], + comments: dict[str, Comment], new_security_comment: bool = True, - new_overview_comment: bool = True + new_overview_comment: bool = True, ) -> None: """Add or update comments on PR""" - pass @abstractmethod - def get_comments_for_pr(self, repo: str, pr: str) -> Dict[str, Comment]: + def get_comments_for_pr(self, repo: str, pr: str) -> dict[str, Comment]: """Get existing comments for PR""" - pass @abstractmethod - def remove_comment_alerts(self, comments: Dict[str, Comment]) -> None: + def remove_comment_alerts(self, comments: dict[str, Comment]) -> None: """Process and remove alerts from comments""" - pass diff --git a/socketsecurity/core/scm/client.py b/socketsecurity/core/scm/client.py index 08769f3f..b7f0dc5f 100644 --- a/socketsecurity/core/scm/client.py +++ b/socketsecurity/core/scm/client.py @@ -1,9 +1,7 @@ from abc import abstractmethod -from typing import Dict from socketsecurity import USER_AGENT - -from ..cli_client import CliClient +from socketsecurity.core.cli_client import CliClient class ScmClient(CliClient): @@ -12,75 +10,52 @@ def __init__(self, token: str, api_url: str): self.api_url = api_url @abstractmethod - def get_headers(self) -> Dict: + def get_headers(self) -> dict: """Each SCM implements its own auth headers""" - pass def request(self, path: str, **kwargs): """Override base request to use SCM-specific headers and base_url""" - headers = kwargs.pop('headers', None) or self.get_headers() - return super().request( - path=path, - headers=headers, - base_url=self.api_url, - **kwargs - ) + headers = kwargs.pop("headers", None) or self.get_headers() + return super().request(path=path, headers=headers, base_url=self.api_url, **kwargs) + class GithubClient(ScmClient): - def get_headers(self) -> Dict: - return { - 'Authorization': f"Bearer {self.token}", - 'User-Agent': USER_AGENT, - "accept": "application/json" - } + def get_headers(self) -> dict: + return {"Authorization": f"Bearer {self.token}", "User-Agent": USER_AGENT, "accept": "application/json"} + class GitlabClient(ScmClient): - def get_headers(self) -> Dict: + def get_headers(self) -> dict: """ Determine the appropriate authentication headers for GitLab API. Uses the same logic as GitlabConfig._get_auth_headers() """ return self._get_gitlab_auth_headers(self.token) - + @staticmethod def _get_gitlab_auth_headers(token: str) -> dict: """ Determine the appropriate authentication headers for GitLab API. - + GitLab supports two authentication patterns: 1. Bearer token (OAuth 2.0 tokens, personal access tokens with api scope) 2. Private token (personal access tokens) """ import os - - base_headers = { - 'User-Agent': USER_AGENT, - "accept": "application/json" - } - + + base_headers = {"User-Agent": USER_AGENT, "accept": "application/json"} + # Check if this is a GitLab CI job token - if token == os.getenv('CI_JOB_TOKEN'): - return { - **base_headers, - 'Authorization': f"Bearer {token}" - } - + if token == os.getenv("CI_JOB_TOKEN"): + return {**base_headers, "Authorization": f"Bearer {token}"} + # Check for personal access token pattern - if token.startswith('glpat-'): - return { - **base_headers, - 'Authorization': f"Bearer {token}" - } - + if token.startswith("glpat-"): + return {**base_headers, "Authorization": f"Bearer {token}"} + # Check for OAuth token pattern (typically longer and alphanumeric) if len(token) > 40 and token.isalnum(): - return { - **base_headers, - 'Authorization': f"Bearer {token}" - } - + return {**base_headers, "Authorization": f"Bearer {token}"} + # Default to PRIVATE-TOKEN for other token types - return { - **base_headers, - 'PRIVATE-TOKEN': f"{token}" - } + return {**base_headers, "PRIVATE-TOKEN": f"{token}"} diff --git a/socketsecurity/core/scm/github.py b/socketsecurity/core/scm/github.py index f5445f9b..66e9b7f3 100644 --- a/socketsecurity/core/scm/github.py +++ b/socketsecurity/core/scm/github.py @@ -16,14 +16,13 @@ # Reopening a PR or marking it ready can require a fresh check on the same commit. PULL_REQUEST_SCAN_ACTIONS = ("opened", "synchronize", "reopened", "ready_for_review") -HANDLED_EVENTS = ( - "push, workflow_dispatch and pull_request (scan); issue_comment (ignore commands)" -) +HANDLED_EVENTS = "push, workflow_dispatch and pull_request (scan); issue_comment (ignore commands)" @dataclass class GithubConfig: """Configuration from GitHub environment variables""" + sha: str api_url: str ref_type: str @@ -48,65 +47,57 @@ def _repository_from_buildkite() -> tuple[str, str]: """Return ``(owner, repository)`` from Buildkite's Git repository URL.""" # Comments and statuses belong to the pipeline/base repository, not a # contributor's fork from BUILDKITE_PULL_REQUEST_REPO. - _, repository_path = parse_git_remote( - os.getenv("BUILDKITE_REPO") or os.getenv("BUILDKITE_PULL_REQUEST_REPO") - ) + _, repository_path = parse_git_remote(os.getenv("BUILDKITE_REPO") or os.getenv("BUILDKITE_PULL_REQUEST_REPO")) parts = repository_path.split("/") if repository_path else [] if len(parts) < 2: return "", "" return parts[-2], parts[-1] @classmethod - def from_env(cls, pr_number: Optional[str] = None) -> 'GithubConfig': + def from_env(cls, pr_number: Optional[str] = None) -> "GithubConfig": """Create config from environment variables with optional overrides""" - token = os.getenv('GH_API_TOKEN') + token = os.getenv("GH_API_TOKEN") if not token: raise InfrastructureError("Unable to get Github API Token from GH_API_TOKEN") - + is_buildkite = os.getenv("BUILDKITE") == "true" buildkite_pr = os.getenv("BUILDKITE_PULL_REQUEST") - is_buildkite_pr = bool( - is_buildkite - and buildkite_pr - and buildkite_pr.casefold() != "false" - ) + is_buildkite_pr = bool(is_buildkite and buildkite_pr and buildkite_pr.casefold() != "false") # Use explicit/GitHub-compatible values first, then native Buildkite PR context. - pr_number = pr_number or os.getenv('PR_NUMBER') + pr_number = pr_number or os.getenv("PR_NUMBER") if not pr_number and is_buildkite_pr: pr_number = buildkite_pr - + # Add debug logging - sha = os.getenv('GITHUB_SHA') or ( - os.getenv("BUILDKITE_COMMIT", "") if is_buildkite else "" - ) + sha = os.getenv("GITHUB_SHA") or (os.getenv("BUILDKITE_COMMIT", "") if is_buildkite else "") log.debug(f"Loading GitHub integration SHA: {sha}") - event_action = os.getenv('EVENT_ACTION', None) + event_action = os.getenv("EVENT_ACTION", None) if not event_action: - event_path = os.getenv('GITHUB_EVENT_PATH') + event_path = os.getenv("GITHUB_EVENT_PATH") if event_path and os.path.exists(event_path): - with open(event_path, 'r') as f: + with open(event_path) as f: event = json.load(f) - event_action = event.get('action') + event_action = event.get("action") if not event_action and is_buildkite_pr: # Buildkite provides the current PR state, not the originating # GitHub webhook action. A running PR build is equivalent to the # supported synchronize path for comment updates. event_action = "synchronize" - repository = os.getenv('GITHUB_REPOSITORY', '') - owner = os.getenv('GITHUB_REPOSITORY_OWNER', '') - if '/' in repository: - owner = repository.split('/')[0] - repository = repository.split('/')[1] + repository = os.getenv("GITHUB_REPOSITORY", "") + owner = os.getenv("GITHUB_REPOSITORY_OWNER", "") + if "/" in repository: + owner = repository.split("/")[0] + repository = repository.split("/")[1] elif is_buildkite: buildkite_owner, buildkite_repository = cls._repository_from_buildkite() owner = owner or buildkite_owner repository = repository or buildkite_repository - default_branch_env = os.getenv('DEFAULT_BRANCH') + default_branch_env = os.getenv("DEFAULT_BRANCH") # Consider the variable truthy if it exists and isn't explicitly 'false' if default_branch_env is not None: - is_default = default_branch_env.lower() != 'false' + is_default = default_branch_env.lower() != "false" elif is_buildkite: # Require a branch name: comparing two unset variables would otherwise report # every build as the default branch and overwrite the repository's baseline. @@ -119,44 +110,29 @@ def from_env(cls, pr_number: Optional[str] = None) -> 'GithubConfig': else: is_default = False - event_name = os.getenv('GITHUB_EVENT_NAME', '') + event_name = os.getenv("GITHUB_EVENT_NAME", "") if not event_name and is_buildkite: event_name = "pull_request" if is_buildkite_pr else "push" return cls( sha=sha, - api_url=os.getenv('GITHUB_API_URL') or ( - "https://api.github.com" if is_buildkite else "" - ), - ref_type=os.getenv('GITHUB_REF_TYPE') or ( - "branch" if is_buildkite else "" - ), + api_url=os.getenv("GITHUB_API_URL") or ("https://api.github.com" if is_buildkite else ""), + ref_type=os.getenv("GITHUB_REF_TYPE") or ("branch" if is_buildkite else ""), event_name=event_name, - workspace=os.getenv('GITHUB_WORKSPACE') or ( - os.getenv("BUILDKITE_BUILD_CHECKOUT_PATH", "") if is_buildkite else "" - ), + workspace=os.getenv("GITHUB_WORKSPACE") + or (os.getenv("BUILDKITE_BUILD_CHECKOUT_PATH", "") if is_buildkite else ""), repository=repository, - ref_name=os.getenv('GITHUB_REF_NAME') or ( - os.getenv("BUILDKITE_BRANCH", "") if is_buildkite else "" - ), + ref_name=os.getenv("GITHUB_REF_NAME") or (os.getenv("BUILDKITE_BRANCH", "") if is_buildkite else ""), default_branch=is_default, is_default_branch=is_default, pr_number=pr_number, - pr_name=os.getenv('PR_NAME'), - commit_message=os.getenv('COMMIT_MESSAGE') or ( - os.getenv("BUILDKITE_MESSAGE") if is_buildkite else None - ), - actor=os.getenv('GITHUB_ACTOR') or ( - os.getenv("BUILDKITE_BUILD_CREATOR", "") if is_buildkite else "" - ), - env=os.getenv('GITHUB_ENV', ''), + pr_name=os.getenv("PR_NAME"), + commit_message=os.getenv("COMMIT_MESSAGE") or (os.getenv("BUILDKITE_MESSAGE") if is_buildkite else None), + actor=os.getenv("GITHUB_ACTOR") or (os.getenv("BUILDKITE_BUILD_CREATOR", "") if is_buildkite else ""), + env=os.getenv("GITHUB_ENV", ""), token=token, owner=owner, event_action=event_action, - headers={ - 'Authorization': f"Bearer {token}", - 'User-Agent': USER_AGENT, - "accept": "application/json" - } + headers={"Authorization": f"Bearer {token}", "User-Agent": USER_AGENT, "accept": "application/json"}, ) @@ -186,7 +162,7 @@ def check_event_type(self) -> str: if not self.config.pr_number: return "main" return "diff" - elif event_name == "pull_request": + if event_name == "pull_request": action = (self.config.event_action or "").lower() if action in PULL_REQUEST_SCAN_ACTIONS: return "diff" @@ -239,22 +215,14 @@ def post_comment(self, body: str) -> None: path = f"repos/{self.config.owner}/{self.config.repository}/issues/{self.config.pr_number}/comments" payload = json.dumps({"body": body}) self.client.request( - path=path, - payload=payload, - method="POST", - headers=self.config.headers, - base_url=self.config.api_url + path=path, payload=payload, method="POST", headers=self.config.headers, base_url=self.config.api_url ) def update_comment(self, body: str, comment_id: str) -> None: path = f"repos/{self.config.owner}/{self.config.repository}/issues/comments/{comment_id}" payload = json.dumps({"body": body}) self.client.request( - path=path, - payload=payload, - method="PATCH", - headers=self.config.headers, - base_url=self.config.api_url + path=path, payload=payload, method="PATCH", headers=self.config.headers, base_url=self.config.api_url ) def write_new_env(self, name: str, content: str) -> None: @@ -265,11 +233,7 @@ def write_new_env(self, name: str, content: str) -> None: def get_comments_for_pr(self) -> dict: log.debug(f"Getting comments for Repo {self.config.repository} for PR {self.config.pr_number}") path = f"repos/{self.config.owner}/{self.config.repository}/issues/{self.config.pr_number}/comments" - response = self.client.request( - path=path, - headers=self.config.headers, - base_url=self.config.api_url - ) + response = self.client.request(path=path, headers=self.config.headers, base_url=self.config.api_url) raw_comments = Comments.process_response(response) comments = {} @@ -298,10 +262,7 @@ def is_ignore_authorized(self, comment: Comment) -> bool: elif author in self._ignore_permission_cache: permission = self._ignore_permission_cache[author] else: - path = ( - f"repos/{self.config.owner}/{self.config.repository}/" - f"collaborators/{author}/permission" - ) + path = f"repos/{self.config.owner}/{self.config.repository}/collaborators/{author}/permission" try: response = self.client.request( path=path, @@ -309,30 +270,21 @@ def is_ignore_authorized(self, comment: Comment) -> bool: base_url=self.config.api_url, ) result = response.json() - if not isinstance(result, dict) or not isinstance( - result.get("permission"), str - ): + if not isinstance(result, dict) or not isinstance(result.get("permission"), str): log.warning("Unexpected GitHub repository permission response") permission = None else: - permission = ( - result["permission"].casefold() in self.WRITE_PERMISSIONS - ) + permission = result["permission"].casefold() in self.WRITE_PERMISSIONS except APIFailure as error: if getattr(error, "status_code", None) == 404: # The repository was readable when its comments were listed, # so a missing collaborator permission is a definitive denial. permission = False else: - log.warning( - "Could not read GitHub repository permission for " - f"{author}: {error}" - ) + log.warning(f"Could not read GitHub repository permission for {author}: {error}") permission = None except Exception as error: - log.warning( - f"Could not read GitHub repository permission for {author}: {error}" - ) + log.warning(f"Could not read GitHub repository permission for {author}: {error}") permission = None self._ignore_permission_cache[author] = permission @@ -358,7 +310,7 @@ def add_socket_comments( overview_comment: str, comments: dict, new_security_comment: bool = True, - new_overview_comment: bool = True + new_overview_comment: bool = True, ) -> None: if new_overview_comment: log.debug("New Dependency Overview comment") @@ -396,11 +348,7 @@ def post_reaction(self, comment_id: int) -> None: path = f"repos/{self.config.owner}/{self.config.repository}/issues/comments/{comment_id}/reactions" payload = json.dumps({"content": "+1"}) self.client.request( - path=path, - payload=payload, - method="POST", - headers=self.config.headers, - base_url=self.config.api_url + path=path, payload=payload, method="POST", headers=self.config.headers, base_url=self.config.api_url ) def comment_reaction_exists(self, comment_id: int) -> bool: diff --git a/socketsecurity/core/scm/gitlab.py b/socketsecurity/core/scm/gitlab.py index d661a897..3346d9f6 100644 --- a/socketsecurity/core/scm/gitlab.py +++ b/socketsecurity/core/scm/gitlab.py @@ -2,7 +2,6 @@ import os import sys from dataclasses import dataclass -from typing import Optional import requests from socketdev.exceptions import APIFailure @@ -14,16 +13,21 @@ from socketsecurity.exit_codes import InfrastructureError from socketsecurity.socketcli import CliClient +# GitLab API calls here are side-channel (MR settings, commit status); a hang +# must not wedge the pipeline the CLI is reporting into. +REQUEST_TIMEOUT_SECONDS = 30 + @dataclass class GitlabConfig: """Configuration from GitLab environment variables""" + commit_sha: str api_url: str project_dir: str - mr_source_branch: Optional[str] - mr_iid: Optional[str] - mr_project_id: Optional[str] + mr_source_branch: str | None + mr_iid: str | None + mr_project_id: str | None commit_message: str default_branch: str project_name: str @@ -35,96 +39,79 @@ class GitlabConfig: headers: dict @classmethod - def from_env(cls) -> 'GitlabConfig': - token = os.getenv('GITLAB_TOKEN') + def from_env(cls) -> "GitlabConfig": + token = os.getenv("GITLAB_TOKEN") if not token: raise InfrastructureError("Unable to get GitLab API Token from GITLAB_TOKEN") - project_name = os.getenv('CI_PROJECT_NAME', '') + project_name = os.getenv("CI_PROJECT_NAME", "") if "/" in project_name: project_name = project_name.rsplit("/")[1] - mr_source_branch = os.getenv('CI_MERGE_REQUEST_SOURCE_BRANCH_NAME') - default_branch = os.getenv('CI_DEFAULT_BRANCH', '') + mr_source_branch = os.getenv("CI_MERGE_REQUEST_SOURCE_BRANCH_NAME") + default_branch = os.getenv("CI_DEFAULT_BRANCH", "") # Determine which authentication pattern to use headers = cls._get_auth_headers(token) # Prefer source branch SHA (real commit) over CI_COMMIT_SHA which # may be a synthetic merge-result commit in merged-results pipelines. - commit_sha = ( - os.getenv('CI_MERGE_REQUEST_SOURCE_BRANCH_SHA') or - os.getenv('CI_COMMIT_SHA', '') - ) + commit_sha = os.getenv("CI_MERGE_REQUEST_SOURCE_BRANCH_SHA") or os.getenv("CI_COMMIT_SHA", "") return cls( commit_sha=commit_sha, - api_url=os.getenv('CI_API_V4_URL', ''), - project_dir=os.getenv('CI_PROJECT_DIR', ''), + api_url=os.getenv("CI_API_V4_URL", ""), + project_dir=os.getenv("CI_PROJECT_DIR", ""), mr_source_branch=mr_source_branch, - mr_iid=os.getenv('CI_MERGE_REQUEST_IID'), - mr_project_id=os.getenv('CI_MERGE_REQUEST_PROJECT_ID'), - commit_message=os.getenv('CI_COMMIT_MESSAGE', ''), + mr_iid=os.getenv("CI_MERGE_REQUEST_IID"), + mr_project_id=os.getenv("CI_MERGE_REQUEST_PROJECT_ID"), + commit_message=os.getenv("CI_COMMIT_MESSAGE", ""), default_branch=default_branch, project_name=project_name, - pipeline_source=os.getenv('CI_PIPELINE_SOURCE', ''), - commit_author=os.getenv('CI_COMMIT_AUTHOR', ''), + pipeline_source=os.getenv("CI_PIPELINE_SOURCE", ""), + commit_author=os.getenv("CI_COMMIT_AUTHOR", ""), token=token, repository=project_name, is_default_branch=(mr_source_branch == default_branch if mr_source_branch else False), - headers=headers + headers=headers, ) @staticmethod def _get_auth_headers(token: str) -> dict: """ Determine the appropriate authentication headers for GitLab API. - + GitLab supports two authentication patterns: 1. Bearer token (OAuth 2.0 tokens, personal access tokens with api scope) 2. Private token (personal access tokens) - + Logic for token type determination: - CI_JOB_TOKEN: Always use Bearer (GitLab CI job token) - Tokens starting with 'glpat-': Personal access tokens, try Bearer first - OAuth tokens: Use Bearer - Other tokens: Use PRIVATE-TOKEN as fallback """ - base_headers = { - 'User-Agent': USER_AGENT, - "accept": "application/json" - } - + base_headers = {"User-Agent": USER_AGENT, "accept": "application/json"} + # Check if this is a GitLab CI job token - if token == os.getenv('CI_JOB_TOKEN'): + if token == os.getenv("CI_JOB_TOKEN"): log.debug("Using Bearer authentication for GitLab CI job token") - return { - **base_headers, - 'Authorization': f"Bearer {token}" - } - + return {**base_headers, "Authorization": f"Bearer {token}"} + # Check for personal access token pattern - if token.startswith('glpat-'): + if token.startswith("glpat-"): log.debug("Using Bearer authentication for GitLab personal access token") - return { - **base_headers, - 'Authorization': f"Bearer {token}" - } - + return {**base_headers, "Authorization": f"Bearer {token}"} + # Check for OAuth token pattern (typically longer and alphanumeric) if len(token) > 40 and token.isalnum(): log.debug("Using Bearer authentication for potential OAuth token") - return { - **base_headers, - 'Authorization': f"Bearer {token}" - } - + return {**base_headers, "Authorization": f"Bearer {token}"} + # Default to PRIVATE-TOKEN for other token types log.debug("Using PRIVATE-TOKEN authentication for GitLab token") - return { - **base_headers, - 'PRIVATE-TOKEN': f"{token}" - } + return {**base_headers, "PRIVATE-TOKEN": f"{token}"} + class Gitlab: # GitLab access levels: 30 Developer, 40 Maintainer, 50 Owner. Reporter (20) @@ -138,7 +125,7 @@ class Gitlab: def __init__( self, client: CliClient, - config: Optional[GitlabConfig] = None, + config: GitlabConfig | None = None, ignore_authorization: str = "enforce", ): self.config = config or GitlabConfig.from_env() @@ -146,7 +133,7 @@ def __init__( self.ignore_authorization = ignore_authorization # None until the first ignore comment forces a lookup; stays None when the # members API cannot be read, which is the "undetermined" state. - self._member_access: Optional[dict] = None + self._member_access: dict | None = None self._member_lookup_attempted = False def _request_with_fallback(self, **kwargs): @@ -167,13 +154,13 @@ def _request_with_fallback(self, **kwargs): raise log.debug("Authentication failed with initial headers, trying fallback method") - original_headers = kwargs.get('headers', self.config.headers) + original_headers = kwargs.get("headers", self.config.headers) fallback_headers = self._get_fallback_headers(original_headers) if not fallback_headers or fallback_headers == original_headers: raise log.debug("Retrying request with fallback authentication method") - kwargs['headers'] = fallback_headers + kwargs["headers"] = fallback_headers return self.client.request(**kwargs) def _get_fallback_headers(self, original_headers: dict) -> dict: @@ -181,39 +168,30 @@ def _get_fallback_headers(self, original_headers: dict) -> dict: Generate fallback authentication headers. If using Bearer, fallback to PRIVATE-TOKEN and vice versa. """ - base_headers = { - 'User-Agent': USER_AGENT, - "accept": "application/json" - } - + base_headers = {"User-Agent": USER_AGENT, "accept": "application/json"} + # If currently using Bearer, try PRIVATE-TOKEN - if 'Authorization' in original_headers and 'Bearer' in original_headers['Authorization']: + if "Authorization" in original_headers and "Bearer" in original_headers["Authorization"]: log.debug("Falling back from Bearer to PRIVATE-TOKEN authentication") - return { - **base_headers, - 'PRIVATE-TOKEN': f"{self.config.token}" - } - + return {**base_headers, "PRIVATE-TOKEN": f"{self.config.token}"} + # If currently using PRIVATE-TOKEN, try Bearer - elif 'PRIVATE-TOKEN' in original_headers: + if "PRIVATE-TOKEN" in original_headers: log.debug("Falling back from PRIVATE-TOKEN to Bearer authentication") - return { - **base_headers, - 'Authorization': f"Bearer {self.config.token}" - } - + return {**base_headers, "Authorization": f"Bearer {self.config.token}"} + # No fallback available return {} def check_event_type(self) -> str: pipeline_source = self.config.pipeline_source.lower() - if pipeline_source in ["web", 'merge_request_event', "push", "api", 'pipeline']: + if pipeline_source in ["web", "merge_request_event", "push", "api", "pipeline"]: if not self.config.mr_iid: return "main" return "diff" - elif pipeline_source == "issue_comment": + if pipeline_source == "issue_comment": return "comment" - elif not pipeline_source: + if not pipeline_source: log.warning( "Could not determine the GitLab pipeline source: CI_PIPELINE_SOURCE is " "not set. No scan ran; exiting 0. Set CI_PIPELINE_SOURCE when running " @@ -233,35 +211,25 @@ def post_comment(self, body: str) -> None: path = f"projects/{self.config.mr_project_id}/merge_requests/{self.config.mr_iid}/notes" payload = {"body": body} self._request_with_fallback( - path=path, - payload=payload, - method="POST", - headers=self.config.headers, - base_url=self.config.api_url + path=path, payload=payload, method="POST", headers=self.config.headers, base_url=self.config.api_url ) def update_comment(self, body: str, comment_id: str) -> None: path = f"projects/{self.config.mr_project_id}/merge_requests/{self.config.mr_iid}/notes/{comment_id}" payload = {"body": body} self._request_with_fallback( - path=path, - payload=payload, - method="PUT", - headers=self.config.headers, - base_url=self.config.api_url + path=path, payload=payload, method="PUT", headers=self.config.headers, base_url=self.config.api_url ) def has_thumbsup_reaction(self, comment_id: int) -> bool: """Best-effort check for 'thumbsup' award emoji on a MR note.""" if not self.config.mr_project_id or not self.config.mr_iid: return False - path = f"projects/{self.config.mr_project_id}/merge_requests/{self.config.mr_iid}/notes/{comment_id}/award_emoji" + path = ( + f"projects/{self.config.mr_project_id}/merge_requests/{self.config.mr_iid}/notes/{comment_id}/award_emoji" + ) try: - response = self._request_with_fallback( - path=path, - headers=self.config.headers, - base_url=self.config.api_url - ) + response = self._request_with_fallback(path=path, headers=self.config.headers, base_url=self.config.api_url) for emoji in response.json(): if emoji.get("name") == "thumbsup": return True @@ -272,11 +240,7 @@ def has_thumbsup_reaction(self, comment_id: int) -> bool: def get_comments_for_pr(self) -> dict: log.debug(f"Getting Gitlab comments for Repo {self.config.repository} for PR {self.config.mr_iid}") path = f"projects/{self.config.mr_project_id}/merge_requests/{self.config.mr_iid}/notes" - response = self._request_with_fallback( - path=path, - headers=self.config.headers, - base_url=self.config.api_url - ) + response = self._request_with_fallback(path=path, headers=self.config.headers, base_url=self.config.api_url) raw_comments = Comments.process_response(response) comments = {} if "message" not in raw_comments: @@ -289,7 +253,7 @@ def get_comments_for_pr(self) -> dict: gate = None if self.ignore_authorization == "off" else self.is_ignore_authorized return Comments.check_for_socket_comments(comments, gate) - def _load_member_access(self) -> Optional[dict]: + def _load_member_access(self) -> dict | None: """Map project member user id -> access level, or None if unreadable. ``members/all`` is used rather than a per-user lookup because it answers @@ -306,15 +270,10 @@ def _load_member_access(self) -> Optional[dict]: access: dict = {} for page in range(1, Gitlab.MEMBER_PAGE_LIMIT + 1): - path = ( - f"projects/{self.config.mr_project_id}/members/all" - f"?per_page={Gitlab.MEMBER_PAGE_SIZE}&page={page}" - ) + path = f"projects/{self.config.mr_project_id}/members/all?per_page={Gitlab.MEMBER_PAGE_SIZE}&page={page}" try: response = self._request_with_fallback( - path=path, - headers=self.config.headers, - base_url=self.config.api_url + path=path, headers=self.config.headers, base_url=self.config.api_url ) members = response.json() except Exception as error: @@ -370,12 +329,12 @@ def is_ignore_authorized(self, comment: Comment) -> bool: return access.get(user_id, 0) >= Gitlab.MIN_IGNORE_ACCESS_LEVEL def add_socket_comments( - self, - security_comment: str, - overview_comment: str, - comments: dict, - new_security_comment: bool = True, - new_overview_comment: bool = True + self, + security_comment: str, + overview_comment: str, + comments: dict, + new_security_comment: bool = True, + new_overview_comment: bool = True, ) -> None: existing_overview_comment = comments.get("overview") existing_security_comment = comments.get("security") @@ -408,6 +367,7 @@ def enable_merge_pipeline_check(self) -> None: url, json={"only_allow_merge_if_pipeline_succeeds": True}, headers=self.config.headers, + timeout=REQUEST_TIMEOUT_SECONDS, ) if resp.status_code == 401: fallback = self._get_fallback_headers(self.config.headers) @@ -416,6 +376,7 @@ def enable_merge_pipeline_check(self) -> None: url, json={"only_allow_merge_if_pipeline_succeeds": True}, headers=fallback, + timeout=REQUEST_TIMEOUT_SECONDS, ) if resp.status_code >= 400: log.error(f"GitLab enable merge check API {resp.status_code}: {resp.text}") @@ -424,7 +385,7 @@ def enable_merge_pipeline_check(self) -> None: except Exception as e: log.error(f"Failed to enable merge pipeline check: {e}") - def set_commit_status(self, state: str, description: str, target_url: str = '') -> None: + def set_commit_status(self, state: str, description: str, target_url: str = "") -> None: """Post a commit status to GitLab. state should be 'success' or 'failed'. Uses requests.post with json= directly because CliClient.request sends @@ -445,11 +406,11 @@ def set_commit_status(self, state: str, description: str, target_url: str = '') payload["target_url"] = target_url try: log.debug(f"Posting commit status to {url}") - resp = requests.post(url, json=payload, headers=self.config.headers) + resp = requests.post(url, json=payload, headers=self.config.headers, timeout=REQUEST_TIMEOUT_SECONDS) if resp.status_code == 401: fallback = self._get_fallback_headers(self.config.headers) if fallback: - resp = requests.post(url, json=payload, headers=fallback) + resp = requests.post(url, json=payload, headers=fallback, timeout=REQUEST_TIMEOUT_SECONDS) if resp.status_code >= 400: log.error(f"GitLab commit status API {resp.status_code}: {resp.text}") resp.raise_for_status() @@ -461,7 +422,9 @@ def post_thumbsup_reaction(self, comment_id: int) -> None: """Best-effort: add 'thumbsup' award emoji to a MR note.""" if not self.config.mr_project_id or not self.config.mr_iid: return - path = f"projects/{self.config.mr_project_id}/merge_requests/{self.config.mr_iid}/notes/{comment_id}/award_emoji" + path = ( + f"projects/{self.config.mr_project_id}/merge_requests/{self.config.mr_iid}/notes/{comment_id}/award_emoji" + ) try: headers = {**self.config.headers, "Content-Type": "application/json"} self._request_with_fallback( @@ -469,7 +432,7 @@ def post_thumbsup_reaction(self, comment_id: int) -> None: payload=json.dumps({"name": "thumbsup"}), method="POST", headers=headers, - base_url=self.config.api_url + base_url=self.config.api_url, ) except Exception as e: log.debug(f"Could not add thumbsup emoji to note {comment_id} (best effort): {e}") diff --git a/socketsecurity/core/scm_comments.py b/socketsecurity/core/scm_comments.py index 0ddb9225..e136b08d 100644 --- a/socketsecurity/core/scm_comments.py +++ b/socketsecurity/core/scm_comments.py @@ -1,6 +1,6 @@ import json import re -from typing import Callable, Optional +from collections.abc import Callable from requests import Response @@ -43,15 +43,11 @@ def remove_alerts(comments: dict, new_alerts: list) -> list: alert: Issue if ignore_all: break + if any(Comments.matches_issue(alert, name, version) for name, version in ignore_commands): + log.info(f"Alerts for {alert.pkg_name}@{alert.pkg_version} ignored") else: - if any( - Comments.matches_issue(alert, name, version) - for name, version in ignore_commands - ): - log.info(f"Alerts for {alert.pkg_name}@{alert.pkg_version} ignored") - else: - log.info(f"Adding alert {alert.type} for {alert.pkg_name}@{alert.pkg_version}") - alerts.append(alert) + log.info(f"Adding alert {alert.type} for {alert.pkg_name}@{alert.pkg_version}") + alerts.append(alert) return alerts @staticmethod @@ -91,10 +87,7 @@ def matches_issue(alert: Issue, name: str, version: str) -> bool: ) @staticmethod - def is_ignore( - pkg_name: str, pkg_version: str, name: str, version: str, - pkg_type: str = "" - ) -> bool: + def is_ignore(pkg_name: str, pkg_version: str, name: str, version: str, pkg_type: str = "") -> bool: """Match an alert's package against one parsed ignore command. Generated commands are ecosystem-qualified (``npm/lodash@4.17.21``) but @@ -114,7 +107,7 @@ def is_ignore( target_names = {name} if not pkg_type and "/" in name and not name.startswith("@"): target_names.add(name.split("/", 1)[1]) - return bool(package_names & target_names) and (pkg_version == version or version == "*") + return bool(package_names & target_names) and version in (pkg_version, "*") @staticmethod def is_heading_line(line) -> bool: @@ -148,7 +141,7 @@ def process_security_comment(comment: Comment, comments) -> str: return new_body @staticmethod - def parse_alert_table_row(line: str) -> Optional[tuple[str, str, str]]: + def parse_alert_table_row(line: str) -> tuple[str, str, str] | None: """Pull ``(ecosystem, package, version)`` out of a legacy alert table row. Returns None for any row that does not have the expected shape rather than @@ -176,19 +169,17 @@ def parse_alert_table_row(line: str) -> Optional[tuple[str, str, str]]: @staticmethod def process_original_security_comment( - comment: Comment, - ignore_all: bool, - ignore_commands: list[tuple[str, str]] + comment: Comment, ignore_all: bool, ignore_commands: list[tuple[str, str]] ) -> str: start = False lines = [] kept_alert = False - for line in comment.body_list: - line = line.strip() + for raw_line in comment.body_list: + line = raw_line.strip() if "start-socket-alerts-table" in line: start = True lines.append(line) - elif start and "end-socket-alerts-table" not in line and not Comments.is_heading_line(line) and line != '': + elif start and "end-socket-alerts-table" not in line and not Comments.is_heading_line(line) and line != "": parsed = Comments.parse_alert_table_row(line) # ignore_all has to be checked outside the loop: an ignore-all # comment produces no ignore_commands, so a loop-internal check @@ -220,9 +211,7 @@ def process_original_security_comment( @staticmethod def process_updated_security_comment( - comment: Comment, - ignore_all: bool, - ignore_commands: list[tuple[str, str]] + comment: Comment, ignore_all: bool, ignore_commands: list[tuple[str, str]] ) -> str: """ Processes an updated security comment containing an HTML table with alert sections. @@ -241,7 +230,8 @@ def process_updated_security_comment( # truncated comment still has undisplayed findings unless ignore-all was # explicitly requested, even after its last visible row is removed. has_undisplayed_alerts = not ignore_all and any( - line.strip() in ( + line.strip() + in ( Messages.NEW_ALERTS_TRUNCATED_MARKER, Messages.EXISTING_ALERTS_TRUNCATED_MARKER, ) @@ -249,10 +239,9 @@ def process_updated_security_comment( ) # Loop through the comment lines - for line in comment.body_list: - # Match on the stripped line but keep the original, so the markup is - # rewritten with the same indentation it was generated with. - line = line.rstrip("\r") + for raw_line in comment.body_list: + # Preserve indentation when rewriting the markup. + line = raw_line.rstrip("\r") stripped = line.strip() # Detect the start of an alert section @@ -316,7 +305,7 @@ def extract_alert_details_from_row(row: str, ignore_all: bool, ignore_commands: # Find the relevant element to extract package information start_index = row.index("") end_index = row.index("") - summary_content = row[start_index + 9:end_index] # Extract content between tags + summary_content = row[start_index + 9 : end_index] # Extract content between tags # Example: "npm/malicious-package@1.0.0 - Known Malware Alert" pkg_info, _ = summary_content.split(" - ", 1) @@ -334,12 +323,8 @@ def extract_alert_details_from_row(row: str, ignore_all: bool, ignore_commands: return pkg_name, pkg_version, ignore - @staticmethod - def check_for_socket_comments( - comments: dict, - is_authorized: Optional[Callable[[Comment], bool]] = None - ): + def check_for_socket_comments(comments: dict, is_authorized: Callable[[Comment], bool] | None = None): """Bucket a pull request's comments into the ones the CLI acts on. ``is_authorized`` gates the ignore bucket, and is the only place that gate diff --git a/socketsecurity/core/socket_config.py b/socketsecurity/core/socket_config.py index 1089a530..68becfe8 100644 --- a/socketsecurity/core/socket_config.py +++ b/socketsecurity/core/socket_config.py @@ -1,6 +1,6 @@ import os from dataclasses import dataclass, field -from typing import List, Optional, Set +from typing import Optional from urllib.parse import urlparse from socketdev.core.issues import AllIssues @@ -8,30 +8,40 @@ from socketsecurity import __version__ default_exclude_dirs = { - "node_modules", "bower_components", "jspm_packages", # JS/TS - "__pycache__", ".venv", "venv", "build", "dist", # Python - ".tox", ".mypy_cache", ".pytest_cache", "*.egg-info", - "vendor" + "node_modules", + "bower_components", + "jspm_packages", # JS/TS + "__pycache__", + ".venv", + "venv", + "build", + "dist", # Python + ".tox", + ".mypy_cache", + ".pytest_cache", + "*.egg-info", + "vendor", } # Subset of default_exclude_dirs that hold installed JS/TS modules. Re-included as a group # by --include-module-folders (see CliConfig.include_module_folders). module_folder_dirs = {"node_modules", "bower_components", "jspm_packages"} + @dataclass class SocketConfig: api_key: str api_url: str = os.getenv("BASE_API_URL", "https://api.socket.dev/v0") timeout: int = 1200 allow_unverified_ssl: bool = False - org_id: Optional[str] = None - org_slug: Optional[str] = None - full_scan_path: Optional[str] = None - repository_path: Optional[str] = None - repo_visibility: Optional[str] = 'private' - all_issues: Optional['AllIssues'] = None - excluded_dirs: Set[str] = field(default_factory=lambda: default_exclude_dirs) - excluded_ecosystems: List[str] = field(default_factory=lambda: []) + org_id: str | None = None + org_slug: str | None = None + full_scan_path: str | None = None + repository_path: str | None = None + repo_visibility: str | None = "private" + all_issues: Optional["AllIssues"] = None + excluded_dirs: set[str] = field(default_factory=lambda: default_exclude_dirs) + excluded_ecosystems: list[str] = field(default_factory=list) version: str = __version__ def __post_init__(self): @@ -55,10 +65,10 @@ def _validate_api_url(url: str) -> None: parsed = urlparse(url) if not all([parsed.scheme, parsed.netloc]): raise ValueError("Invalid URL format") - if parsed.scheme != "https" and os.getenv("RUN_ENVIRONMENT", 'prod') != "dev": + if parsed.scheme != "https" and os.getenv("RUN_ENVIRONMENT", "prod") != "dev": raise ValueError("API URL must use HTTPS") except Exception as e: - raise ValueError(f"Invalid API URL: {str(e)}") + raise ValueError(f"Invalid API URL: {e!s}") from e def update_org_details(self, org_id: str, org_slug: str) -> None: """Update organization details and related paths""" @@ -67,4 +77,3 @@ def update_org_details(self, org_id: str, org_slug: str) -> None: base_path = f"orgs/{org_slug}" self.full_scan_path = f"{base_path}/full-scans" self.repository_path = f"{base_path}/repos" - diff --git a/socketsecurity/core/streaming.py b/socketsecurity/core/streaming.py index e6910b44..21cd42aa 100644 --- a/socketsecurity/core/streaming.py +++ b/socketsecurity/core/streaming.py @@ -14,7 +14,6 @@ import logging import time -from typing import Optional from .cli_client import CliClient from .cli_run import finalize_cli_run, register_cli_run @@ -29,7 +28,7 @@ def __init__( cli_logger: logging.Logger, sdk_logger: logging.Logger, client_version: str, - upload_logs: Optional[bool], + upload_logs: bool | None, enable_debug: bool, ): self._client = client @@ -38,15 +37,15 @@ def __init__( self._upload_logs = upload_logs self._enable_debug = enable_debug - self._run_id: Optional[str] = None - self._report_run_id: Optional[str] = None - self._uploader: Optional[BatchedLogUploader] = None - self._upload_handler: Optional[UploadingLogHandler] = None - self._terminal_handler: Optional[logging.StreamHandler] = None + self._run_id: str | None = None + self._report_run_id: str | None = None + self._uploader: BatchedLogUploader | None = None + self._upload_handler: UploadingLogHandler | None = None + self._terminal_handler: logging.StreamHandler | None = None self._saved_levels: tuple = () self._saved_propagate: tuple = () - def set_report_run_id(self, report_run_id: Optional[str]) -> None: + def set_report_run_id(self, report_run_id: str | None) -> None: self._report_run_id = report_run_id def __enter__(self) -> "StreamingLogs": @@ -57,10 +56,7 @@ def __enter__(self) -> "StreamingLogs": upload_logs=self._upload_logs, ) cli_logger = self._loggers[0] - cli_logger.info( - "CLI run registration completed in " - f"{time.perf_counter() - registration_start:.2f}s" - ) + cli_logger.info(f"CLI run registration completed in {time.perf_counter() - registration_start:.2f}s") if not self._run_id: cli_logger.debug("server log streaming not active for this run") return self @@ -101,7 +97,7 @@ def __exit__(self, exc_type, exc_val, exc_tb) -> bool: ) for lg in self._loggers: lg.removeHandler(self._terminal_handler) - for lg, level, propagate in zip(self._loggers, self._saved_levels, self._saved_propagate): + for lg, level, propagate in zip(self._loggers, self._saved_levels, self._saved_propagate, strict=False): lg.setLevel(level) lg.propagate = propagate return False diff --git a/socketsecurity/core/tools/reachability.py b/socketsecurity/core/tools/reachability.py index f177f1fd..a100aaae 100644 --- a/socketsecurity/core/tools/reachability.py +++ b/socketsecurity/core/tools/reachability.py @@ -9,8 +9,9 @@ import sys import tarfile import tempfile +from collections.abc import Mapping from dataclasses import dataclass -from typing import Any, Dict, Final, List, Mapping, Optional +from typing import Any, Final, Optional from urllib.parse import unquote, urlsplit import requests @@ -91,24 +92,18 @@ class _CoanaMirror: base_url: str @classmethod - def parse(cls, value: Optional[str]) -> Optional["_CoanaMirror"]: + def parse(cls, value: str | None) -> Optional["_CoanaMirror"]: """The mirror ``value`` names, or None when it is unset or empty.""" if not value: return None try: parts = urlsplit(value) # Raises ValueError for an invalid port. - parts.port + _ = parts.port except ValueError: parts = None # urlsplit drops a bare "?" or "#". - if ( - parts is None - or parts.scheme not in ("http", "https") - or not parts.hostname - or "?" in value - or "#" in value - ): + if parts is None or parts.scheme not in ("http", "https") or not parts.hostname or "?" in value or "#" in value: # The value may carry credentials. raise Exception("SOCKET_COANA_MIRROR_URL must be an http or https URL without a query or fragment.") return cls(value if value.endswith("/") else f"{value}/") @@ -117,9 +112,7 @@ def download_url(self, signed_url: str) -> str: """Where to download ``signed_url`` from. The query, which holds the signature, is kept.""" rest = signed_url.removeprefix(_COANA_BUCKET_URL) # A dot segment could climb out of the bucket, or out of the mirror's base URL. - if rest == signed_url or any( - unquote(segment) in (".", "..") for segment in rest.partition("?")[0].split("/") - ): + if rest == signed_url or any(unquote(segment) in (".", "..") for segment in rest.partition("?")[0].split("/")): raise Exception( f"Socket provided the Coana CLI at {signed_url.partition('?')[0]}, " f"outside {_COANA_BUCKET_URL}, which SOCKET_COANA_MIRROR_URL mirrors." @@ -148,25 +141,25 @@ class ReachabilityAnalyzer: def __init__(self, client: CliClient): self.client = client - def run_reachability_analysis( + def run_reachability_analysis( # noqa: C901, PLR0913 self, org_slug: str, target_directory: str, tar_hash: str, output_path: str = ".socket.facts.json", - timeout: Optional[str] = None, - memory_limit: Optional[str] = None, - ecosystems: Optional[List[str]] = None, - exclude_paths: Optional[List[str]] = None, - min_severity: Optional[str] = None, + timeout: str | None = None, + memory_limit: str | None = None, + ecosystems: list[str] | None = None, + exclude_paths: list[str] | None = None, + min_severity: str | None = None, skip_cache: bool = False, disable_analytics: bool = False, detailed_analysis_log_file: bool = False, - repo_name: Optional[str] = None, - branch_name: Optional[str] = None, - version: Optional[str] = None, - concurrency: Optional[int] = None, - additional_params: Optional[List[str]] = None, + repo_name: str | None = None, + branch_name: str | None = None, + version: str | None = None, + concurrency: int | None = None, + additional_params: list[str] | None = None, enable_debug: bool = False, use_only_pregenerated_sboms: bool = False, continue_on_analysis_errors: bool = False, @@ -176,7 +169,7 @@ def run_reachability_analysis( reach_debug: bool = False, disable_external_tool_checks: bool = False, disable_dependency_downloads: bool = False, - ) -> Dict[str, Any]: + ) -> dict[str, Any]: """ Run reachability analysis. @@ -213,12 +206,8 @@ def run_reachability_analysis( # Add required arguments output_dir = str(pathlib.Path(output_path).parent) log.debug(f"output_dir: {output_dir}, output_path: {output_path}") - coana_args.extend([ - "--output-dir", output_dir, - "--socket-mode", output_path, - "--disable-report-submission" - ]) - + coana_args.extend(["--output-dir", output_dir, "--socket-mode", output_path, "--disable-report-submission"]) + # Add conditional arguments. timeout/memory_limit are forwarded verbatim; coana owns # unit parsing/validation (e.g. '90s', '8GB'). We coerce to str only for subprocess # safety โ€” config-file values can arrive as ints via argparse set_defaults. @@ -227,7 +216,7 @@ def run_reachability_analysis( if memory_limit is not None: coana_args.extend(["--memory-limit", str(memory_limit)]) - + if disable_analytics: coana_args.append("--disable-analytics-sharing") @@ -238,22 +227,22 @@ def run_reachability_analysis( coana_args.append("--print-analysis-log-file") coana_args.extend(["--run-without-docker", "--manifests-tar-hash", tar_hash]) - + if ecosystems: - coana_args.extend(["--purl-types"] + ecosystems) - + coana_args.extend(["--purl-types", *ecosystems]) + if exclude_paths: - coana_args.extend(["--exclude-dirs"] + exclude_paths) - + coana_args.extend(["--exclude-dirs", *exclude_paths]) + if min_severity: coana_args.extend(["--min-severity", min_severity]) - + if skip_cache: coana_args.append("--skip-cache-usage") - + if concurrency: coana_args.extend(["--concurrency", str(concurrency)]) - + if enable_debug: coana_args.append("-d") @@ -284,7 +273,7 @@ def run_reachability_analysis( # Add any additional parameters provided by the user if additional_params: coana_args.extend(additional_params) - + # Set up environment variables env = self._sanitize_coana_env(os.environ) @@ -314,10 +303,12 @@ def run_reachability_analysis( if self.client.config.allow_unverified_ssl: env["NODE_TLS_REJECT_UNAUTHORIZED"] = "0" - + # Execute coana log.info("Running reachability analysis...") - log.debug(f"Environment: SOCKET_ORG_SLUG={org_slug}, SOCKET_REPO_NAME={repo_name or 'not set'}, SOCKET_BRANCH_NAME={branch_name or 'not set'}") + log.debug( + f"Environment: SOCKET_ORG_SLUG={org_slug}, SOCKET_REPO_NAME={repo_name or 'not set'}, SOCKET_BRANCH_NAME={branch_name or 'not set'}" + ) try: cli_dir = self._get_coana_cli_dir((version or DEFAULT_COANA_CLI_VERSION).strip(), org_slug, env) @@ -329,32 +320,29 @@ def run_reachability_analysis( cwd=target_directory, stdout=sys.stderr, # Send stdout to stderr so the user sees it stderr=sys.stderr, + check=False, ).returncode if returncode != 0: log.error(f"Reachability analysis failed with exit code {returncode}") raise Exception(f"Reachability analysis failed with exit code {returncode}") - + # Coana runs in target_directory, so a relative output_path lands there. report_path = os.path.join(target_directory, output_path) scan_id = self._extract_scan_id(report_path) - + log.info("Reachability analysis completed successfully") if scan_id: log.info(f"Scan ID: {scan_id}") - - return { - "scan_id": scan_id, - "report_path": report_path, - "tar_hash_used": tar_hash - } - + + return {"scan_id": scan_id, "report_path": report_path, "tar_hash_used": tar_hash} + except Exception as e: - log.error(f"Failed to run reachability analysis: {str(e)}") - raise Exception(f"Failed to run reachability analysis: {str(e)}") + log.error(f"Failed to run reachability analysis: {e!s}") + raise Exception(f"Failed to run reachability analysis: {e!s}") from e @staticmethod - def _sanitize_coana_env(env: Mapping[str, str]) -> Dict[str, str]: + def _sanitize_coana_env(env: Mapping[str, str]) -> dict[str, str]: """Drop npm-injected ``npm_package_*`` vars before spawning coana. TODO: probably unnecessary. The E2BIG came from npm exec re-adding these vars, and @@ -368,7 +356,7 @@ def _sanitize_coana_env(env: Mapping[str, str]) -> Dict[str, str]: """ return {k: v for k, v in env.items() if not k.startswith("npm_package_")} - def _get_coana_cli_dir(self, version_spec: str, org_slug: str, env: Dict[str, str]) -> str: + def _get_coana_cli_dir(self, version_spec: str, org_slug: str, env: dict[str, str]) -> str: # noqa: C901 """The directory of the Coana CLI's ``cli`` component for ``version_spec``. ``version_spec`` is an exact version, a range or ``latest``. On a cache miss the @@ -378,7 +366,7 @@ def _get_coana_cli_dir(self, version_spec: str, org_slug: str, env: Dict[str, st def run_coana_cache(*args: str) -> subprocess.CompletedProcess[str]: return subprocess.run( - ["node", str(_COANA_CACHE_SCRIPT), *args], env=env, capture_output=True, text=True + ["node", str(_COANA_CACHE_SCRIPT), *args], env=env, capture_output=True, text=True, check=False ) def printed_dir(result: subprocess.CompletedProcess[str]) -> str: @@ -388,7 +376,7 @@ def printed_dir(result: subprocess.CompletedProcess[str]) -> str: raise Exception(f"The Coana cache failed: {detail}") return result.stdout.strip() - def lookup(version: str) -> Optional[str]: + def lookup(version: str) -> str | None: result = run_coana_cache("lookup", version, _COANA_COMPONENT) return None if result.returncode == _NOT_CACHED_EXIT_CODE else printed_dir(result) @@ -429,9 +417,7 @@ def download(component: _CoanaComponent, dest: pathlib.Path) -> None: for chunk in response.raw.stream(1 << 16, decode_content=False): received += len(chunk) if received > component.size: - raise Exception( - f"The Coana CLI tarball is larger than the expected {component.size} bytes" - ) + raise Exception(f"The Coana CLI tarball is larger than the expected {component.size} bytes") digest.update(chunk) f.write(chunk) sha256 = digest.hexdigest() @@ -442,7 +428,7 @@ def download(component: _CoanaComponent, dest: pathlib.Path) -> None: f"got {received} bytes with sha256 {sha256})" ) - def regular_files_only(member: tarfile.TarInfo, path: str) -> Optional[tarfile.TarInfo]: + def regular_files_only(member: tarfile.TarInfo, path: str) -> tarfile.TarInfo | None: return tarfile.data_filter(member, path) if member.isfile() or member.isdir() else None if _EXACT_VERSION.fullmatch(version_spec) and (cached := lookup(version_spec)): @@ -465,20 +451,20 @@ def regular_files_only(member: tarfile.TarInfo, path: str) -> Optional[tarfile.T extract_dir = pathlib.Path(tmp, "cli") with tarfile.open(tarball, "r:gz") as archive: # Without extraction filters, the checked sha256 vouches for the tarball. - archive.extractall( + archive.extractall( # noqa: S202 # filtered when supported; tarball size and checksum are verified extract_dir, **({"filter": regular_files_only} if hasattr(tarfile, "data_filter") else {}) ) return printed_dir( run_coana_cache("install", artifacts.version, _COANA_COMPONENT, artifacts.cli.sha256, str(extract_dir)) ) - def _extract_scan_id(self, facts_file_path: str) -> Optional[str]: + def _extract_scan_id(self, facts_file_path: str) -> str | None: """ Extract tier1ReachabilityScanId from the socket facts JSON file. - + Args: facts_file_path: Path to the .socket.facts.json file - + Returns: Optional[str]: The scan ID if found, None otherwise """ @@ -486,13 +472,13 @@ def _extract_scan_id(self, facts_file_path: str) -> Optional[str]: if not os.path.exists(facts_file_path): log.warning(f"Facts file not found: {facts_file_path}") return None - - with open(facts_file_path, 'r') as f: + + with open(facts_file_path) as f: facts = json.load(f) - - scan_id = facts.get('tier1ReachabilityScanId') + + scan_id = facts.get("tier1ReachabilityScanId") return scan_id.strip() if scan_id else None - - except (json.JSONDecodeError, IOError) as e: + + except (OSError, json.JSONDecodeError) as e: log.warning(f"Failed to extract scan ID from {facts_file_path}: {e}") return None diff --git a/socketsecurity/core/utils.py b/socketsecurity/core/utils.py index 9485ec8b..bd0ae169 100644 --- a/socketsecurity/core/utils.py +++ b/socketsecurity/core/utils.py @@ -1,117 +1,43 @@ - # File pattern definitions socket_globs = { - "spdx": { - "spdx.json": { - "pattern": "*[-.]spdx.json" - } - }, + "spdx": {"spdx.json": {"pattern": "*[-.]spdx.json"}}, "cdx": { - "cyclonedx.json": { - "pattern": "{bom,*[-.]c{yclone,}dx}.json" - }, - "xml": { - "pattern": "{bom,*[-.]c{yclone,}dx}.xml" - } + "cyclonedx.json": {"pattern": "{bom,*[-.]c{yclone,}dx}.json"}, + "xml": {"pattern": "{bom,*[-.]c{yclone,}dx}.xml"}, }, "npm": { - "package.json": { - "pattern": "package.json" - }, - "package-lock.json": { - "pattern": "package-lock.json" - }, - "npm-shrinkwrap.json": { - "pattern": "npm-shrinkwrap.json" - }, - "yarn.lock": { - "pattern": "yarn.lock" - }, - "pnpm-lock.yaml": { - "pattern": "pnpm-lock.yaml" - }, - "pnpm-lock.yml": { - "pattern": "pnpm-lock.yml" - }, - "pnpm-workspace.yaml": { - "pattern": "pnpm-workspace.yaml" - }, - "pnpm-workspace.yml": { - "pattern": "pnpm-workspace.yml" - }, - "bun.lock": { - "pattern": "bun.lock" - }, - "bun.lockb": { - "pattern": "bun.lockb" - }, - "vlt-lock.json": { - "pattern": "vlt-lock.json" - } + "package.json": {"pattern": "package.json"}, + "package-lock.json": {"pattern": "package-lock.json"}, + "npm-shrinkwrap.json": {"pattern": "npm-shrinkwrap.json"}, + "yarn.lock": {"pattern": "yarn.lock"}, + "pnpm-lock.yaml": {"pattern": "pnpm-lock.yaml"}, + "pnpm-lock.yml": {"pattern": "pnpm-lock.yml"}, + "pnpm-workspace.yaml": {"pattern": "pnpm-workspace.yaml"}, + "pnpm-workspace.yml": {"pattern": "pnpm-workspace.yml"}, + "bun.lock": {"pattern": "bun.lock"}, + "bun.lockb": {"pattern": "bun.lockb"}, + "vlt-lock.json": {"pattern": "vlt-lock.json"}, }, "pypi": { - "pipfile": { - "pattern": "pipfile" - }, - "pyproject.toml": { - "pattern": "pyproject.toml" - }, - "poetry.lock": { - "pattern": "poetry.lock" - }, - "requirements.txt": { - "pattern": "*requirements.txt" - }, - "requirements": { - "pattern": "requirements/*.txt" - }, - "requirements-*.txt": { - "pattern": "requirements-*.txt" - }, - "requirements_*.txt": { - "pattern": "requirements_*.txt" - }, - "requirements.frozen": { - "pattern": "requirements.frozen" - }, - "setup.py": { - "pattern": "setup.py" - } - }, - "golang": { - "go.mod": { - "pattern": "go.mod" - }, - "go.sum": { - "pattern": "go.sum" - } - }, - "java": { - "pom.xml": { - "pattern": "pom.xml" - } + "pipfile": {"pattern": "pipfile"}, + "pyproject.toml": {"pattern": "pyproject.toml"}, + "poetry.lock": {"pattern": "poetry.lock"}, + "requirements.txt": {"pattern": "*requirements.txt"}, + "requirements": {"pattern": "requirements/*.txt"}, + "requirements-*.txt": {"pattern": "requirements-*.txt"}, + "requirements_*.txt": {"pattern": "requirements_*.txt"}, + "requirements.frozen": {"pattern": "requirements.frozen"}, + "setup.py": {"pattern": "setup.py"}, }, + "golang": {"go.mod": {"pattern": "go.mod"}, "go.sum": {"pattern": "go.sum"}}, + "java": {"pom.xml": {"pattern": "pom.xml"}}, ".net": { - "proj": { - "pattern": "*.*proj" - }, - "props": { - "pattern": "*.props" - }, - "targets": { - "pattern": "*.targets" - }, - "nuspec": { - "pattern": "*.nuspec" - }, - "nugetConfig": { - "pattern": "nuget.config" - }, - "packagesConfig": { - "pattern": "packages.config" - }, - "packagesLock": { - "pattern": "packages.lock.json" - } - } + "proj": {"pattern": "*.*proj"}, + "props": {"pattern": "*.props"}, + "targets": {"pattern": "*.targets"}, + "nuspec": {"pattern": "*.nuspec"}, + "nugetConfig": {"pattern": "nuget.config"}, + "packagesConfig": {"pattern": "packages.config"}, + "packagesLock": {"pattern": "packages.lock.json"}, + }, } diff --git a/socketsecurity/fossa_compat.py b/socketsecurity/fossa_compat.py index 0be11a9c..dbe7110f 100644 --- a/socketsecurity/fossa_compat.py +++ b/socketsecurity/fossa_compat.py @@ -33,9 +33,11 @@ copyrightsByLicense -> {} (would require parsing attribText for `Copyright (c)` lines) licenses -> {} (would require bundling SPDX license body texts) """ + from __future__ import annotations -from typing import Any, Iterable, Optional +from collections.abc import Iterable +from typing import Any from socketsecurity.config import CliConfig from socketsecurity.core.classes import Diff, Issue, Package @@ -44,7 +46,7 @@ QUALITY_ALERT_PREFIXES = ("risk", "quality", "outdated", "unmaintained") -def _ecosystem_to_package_manager(ecosystem: Optional[str]) -> str: +def _ecosystem_to_package_manager(ecosystem: str | None) -> str: mapping = { "pypi": "pip", "npm": "npm", @@ -89,10 +91,8 @@ def _build_project_metadata(diff_report: Diff, config: CliConfig) -> dict[str, A } -def _build_source_metadata(issue: Issue, package: Optional[Package]) -> dict[str, Any]: - package_type = _ecosystem_to_package_manager( - getattr(package, "type", None) or getattr(issue, "pkg_type", None) - ) +def _build_source_metadata(issue: Issue, package: Package | None) -> dict[str, Any]: + package_type = _ecosystem_to_package_manager(getattr(package, "type", None) or getattr(issue, "pkg_type", None)) package_name = getattr(package, "name", None) or getattr(issue, "pkg_name", None) package_version = getattr(package, "version", None) or getattr(issue, "pkg_version", None) package_url = getattr(package, "url", None) or getattr(issue, "url", None) @@ -105,7 +105,7 @@ def _build_source_metadata(issue: Issue, package: Optional[Package]) -> dict[str } -def _build_depths(package: Optional[Package]) -> dict[str, int]: +def _build_depths(package: Package | None) -> dict[str, int]: is_direct = bool(getattr(package, "direct", False)) return { "direct": 1 if is_direct else 0, @@ -121,32 +121,34 @@ def _build_statuses(issue: Issue) -> dict[str, int]: } -def _build_projects_entry(project: dict[str, Any], package: Optional[Package]) -> list[dict[str, Any]]: +def _build_projects_entry(project: dict[str, Any], package: Package | None) -> list[dict[str, Any]]: is_direct = bool(getattr(package, "direct", False)) - return [{ - "id": project["projectId"], - "status": "active", - "depth": 1 if is_direct else 2, - "title": project["project"], - "scannedAt": None, - "analyzedAt": None, - "url": project["url"], - "firstFoundAt": None, - "defaultBranch": project["branch"], - "latest": True, - "revisionId": f"{project['projectId']}${project['revision']}", - "revisionScanId": project["revision"], - }] - - -def _extract_cve(props: dict[str, Any]) -> Optional[str]: + return [ + { + "id": project["projectId"], + "status": "active", + "depth": 1 if is_direct else 2, + "title": project["project"], + "scannedAt": None, + "analyzedAt": None, + "url": project["url"], + "firstFoundAt": None, + "defaultBranch": project["branch"], + "latest": True, + "revisionId": f"{project['projectId']}${project['revision']}", + "revisionScanId": project["revision"], + } + ] + + +def _extract_cve(props: dict[str, Any]) -> str | None: cve = _first_non_empty(props.get("cveId"), props.get("cve")) if isinstance(cve, list): return cve[0] if cve else None return cve -def _extract_float(*values: Any) -> Optional[float]: +def _extract_float(*values: Any) -> float | None: value = _first_non_empty(*values) if value is None: return None @@ -207,11 +209,7 @@ def _build_metrics(props: dict[str, Any]) -> list[dict[str, Any]]: ("Integrity Impact", props.get("integrityImpact")), ("Availability Impact", props.get("availabilityImpact")), ] - return [ - {"name": name, "value": value} - for name, value in metric_map - if value not in (None, "") - ] + return [{"name": name, "value": value} for name, value in metric_map if value not in (None, "")] def _extract_references(issue: Issue, props: dict[str, Any]) -> list[str]: @@ -233,7 +231,7 @@ def _extract_references(issue: Issue, props: dict[str, Any]) -> list[str]: def _build_vulnerability_entry( - issue: Issue, package: Optional[Package], project: dict[str, Any], index: int + issue: Issue, package: Package | None, project: dict[str, Any], index: int ) -> dict[str, Any]: props = getattr(issue, "props", {}) or {} return { @@ -277,7 +275,7 @@ def _build_vulnerability_entry( def _build_licensing_entry( - issue: Issue, package: Optional[Package], project: dict[str, Any], index: int + issue: Issue, package: Package | None, project: dict[str, Any], index: int ) -> dict[str, Any]: props = getattr(issue, "props", {}) or {} package_license = getattr(package, "license", None) @@ -303,9 +301,7 @@ def _build_licensing_entry( } -def _build_quality_entry( - issue: Issue, package: Optional[Package], project: dict[str, Any], index: int -) -> dict[str, Any]: +def _build_quality_entry(issue: Issue, package: Package | None, project: dict[str, Any], index: int) -> dict[str, Any]: props = getattr(issue, "props", {}) or {} return { "id": props.get("id") or f"socket-quality-{index}", @@ -369,11 +365,7 @@ def build_fossa_report_payload(diff_report: Diff, config: CliConfig) -> dict[str def _build_attribution_project(diff_report: Diff, config: CliConfig) -> dict[str, Any]: repo = getattr(config, "repo", None) or "socket-default-repo" - revision = ( - getattr(diff_report, "id", None) - or getattr(diff_report, "new_scan_id", None) - or "unknown-revision" - ) + revision = getattr(diff_report, "id", None) or getattr(diff_report, "new_scan_id", None) or "unknown-revision" return {"name": repo, "revision": revision} diff --git a/socketsecurity/output.py b/socketsecurity/output.py index e3a5b03e..780025dc 100644 --- a/socketsecurity/output.py +++ b/socketsecurity/output.py @@ -1,7 +1,7 @@ import json import logging from pathlib import Path -from typing import Any, Dict, Optional +from typing import Any from socketdev import socketdev @@ -17,6 +17,7 @@ from .core.classes import Diff, Issue from .core.messages import Messages from .fossa_compat import build_fossa_report_payload +from .redaction import redact_mapping class OutputHandler: @@ -27,17 +28,17 @@ def __init__(self, config: CliConfig, sdk: socketdev): self.config = config self.logger = logging.getLogger("socketcli") - def handle_output(self, diff_report: Diff) -> None: + def handle_output(self, diff_report: Diff) -> None: # noqa: C901 """Main output handler that determines output format""" # Determine which formats to output formats_to_output = [] if self.config.enable_json: - formats_to_output.append('json') + formats_to_output.append("json") if self.config.enable_sarif: - formats_to_output.append('sarif') + formats_to_output.append("sarif") if self.config.enable_gitlab_security: - formats_to_output.append('gitlab') + formats_to_output.append("gitlab") # If no format specified, default to console comments if not formats_to_output: @@ -45,17 +46,17 @@ def handle_output(self, diff_report: Diff) -> None: else: # Output all enabled formats for format_type in formats_to_output: - if format_type == 'json': + if format_type == "json": self.output_console_json(diff_report, self.config.sbom_file) - elif format_type == 'sarif': + elif format_type == "sarif": self.output_console_sarif(diff_report, self.config.sbom_file) - elif format_type == 'gitlab': + elif format_type == "gitlab": self.output_gitlab_security(diff_report) if self.config.jira_plugin.enabled: jira_config = { "enabled": self.config.jira_plugin.enabled, "levels": self.config.jira_plugin.levels or [], - **(self.config.jira_plugin.config or {}) + **(self.config.jira_plugin.config or {}), } plugin_mgr = PluginManager({"jira": jira_config}) plugin_mgr.send(diff_report, config=self.config) @@ -63,11 +64,12 @@ def handle_output(self, diff_report: Diff) -> None: # Debug Slack webhook configuration when debug is enabled (always show when debug is on) if self.config.enable_debug: import os + slack_enabled_env = os.getenv("SOCKET_SLACK_ENABLED", "Not set") - slack_config_env = os.getenv("SOCKET_SLACK_CONFIG_JSON", "Not set") + slack_config_env = "Set" if os.getenv("SOCKET_SLACK_CONFIG_JSON") else "Not set" slack_url = "Not configured" if self.config.slack_plugin.config and self.config.slack_plugin.config.get("url"): - slack_url = self.config.slack_plugin.config.get("url") + slack_url = redact_mapping(self.config.slack_plugin.config)["url"] slack_mode = (self.config.slack_plugin.config or {}).get("mode", "webhook") bot_token = os.getenv("SOCKET_SLACK_BOT_TOKEN") bot_token_status = "Set" if bot_token else "Not set" @@ -76,11 +78,13 @@ def handle_output(self, diff_report: Diff) -> None: self.logger.debug(f"Slack Mode: {slack_mode}") self.logger.debug(f"SOCKET_SLACK_ENABLED environment variable: {slack_enabled_env}") self.logger.debug(f"SOCKET_SLACK_CONFIG_JSON environment variable: {slack_config_env}") - self.logger.debug(f"Slack Webhook URL: {slack_url}") + self.logger.debug("Slack Webhook URL: %s", slack_url) self.logger.debug(f"SOCKET_SLACK_BOT_TOKEN: {bot_token_status}") self.logger.debug(f"Slack Alert Levels: {self.config.slack_plugin.levels}") if self.config.reach: - facts_path = os.path.join(self.config.target_path or ".", self.config.reach_output_file or ".socket.facts.json") + facts_path = os.path.join( + self.config.target_path or ".", self.config.reach_output_file or ".socket.facts.json" + ) self.logger.debug(f"Reachability facts file: {facts_path} (exists: {os.path.exists(facts_path)})") self.logger.debug("=====================================") @@ -88,7 +92,7 @@ def handle_output(self, diff_report: Diff) -> None: slack_config = { "enabled": self.config.slack_plugin.enabled, "levels": self.config.slack_plugin.levels or [], - **(self.config.slack_plugin.config or {}) + **(self.config.slack_plugin.config or {}), } plugin_mgr = PluginManager({"slack": slack_config}) @@ -98,11 +102,11 @@ def handle_output(self, diff_report: Diff) -> None: self.save_summary_file(diff_report, getattr(self.config, "summary_file", None)) self.save_report_link_file(diff_report, getattr(self.config, "report_link_file", None)) self.save_sbom_file(diff_report, self.config.sbom_file) - + def return_exit_code(self, diff_report: Diff) -> int: if self.config.disable_blocking: return 0 - + if not self.report_pass(diff_report): return 1 @@ -110,9 +114,9 @@ def return_exit_code(self, diff_report: Diff) -> int: # if len(diff_report.new_alerts) > 0: # # 5 means warning alerts but no blocking alerts # return 5 - return 0 + return 0 - def output_console_comments(self, diff_report: Diff, sbom_file_name: Optional[str] = None) -> None: + def output_console_comments(self, diff_report: Diff, sbom_file_name: str | None = None) -> None: """Outputs formatted console comments""" summary_text = self.build_summary_text(diff_report) for line in summary_text.splitlines(): @@ -120,13 +124,13 @@ def output_console_comments(self, diff_report: Diff, sbom_file_name: Optional[st if not summary_text.strip(): self.logger.info("") - def output_console_json(self, diff_report: Diff, sbom_file_name: Optional[str] = None) -> None: + def output_console_json(self, diff_report: Diff, sbom_file_name: str | None = None) -> None: """Outputs JSON formatted results""" console_security_comment = self.build_json_report(diff_report) self.save_sbom_file(diff_report, sbom_file_name) self.logger.info(json.dumps(console_security_comment)) - def output_console_sarif(self, diff_report: Diff, sbom_file_name: Optional[str] = None) -> None: + def output_console_sarif(self, diff_report: Diff, sbom_file_name: str | None = None) -> None: """ Generate SARIF output from the diff report and print to console. If --sarif-file is configured, also save to file. @@ -148,9 +152,7 @@ def output_console_sarif(self, diff_report: Diff, sbom_file_name: Optional[str] self.config.reach_output_file, ) if not components_with_alerts: - self.logger.error( - "Unable to generate full-scope SARIF: .socket.facts.json missing or invalid" - ) + self.logger.error("Unable to generate full-scope SARIF: .socket.facts.json missing or invalid") components_with_alerts = [] console_security_comment = Messages.create_security_comment_sarif_from_facts( components_with_alerts, @@ -175,7 +177,7 @@ def output_console_sarif(self, diff_report: Diff, sbom_file_name: Optional[str] # Avoid flooding logs for full-scope SARIF when writing to file. if not (sarif_scope == "full" and self.config.sarif_file): # Print the SARIF output to the console in JSON format - print(json.dumps(console_security_comment, indent=2)) + print(json.dumps(console_security_comment, indent=2)) # noqa: T201 else: self.logger.info( "SARIF stdout output suppressed for full scope; report will be written to --sarif-file" @@ -200,23 +202,19 @@ def report_pass(self, diff_report: Diff) -> bool: # Check unchanged alerts if --strict-blocking is enabled has_unchanged_blocking_alerts = False - if self.config.strict_blocking and hasattr(diff_report, 'unchanged_alerts'): - has_unchanged_blocking_alerts = any( - issue.error for issue in diff_report.unchanged_alerts - ) + if self.config.strict_blocking and hasattr(diff_report, "unchanged_alerts"): + has_unchanged_blocking_alerts = any(issue.error for issue in diff_report.unchanged_alerts) # If no alerts at all, pass if not diff_report.new_alerts and not ( - self.config.strict_blocking and - hasattr(diff_report, 'unchanged_alerts') and - diff_report.unchanged_alerts + self.config.strict_blocking and hasattr(diff_report, "unchanged_alerts") and diff_report.unchanged_alerts ): return True # Fail if there are any blocking alerts (new or unchanged with --strict-blocking) return not (has_new_blocking_alerts or has_unchanged_blocking_alerts) - def save_sbom_file(self, diff_report: Diff, sbom_file_name: Optional[str] = None) -> None: + def save_sbom_file(self, diff_report: Diff, sbom_file_name: str | None = None) -> None: """Saves SBOM file if filename is provided""" if not sbom_file_name: return @@ -232,9 +230,7 @@ def build_summary_text(self, diff_report: Diff) -> str: is_full_scan = getattr(diff_report, "is_full_scan", False) if is_full_scan and not getattr(diff_report, "alerts_fetched", False): lines = ["Full scan completed. Findings were not fetched for console output."] - report_link = getattr(diff_report, "report_url", "") or getattr( - diff_report, "diff_url", "" - ) + report_link = getattr(diff_report, "report_url", "") or getattr(diff_report, "diff_url", "") if report_link: lines.append(f"Report Url: {report_link}") return "\n".join(lines) @@ -242,9 +238,9 @@ def build_summary_text(self, diff_report: Diff) -> str: selected_alerts = select_diff_alerts(diff_report, strict_blocking=self.config.strict_blocking) has_new_alerts = len(selected_alerts) > 0 has_unchanged_alerts = ( - self.config.strict_blocking and - hasattr(diff_report, 'unchanged_alerts') and - len(diff_report.unchanged_alerts) > 0 + self.config.strict_blocking + and hasattr(diff_report, "unchanged_alerts") + and len(diff_report.unchanged_alerts) > 0 ) if not has_new_alerts and not has_unchanged_alerts: @@ -315,17 +311,17 @@ def build_json_report(self, diff_report: Diff) -> dict: report["legal_mode"] = legal_flag if isinstance(legal_flag, bool) else False return report - def save_json_file(self, diff_report: Diff, json_file_name: Optional[str] = None) -> None: + def save_json_file(self, diff_report: Diff, json_file_name: str | None = None) -> None: if not json_file_name: return self.write_json_file(json_file_name, self.build_json_report(diff_report)) - def save_summary_file(self, diff_report: Diff, summary_file_name: Optional[str] = None) -> None: + def save_summary_file(self, diff_report: Diff, summary_file_name: str | None = None) -> None: if not summary_file_name: return self.write_text_file(summary_file_name, self.build_summary_text(diff_report) + "\n") - def save_report_link_file(self, diff_report: Diff, report_link_file_name: Optional[str] = None) -> None: + def save_report_link_file(self, diff_report: Diff, report_link_file_name: str | None = None) -> None: if not report_link_file_name: return report_link = getattr(diff_report, "report_url", "") or getattr(diff_report, "diff_url", "") @@ -391,7 +387,7 @@ def _output_issue(self, issue: Issue) -> None: if issue.suggestion: self.logger.warning(f"suggestion: {issue.suggestion}") - def _format_issue(self, issue: Issue) -> Dict[str, Any]: + def _format_issue(self, issue: Issue) -> dict[str, Any]: """Helper method to format an issue for JSON output""" return { "purl": issue.purl, diff --git a/socketsecurity/plugins/base.py b/socketsecurity/plugins/base.py index 3aba645e..88383b6f 100644 --- a/socketsecurity/plugins/base.py +++ b/socketsecurity/plugins/base.py @@ -1,6 +1,11 @@ +# Notification delivery must never be able to wedge a CI job. Every plugin +# HTTP call passes this explicitly; requests defaults to blocking forever. +REQUEST_TIMEOUT_SECONDS = 30 + + class Plugin: def __init__(self, config): self.config = config def send(self, diff, config): - raise NotImplementedError("Plugin must implement send()") \ No newline at end of file + raise NotImplementedError("Plugin must implement send()") diff --git a/socketsecurity/plugins/formatters/__init__.py b/socketsecurity/plugins/formatters/__init__.py index b7d4637e..fdaef902 100644 --- a/socketsecurity/plugins/formatters/__init__.py +++ b/socketsecurity/plugins/formatters/__init__.py @@ -2,4 +2,4 @@ from .slack import format_socket_facts_for_slack -__all__ = ['format_socket_facts_for_slack'] +__all__ = ["format_socket_facts_for_slack"] diff --git a/socketsecurity/plugins/formatters/slack.py b/socketsecurity/plugins/formatters/slack.py index 955b330a..3d9cfc00 100644 --- a/socketsecurity/plugins/formatters/slack.py +++ b/socketsecurity/plugins/formatters/slack.py @@ -2,162 +2,155 @@ import logging from collections import defaultdict -from typing import Any, Dict, List +from typing import Any logger = logging.getLogger(__name__) # Severity display configuration -SEVERITY_ORDER = {'critical': 0, 'high': 1, 'medium': 2, 'low': 3} -SEVERITY_EMOJI = { - 'critical': '๐Ÿ”ด', - 'high': '๐ŸŸ ', - 'medium': '๐ŸŸก', - 'low': 'โšช' -} +SEVERITY_ORDER = {"critical": 0, "high": 1, "medium": 2, "low": 3} +SEVERITY_EMOJI = {"critical": "๐Ÿ”ด", "high": "๐ŸŸ ", "medium": "๐ŸŸก", "low": "โšช"} -def _make_purl(component: Dict[str, Any]) -> str: +def _make_purl(component: dict[str, Any]) -> str: """ Construct a package URL (purl) from a component entry. - + Args: component: Component dictionary from socket facts - + Returns: Package URL string in format: pkg:type/namespace/name@version """ - pkg_type = component.get('type', '') - namespace = component.get('namespace', '') - name = component.get('name') or component.get('id', '') - version = component.get('version', '') - + pkg_type = component.get("type", "") + namespace = component.get("namespace", "") + name = component.get("name") or component.get("id", "") + version = component.get("version", "") + if not name: - return '' - + return "" + # Construct purl - handle scoped packages (namespace with @) if namespace: # Percent-encode @ in namespace for purl spec compliance - ns_encoded = namespace.replace('@', '%40') + ns_encoded = namespace.replace("@", "%40") purl = f"pkg:{pkg_type}/{ns_encoded}/{name}" else: purl = f"pkg:{pkg_type}/{name}" - + if version: purl = f"{purl}@{version}" - + return purl -def _get_reachability_from_alert(alert: Dict[str, Any]) -> str: +def _get_reachability_from_alert(alert: dict[str, Any]) -> str: """ Extract reachability status from an alert. - + Args: alert: Alert dictionary from component - + Returns: Reachability status: 'reachable', 'unreachable', 'unknown', or 'error' """ - props = alert.get('props', {}) or {} - reachability = props.get('reachability', 'unknown') - + props = alert.get("props", {}) or {} + reachability = props.get("reachability", "unknown") + # Normalize to expected values if isinstance(reachability, str): return reachability.lower() - - return 'unknown' + return "unknown" -def _get_trace_from_alert(alert: Dict[str, Any], max_length: int = 500) -> str: + +def _get_trace_from_alert(alert: dict[str, Any], max_length: int = 500) -> str: """ Extract and format trace data from an alert. - + Args: alert: Alert dictionary from component max_length: Maximum length for trace output (truncate if longer) - + Returns: Formatted trace string """ - props = alert.get('props', {}) or {} - trace_raw = props.get('trace', '') - - trace_str = '' + props = alert.get("props", {}) or {} + trace_raw = props.get("trace", "") + + trace_str = "" if isinstance(trace_raw, list): - trace_str = '\n'.join(str(item) for item in trace_raw) + trace_str = "\n".join(str(item) for item in trace_raw) elif isinstance(trace_raw, str): trace_str = trace_raw - + # Truncate if too long if trace_str and len(trace_str) > max_length: - trace_str = trace_str[:max_length] + '\n...' - + trace_str = trace_str[:max_length] + "\n..." + return trace_str -def _extract_alert_info(component: Dict[str, Any], alert: Dict[str, Any]) -> Dict[str, Any]: +def _extract_alert_info(component: dict[str, Any], alert: dict[str, Any]) -> dict[str, Any]: """ Extract standardized information from an alert. - + Args: component: Component dictionary containing the alert alert: Alert dictionary - + Returns: Dictionary with standardized alert information """ - props = alert.get('props', {}) or {} - severity = str(alert.get('severity') or props.get('severity') or '').lower() + props = alert.get("props", {}) or {} + severity = str(alert.get("severity") or props.get("severity") or "").lower() # The API's mid-level severity is "middle"; every lookup in this module is # keyed on "medium". Normalizing here rather than adding a parallel key to # each dict keeps one canonical spelling downstream, matching what # Messages.map_socket_severity_to_gitlab already does. - if severity == 'middle': - severity = 'medium' - + if severity == "middle": + severity = "medium" + return { - 'cve_id': str(props.get('ghsaId') or props.get('cveId') or alert.get('title') or 'Unknown'), - 'severity': severity, - 'severity_order': SEVERITY_ORDER.get(severity, 4), - 'severity_emoji': SEVERITY_EMOJI.get(severity, 'โšช'), - 'reachability': _get_reachability_from_alert(alert), - 'trace': _get_trace_from_alert(alert), - 'purl': str(props.get('purl') or _make_purl(component) or component.get('name') or '-') + "cve_id": str(props.get("ghsaId") or props.get("cveId") or alert.get("title") or "Unknown"), + "severity": severity, + "severity_order": SEVERITY_ORDER.get(severity, 4), + "severity_emoji": SEVERITY_EMOJI.get(severity, "โšช"), + "reachability": _get_reachability_from_alert(alert), + "trace": _get_trace_from_alert(alert), + "purl": str(props.get("purl") or _make_purl(component) or component.get("name") or "-"), } -def format_socket_facts_for_slack( - components: List[Dict[str, Any]], - max_blocks: int = 45, - include_traces: bool = True -) -> List[Dict[str, Any]]: +def format_socket_facts_for_slack( # noqa: C901 + components: list[dict[str, Any]], max_blocks: int = 45, include_traces: bool = True +) -> list[dict[str, Any]]: """ Format socket facts components with alerts for Slack notification. - + This function processes vulnerability data from Socket's reachability analysis and formats it for display in Slack with smart block limiting. - + Slack has a 50 block limit. We use ~4 blocks for header/summary, leaving ~45 for findings. - + Prioritization (when space limited): 1. Reachable vulnerabilities (all severities) 2. Unknown/error reachability (critical/high only) 3. Skip unreachable vulnerabilities - + Further filtering by severity: - Critical (always show if reachable) - High (show if space allows) - Medium (show if space allows) - Low (skip if space limited) - + Args: components: List of component dictionaries from socket facts JSON max_blocks: Maximum number of blocks for findings (default: 45, Slack limit is 50) include_traces: Whether to include trace data for reachable findings - + Returns: List of notification dictionaries with structured vulnerability data. - + Example: >>> components = socket_facts['components'] >>> notifications = format_socket_facts_for_slack(components) @@ -165,53 +158,50 @@ def format_socket_facts_for_slack( ... send_to_slack(notif['title'], notif['vulnerabilities']) """ # Group findings by PURL and reachability status - purl_groups = defaultdict(lambda: { - 'reachable': [], - 'unknown': [], - 'error': [], - 'unreachable': [] - }) - - severity_counts = {'critical': 0, 'high': 0, 'medium': 0, 'low': 0} - reachability_counts = {'reachable': 0, 'unknown': 0, 'error': 0, 'unreachable': 0} - + purl_groups = defaultdict(lambda: {"reachable": [], "unknown": [], "error": [], "unreachable": []}) + + severity_counts = {"critical": 0, "high": 0, "medium": 0, "low": 0} + reachability_counts = {"reachable": 0, "unknown": 0, "error": 0, "unreachable": 0} + # Process all components and their alerts for component in components: - alerts = component.get('alerts', []) - + alerts = component.get("alerts", []) + for alert in alerts: alert_info = _extract_alert_info(component, alert) - purl = alert_info['purl'] - reachability = alert_info['reachability'] - + purl = alert_info["purl"] + reachability = alert_info["reachability"] + # Count by severity - if alert_info['severity'] in severity_counts: - severity_counts[alert_info['severity']] += 1 - + if alert_info["severity"] in severity_counts: + severity_counts[alert_info["severity"]] += 1 + # Count by reachability if reachability in reachability_counts: reachability_counts[reachability] += 1 - + # Group by reachability status if reachability in purl_groups[purl]: purl_groups[purl][reachability].append(alert_info) - + # Sort findings within each group by severity (most severe first) for purl in purl_groups: - for reach_type in ['reachable', 'unknown', 'error', 'unreachable']: - purl_groups[purl][reach_type].sort(key=lambda x: x['severity_order']) - + for reach_type in ["reachable", "unknown", "error", "unreachable"]: + purl_groups[purl][reach_type].sort(key=lambda x: x["severity_order"]) + # Build Slack message content if not purl_groups: - return [{ - 'title': 'Socket Reachability Analysis', - 'summary': "โœ… No vulnerabilities found in reachability analysis.", - 'vulnerabilities': [] - }] - + return [ + { + "title": "Socket Reachability Analysis", + "summary": "โœ… No vulnerabilities found in reachability analysis.", + "vulnerabilities": [], + } + ] + # Calculate totals total_findings = sum(severity_counts.values()) - + # Build summary summary = ( f"๐Ÿ”ด Critical: {severity_counts['critical']} | " @@ -221,58 +211,66 @@ def format_socket_facts_for_slack( f"๐ŸŽฏ Reachable: {reachability_counts['reachable']} | " f"โœ“ Unreachable: {reachability_counts['unreachable']}" ) - + # Collect and prioritize vulnerabilities for display # Priority: reachable (all) > unknown/error (critical/high) > skip unreachable unless space vulnerabilities_to_show = [] - + # First, add all reachable vulnerabilities (highest priority) for purl in purl_groups: - for finding in purl_groups[purl]['reachable']: - vulnerabilities_to_show.append({ - 'purl': purl, - 'finding': finding, - 'reachability': 'reachable', - 'priority': (0, finding['severity_order']) # (reachability_pri, severity_pri) - }) - + for finding in purl_groups[purl]["reachable"]: + vulnerabilities_to_show.append( + { + "purl": purl, + "finding": finding, + "reachability": "reachable", + "priority": (0, finding["severity_order"]), # (reachability_pri, severity_pri) + } + ) + # Add unknown/error reachability (critical and high only) for purl in purl_groups: - for finding in purl_groups[purl]['unknown']: - if finding['severity'] in ['critical', 'high']: - vulnerabilities_to_show.append({ - 'purl': purl, - 'finding': finding, - 'reachability': 'unknown', - 'priority': (1, finding['severity_order']) - }) - for finding in purl_groups[purl]['error']: - if finding['severity'] in ['critical', 'high']: - vulnerabilities_to_show.append({ - 'purl': purl, - 'finding': finding, - 'reachability': 'error', - 'priority': (1, finding['severity_order']) - }) - + for finding in purl_groups[purl]["unknown"]: + if finding["severity"] in ["critical", "high"]: + vulnerabilities_to_show.append( + { + "purl": purl, + "finding": finding, + "reachability": "unknown", + "priority": (1, finding["severity_order"]), + } + ) + for finding in purl_groups[purl]["error"]: + if finding["severity"] in ["critical", "high"]: + vulnerabilities_to_show.append( + { + "purl": purl, + "finding": finding, + "reachability": "error", + "priority": (1, finding["severity_order"]), + } + ) + # Sort by priority (reachability first, then severity) - vulnerabilities_to_show.sort(key=lambda x: x['priority']) - + vulnerabilities_to_show.sort(key=lambda x: x["priority"]) + # Limit to max_blocks (each vulnerability = 1 block) selected_vulnerabilities = vulnerabilities_to_show[:max_blocks] - + # Calculate what was omitted omitted_count = total_findings - len(selected_vulnerabilities) - omitted_unreachable = reachability_counts['unreachable'] - omitted_low = severity_counts['low'] - sum(1 for v in selected_vulnerabilities if v['finding']['severity'] == 'low') - - return [{ - 'title': 'Socket Reachability Analysis', - 'summary': summary, - 'total_findings': total_findings, - 'vulnerabilities': selected_vulnerabilities, - 'omitted_count': omitted_count, - 'omitted_unreachable': omitted_unreachable, - 'omitted_low': omitted_low, - 'include_traces': include_traces - }] + omitted_unreachable = reachability_counts["unreachable"] + omitted_low = severity_counts["low"] - sum(1 for v in selected_vulnerabilities if v["finding"]["severity"] == "low") + + return [ + { + "title": "Socket Reachability Analysis", + "summary": summary, + "total_findings": total_findings, + "vulnerabilities": selected_vulnerabilities, + "omitted_count": omitted_count, + "omitted_unreachable": omitted_unreachable, + "omitted_low": omitted_low, + "include_traces": include_traces, + } + ] diff --git a/socketsecurity/plugins/jira.py b/socketsecurity/plugins/jira.py index 9de187f9..9dc86671 100644 --- a/socketsecurity/plugins/jira.py +++ b/socketsecurity/plugins/jira.py @@ -5,8 +5,9 @@ from socketsecurity.config import CliConfig from socketsecurity.core import log from socketsecurity.core.classes import Diff +from socketsecurity.redaction import redact_url -from .base import Plugin +from .base import REQUEST_TIMEOUT_SECONDS, Plugin class JiraPlugin(Plugin): @@ -44,38 +45,37 @@ def send(self, diff: Diff, config: CliConfig): { "type": "text", "text": "View Socket Security scan results", - "marks": [{"type": "link", "attrs": {"href": scan_link}}] - } - ] + "marks": [{"type": "link", "attrs": {"href": scan_link}}], + }, + ], }, - self.create_adf_table_from_diff(diff) - ] + self.create_adf_table_from_diff(diff), + ], } # log.debug("ADF Description Payload:\n" + json.dumps(description_adf, indent=2)) log.debug("Sending Jira Issue") # ๐Ÿ› ๏ธ Build and send the Jira issue url = self.config["url"] project = self.config["project"] - auth = base64.b64encode( - f"{self.config['email']}:{self.config['api_token']}".encode() - ).decode() + auth = base64.b64encode(f"{self.config['email']}:{self.config['api_token']}".encode()).decode() payload = { "fields": { "project": {"key": project}, "summary": title, "description": description_adf, - "issuetype": {"name": "Task"} + "issuetype": {"name": "Task"}, } } - headers = { - "Authorization": f"Basic {auth}", - "Content-Type": "application/json" - } + headers = {"Authorization": f"Basic {auth}", "Content-Type": "application/json"} jira_url = f"{url}/rest/api/3/issue" - log.debug(f"Jira URL: {jira_url}") - response = requests.post(jira_url, json=payload, headers=headers) + log.debug(f"Jira URL: {redact_url(jira_url)}") + try: + response = requests.post(jira_url, json=payload, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS) + except requests.RequestException as error: + log.error("Jira request failed (%s) for %s", type(error).__name__, redact_url(jira_url)) + return if response.status_code >= 300: log.error(f"Jira error {response.status_code}: {response.text}") else: @@ -88,7 +88,7 @@ def extract_text(node): if node.get("type") == "text": return node.get("text", "") return "".join(extract_text(child) for child in node.get("content", [])) - elif isinstance(node, list): + if isinstance(node, list): return "".join(extract_text(child) for child in node) return "" @@ -101,12 +101,7 @@ def create_adf_table_from_diff(diff): def make_cell(text): return { "type": "tableCell", - "content": [ - { - "type": "paragraph", - "content": [{"type": "text", "text": text}] - } - ] + "content": [{"type": "paragraph", "content": [{"type": "text", "text": text}]}], } def make_link_cell(text, url): @@ -115,13 +110,11 @@ def make_link_cell(text, url): "content": [ { "type": "paragraph", - "content": [{ - "type": "text", - "text": text, - "marks": [{"type": "link", "attrs": {"href": url}}] - }] + "content": [ + {"type": "text", "text": text, "marks": [{"type": "link", "attrs": {"href": url}}]} + ], } - ] + ], } # Header row (must use tableCell not tableHeader!) @@ -132,8 +125,8 @@ def make_link_cell(text, url): make_cell("Package"), make_cell("Introduced by"), make_cell("Manifest File"), - make_cell("CI") - ] + make_cell("CI"), + ], } rows = [header_row] @@ -148,14 +141,11 @@ def make_link_cell(text, url): make_link_cell(alert.purl, alert.url) if alert.url else make_cell(alert.purl), make_cell(source_str), make_cell(manifest_str), - make_cell("๐Ÿšซ" if alert.error else "โš ๏ธ") - ] + make_cell("๐Ÿšซ" if alert.error else "โš ๏ธ"), + ], } rows.append(row) # Final return is a block array - return { - "type": "table", - "content": rows - } + return {"type": "table", "content": rows} diff --git a/socketsecurity/plugins/manager.py b/socketsecurity/plugins/manager.py index 9929fa79..127e43b9 100644 --- a/socketsecurity/plugins/manager.py +++ b/socketsecurity/plugins/manager.py @@ -7,6 +7,7 @@ "teams": teams.TeamsPlugin, } + class PluginManager: def __init__(self, config): self.plugins = [] @@ -18,4 +19,4 @@ def __init__(self, config): def send(self, diff, config): for plugin in self.plugins: - plugin.send(diff, config) \ No newline at end of file + plugin.send(diff, config) diff --git a/socketsecurity/plugins/slack.py b/socketsecurity/plugins/slack.py index fae3b2c7..fbd06220 100644 --- a/socketsecurity/plugins/slack.py +++ b/socketsecurity/plugins/slack.py @@ -17,8 +17,9 @@ ) from socketsecurity.core.messages import Messages from socketsecurity.plugins.formatters.slack import format_socket_facts_for_slack +from socketsecurity.redaction import redact_url -from .base import Plugin +from .base import REQUEST_TIMEOUT_SECONDS, Plugin logger = logging.getLogger(__name__) @@ -31,7 +32,7 @@ def get_name(): def send(self, diff, config: CliConfig): # Check mode and route to appropriate handler mode = self.config.get("mode", "webhook") - + if mode == "webhook": self._send_webhook_alerts(diff, config) elif mode == "bot": @@ -40,17 +41,17 @@ def send(self, diff, config: CliConfig): logger.error(f"Invalid Slack mode '{mode}'. Valid modes are 'webhook' or 'bot'.") return - def _send_webhook_alerts(self, diff, config: CliConfig): + def _send_webhook_alerts(self, diff, config: CliConfig): # noqa: C901 """Send alerts using webhook mode.""" if not self.config.get("url"): logger.warning("Slack webhook URL not configured.") if config.enable_debug: logger.debug("Slack webhook URL is missing from configuration") return - + # Normalize URL configuration to list of dicts url_configs = self._normalize_url_config(self.config.get("url")) - + if not url_configs: logger.warning("No valid Slack webhook URLs configured.") return @@ -60,7 +61,7 @@ def _send_webhook_alerts(self, diff, config: CliConfig): # Get url_configs parameter (filtering configuration) webhook_configs = self.config.get("url_configs", {}) - + # Validate that all URLs have corresponding configs valid_webhooks = [] for url_config in url_configs: @@ -69,19 +70,19 @@ def _send_webhook_alerts(self, diff, config: CliConfig): logger.warning(f"No url_configs entry found for webhook '{name}'. This webhook will be disabled.") continue valid_webhooks.append(url_config) - + if not valid_webhooks: logger.warning("No valid Slack webhooks with configurations. All webhooks disabled.") return - + # Get repo name from config repo_name = config.repo or "" diff_alert_source = select_diff_alerts(diff, strict_blocking=config.strict_blocking) - + # Handle reachability data if --reach is enabled if config.reach: self._send_reachability_alerts(valid_webhooks, webhook_configs, repo_name, config, diff) - + # Handle diff alerts (if any) if not diff_alert_source: logger.debug("No new diff alerts to notify via Slack.") @@ -91,38 +92,41 @@ def _send_webhook_alerts(self, diff, config: CliConfig): url = url_config["url"] name = url_config["name"] webhook_config = webhook_configs[name] - + # Filter alerts based on webhook config # When --reach is used, reachability_alerts_only applies to diff alerts filtered_alerts = self._filter_alerts( diff_alert_source, - webhook_config, - repo_name, + webhook_config, + repo_name, config, is_reachability_data=False, - apply_reachability_only_filter=config.reach + apply_reachability_only_filter=config.reach, ) - + if not filtered_alerts: logger.debug(f"No diff alerts match filter criteria for webhook '{name}'. Skipping.") continue - + # Create a temporary diff object with filtered alerts for message creation filtered_diff = clone_diff_with_selected_alerts(diff, filtered_alerts) - + message = self.create_slack_blocks_from_diff(filtered_diff, config) - - logger.debug(f"Sending diff alerts message to {name} ({url})") - + + logger.debug(f"Sending diff alerts message to {name} ({redact_url(url)})") + if config.enable_debug: - logger.debug(f"Slack webhook URL: {url}") + logger.debug(f"Slack webhook URL: {redact_url(url)}") logger.debug(f"Slack webhook name: {name}") - logger.debug(f"Total diff alerts: {len(diff_alert_source)}, Filtered alerts: {len(filtered_alerts)}") + logger.debug( + f"Total diff alerts: {len(diff_alert_source)}, Filtered alerts: {len(filtered_alerts)}" + ) logger.debug(f"Message blocks count: {len(message)}") - + response = requests.post( url, - json={"blocks": message} + json={"blocks": message}, + timeout=REQUEST_TIMEOUT_SECONDS, ) if response.status_code >= 400: @@ -134,7 +138,7 @@ def _send_bot_alerts(self, diff, config: CliConfig): """Send alerts using bot mode with Slack API.""" # Get bot token from environment bot_token = os.getenv("SOCKET_SLACK_BOT_TOKEN") - + if not bot_token: logger.error("SOCKET_SLACK_BOT_TOKEN environment variable not set for bot mode.") return @@ -158,14 +162,14 @@ def _send_bot_alerts(self, diff, config: CliConfig): logger.debug(f"config.reach: {config.reach}") diff_alert_source = select_diff_alerts(diff, strict_blocking=config.strict_blocking) logger.debug(f"len(diff alert source): {len(diff_alert_source) if diff_alert_source else 0}") - + # Get repo name from config repo_name = config.repo or "" - + # Handle reachability data if --reach is enabled if config.reach: self._send_bot_reachability_alerts(bot_configs, bot_token, repo_name, config, diff) - + # Handle diff alerts (if any) if not diff_alert_source: logger.debug("No new diff alerts to notify via Slack.") @@ -174,41 +178,45 @@ def _send_bot_alerts(self, diff, config: CliConfig): for bot_config in bot_configs: name = bot_config.get("name", "unnamed") channels = bot_config.get("channels", []) - + if not channels: logger.warning(f"No channels configured for bot_config '{name}'. Skipping.") continue - + # Filter alerts based on bot config # When --reach is used, reachability_alerts_only applies to diff alerts filtered_alerts = self._filter_alerts( diff_alert_source, - bot_config, - repo_name, + bot_config, + repo_name, config, is_reachability_data=False, - apply_reachability_only_filter=config.reach + apply_reachability_only_filter=config.reach, ) - + if not filtered_alerts: logger.debug(f"No diff alerts match filter criteria for bot_config '{name}'. Skipping.") continue - + # Create a temporary diff object with filtered alerts for message creation filtered_diff = clone_diff_with_selected_alerts(diff, filtered_alerts) - + message = self.create_slack_blocks_from_diff(filtered_diff, config) - + if config.enable_debug: - logger.debug(f"Bot config '{name}': Total diff alerts: {len(diff_alert_source)}, Filtered alerts: {len(filtered_alerts)}") + logger.debug( + f"Bot config '{name}': Total diff alerts: {len(diff_alert_source)}, Filtered alerts: {len(filtered_alerts)}" + ) logger.debug(f"Message blocks count: {len(message)}") - + # Send to each channel in the bot_config for channel in channels: logger.debug(f"Sending diff alerts message to channel '{channel}' (bot_config: {name})") self._post_to_slack_api(bot_token, channel, message, config, name) - def _send_bot_reachability_alerts(self, bot_configs: list, bot_token: str, repo_name: str, config: CliConfig, diff=None): + def _send_bot_reachability_alerts( # noqa: C901 + self, bot_configs: list, bot_token: str, repo_name: str, config: CliConfig, diff=None + ): """Send reachability alerts using bot mode with Slack API.""" # Construct path to socket facts file facts_file_path = os.path.join(config.target_path or ".", f"{config.reach_output_file}") @@ -228,7 +236,9 @@ def _send_bot_reachability_alerts(self, bot_configs: list, bot_token: str, repo_ # Get components with vulnerabilities components_with_vulns = get_components_with_vulnerabilities(facts_data) - logger.debug(f"Components with vulnerabilities in facts file: {len(components_with_vulns) if components_with_vulns else 0}") + logger.debug( + f"Components with vulnerabilities in facts file: {len(components_with_vulns) if components_with_vulns else 0}" + ) if not components_with_vulns: logger.debug("No components with vulnerabilities found in .socket.facts.json") @@ -242,92 +252,78 @@ def _send_bot_reachability_alerts(self, bot_configs: list, bot_token: str, repo_ return logger.debug(f"Found {len(components_with_alerts)} components with reachability alerts") - + # Send to each configured bot_config with filtering for bot_config in bot_configs: name = bot_config.get("name", "unnamed") channels = bot_config.get("channels", []) - + if not channels: logger.warning(f"No channels configured for bot_config '{name}'. Skipping.") continue - + # Filter components based on severities only (for reachability data) filtered_components = [] for component in components_with_alerts: - component_alerts = component.get('alerts', []) + component_alerts = component.get("alerts", []) # Filter alerts using only severities filtered_component_alerts = self._filter_alerts( - component_alerts, - bot_config, - repo_name, - config, - is_reachability_data=True + component_alerts, bot_config, repo_name, config, is_reachability_data=True ) - + if filtered_component_alerts: # Create a copy of component with only filtered alerts filtered_component = component.copy() - filtered_component['alerts'] = filtered_component_alerts + filtered_component["alerts"] = filtered_component_alerts filtered_components.append(filtered_component) - - logger.debug(f"Bot config '{name}': {len(filtered_components)} components after severity filter {bot_config.get('severities', '(all)')}") + + logger.debug( + f"Bot config '{name}': {len(filtered_components)} components after severity filter {bot_config.get('severities', '(all)')}" + ) if not filtered_components: logger.debug(f"No reachability alerts match filter criteria for bot_config '{name}'. Skipping.") continue # Format for Slack using the formatter (max 45 blocks for findings + 5 for header/footer) - slack_notifications = format_socket_facts_for_slack( - filtered_components, - max_blocks=45, - include_traces=True - ) - + slack_notifications = format_socket_facts_for_slack(filtered_components, max_blocks=45, include_traces=True) + # Convert to Slack blocks format and send for notification in slack_notifications: - blocks = self._create_reachability_slack_blocks_from_structured( - notification, - config, - diff - ) - + blocks = self._create_reachability_slack_blocks_from_structured(notification, config, diff) + if config.enable_debug: logger.debug(f"Bot config '{name}': Reachability components: {len(filtered_components)}") logger.debug(f"Message blocks count: {len(blocks)}") - + # Send to each channel in the bot_config for channel in channels: logger.debug(f"Sending reachability alerts message to channel '{channel}' (bot_config: {name})") self._post_to_slack_api(bot_token, channel, blocks, config, name) - def _post_to_slack_api(self, bot_token: str, channel: str, blocks: list, config: CliConfig, config_name: str = None): + def _post_to_slack_api( + self, bot_token: str, channel: str, blocks: list, config: CliConfig, config_name: str | None = None + ): """Post message to Slack using chat.postMessage API. - + Args: bot_token: Slack bot token (starts with xoxb-) channel: Channel name (without #) or channel ID (C1234567890) blocks: List of Slack blocks to send config: CliConfig object for debug logging config_name: Name of the bot_config for logging - + Returns: Response dict from Slack API """ url = "https://slack.com/api/chat.postMessage" - headers = { - "Authorization": f"Bearer {bot_token}", - "Content-Type": "application/json" - } - payload = { - "channel": channel, - "blocks": blocks - } - + headers = {"Authorization": f"Bearer {bot_token}", "Content-Type": "application/json"} + payload = {"channel": channel, "blocks": blocks} + try: - response = requests.post(url, headers=headers, json=payload) + response = requests.post(url, headers=headers, json=payload, timeout=REQUEST_TIMEOUT_SECONDS) response_data = response.json() - + # Slack returns 200 even on errors, check response JSON if not response_data.get("ok", False): error_msg = response_data.get("error", "unknown error") @@ -336,31 +332,31 @@ def _post_to_slack_api(self, bot_token: str, channel: str, blocks: list, config: logger.debug(f"Full response: {response_data}") elif config.enable_debug: logger.debug(f"Successfully posted to channel '{channel}' (config: {config_name})") - + return response_data - + except Exception as e: - logger.error(f"Exception posting to Slack channel '{channel}': {str(e)}") + logger.error(f"Exception posting to Slack channel '{channel}': {e!s}") return {"ok": False, "error": str(e)} - def _filter_alerts( - self, - alerts: list, - webhook_config: dict, - repo_name: str, + def _filter_alerts( # noqa: C901 + self, + alerts: list, + webhook_config: dict, + repo_name: str, config: CliConfig, is_reachability_data: bool = False, - apply_reachability_only_filter: bool = False + apply_reachability_only_filter: bool = False, ) -> list: """ Filter alerts based on webhook configuration. - + Empty lists or missing keys mean no filtering for that criteria: - repos: [] or missing โ†’ all repos allowed - alert_types: [] or missing โ†’ no alert_type filtering - - severities: [] or missing โ†’ no severity filtering + - severities: [] or missing โ†’ no severity filtering - reachability_alerts_only: missing โ†’ defaults to False - + Args: alerts: List of Issue objects to filter webhook_config: Config dict with optional keys: repos, alert_types, severities, reachability_alerts_only @@ -368,23 +364,25 @@ def _filter_alerts( config: CliConfig object is_reachability_data: If True, only apply severities filter (for .socket.facts.json data) apply_reachability_only_filter: If True, apply reachability_alerts_only filter (only when --reach is used) - + Returns: Filtered list of alerts matching the criteria """ filtered = [] - + # Extract filter configs (empty list/False means no filtering) repos_filter = webhook_config.get("repos", []) alert_types = webhook_config.get("alert_types", []) severities = webhook_config.get("severities", []) reachability_only = webhook_config.get("reachability_alerts_only", False) - + if config.enable_debug: - logger.debug(f"Filtering {'reachability' if is_reachability_data else 'diff'} alerts with: " - f"repos={repos_filter}, alert_types={alert_types}, " - f"severities={severities}, reachability_only={reachability_only}, " - f"apply_reachability_only={apply_reachability_only_filter}") + logger.debug( + f"Filtering {'reachability' if is_reachability_data else 'diff'} alerts with: " + f"repos={repos_filter}, alert_types={alert_types}, " + f"severities={severities}, reachability_only={reachability_only}, " + f"apply_reachability_only={apply_reachability_only_filter}" + ) reachable_alert_identity_set = None if apply_reachability_only_filter and reachability_only: @@ -397,7 +395,7 @@ def _filter_alerts( fallback_to_blocking_for_reachable=True, ) reachable_alert_identity_set = {id(a) for a in reachable_alerts} - + for alert in alerts: # For reachability data, only apply severities filter if is_reachability_data: @@ -408,37 +406,38 @@ def _filter_alerts( continue filtered.append(alert) continue - + # For diff alerts, apply all filters # Filter by repos (empty list = all repos allowed) if repos_filter and repo_name not in repos_filter: continue - + # Filter by reachability_alerts_only (only when --reach is used) if reachable_alert_identity_set is not None and id(alert) not in reachable_alert_identity_set: - continue - + continue + # Filter by alert_types (overrides severity, empty list = no filtering) if alert_types: alert_type = getattr(alert, "type", "") if alert_type not in alert_types: continue - else: - # Only apply severity filter if alert_types is not specified - # Empty severities list = all severities allowed - if severities: - alert_severity = getattr(alert, "severity", "") - if alert_severity not in severities: - continue - + # Only apply severity filter if alert_types is not specified + # Empty severities list = all severities allowed + elif severities: + alert_severity = getattr(alert, "severity", "") + if alert_severity not in severities: + continue + filtered.append(alert) - + return filtered - def _send_reachability_alerts(self, valid_webhooks: list, webhook_configs: dict, repo_name: str, config: CliConfig, diff=None): + def _send_reachability_alerts( + self, valid_webhooks: list, webhook_configs: dict, repo_name: str, config: CliConfig, diff=None + ): """ Load and send reachability alerts from .socket.facts.json file. - + Args: valid_webhooks: List of validated webhook configurations webhook_configs: Dictionary of webhook configurations with filters @@ -448,226 +447,188 @@ def _send_reachability_alerts(self, valid_webhooks: list, webhook_configs: dict, """ # Construct path to socket facts file import os as os_module + facts_file_path = os_module.path.join(config.target_path or ".", config.reach_output_file) logger.debug(f"Loading reachability data from {facts_file_path}") - + # Load socket facts file facts_data = load_socket_facts(facts_file_path) - + if not facts_data: logger.debug("No .socket.facts.json file found or failed to load") return - + # Get components with vulnerabilities components_with_vulns = get_components_with_vulnerabilities(facts_data) - + if not components_with_vulns: logger.debug("No components with vulnerabilities found in .socket.facts.json") return - + # Convert to alerts format components_with_alerts = convert_to_alerts(components_with_vulns) - + if not components_with_alerts: logger.debug("No alerts generated from .socket.facts.json") return - + logger.debug(f"Found {len(components_with_alerts)} components with reachability alerts") - + # Send to each configured webhook with filtering for url_config in valid_webhooks: url = url_config["url"] name = url_config["name"] webhook_config = webhook_configs[name] - + # Filter components based on severities only (for reachability data) filtered_components = [] for component in components_with_alerts: - component_alerts = component.get('alerts', []) + component_alerts = component.get("alerts", []) # Filter alerts using only severities filtered_component_alerts = self._filter_alerts( - component_alerts, - webhook_config, - repo_name, - config, - is_reachability_data=True + component_alerts, webhook_config, repo_name, config, is_reachability_data=True ) - + if filtered_component_alerts: # Create a copy of component with only filtered alerts filtered_component = component.copy() - filtered_component['alerts'] = filtered_component_alerts + filtered_component["alerts"] = filtered_component_alerts filtered_components.append(filtered_component) - + if not filtered_components: logger.debug(f"No reachability alerts match filter criteria for webhook '{name}'. Skipping.") continue - + # Format for Slack using the formatter (max 45 blocks for findings + 5 for header/footer) - slack_notifications = format_socket_facts_for_slack( - filtered_components, - max_blocks=45, - include_traces=True - ) - + slack_notifications = format_socket_facts_for_slack(filtered_components, max_blocks=45, include_traces=True) + # Convert to Slack blocks format for notification in slack_notifications: - blocks = self._create_reachability_slack_blocks_from_structured( - notification, - config, - diff - ) - - logger.debug(f"Sending reachability alerts message to {name} ({url})") - + blocks = self._create_reachability_slack_blocks_from_structured(notification, config, diff) + + logger.debug(f"Sending reachability alerts message to {name} ({redact_url(url)})") + if config.enable_debug: - logger.debug(f"Slack webhook URL: {url}") + logger.debug(f"Slack webhook URL: {redact_url(url)}") logger.debug(f"Slack webhook name: {name}") logger.debug(f"Reachability components: {len(filtered_components)}") logger.debug(f"Message blocks count: {len(blocks)}") - + response = requests.post( url, - json={"blocks": blocks} + json={"blocks": blocks}, + timeout=REQUEST_TIMEOUT_SECONDS, ) - + if response.status_code >= 400: logger.error("Slack error for %s: %s - %s", name, response.status_code, response.text) elif config.enable_debug: logger.debug(f"Slack webhook response for {name}: {response.status_code}") - - def _create_reachability_slack_blocks_from_structured(self, notification: dict, config: CliConfig, diff=None) -> list: + + def _create_reachability_slack_blocks_from_structured( + self, notification: dict, config: CliConfig, diff=None + ) -> list: """ Create Slack blocks from structured reachability notification data. Respects Slack's 50 block limit by prioritizing critical findings. - + Args: notification: Structured notification dict from format_socket_facts_for_slack config: CliConfig object diff: Diff object containing diff_url for report link - + Returns: List of Slack block dictionaries (max 50 blocks) """ pr = getattr(config, "pr_number", None) sha = getattr(config, "commit_sha", None) diff_url = getattr(diff, "diff_url", "") if diff else "" - + title_part = "" if pr: title_part += f" for PR {pr}" if sha: title_part += f" - {sha[:8]}" - + # Header blocks (2 blocks) blocks = [ - { - "type": "section", - "text": { - "type": "mrkdwn", - "text": f"*{notification['title']}*{title_part}" - } - }, - {"type": "divider"} + {"type": "section", "text": {"type": "mrkdwn", "text": f"*{notification['title']}*{title_part}"}}, + {"type": "divider"}, ] - + # Summary block (2 blocks) - blocks.append({ - "type": "section", - "text": { - "type": "mrkdwn", - "text": notification['summary'] - } - }) + blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": notification["summary"]}}) blocks.append({"type": "divider"}) - + # Vulnerability blocks (1 block per vulnerability, max ~45) - include_traces = notification.get('include_traces', True) - for vuln in notification.get('vulnerabilities', []): - finding = vuln['finding'] - reachability = vuln['reachability'] - + include_traces = notification.get("include_traces", True) + for vuln in notification.get("vulnerabilities", []): + finding = vuln["finding"] + reachability = vuln["reachability"] + # Reachability indicator reach_indicator = { - 'reachable': '๐ŸŽฏ *Reachable*', - 'unreachable': 'โœ“ *Unreachable*', - 'unknown': 'โ“ *Unknown*', - 'error': 'โš ๏ธ *Error*' - }.get(reachability, '') - + "reachable": "๐ŸŽฏ *Reachable*", + "unreachable": "โœ“ *Unreachable*", + "unknown": "โ“ *Unknown*", + "error": "โš ๏ธ *Error*", + }.get(reachability, "") + # Build vulnerability text vuln_text = f"*Package:* `{vuln['purl']}`\n\n{reach_indicator}\n" vuln_text += f"{finding['severity_emoji']} *{finding['cve_id']}*: {finding['severity'].upper()}" - + # Add trace if enabled and available - if include_traces and reachability == 'reachable' and finding.get('trace'): + if include_traces and reachability == "reachable" and finding.get("trace"): # Format trace lines with indentation - trace_lines = finding['trace'].split('\n') - trace_text = '\n'.join(f" {line}" for line in trace_lines if line.strip()) + trace_lines = finding["trace"].split("\n") + trace_text = "\n".join(f" {line}" for line in trace_lines if line.strip()) if trace_text: vuln_text += f"\n```\n{trace_text}\n```" - - blocks.append({ - "type": "section", - "text": { - "type": "mrkdwn", - "text": vuln_text - } - }) + + blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": vuln_text}}) blocks.append({"type": "divider"}) - + # Footer with omission notice and link (1-2 blocks) - omitted_count = notification.get('omitted_count', 0) + omitted_count = notification.get("omitted_count", 0) if omitted_count > 0: - omitted_unreachable = notification.get('omitted_unreachable', 0) - omitted_low = notification.get('omitted_low', 0) - + omitted_unreachable = notification.get("omitted_unreachable", 0) + omitted_low = notification.get("omitted_low", 0) + footer_parts = [] if omitted_unreachable > 0: footer_parts.append(f"{omitted_unreachable} unreachable") if omitted_low > 0: footer_parts.append(f"{omitted_low} low severity") - + omission_text = f"โš ๏ธ *{omitted_count} findings not shown*" if footer_parts: omission_text += f" ({', '.join(footer_parts)})" - - blocks.append({ - "type": "section", - "text": { - "type": "mrkdwn", - "text": omission_text - } - }) - + + blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": omission_text}}) + # Add link to full report if available if diff_url: - blocks.append({ - "type": "section", - "text": { - "type": "mrkdwn", - "text": f"<{diff_url}|View full report >" - } - }) - + blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": f"<{diff_url}|View full report >"}}) + return blocks def _normalize_url_config(self, url_input): """ Normalize URL configuration to a consistent list of dicts format. - + Args: url_input: Can be: - string: "https://webhook.url" - list of strings: ["https://webhook1.url", "https://webhook2.url"] - list of dicts: [{"url": "https://webhook.url", "name": "unique_name"}] - + Returns: List of dicts with 'url' and 'name' keys """ if isinstance(url_input, str): return [{"url": url_input, "name": "default"}] - + if isinstance(url_input, list): normalized = [] for idx, item in enumerate(url_input): @@ -675,14 +636,14 @@ def _normalize_url_config(self, url_input): normalized.append({"url": item, "name": f"webhook_{idx}"}) elif isinstance(item, dict): if "url" not in item: - logger.warning(f"URL config item missing 'url' key: {item}") + logger.warning("URL config item missing 'url' key") continue name = item.get("name", f"webhook_{idx}") normalized.append({"url": item["url"], "name": name}) else: logger.warning(f"Invalid URL config item type: {type(item)}") return normalized - + logger.warning(f"Invalid URL config type: {type(url_input)}") return [] @@ -700,31 +661,30 @@ def create_slack_blocks_from_diff(diff: Diff, config: CliConfig): blocks = [ { "type": "section", - "text": { - "type": "mrkdwn", - "text": f"*Socket Security issues were found in this *{scan}*{title_part}*" - } + "text": {"type": "mrkdwn", "text": f"*Socket Security issues were found in this *{scan}*{title_part}*"}, }, - {"type": "divider"} + {"type": "divider"}, ] for alert in diff.new_alerts: manifest_str, source_str = Messages.create_sources(alert, "plain") manifest_str = manifest_str.lstrip("โ€ข ") source_str = source_str.lstrip("โ€ข ") - blocks.append({ - "type": "section", - "text": { - "type": "mrkdwn", - "text": ( - f"*{alert.title}*\n" - f"<{alert.url}|{alert.purl}>\n" - f"*Introduced by:* `{source_str}`\n" - f"*Manifest:* `{manifest_str}`\n" - f"*CI Status:* {'Block' if alert.error else 'Warn'}" - ) + blocks.append( + { + "type": "section", + "text": { + "type": "mrkdwn", + "text": ( + f"*{alert.title}*\n" + f"<{alert.url}|{alert.purl}>\n" + f"*Introduced by:* `{source_str}`\n" + f"*Manifest:* `{manifest_str}`\n" + f"*CI Status:* {'Block' if alert.error else 'Warn'}" + ), + }, } - }) + ) blocks.append({"type": "divider"}) return blocks diff --git a/socketsecurity/plugins/teams.py b/socketsecurity/plugins/teams.py index 9f347094..61c483b6 100644 --- a/socketsecurity/plugins/teams.py +++ b/socketsecurity/plugins/teams.py @@ -1,6 +1,6 @@ import requests -from .base import Plugin +from .base import REQUEST_TIMEOUT_SECONDS, Plugin class TeamsPlugin(Plugin): @@ -11,4 +11,4 @@ def send(self, message, level): return payload = {"text": message.get("title", "No title")} - requests.post(self.config["webhook_url"], json=payload) \ No newline at end of file + requests.post(self.config["webhook_url"], json=payload, timeout=REQUEST_TIMEOUT_SECONDS) diff --git a/socketsecurity/plugins/webhook.py b/socketsecurity/plugins/webhook.py index 17857529..921b87aa 100644 --- a/socketsecurity/plugins/webhook.py +++ b/socketsecurity/plugins/webhook.py @@ -1,6 +1,6 @@ import requests -from .base import Plugin +from .base import REQUEST_TIMEOUT_SECONDS, Plugin class WebhookPlugin(Plugin): @@ -12,4 +12,4 @@ def send(self, message, level): url = self.config["url"] headers = self.config.get("headers", {"Content-Type": "application/json"}) - requests.post(url, json=message, headers=headers) \ No newline at end of file + requests.post(url, json=message, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS) diff --git a/socketsecurity/redaction.py b/socketsecurity/redaction.py new file mode 100644 index 00000000..c5fbd11d --- /dev/null +++ b/socketsecurity/redaction.py @@ -0,0 +1,94 @@ +"""Mask credential fields and integration URL paths in debug logging.""" + +from typing import Any +from urllib.parse import urlsplit + +REDACTED = "***redacted***" + +# Match credential-bearing field names, including nested plugin settings. +_SENSITIVE_NAME_MARKERS = ( + "apikey", + "api_key", + "auth", + "credential", + "passwd", + "password", + "secret", + "token", + "url", + "webhook", +) + + +def is_sensitive_name(name: str) -> bool: + """Whether a field name looks like it holds a credential.""" + lowered = name.lower() + # The ignore-command authorization policy is public configuration. + if lowered == "ignore_authorization": + return False + return any(marker in lowered for marker in _SENSITIVE_NAME_MARKERS) + + +def redact_url(value: Any) -> Any: + """Reduce a URL to scheme and host, dropping the parts that carry secrets. + + For webhook-style URLs the sensitive part is the path, so keeping the host + preserves what a debug line is for -- seeing which endpoint is configured -- + without writing the rest. + + Values that are not absolute URLs are returned unchanged, so placeholders + such as "Not configured" stay readable. + """ + if not isinstance(value, str) or not value: + return value + try: + parts = urlsplit(value) + host = parts.hostname + port = parts.port + except ValueError: + return REDACTED + if not parts.scheme or not host: + return value + if ":" in host: + host = f"[{host}]" + if port: + host = f"{host}:{port}" + return f"{parts.scheme}://{host}/{REDACTED}" + + +def redact_mapping(data: dict[str, Any]) -> dict[str, Any]: + """Copy a mapping, masking credential fields recursively. + + Empty and unset values are left alone: "no token configured" is useful + debugging information and is not a secret. + """ + redacted: dict[str, Any] = {} + for key, value in data.items(): + if not value: + redacted[key] = value + elif is_sensitive_name(key): + redacted[key] = _redact_sensitive_value(value) + else: + redacted[key] = _redact_nested(value) + return redacted + + +def _redact_sensitive_value(value: Any) -> str: + if isinstance(value, str): + try: + parts = urlsplit(value) + if parts.scheme and parts.hostname: + return redact_url(value) + except ValueError: + pass + return REDACTED + + +def _redact_nested(value: Any) -> Any: + if isinstance(value, dict): + return redact_mapping(value) + if isinstance(value, list): + return [_redact_nested(item) for item in value] + if isinstance(value, tuple): + return tuple(_redact_nested(item) for item in value) + return value diff --git a/socketsecurity/socketcli.py b/socketsecurity/socketcli.py index 586d1c0a..6aef1448 100644 --- a/socketsecurity/socketcli.py +++ b/socketsecurity/socketcli.py @@ -4,8 +4,8 @@ import shutil import sys import traceback -from datetime import datetime, timezone -from typing import List, NoReturn, Optional, Tuple +from datetime import UTC, datetime +from typing import NoReturn from uuid import uuid4 from dotenv import load_dotenv @@ -58,8 +58,8 @@ def _emit_infrastructure_error(message: str, include_traceback: bool = False) -> --exit-code-on-api-error). """ if IS_BUILDKITE: - print("^^^ +++", flush=True) - print("--- :warning: Socket infrastructure error", flush=True) + print("^^^ +++", flush=True) # noqa: T201 + print("--- :warning: Socket infrastructure error", flush=True) # noqa: T201 log.error(message) @@ -75,9 +75,7 @@ def _emit_infrastructure_error(message: str, include_traceback: bool = False) -> def _log_scan_mode_fallback(requested: str, effective: str, reason: str) -> None: - log.info( - f"Scan mode: requested={requested} effective={effective} reason={reason}" - ) + log.info(f"Scan mode: requested={requested} effective={effective} reason={reason}") def build_license_artifact_payload( @@ -110,6 +108,7 @@ def build_license_artifact_payload( all_packages[package.id] = output return all_packages + def _write_attribution_file(config, payload: dict) -> None: Core.save_file(config.license_file_name, json.dumps(payload, indent=2)) @@ -159,29 +158,27 @@ def _match_ignored_alerts_for_telemetry( return [ alert for alert in ignored_alerts - if any( - Comments.matches_issue(alert, name, version) - for name, version in ignore_commands - ) + if any(Comments.matches_issue(alert, name, version) for name, version in ignore_commands) ] + def _select_pull_request_provider(integration_type: str, scm_type: str) -> str: """Prefer an active comment adapter when resolving pull request context.""" return scm_type if scm_type in ("github", "gitlab") else integration_type -def create_scm_scan( +def create_scm_scan( # noqa: PLR0913 core: Core, config: CliConfig, - scm_event_type: Optional[str], + scm_event_type: str | None, *, - scan_paths: List[str], + scan_paths: list[str], params: FullScanParams, no_change: bool, - base_paths: Optional[List[str]], - explicit_files: Optional[List[str]], - external_href: Optional[str], -) -> Tuple[Diff, bool]: + base_paths: list[str] | None, + explicit_files: list[str] | None, + external_href: str | None, +) -> tuple[Diff, bool]: """Create the scan for an SCM-integrated run. Only a pull request or merge request event has a baseline to compare against, @@ -202,9 +199,7 @@ def create_scm_scan( } if scm_event_type == "diff": log.info("Starting comment logic for PR/MR event") - diff = core.create_new_diff( - scan_paths, params, external_href=external_href, **scan_kwargs - ) + diff = core.create_new_diff(scan_paths, params, external_href=external_href, **scan_kwargs) return diff, True log.info("Starting non-PR/MR flow") @@ -213,7 +208,7 @@ def create_scm_scan( return diff, False -def apply_git_context(config: CliConfig) -> Tuple[bool, Optional[Git]]: +def apply_git_context(config: CliConfig) -> tuple[bool, Git | None]: """ Fill in any repo details the caller did not pass from the checkout at target_path. @@ -225,8 +220,8 @@ def apply_git_context(config: CliConfig) -> Tuple[bool, Optional[Git]]: log.debug("Not a git repository, setting ignore_commit_files=True") config.ignore_commit_files = True return False, None - except NoSuchPathError: - raise Exception(f"Unable to find path {config.target_path}") + except NoSuchPathError as error: + raise Exception(f"Unable to find path {config.target_path}") from error if not config.repo: config.repo = git_repo.repo_name @@ -248,7 +243,7 @@ def build_socket_sdk(config: CliConfig) -> socketdev: token=config.api_token, timeout=get_api_request_timeout(config), allow_unverified=config.allow_unverified, - user_agent=cli_user_agent_string + user_agent=cli_user_agent_string, ) @@ -283,17 +278,19 @@ def _exit_for_infrastructure_error(message: str, include_traceback: bool, config sys.exit(EXIT_OK if config.disable_blocking else config.exit_code_on_api_error) -def main_code(config: Optional[CliConfig] = None): +def main_code(config: CliConfig | None = None): # noqa: C901 config = config if config is not None else CliConfig.from_args() specified_files = parse_files(config.files) files_explicitly_specified = bool(specified_files) log.info(f"Starting Socket Security CLI version {config.version}") - log.debug(f"config: {config.to_dict()}") + log.debug(f"config: {config.to_redacted_dict()}") # Warn if strict-blocking is used with disable-blocking if config.strict_blocking and config.disable_blocking: - log.warning("Both --strict-blocking and --disable-blocking specified. " - "--disable-blocking takes precedence and will always return exit code 0.") + log.warning( + "Both --strict-blocking and --disable-blocking specified. " + "--disable-blocking takes precedence and will always return exit code 0." + ) # Validate API token if not config.api_token: @@ -303,12 +300,13 @@ def main_code(config: Optional[CliConfig] = None): "2. Environment variable: SOCKET_SECURITY_API_TOKEN" ) sdk = build_socket_sdk(config) - + # Suppress urllib3 InsecureRequestWarning when using --allow-unverified if config.allow_unverified: import urllib3 + urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) - + output_handler = OutputHandler(config, sdk) log.debug("sdk loaded") @@ -316,12 +314,9 @@ def main_code(config: Optional[CliConfig] = None): set_debug_mode(True) log.debug("Debug logging enabled") - # Initialize Socket core components socket_config = SocketConfig( - api_key=config.api_token, - allow_unverified_ssl=config.allow_unverified, - timeout=get_api_request_timeout(config) + api_key=config.api_token, allow_unverified_ssl=config.allow_unverified, timeout=get_api_request_timeout(config) ) log.debug("loaded socket_config") client = CliClient(socket_config) @@ -359,46 +354,44 @@ def main_code(config: Optional[CliConfig] = None): required_deps = ["node", "uv"] missing_deps = [] found_deps = [] - + for dep in required_deps: if shutil.which(dep): found_deps.append(dep) log.debug(f"Found required dependency: {dep}") else: missing_deps.append(dep) - + if missing_deps: raise InfrastructureError( f"Reachability analysis requires the following dependencies: {', '.join(required_deps)}\n" f"Missing dependencies: {', '.join(missing_deps)}\n" "Please install the missing dependencies and try again." ) - + log.info(f"All required dependencies found: {', '.join(found_deps)}") - + # Check if organization has an enterprise plan log.info("Checking organization plan for reachability analysis eligibility...") org_response = sdk.org.get(use_types=True) organizations = org_response.get("organizations", {}) - + if organizations: org_id = next(iter(organizations)) - org_plan = organizations[org_id].get('plan', '') - + org_plan = organizations[org_id].get("plan", "") + # Check if plan matches enterprise* pattern (enterprise, enterprise_trial, etc.) - if not org_plan.startswith('enterprise'): + if not org_plan.startswith("enterprise"): raise InfrastructureError( "Reachability analysis is only available for enterprise plans.\n" f"Your organization plan is: {org_plan}\n" "Please upgrade to an enterprise plan to use reachability analysis." ) - + log.info(f"Organization plan verified: {org_plan}") else: - raise InfrastructureError( - "Unable to retrieve organization information for plan verification." - ) - + raise InfrastructureError("Unable to retrieve organization information for plan verification.") + # Variable to track if we need to override files with facts file facts_file_to_submit = None # Variable to track SBOM files to submit when using --reach-use-only-pregenerated-sboms @@ -406,7 +399,7 @@ def main_code(config: Optional[CliConfig] = None): # Manifest results retained from the --sub-path routing pre-check. Reusing # these avoids walking every selected sub-path again during scan creation. discovered_scan_files = None - + # Git setup is_repo, git_repo = apply_git_context(config) @@ -430,7 +423,7 @@ def main_code(config: Optional[CliConfig] = None): # Calculate the scan paths - combine target_path with sub_paths if provided scan_paths = [] base_paths = [config.target_path] # Always use target_path as the single base path - + if config.sub_paths: for sub_path in config.sub_paths: full_scan_path = os.path.join(config.target_path, sub_path) @@ -461,38 +454,41 @@ def main_code(config: Optional[CliConfig] = None): log.info("Finding manifest files for reachability analysis...") manifest_files = [ # Always find all manifest files for the tar hash upload - f for scan_path in scan_paths for f in core.find_files(scan_path) - if not f.endswith('.socket.facts.json') + f + for scan_path in scan_paths + for f in core.find_files(scan_path) + if not f.endswith(".socket.facts.json") ] - + if not manifest_files: log.warning("No manifest files found for reachability analysis") else: log.info(f"Found {len(manifest_files)} manifest files for reachability upload") - + # Upload manifests and get tar hash log.info("Uploading manifest files...") try: # Get org_slug early (we'll need it) org_slug = core.config.org_slug - assert org_slug - + if not org_slug: + raise ValueError("Organization slug is not configured") + # Upload manifest files tar_hash = sdk.uploadmanifests.upload_manifest_files( org_slug=org_slug, file_paths=manifest_files, workspace=config.repo or "default-workspace", base_paths=[config.target_path], - use_lazy_loading=False + use_lazy_loading=False, ) log.info(f"Manifest upload successful, tar hash: {tar_hash}") - + # Initialize and run reachability analyzer analyzer = ReachabilityAnalyzer(client) - + # Determine output path output_path = config.reach_output_file or ".socket.facts.json" - + # Run the analysis result = analyzer.run_reachability_analysis( org_slug=org_slug, @@ -508,9 +504,7 @@ def main_code(config: Optional[CliConfig] = None): # here is `.` == cwd == scan root, so passthrough is correct. If a nested # target is ever supported, re-anchor patterns to the target first (see Node's # pathRelativeToTarget in exclude-paths.mts). - exclude_paths=( - (config.reach_exclude_paths or []) + (config.exclude_paths or []) - ) or None, + exclude_paths=((config.reach_exclude_paths or []) + (config.exclude_paths or [])) or None, min_severity=config.reach_min_severity, skip_cache=config.reach_skip_cache or False, disable_analytics=config.reach_disable_analytics or False, @@ -530,15 +524,15 @@ def main_code(config: Optional[CliConfig] = None): disable_external_tool_checks=config.reach_disable_external_tool_checks, disable_dependency_downloads=config.reach_disable_dependency_downloads, ) - + log.info("Reachability analysis completed successfully") log.info(f"Results written to: {result['report_path']}") - if result.get('scan_id'): + if result.get("scan_id"): log.info(f"Reachability scan ID: {result['scan_id']}") - + # If only-facts-file mode, mark the facts file for submission if config.only_facts_file: - facts_file_to_submit = os.path.abspath(result['report_path']) + facts_file_to_submit = os.path.abspath(result["report_path"]) log.info(f"Only-facts-file mode: will submit only {facts_file_to_submit}") # If reach-use-only-pregenerated-sboms mode, submit CDX, SPDX, and facts file @@ -547,17 +541,19 @@ def main_code(config: Optional[CliConfig] = None): sbom_files_to_submit = [] for scan_path in scan_paths: sbom_files_to_submit.extend(core.find_sbom_files(scan_path)) - if os.path.exists(result['report_path']): - sbom_files_to_submit.append(result['report_path']) - log.info(f"Pre-generated SBOMs mode: will submit {len(sbom_files_to_submit)} files (CDX, SPDX, and facts file)") - + if os.path.exists(result["report_path"]): + sbom_files_to_submit.append(result["report_path"]) + log.info( + f"Pre-generated SBOMs mode: will submit {len(sbom_files_to_submit)} files (CDX, SPDX, and facts file)" + ) + except Exception as e: # With --disable-blocking the scan carries on without reachability # data instead of exiting 0 before anything is reported. if not config.disable_blocking: raise InfrastructureError(f"Reachability analysis failed: {e}") from e - log.error(f"Reachability analysis failed: {str(e)}") - + log.error(f"Reachability analysis failed: {e!s}") + log.info("Continuing with normal scan flow...") # Canonicalize before any adapter reads it. Buildkite always sets @@ -570,12 +566,14 @@ def main_code(config: Optional[CliConfig] = None): scm = None if config.scm == "github": from socketsecurity.core.scm.github import Github, GithubConfig + # Only pass pr_number if it's not "0" (the default) pr_number = config.pr_number if config.pr_number != "0" else None github_config = GithubConfig.from_env(pr_number=pr_number) scm = Github(client=client, config=github_config, ignore_authorization=config.ignore_authorization) - elif config.scm == 'gitlab': + elif config.scm == "gitlab": from socketsecurity.core.scm.gitlab import Gitlab, GitlabConfig + gitlab_config = GitlabConfig.from_env() scm = Gitlab(client=client, config=gitlab_config, ignore_authorization=config.ignore_authorization) config.repository_url = resolve_repository_url( @@ -605,7 +603,7 @@ def main_code(config: Optional[CliConfig] = None): files_to_check = [] force_api_mode = False force_diff_mode = False - + if files_explicitly_specified: # Case 2: Files are specified - use them and don't check commit details files_to_check = specified_files @@ -623,7 +621,9 @@ def main_code(config: Optional[CliConfig] = None): # Case 4: Not a git repo (ignore_commit_files was auto-set to True) files_to_check = [] # If --enable-diff is set, force diff mode for non-git repos - log.debug(f"Case 4: Non-git repo - config.enable_diff={config.enable_diff}, type={type(config.enable_diff)}") + log.debug( + f"Case 4: Non-git repo - config.enable_diff={config.enable_diff}, type={type(config.enable_diff)}" + ) if config.enable_diff: force_diff_mode = True log.debug("Non-git repo with --enable-diff: forcing diff mode") @@ -632,7 +632,7 @@ def main_code(config: Optional[CliConfig] = None): # Check if we have supported manifest files has_supported_files = files_to_check and core.has_manifest_files(files_to_check) - + # If using sub_paths, we need to check if manifest files exist in the scan paths if config.sub_paths and not files_explicitly_specified: # Override file checking to look in the scan paths instead @@ -643,30 +643,27 @@ def main_code(config: Optional[CliConfig] = None): scan_files = core.find_files(scan_path) discovered_scan_files.extend(scan_files) has_supported_files = len(discovered_scan_files) > 0 - log.debug( - f"Found {len(discovered_scan_files)} manifest files across " - f"{len(scan_paths)} scan paths" - ) + log.debug(f"Found {len(discovered_scan_files)} manifest files across {len(scan_paths)} scan paths") except Exception as e: log.debug(f"Error finding files in scan paths: {e}") discovered_scan_files = None has_supported_files = False # Strict blocking needs a comparison even when file selection finds no manifest. - strict_forced_comparison = ( - config.strict_blocking and not has_supported_files and not force_diff_mode - ) + strict_forced_comparison = config.strict_blocking and not has_supported_files and not force_diff_mode if strict_forced_comparison: force_diff_mode = True # Case 3: If no supported files or files are empty, force API mode (no PR comments) # BUT: Don't force API mode if we're in force_diff_mode - log.debug(f"files_to_check={files_to_check}, has_supported_files={has_supported_files}, force_diff_mode={force_diff_mode}, config.enable_diff={config.enable_diff}") + log.debug( + f"files_to_check={files_to_check}, has_supported_files={has_supported_files}, force_diff_mode={force_diff_mode}, config.enable_diff={config.enable_diff}" + ) if not has_supported_files and not force_diff_mode: force_api_mode = True log.debug("No supported manifest files found, forcing API mode") log.debug(f"force_api_mode={force_api_mode}") - + # Determine scan behavior should_skip_scan = False # Always perform scan, but behavior changes based on supported files if not has_supported_files and not force_diff_mode: @@ -708,11 +705,11 @@ def main_code(config: Optional[CliConfig] = None): # 2. If SCM detected it's the default branch, use that # 3. If it's a git repo, use git_repo.is_default_branch # 4. Otherwise, default to False - if config.default_branch: - is_default_branch = True - elif scm is not None and hasattr(scm.config, 'is_default_branch') and scm.config.is_default_branch: - is_default_branch = True - elif is_repo and git_repo.is_default_branch: + if ( + config.default_branch + or (scm is not None and hasattr(scm.config, "is_default_branch") and scm.config.is_default_branch) + or (is_repo and git_repo.is_default_branch) + ): is_default_branch = True else: is_default_branch = False @@ -730,7 +727,7 @@ def main_code(config: Optional[CliConfig] = None): make_default_branch=is_default_branch, set_as_pending_head=is_default_branch, tmp=False, - scan_type='socket_tier1' if config.reach else 'socket', + scan_type="socket_tier1" if config.reach else "socket", workspace=config.workspace or None, ) @@ -742,14 +739,12 @@ def main_code(config: Optional[CliConfig] = None): diff.diff_url = "" diff.report_url = "" - scan_explicit_files = ( - sbom_files_to_submit - if sbom_files_to_submit is not None - else discovered_scan_files - ) + scan_explicit_files = sbom_files_to_submit if sbom_files_to_submit is not None else discovered_scan_files # Handle SCM-specific flows - log.debug(f"Flow decision: scm={scm is not None}, force_diff_mode={force_diff_mode}, force_api_mode={force_api_mode}, enable_diff={config.enable_diff}") + log.debug( + f"Flow decision: scm={scm is not None}, force_diff_mode={force_diff_mode}, force_api_mode={force_api_mode}, enable_diff={config.enable_diff}" + ) def _is_unprocessed(c): """Check if an ignore comment has not yet been marked with '+1' reaction. @@ -757,9 +752,7 @@ def _is_unprocessed(c): For GitLab, has_thumbsup_reaction() makes a lazy API call per comment.""" if getattr(c, "reactions", {}).get("+1"): return False - if hasattr(scm, "has_thumbsup_reaction") and scm.has_thumbsup_reaction(c.id): - return False - return True + return not (hasattr(scm, "has_thumbsup_reaction") and scm.has_thumbsup_reaction(c.id)) scm_event_type = scm.check_event_type() if scm is not None else None if strict_forced_comparison and scm_event_type in (None, "diff"): @@ -794,7 +787,7 @@ def _is_unprocessed(c): single = {"ignore": [c]} ignore_all, ignore_commands = Comments.get_ignore_options(single) user = getattr(c, "user", None) or getattr(c, "author", None) or {} - now = datetime.now(timezone.utc).isoformat() + now = datetime.now(UTC).isoformat() shared_fields = { "event_kind": "user-action", "client_action": "ignore", @@ -810,7 +803,13 @@ def _is_unprocessed(c): } if ignore_commands: for name, version in ignore_commands: - events.append({**shared_fields, "event_id": str(uuid4()), "artifact_input": f"{name}@{version}"}) + events.append( + { + **shared_fields, + "event_id": str(uuid4()), + "artifact_input": f"{name}@{version}", + } + ) elif ignore_all: events.append({**shared_fields, "event_id": str(uuid4())}) @@ -824,7 +823,7 @@ def _is_unprocessed(c): scm.remove_comment_alerts(comments) else: log.info("Ignore commands disabled (--disable-ignore), skipping comment processing") - + elif scm is not None and not force_api_mode: log.info("Push initiated flow") diff, comparison_ran = create_scm_scan( @@ -856,14 +855,11 @@ def _is_unprocessed(c): diff.unchanged_alerts = Comments.remove_alerts(comments, diff.unchanged_alerts) ignored_alerts += [a for a in existing_before if a not in diff.unchanged_alerts] # Emit telemetry per-comment so each event carries the comment author. - unprocessed_ignore = [ - c for c in comments.get("ignore", []) - if _is_unprocessed(c) - ] + unprocessed_ignore = [c for c in comments.get("ignore", []) if _is_unprocessed(c)] if ignored_alerts and unprocessed_ignore: try: events = [] - now = datetime.now(timezone.utc).isoformat() + now = datetime.now(UTC).isoformat() for c in unprocessed_ignore: single = {"ignore": [c]} c_ignore_all, c_ignore_commands = Comments.get_ignore_options(single) @@ -901,7 +897,14 @@ def _is_unprocessed(c): alert_action = "monitor" else: alert_action = "error" - events.append({**shared_fields, "alert_action": alert_action, "event_id": str(uuid4()), "artifact_purl": alert.purl}) + events.append( + { + **shared_fields, + "alert_action": alert_action, + "event_id": str(uuid4()), + "artifact_purl": alert.purl, + } + ) elif c_ignore_all: events.append({**shared_fields, "event_id": str(uuid4())}) @@ -917,24 +920,24 @@ def _is_unprocessed(c): log.info("Ignore commands disabled (--disable-ignore), all alerts will be reported") log.debug("Creating Dependency Overview Comment") - + overview_comment = Messages.dependency_overview_template(diff) log.debug("Creating Security Issues Comment") - + security_comment = Messages.security_comment_template(diff, config) - + update_old_security_comment = ( - security_comment is None or - security_comment == "" or - (len(comments) != 0 and comments.get("security") is not None) + security_comment is None + or security_comment == "" + or (len(comments) != 0 and comments.get("security") is not None) ) - + update_old_overview_comment = ( - overview_comment is None or - overview_comment == "" or - (len(comments) != 0 and comments.get("overview") is not None) + overview_comment is None + or overview_comment == "" + or (len(comments) != 0 and comments.get("overview") is not None) ) - + new_security_comment = should_write_comment( config.disable_security_issue, len(diff.new_alerts) > 0 or bool(Messages.existing_comment_alerts(diff, config)), @@ -943,12 +946,14 @@ def _is_unprocessed(c): if not new_security_comment: log.debug("Security issue comment disabled, or no alerts and none to update") - has_dependency_changes = any(( - diff.new_packages, - diff.updated_packages, - diff.removed_packages, - diff.replaced_packages, - )) + has_dependency_changes = any( + ( + diff.new_packages, + diff.updated_packages, + diff.removed_packages, + diff.replaced_packages, + ) + ) new_overview_comment = should_write_comment( config.disable_overview, has_dependency_changes, @@ -956,14 +961,10 @@ def _is_unprocessed(c): ) if not new_overview_comment: log.debug("Dependency Overview comment disabled, or no packages and none to update") - + log.debug(f"Adding comments for {config.scm}") scm.add_socket_comments( - security_comment, - overview_comment, - comments, - new_security_comment, - new_overview_comment + security_comment, overview_comment, comments, new_security_comment, new_overview_comment ) output_handler.handle_output(diff) @@ -982,9 +983,11 @@ def _is_unprocessed(c): external_href=pr_context.url, ) output_handler.handle_output(diff) - + elif (config.enable_diff or force_diff_mode) and force_api_mode: - log.warning("--enable-diff was specified but no supported manifest files were detected in the changed files. Falling back to full scan mode.") + log.warning( + "--enable-diff was specified but no supported manifest files were detected in the changed files. Falling back to full scan mode." + ) _log_scan_mode_fallback( "diff", "full", @@ -1003,58 +1006,55 @@ def _is_unprocessed(c): save_files_list_path=config.save_submitted_files_list, save_manifest_tar_path=config.save_manifest_tar, base_paths=base_paths, - explicit_files=scan_explicit_files + explicit_files=scan_explicit_files, ) log.info(f"Full scan created with ID: {diff.id}") log.info(f"Full scan report URL: {diff.report_url}") output_handler.handle_output(diff) + elif force_api_mode: + _log_scan_mode_fallback( + "default", + "full", + "no-supported-manifest-in-changed-files", + ) + log.info("No supported manifest detected in the changed-file set; creating a full Socket report") + serializable_params = { + key: value if isinstance(value, (int, float, str, list, dict, bool, type(None))) else str(value) + for key, value in params.__dict__.items() + } + log.debug(f"params={serializable_params}") + diff = core.create_full_scan_with_report_url( + scan_paths, + params, + no_change=should_skip_scan, + save_files_list_path=config.save_submitted_files_list, + save_manifest_tar_path=config.save_manifest_tar, + base_paths=base_paths, + explicit_files=scan_explicit_files, + ) + log.info(f"Full scan created with ID: {diff.id}") + log.info(f"Full scan report URL: {diff.report_url}") + output_handler.handle_output(diff) else: - if force_api_mode: - _log_scan_mode_fallback( - "default", - "full", - "no-supported-manifest-in-changed-files", - ) - log.info( - "No supported manifest detected in the changed-file set; " - "creating a full Socket report" - ) - serializable_params = { - key: value if isinstance(value, (int, float, str, list, dict, bool, type(None))) else str(value) - for key, value in params.__dict__.items() - } - log.debug(f"params={serializable_params}") - diff = core.create_full_scan_with_report_url( - scan_paths, - params, - no_change=should_skip_scan, - save_files_list_path=config.save_submitted_files_list, - save_manifest_tar_path=config.save_manifest_tar, - base_paths=base_paths, - explicit_files=scan_explicit_files - ) - log.info(f"Full scan created with ID: {diff.id}") - log.info(f"Full scan report URL: {diff.report_url}") - output_handler.handle_output(diff) - else: - log.info("API Mode") - diff = core.create_new_diff( - scan_paths, params, - no_change=should_skip_scan, - save_files_list_path=config.save_submitted_files_list, - save_manifest_tar_path=config.save_manifest_tar, - base_paths=base_paths, - explicit_files=scan_explicit_files, - external_href=pr_context.url, - ) - output_handler.handle_output(diff) + log.info("API Mode") + diff = core.create_new_diff( + scan_paths, + params, + no_change=should_skip_scan, + save_files_list_path=config.save_submitted_files_list, + save_manifest_tar_path=config.save_manifest_tar, + base_paths=base_paths, + explicit_files=scan_explicit_files, + external_href=pr_context.url, + ) + output_handler.handle_output(diff) if diff.id not in ("NO_DIFF_RAN", "NO_SCAN_RAN"): streaming.set_report_run_id(diff.id) # Handle license generation - if not should_skip_scan and diff.id != "NO_DIFF_RAN" and diff.id != "NO_SCAN_RAN" and config.generate_license: + if not should_skip_scan and diff.id not in {"NO_DIFF_RAN", "NO_SCAN_RAN"} and config.generate_license: all_packages = build_license_artifact_payload( diff, legal_format=getattr(config, "legal_format", "socket"), @@ -1072,8 +1072,10 @@ def _is_unprocessed(c): # (no supported manifest files, so nothing to compare). if force_api_mode or not comparison_ran: if config.strict_blocking: - log.warning("--strict-blocking is only supported in diff mode. " - "A full scan (no diff) cannot evaluate existing violations.") + log.warning( + "--strict-blocking is only supported in diff mode. " + "A full scan (no diff) cannot evaluate existing violations." + ) if not config.disable_blocking: log.debug("Temporarily enabling disable_blocking: this run created a full scan, not a comparison") config.disable_blocking = True @@ -1081,13 +1083,14 @@ def _is_unprocessed(c): # Post commit status to GitLab if enabled if config.enable_commit_status and scm is not None: from socketsecurity.core.scm.gitlab import Gitlab + if isinstance(scm, Gitlab) and scm.config.mr_project_id: scm.enable_merge_pipeline_check() passed = output_handler.report_pass(diff) state = "success" if passed else "failed" new_blocking = sum(1 for a in diff.new_alerts if a.error) unchanged_blocking = 0 - if config.strict_blocking and hasattr(diff, 'unchanged_alerts'): + if config.strict_blocking and hasattr(diff, "unchanged_alerts"): unchanged_blocking = sum(1 for a in diff.unchanged_alerts if a.error) blocking_count = new_blocking + unchanged_blocking if passed: @@ -1105,5 +1108,5 @@ def _is_unprocessed(c): sys.exit(output_handler.return_exit_code(diff)) -if __name__ == '__main__': +if __name__ == "__main__": cli() diff --git a/tests/core/conftest.py b/tests/core/conftest.py index ae6b10c0..45575019 100644 --- a/tests/core/conftest.py +++ b/tests/core/conftest.py @@ -30,61 +30,49 @@ def _load_json(path: Path): @pytest.fixture def repo_info_response(data_dir, load_json): json_data = load_json(data_dir / "repos" / "repo_info_success.json") - return GetRepoResponse.from_dict({ - "success": json_data["success"], - "status": json_data["status"], - "data": json_data["data"] - }) + return GetRepoResponse.from_dict( + {"success": json_data["success"], "status": json_data["status"], "data": json_data["data"]} + ) @pytest.fixture def head_scan_metadata(data_dir, load_json): json_data = load_json(data_dir / "fullscans" / "head_scan" / "metadata.json") - return GetFullScanMetadataResponse.from_dict({ - "success": json_data["success"], - "status": json_data["status"], - "data": json_data["data"] - }) + return GetFullScanMetadataResponse.from_dict( + {"success": json_data["success"], "status": json_data["status"], "data": json_data["data"]} + ) @pytest.fixture def head_scan_stream(data_dir, load_json): json_data = load_json(data_dir / "fullscans" / "head_scan" / "stream_scan.json") - return FullScanStreamResponse.from_dict({ - "success": json_data["success"], - "status": json_data["status"], - "artifacts": json_data["artifacts"] - }) + return FullScanStreamResponse.from_dict( + {"success": json_data["success"], "status": json_data["status"], "artifacts": json_data["artifacts"]} + ) @pytest.fixture def new_scan_metadata(data_dir, load_json): json_data = load_json(data_dir / "fullscans" / "new_scan" / "metadata.json") - return GetFullScanMetadataResponse.from_dict({ - "success": json_data["success"], - "status": json_data["status"], - "data": json_data["data"] - }) + return GetFullScanMetadataResponse.from_dict( + {"success": json_data["success"], "status": json_data["status"], "data": json_data["data"]} + ) @pytest.fixture def new_scan_stream(data_dir, load_json): json_data = load_json(data_dir / "fullscans" / "new_scan" / "stream_scan.json") - return FullScanStreamResponse.from_dict({ - "success": json_data["success"], - "status": json_data["status"], - "artifacts": json_data["artifacts"] - }) + return FullScanStreamResponse.from_dict( + {"success": json_data["success"], "status": json_data["status"], "artifacts": json_data["artifacts"]} + ) @pytest.fixture def stream_diff_response(data_dir, load_json): json_data = load_json(data_dir / "fullscans" / "diff" / "stream_diff.json") - return StreamDiffResponse.from_dict({ - "success": json_data["success"], - "status": json_data["status"], - "data": json_data["data"] - }) + return StreamDiffResponse.from_dict( + {"success": json_data["success"], "status": json_data["status"], "data": json_data["data"]} + ) @pytest.fixture @@ -103,37 +91,30 @@ def diff_scan_get_response(data_dir, load_json): } - - - @pytest.fixture def repo_info_error(data_dir, load_json): json_data = load_json(data_dir / "repos" / "repo_info_error.json") - return GetRepoResponse.from_dict({ - "success": json_data["success"], - "status": json_data["status"], - "message": json_data["message"], - }) + return GetRepoResponse.from_dict( + { + "success": json_data["success"], + "status": json_data["status"], + "message": json_data["message"], + } + ) @pytest.fixture def repo_info_no_head(data_dir, load_json): json_data = load_json(data_dir / "repos" / "repo_info_no_head.json") - return GetRepoResponse.from_dict({ - "success": json_data["success"], - "status": json_data["status"], - "data": json_data["data"] - }) + return GetRepoResponse.from_dict( + {"success": json_data["success"], "status": json_data["status"], "data": json_data["data"]} + ) @pytest.fixture def create_full_scan_response(data_dir, load_json): json_data = load_json(data_dir / "fullscans" / "create_response.json") - return CreateFullScanResponse.from_dict({ - "success": True, - "status": 201, - "data": json_data - }) + return CreateFullScanResponse.from_dict({"success": True, "status": 201, "data": json_data}) # Mock SDK Fixtures @@ -144,7 +125,7 @@ def mock_socket_sdk(mocker): @pytest.fixture -def mock_sdk_with_responses( +def mock_sdk_with_responses( # noqa: PLR0913 mock_socket_sdk, repo_info_response, repo_info_error, @@ -159,11 +140,7 @@ def mock_sdk_with_responses( ): sdk = mock_socket_sdk.return_value - sdk.org.get.return_value = { - "organizations": { - "test-org-id": {"slug": "test-org"} - } - } + sdk.org.get.return_value = {"organizations": {"test-org-id": {"slug": "test-org"}}} sdk.licensemetadata.post.return_value = [{"text": ""}] # Simple returns @@ -186,9 +163,7 @@ def mock_sdk_with_responses( "new": new_scan_stream, }[scan_id] - sdk.fullscans.stream_diff.side_effect = ( - lambda org_slug, head_id, new_id, **kwargs: stream_diff_response - ) + sdk.fullscans.stream_diff.side_effect = lambda org_slug, head_id, new_id, **kwargs: stream_diff_response # Diff-scans endpoints (primary scan-comparison path) sdk.diffscans.create_from_ids.return_value = {"diff_scan": {"id": "diff-scan-123"}} diff --git a/tests/core/test_alert_consolidation.py b/tests/core/test_alert_consolidation.py index e0a7d331..d2e79c85 100644 --- a/tests/core/test_alert_consolidation.py +++ b/tests/core/test_alert_consolidation.py @@ -5,6 +5,7 @@ package shares an alert type, so the key has to include the advisory ID, or a package's second advisory is dropped along with any blocking action it carries. """ + from unittest.mock import Mock import pytest @@ -156,10 +157,13 @@ def test_gitlab_report_keeps_each_advisory_as_its_own_finding(): @pytest.mark.parametrize("advisory", ["", "GHSA-aaaa-aaaa-aaaa"]) -@pytest.mark.parametrize("coordinates", [ - (("npm", "lodash@4.17.20"), ("pypi", "lodash@4.17.20")), - (("maven", "org.first/lodash@4.17.20"), ("maven", "org.second/lodash@4.17.20")), -]) +@pytest.mark.parametrize( + "coordinates", + [ + (("npm", "lodash@4.17.20"), ("pypi", "lodash@4.17.20")), + (("maven", "org.first/lodash@4.17.20"), ("maven", "org.second/lodash@4.17.20")), + ], +) def test_gitlab_report_keeps_distinct_package_coordinates(advisory, coordinates): alerts = [] for index, (ecosystem, purl) in enumerate(coordinates): @@ -190,10 +194,14 @@ def test_gitlab_report_deduplicates_a_finding_listed_as_new_and_existing(): assert len(report["vulnerabilities"]) == 1 -@pytest.mark.parametrize("purl", [ - "org.first/lodash@4.17.20", "maven/org.first/lodash@4.17.20", - "pkg:maven/org.first/lodash@4.17.20", -]) +@pytest.mark.parametrize( + "purl", + [ + "org.first/lodash@4.17.20", + "maven/org.first/lodash@4.17.20", + "pkg:maven/org.first/lodash@4.17.20", + ], +) def test_gitlab_ids_are_stable_across_full_scan_and_diff_purl_formats(purl): alert = _cve("GHSA-aaaa-aaaa-aaaa", pkg_type="maven") alert.purl = "org.first/lodash@4.17.20" @@ -205,8 +213,14 @@ def test_gitlab_ids_are_stable_across_full_scan_and_diff_purl_formats(purl): def test_gitlab_ids_for_findings_without_an_advisory_ignore_manifest_changes(): alert = Issue( - pkg_type="npm", pkg_name="a", pkg_version="1.0.0", purl="a@1.0.0", - type="malware", severity="critical", props={}, manifests="package.json", + pkg_type="npm", + pkg_name="a", + pkg_version="1.0.0", + purl="a@1.0.0", + type="malware", + severity="critical", + props={}, + manifests="package.json", ) expected = Messages.generate_uuid_from_alert_gitlab(alert) alert.manifests = "nested/package.json" diff --git a/tests/core/test_cli_exit_contract.py b/tests/core/test_cli_exit_contract.py index 0ac35be9..2ba6a27c 100644 --- a/tests/core/test_cli_exit_contract.py +++ b/tests/core/test_cli_exit_contract.py @@ -25,8 +25,12 @@ pytest.param(["--disable-blocking", "--exit-code-on-api-error", "100"], 0, id="both"), ] TOKEN_VARS = ( - "SOCKET_SECURITY_API_KEY", "SOCKET_SECURITY_API_TOKEN", "SOCKET_API_KEY", "SOCKET_API_TOKEN", - "GH_API_TOKEN", "GITLAB_TOKEN", + "SOCKET_SECURITY_API_KEY", + "SOCKET_SECURITY_API_TOKEN", + "SOCKET_API_KEY", + "SOCKET_API_TOKEN", + "GH_API_TOKEN", + "GITLAB_TOKEN", ) @@ -61,9 +65,17 @@ def run(flags=(), *, token=True): @pytest.mark.parametrize("policy, infrastructure_code", POLICIES) -@pytest.mark.parametrize("stage", [ - "socket-token", "github-token", "gitlab-token", "reach-dependency", "reach-plan", "reach-org", -]) +@pytest.mark.parametrize( + "stage", + [ + "socket-token", + "github-token", + "gitlab-token", + "reach-dependency", + "reach-plan", + "reach-org", + ], +) def test_setup_failures_follow_exit_policy(cli_runtime, monkeypatch, policy, infrastructure_code, stage): flags = list(policy) if stage.endswith("-token") and stage != "socket-token": @@ -82,10 +94,18 @@ def test_setup_failures_follow_exit_policy(cli_runtime, monkeypatch, policy, inf @pytest.mark.parametrize("policy, infrastructure_code", POLICIES) -@pytest.mark.parametrize("outcome, expected", [ - ("clean", 0), ("warning", 0), ("new-blocker", 1), ("existing-blocker", 0), - ("strict-existing-blocker", 1), ("infrastructure", 3), ("interrupt", 130), -]) +@pytest.mark.parametrize( + "outcome, expected", + [ + ("clean", 0), + ("warning", 0), + ("new-blocker", 1), + ("existing-blocker", 0), + ("strict-existing-blocker", 1), + ("infrastructure", 3), + ("interrupt", 130), + ], +) def test_scan_outcomes_follow_exit_policy(cli_runtime, policy, infrastructure_code, outcome, expected): flags = list(policy) if outcome in ("new-blocker", "warning"): @@ -107,20 +127,34 @@ def test_scan_outcomes_follow_exit_policy(cli_runtime, policy, infrastructure_co @pytest.mark.parametrize("policy, infrastructure_code", POLICIES) -@pytest.mark.parametrize("flags", [ - ["--files", "not-json"], ["--files", "null"], ["--files", "{}"], - ["--files", "[1]"], ["--timeout", "0"], ["--timeout", "-1"], -]) +@pytest.mark.parametrize( + "flags", + [ + ["--files", "not-json"], + ["--files", "null"], + ["--files", "{}"], + ["--files", "[1]"], + ["--timeout", "0"], + ["--timeout", "-1"], + ], +) def test_usage_errors_fail_before_setup(cli_runtime, policy, infrastructure_code, flags): # Missing credentials must not hide invalid input, even in nonblocking mode. assert cli_runtime.run([*policy, *flags], token=False) == 2 socketcli.build_socket_sdk.assert_not_called() -@pytest.mark.parametrize("setting", [ - {"strict_blocking": "false"}, {"timeout": 0}, {"timeout": 1.5}, - {"sarif_scope": "invalid"}, {"target_path": 123}, {"socketcli": []}, -]) +@pytest.mark.parametrize( + "setting", + [ + {"strict_blocking": "false"}, + {"timeout": 0}, + {"timeout": 1.5}, + {"sarif_scope": "invalid"}, + {"target_path": 123}, + {"socketcli": []}, + ], +) def test_invalid_config_file_is_a_usage_error(tmp_path, setting): path = tmp_path / "socketcli.json" path.write_text(json.dumps(setting)) @@ -143,9 +177,17 @@ def test_cli_overrides_invalid_config_defaults_before_validation(tmp_path): path = tmp_path / "socketcli.json" path.write_text(json.dumps({"strict_blocking": "false", "timeout": 0, "sarif_scope": "invalid"})) - config = CliConfig.from_args([ - "--config", str(path), "--strict-blocking", "--timeout", "30", "--sarif-scope", "diff", - ]) + config = CliConfig.from_args( + [ + "--config", + str(path), + "--strict-blocking", + "--timeout", + "30", + "--sarif-scope", + "diff", + ] + ) assert config.strict_blocking is True assert config.timeout == 30 @@ -166,9 +208,15 @@ def test_unreadable_config_is_a_usage_error(tmp_path, config_kind): assert result.value.code == 2 -@pytest.mark.parametrize("files", [ - '["package.json"]', "['package.json']", "'[\"package.json\"]'", ["package.json"], -]) +@pytest.mark.parametrize( + "files", + [ + '["package.json"]', + "['package.json']", + "'[\"package.json\"]'", + ["package.json"], + ], +) def test_supported_file_list_formats_are_preserved(files): assert parse_files(files) == ["package.json"] @@ -183,9 +231,7 @@ def test_help_describes_the_current_exit_contract(): @pytest.mark.parametrize("policy, infrastructure_code", POLICIES) -def test_exit_policy_survives_config_file_removal( - cli_runtime, tmp_path, policy, infrastructure_code -): +def test_exit_policy_survives_config_file_removal(cli_runtime, tmp_path, policy, infrastructure_code): path = tmp_path / "socketcli.json" path.write_text("{}") @@ -215,6 +261,7 @@ def fail_after_findings_override(handler, diff): def test_missing_existing_alert_data_reaches_cli_exit_policy(cli_runtime, policy, infrastructure_code): package = Package(id="pkg", type="npm", name="pkg", version="1", score={}, alerts=[]) cli_runtime.sdk.fullscans.stream.return_value = SimpleNamespace(success=True, artifacts={}) + # Run the real hydration step from the scan boundary without making any network request. def compare(*args, **kwargs): core = Core.__new__(Core) @@ -241,7 +288,10 @@ def wait_for_interrupt(config=None): env = {key: value for key, value in os.environ.items() if key not in TOKEN_VARS} with subprocess.Popen( [sys.executable, "-c", script, "--api-token", "test", *policy], - stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=env, ) as process: try: assert process.stdout.readline().strip() == "READY" @@ -273,10 +323,15 @@ def test_branch_full_scan_does_not_gate_on_findings(cli_runtime, monkeypatch, ou cli_runtime.scan.assert_not_called() -@pytest.mark.parametrize("scm, event, action", [ - ("github", "pull_request", "closed"), ("github", "unsupported", ""), - ("github", "pull_request_target", "opened"), ("gitlab", "unsupported", ""), -]) +@pytest.mark.parametrize( + "scm, event, action", + [ + ("github", "pull_request", "closed"), + ("github", "unsupported", ""), + ("github", "pull_request_target", "opened"), + ("gitlab", "unsupported", ""), + ], +) def test_scm_event_filters_skip_without_scanning(cli_runtime, monkeypatch, caplog, scm, event, action): monkeypatch.setenv("GH_API_TOKEN", "test") monkeypatch.setenv("GITLAB_TOKEN", "test") @@ -287,7 +342,4 @@ def test_scm_event_filters_skip_without_scanning(cli_runtime, monkeypatch, caplo with caplog.at_level("INFO", logger="socketdev"): assert cli_runtime.run(["--scm", scm]) == 0 cli_runtime.scan.assert_not_called() - assert any( - record.levelname == "WARNING" and "No scan ran" in record.getMessage() - for record in caplog.records - ) + assert any(record.levelname == "WARNING" and "No scan ran" in record.getMessage() for record in caplog.records) diff --git a/tests/core/test_diff_alerts.py b/tests/core/test_diff_alerts.py index 9b5be92d..f930509e 100644 --- a/tests/core/test_diff_alerts.py +++ b/tests/core/test_diff_alerts.py @@ -8,13 +8,11 @@ class TestDiffAlerts: def test_get_unchanged_alerts_filters_errors(self): """Test that get_unchanged_alerts only returns error/warn alerts""" alerts_dict = { - 'alert1': [ - Issue(error=True, warn=False, purl='npm/pkg1', type='malicious'), - Issue(error=False, warn=False, purl='npm/pkg1', type='info', monitor=True) + "alert1": [ + Issue(error=True, warn=False, purl="npm/pkg1", type="malicious"), + Issue(error=False, warn=False, purl="npm/pkg1", type="info", monitor=True), ], - 'alert2': [ - Issue(error=False, warn=True, purl='npm/pkg2', type='typosquat') - ] + "alert2": [Issue(error=False, warn=True, purl="npm/pkg2", type="typosquat")], } result = Core.get_unchanged_alerts(alerts_dict) @@ -28,9 +26,9 @@ def test_get_unchanged_alerts_filters_errors(self): def test_get_unchanged_alerts_deduplicates(self): """Test that get_unchanged_alerts deduplicates by purl+type""" alerts_dict = { - 'alert1': [ - Issue(error=True, warn=False, purl='npm/pkg1', type='malicious'), - Issue(error=True, warn=False, purl='npm/pkg1', type='malicious') # Duplicate + "alert1": [ + Issue(error=True, warn=False, purl="npm/pkg1", type="malicious"), + Issue(error=True, warn=False, purl="npm/pkg1", type="malicious"), # Duplicate ] } @@ -47,9 +45,9 @@ def test_get_unchanged_alerts_empty(self): def test_get_removed_alerts_all_alerts(self): """Test that get_removed_alerts returns all alerts from removed packages""" alerts_dict = { - 'alert1': [ - Issue(error=True, warn=False, purl='npm/pkg1', type='malicious'), - Issue(error=False, warn=True, purl='npm/pkg1', type='typosquat') + "alert1": [ + Issue(error=True, warn=False, purl="npm/pkg1", type="malicious"), + Issue(error=False, warn=True, purl="npm/pkg1", type="typosquat"), ] } @@ -61,9 +59,9 @@ def test_get_removed_alerts_all_alerts(self): def test_get_removed_alerts_deduplicates(self): """Test that get_removed_alerts deduplicates by purl+type""" alerts_dict = { - 'alert1': [ - Issue(error=True, warn=False, purl='npm/pkg1', type='malicious'), - Issue(error=True, warn=False, purl='npm/pkg1', type='malicious') # Duplicate + "alert1": [ + Issue(error=True, warn=False, purl="npm/pkg1", type="malicious"), + Issue(error=True, warn=False, purl="npm/pkg1", type="malicious"), # Duplicate ] } diff --git a/tests/core/test_diff_generation.py b/tests/core/test_diff_generation.py index b48fabe4..ac69b47e 100644 --- a/tests/core/test_diff_generation.py +++ b/tests/core/test_diff_generation.py @@ -13,61 +13,62 @@ @pytest.fixture def core(mock_sdk_with_responses): config = SocketConfig(api_key="test_key") - core = Core(config=config, sdk=mock_sdk_with_responses) - return core + return Core(config=config, sdk=mock_sdk_with_responses) + @pytest.fixture def diff_input() -> tuple[dict[str, Package], dict[str, Package]]: """Fixture that loads the saved diff input and converts it to Package objects - + Returns: Tuple of (added_packages, removed_packages) as Package dictionaries """ test_dir = Path(__file__).parent input_file = test_dir / "create_diff_input.json" - + with open(input_file) as f: data = json.load(f) - + # Convert the dictionaries back to Package objects, ignoring legacy keys package_fields = {field.name for field in fields(Package)} added = {k: Package(**{pk: pv for pk, pv in v.items() if pk in package_fields}) for k, v in data["added"].items()} - removed = {k: Package(**{pk: pv for pk, pv in v.items() if pk in package_fields}) for k, v in data["removed"].items()} - + removed = { + k: Package(**{pk: pv for pk, pv in v.items() if pk in package_fields}) for k, v in data["removed"].items() + } + return added, removed + def test_create_diff_report(core, diff_input): """Test creating a diff report""" added, removed = diff_input - + # Create the diff report diff = core.create_diff_report(added, removed) - - # Debug what alerts we have # print("\nAdded packages alerts:") # for pkg_id, pkg in added.items(): # print(f"{pkg_id}: {pkg.alerts}") - + # print("\nRemoved packages alerts:") # for pkg_id, pkg in removed.items(): # print(f"{pkg_id}: {pkg.alerts}") - + # print("\nFinal new alerts:") # for alert in diff.new_alerts: # print(f"{alert.pkg_id}: {alert.type} ({alert.severity})") - + # By default direct_only=True, so only direct dependencies should be in new/removed assert len(diff.new_packages) == 2 # dp3 and dp4 are direct assert len(diff.removed_packages) == 1 # only dp2 is direct - + # Verify dp3 Purl object's transformed fields dp3_purl = next(p for p in diff.new_packages if p.id == "dp3") assert dp3_purl.ecosystem == "pypi" # Transformed from package.type assert dp3_purl.transitives == 3 # Calculated count of transitive deps assert dp3_purl.introduced_by == [("direct", "requirements.txt")] # Generated for direct deps - + # Verify dp2 Purl object's transformed fields dp2_purl = next(p for p in diff.removed_packages if p.id == "dp2") assert dp2_purl.ecosystem == "pypi" @@ -79,14 +80,14 @@ def test_create_diff_report(core, diff_input): assert "dp3" in new_pkg_ids # Direct package assert "dp4" in new_pkg_ids # Direct package assert "dp3_t1" not in new_pkg_ids # Transitive dependency - + removed_pkg_ids = {p.id for p in diff.removed_packages} assert "dp2" in removed_pkg_ids # Direct package assert "dp2_t1" not in removed_pkg_ids # Transitive dependency # Alerts require explicit action mapping (warn/error) and may be empty in fixtures assert len(diff.new_alerts) == 0 - + # Verify new capabilities assert "dp3" in diff.new_capabilities assert set(diff.new_capabilities["dp3"]) == {"Environment Variables"} @@ -117,13 +118,12 @@ def _diff_artifact(change_type: str, flattened: bool) -> dict: context in a head/base ref instead, and Package.from_diff_artifact reads diffType differently in each. """ - raw = json.loads( - (Path(__file__).parent.parent / "data/fullscans/diff/stream_diff.json").read_text() - )["data"]["artifacts"]["added"][0] + raw = json.loads((Path(__file__).parent.parent / "data/fullscans/diff/stream_diff.json").read_text())["data"][ + "artifacts" + ]["added"][0] artifact = dict(raw, diffType=change_type, head=None, base=None) if not flattened: - link = {"topLevelAncestors": ["x"], "direct": True, "artifact": None, - "dependencies": [], "manifestFiles": []} + link = {"topLevelAncestors": ["x"], "direct": True, "artifact": None, "dependencies": [], "manifestFiles": []} key = "head" if change_type in ("added", "updated") else "base" artifact[key] = [link] return asdict(DiffArtifact.from_dict(artifact)) @@ -142,6 +142,7 @@ def test_change_type_survives_artifact_conversion(change_type, flattened): assert package.diffType == change_type + def create_input(core): # Get two different scans to compare head_scan = core.get_full_scan("head") @@ -152,7 +153,7 @@ def create_input(core): input_to_save = { "added": {k: v.to_dict() for k, v in added.items()}, - "removed": {k: v.to_dict() for k, v in removed.items()} + "removed": {k: v.to_dict() for k, v in removed.items()}, } # Get the directory of the current test file @@ -161,35 +162,37 @@ def create_input(core): with open(output_file, "w") as f: json.dump(input_to_save, f, indent=4) - + + def print_scan_packages(head_scan, new_scan): print("\n=== HEAD SCAN PACKAGES ===") for pkg_id, pkg in head_scan.packages.items(): print(f"\nPackage: {pkg_id}") pkg_dict = pkg.to_dict() - pkg_dict.pop('license_text', None) # Remove license_text from output + pkg_dict.pop("license_text", None) # Remove license_text from output print(json.dumps(pkg_dict, indent=2)) print("\n=== NEW SCAN PACKAGES ===") for pkg_id, pkg in new_scan.packages.items(): print(f"\nPackage: {pkg_id}") pkg_dict = pkg.to_dict() - pkg_dict.pop('license_text', None) # Remove license_text from output + pkg_dict.pop("license_text", None) # Remove license_text from output print(json.dumps(pkg_dict, indent=2)) + def print_added_and_removed(added, removed): print("\n=== ADDED PACKAGES ===") for pkg_id, pkg in added.items(): print(f"\nPackage: {pkg_id}") pkg_dict = pkg.to_dict() - pkg_dict.pop('license_text', None) # Remove license_text from output + pkg_dict.pop("license_text", None) # Remove license_text from output print(json.dumps(pkg_dict, indent=2)) print("\n=== REMOVED PACKAGES ===") for pkg_id, pkg in removed.items(): print(f"\nPackage: {pkg_id}") pkg_dict = pkg.to_dict() - pkg_dict.pop('license_text', None) # Remove license_text from output + pkg_dict.pop("license_text", None) # Remove license_text from output print(json.dumps(pkg_dict, indent=2)) # def test_create_diff_report_other(core): @@ -214,7 +217,7 @@ def print_added_and_removed(added, removed): # }, # { # "key": "net_access", - # "type": "networkAccess", + # "type": "networkAccess", # "severity": "medium", # "props": {}, # "category": "capability" @@ -227,7 +230,7 @@ def print_added_and_removed(added, removed): # purl="pkg:npm/package-1@1.0.0" # ), # "pkg2": Package( - # id="pkg2", + # id="pkg2", # name="package-2", # version="1.0.0", # type="npm", @@ -316,9 +319,7 @@ def print_added_and_removed(added, removed): def _namespaced_diff_response(namespace: str = "com.example"): """One namespaced artifact, delivered as both an addition and a removal.""" - raw = json.loads( - (Path(__file__).parent.parent / "data/fullscans/diff/stream_diff.json").read_text() - ) + raw = json.loads((Path(__file__).parent.parent / "data/fullscans/diff/stream_diff.json").read_text()) template = raw["data"]["artifacts"]["added"][0] artifacts = {bucket: [] for bucket in ("added", "removed", "unchanged", "replaced", "updated")} for bucket in ("added", "removed"): @@ -335,11 +336,13 @@ def _namespaced_diff_response(namespace: str = "com.example"): type="maven", ) ) - return StreamDiffResponse.from_dict({ - "success": raw["success"], - "status": raw["status"], - "data": {**raw["data"], "artifacts": artifacts}, - }) + return StreamDiffResponse.from_dict( + { + "success": raw["success"], + "status": raw["status"], + "data": {**raw["data"], "artifacts": artifacts}, + } + ) def test_removed_package_purl_matches_the_added_form(core): diff --git a/tests/core/test_diff_scan_polling.py b/tests/core/test_diff_scan_polling.py index 8cd28c7f..9abc05b8 100644 --- a/tests/core/test_diff_scan_polling.py +++ b/tests/core/test_diff_scan_polling.py @@ -4,6 +4,7 @@ resource and polls the cached endpoint (202 while processing, 200 when ready), falling back to the legacy streaming diff if the new flow is unavailable. """ + import pytest from socketdev.exceptions import APIConnectionError, APIFailure @@ -77,9 +78,7 @@ def test_poll_timeout_raises(core, no_sleep, monkeypatch): def test_duplicate_conflict_uses_cached_polling(core, diff_scan_get_response): """A duplicate is resolved explicitly so the SDK cannot follow an uncached redirect.""" - core.sdk.diffscans.create_from_ids.side_effect = APIFailure( - "duplicate", status_code=409 - ) + core.sdk.diffscans.create_from_ids.side_effect = APIFailure("duplicate", status_code=409) core.sdk.diffscans.list.return_value = { "results": [{"id": "existing-diff-scan"}], } @@ -141,9 +140,7 @@ def test_eager_list_artifacts_do_not_bypass_filtered_get(core, diff_scan_get_res generate_license=False, legal_format="socket", ) - core.sdk.diffscans.create_from_ids.side_effect = APIFailure( - "duplicate", status_code=409 - ) + core.sdk.diffscans.create_from_ids.side_effect = APIFailure("duplicate", status_code=409) core.sdk.diffscans.list.return_value = { "results": [ { @@ -188,13 +185,9 @@ def test_updated_duplicate_is_polled_like_a_created_diff_scan(core, diff_scan_ge The existing scan must then flow through the same cached-polling path, and the duplicate-resolving list call must not be needed at all. """ - core.sdk.diffscans.create_from_ids.return_value = { - "diff_scan": {"id": "existing-diff-scan"} - } + core.sdk.diffscans.create_from_ids.return_value = {"diff_scan": {"id": "existing-diff-scan"}} - artifacts = core.get_diff_scan_artifacts( - "head", "new", external_href="https://github.com/acme/widgets/pull/42" - ) + artifacts = core.get_diff_scan_artifacts("head", "new", external_href="https://github.com/acme/widgets/pull/42") core.sdk.diffscans.list.assert_not_called() assert core.sdk.diffscans.get.call_args.args[1] == "existing-diff-scan" @@ -203,14 +196,10 @@ def test_updated_duplicate_is_polled_like_a_created_diff_scan(core, diff_scan_ge def test_link_falls_back_to_resolving_the_duplicate_on_older_deployments(core): """Deployments without on_duplicate=update may answer 409; keep working.""" - core.sdk.diffscans.create_from_ids.side_effect = APIFailure( - "duplicate", status_code=409 - ) + core.sdk.diffscans.create_from_ids.side_effect = APIFailure("duplicate", status_code=409) core.sdk.diffscans.list.return_value = {"results": [{"id": "existing-diff-scan"}]} - artifacts = core.get_diff_scan_artifacts( - "head", "new", external_href="https://github.com/acme/widgets/pull/42" - ) + artifacts = core.get_diff_scan_artifacts("head", "new", external_href="https://github.com/acme/widgets/pull/42") assert core.sdk.diffscans.get.call_args.args[1] == "existing-diff-scan" assert len(artifacts.added) > 0 @@ -221,7 +210,7 @@ def test_fallback_to_streaming_diff_on_failure(core): the comparison falls back to the legacy streaming diff transparently.""" core.sdk.diffscans.create_from_ids.side_effect = APIFailure("forbidden", status_code=403) - added, removed, all_packages = core.get_added_and_removed_packages("head", "new") + added, removed, _all_packages = core.get_added_and_removed_packages("head", "new") core.sdk.fullscans.stream_diff.assert_called_once_with( core.config.org_slug, @@ -234,9 +223,7 @@ def test_fallback_to_streaming_diff_on_failure(core): assert "dp2" in removed -def test_completion_log_reports_id_polls_and_final_wait( - core, diff_scan_get_response, no_sleep, caplog, monkeypatch -): +def test_completion_log_reports_id_polls_and_final_wait(core, diff_scan_get_response, no_sleep, caplog, monkeypatch): """The completion log must let a CI log separate backend compute time from the time a finished comparison sat unnoticed between polls.""" import logging @@ -261,10 +248,7 @@ def test_completion_log_reports_id_polls_and_final_wait( def test_max_poll_interval_bounds_dead_time_for_ci_budgets(): """A finished comparison is never left unobserved longer than the max interval.""" assert core_module.DIFF_SCAN_POLL_MAX_INTERVAL_SECONDS <= 10.0 - assert ( - core_module.DIFF_SCAN_POLL_INITIAL_INTERVAL_SECONDS - <= core_module.DIFF_SCAN_POLL_MAX_INTERVAL_SECONDS - ) + assert core_module.DIFF_SCAN_POLL_INITIAL_INTERVAL_SECONDS <= core_module.DIFF_SCAN_POLL_MAX_INTERVAL_SECONDS UNCHANGED_ARTIFACT_CONSUMERS = [ @@ -286,8 +270,7 @@ def test_unchanged_artifacts_gating(core, diff_scan_get_response, flag, value): """ from types import SimpleNamespace - defaults = {name: (False if name != "legal_format" else "socket") - for name, _ in UNCHANGED_ARTIFACT_CONSUMERS} + defaults = {name: (False if name != "legal_format" else "socket") for name, _ in UNCHANGED_ARTIFACT_CONSUMERS} core.cli_config = SimpleNamespace(**{**defaults, flag: value}) core.sdk.diffscans.get.side_effect = None core.sdk.diffscans.get.return_value = diff_scan_get_response diff --git a/tests/core/test_existing_alerts.py b/tests/core/test_existing_alerts.py index d184c6cc..63851835 100644 --- a/tests/core/test_existing_alerts.py +++ b/tests/core/test_existing_alerts.py @@ -1,4 +1,5 @@ """The full scan supplies current alerts omitted by the comparison.""" + import json import re from pathlib import Path @@ -81,19 +82,23 @@ def _scan_artifact(artifact_id, name, alerts, *, version="1.0.0"): def _diff_response(**buckets): raw = json.loads((Path(__file__).parent.parent / "data/fullscans/diff/stream_diff.json").read_text()) artifacts = {name: buckets.get(name, []) for name in BUCKETS} - return StreamDiffResponse.from_dict({ - "success": raw["success"], - "status": raw["status"], - "data": {**raw["data"], "artifacts": artifacts}, - }) + return StreamDiffResponse.from_dict( + { + "success": raw["success"], + "status": raw["status"], + "data": {**raw["data"], "artifacts": artifacts}, + } + ) def _scan_response(*artifacts): - return FullScanStreamResponse.from_dict({ - "success": True, - "status": 200, - "artifacts": {artifact["id"]: artifact for artifact in artifacts}, - }) + return FullScanStreamResponse.from_dict( + { + "success": True, + "status": 200, + "artifacts": {artifact["id"]: artifact for artifact in artifacts}, + } + ) @pytest.fixture @@ -195,9 +200,15 @@ def test_strict_blocking_loads_unchanged_and_updated_alerts_once(core): new_alert = {**_alert("new", alert_type="criticalCVE"), "props": {"cveId": "CVE-2025-12345"}} existing_alert = {**_alert("existing", alert_type="criticalCVE"), "props": {"cveId": "CVE-2025-54321"}} updated = _diff_artifact("updated", "a2", "alpha", [new_alert], version="2.0.0") - replaced = _diff_artifact("replaced", "a1", "alpha", [ - {**existing_alert, "action": "warn"}, _alert("resolved"), - ]) + replaced = _diff_artifact( + "replaced", + "a1", + "alpha", + [ + {**existing_alert, "action": "warn"}, + _alert("resolved"), + ], + ) updated["namespace"] = replaced["namespace"] = "@team" core.sdk.fullscans.stream_diff.return_value = _diff_response( updated=[updated], @@ -301,7 +312,7 @@ def test_strict_blocking_fails_if_changed_package_is_missing_from_full_scan(core params = FullScanParams(repo="repo", branch="feature") params.include_license_details = True - with pytest.raises(InfrastructureError, match="current packages.*full scan new"): + with pytest.raises(InfrastructureError, match=r"current packages.*full scan new"): core.create_new_diff(["/repo"], params, explicit_files=["/repo/package.json"]) @@ -313,7 +324,8 @@ def test_existing_alerts_match_by_package_when_artifact_ids_differ(core): def test_existing_warnings_are_kept_and_ignored_alerts_are_not(core): diff = _run( - core, "--strict-blocking", + core, + "--strict-blocking", scan_alerts=[_alert("k3", action="warn"), _alert("k4", action="ignore", alert_type="envVars")], ) @@ -365,17 +377,24 @@ def test_failed_full_scan_fetch_fails_the_run(core): core.create_new_diff(["/repo"], params, explicit_files=["/repo/package.json"]) -@pytest.mark.parametrize("flags", [ - ("--strict-blocking",), ("--enable-gitlab-security",), ("--legal-format", "fossa"), -]) +@pytest.mark.parametrize( + "flags", + [ + ("--strict-blocking",), + ("--enable-gitlab-security",), + ("--legal-format", "fossa"), + ], +) @pytest.mark.parametrize("response_kind", ["missing", "malformed", "empty"]) def test_incomplete_existing_alert_data_fails_the_run(core, flags, response_kind): """A successful response can still omit packages, including SDK parse failures.""" core.cli_config = CliConfig.from_args(["--api-token", "test", *flags]) - core.sdk.fullscans.stream_diff.return_value = _diff_response(unchanged=[ - _diff_artifact("unchanged", "u1", "gamma"), - _diff_artifact("unchanged", "u2", "delta"), - ]) + core.sdk.fullscans.stream_diff.return_value = _diff_response( + unchanged=[ + _diff_artifact("unchanged", "u1", "gamma"), + _diff_artifact("unchanged", "u2", "delta"), + ] + ) artifacts = [_scan_artifact("u2", "delta", [])] if response_kind == "malformed": broken = _scan_artifact("u1", "gamma", [_alert("k3")]) @@ -387,7 +406,7 @@ def test_incomplete_existing_alert_data_fails_the_run(core, flags, response_kind params = FullScanParams(repo="repo", branch="feature") params.include_license_details = True - with pytest.raises(InfrastructureError, match="unchanged packages.*full scan new"): + with pytest.raises(InfrastructureError, match=r"unchanged packages.*full scan new"): core.create_new_diff(["/repo"], params, explicit_files=["/repo/package.json"]) @@ -429,9 +448,9 @@ def _stream_through_sdk(core, *artifacts): def _existing_only_diff(core, *scan_artifacts): core.cli_config = CliConfig.from_args(["--api-token", "test", "--strict-blocking"]) - core.sdk.fullscans.stream_diff.return_value = _diff_response(unchanged=[ - _diff_artifact("unchanged", artifact["id"], artifact["name"]) for artifact in scan_artifacts - ]) + core.sdk.fullscans.stream_diff.return_value = _diff_response( + unchanged=[_diff_artifact("unchanged", artifact["id"], artifact["name"]) for artifact in scan_artifacts] + ) _stream_through_sdk(core, *scan_artifacts) params = FullScanParams(repo="repo", branch="feature") params.include_license_details = True @@ -473,9 +492,15 @@ def test_a_triaged_advisory_does_not_hide_a_blocking_one_on_the_same_package(cor @pytest.mark.parametrize("direct", [True, False]) def test_full_scan_reports_distinguish_advisories_on_the_same_manifest(core, direct): - core.cli_config = CliConfig.from_args([ - "--api-token", "test", "--enable-json", "--enable-sarif", "--enable-gitlab-security", - ]) + core.cli_config = CliConfig.from_args( + [ + "--api-token", + "test", + "--enable-json", + "--enable-sarif", + "--enable-gitlab-security", + ] + ) advisories = HANDLEBARS_CRITICAL_ADVISORIES[:2] alerts = [_cve_alert(ghsa, cve) for ghsa, cve in advisories] artifact = _scan_artifact("u1", "handlebars", alerts) @@ -493,9 +518,9 @@ def test_full_scan_reports_distinguish_advisories_on_the_same_manifest(core, dir assert len(sarif["results"]) == 2 assert {result["ruleId"].split()[1] for result in sarif["results"]} == expected_ids assert {result["message"]["text"].split("
    ")[0] for result in sarif["results"]} == expected_ids - assert { - result["locations"][0]["physicalLocation"]["artifactLocation"]["uri"] for result in sarif["results"] - } == {"package.json"} + assert {result["locations"][0]["physicalLocation"]["artifactLocation"]["uri"] for result in sarif["results"]} == { + "package.json" + } gitlab = Messages.create_security_comment_gitlab(diff) assert len({finding["id"] for finding in gitlab["vulnerabilities"]}) == 2 @@ -588,11 +613,13 @@ def test_existing_comment_truncation_keeps_the_blocking_first_order(monkeypatch) monkeypatch.setattr(Messages, "SECURITY_COMMENT_SIZE_BUDGET", 6000) large_blocker = _issue("large-blocker") large_blocker.description = "รฉ" * 3000 - diff = _comment_diff(existing=[ - _issue("later-warning", error=False, warn=True), - _issue("first-blocker"), - large_blocker, - ]) + diff = _comment_diff( + existing=[ + _issue("later-warning", error=False, warn=True), + _issue("first-blocker"), + large_blocker, + ] + ) comment = Messages.security_comment_template(diff, _config()) @@ -625,10 +652,7 @@ def test_ignoring_visible_alerts_keeps_the_truncation_warning(monkeypatch, budge visible = re.findall(r"", body) assert len(visible) < len(diff.unchanged_alerts) assert bool(visible) == (budget == 6000) - comments = {"ignore": [ - Comment(body_list=[f"@SocketSecurity ignore npm/{package}"]) - for package in visible - ]} + comments = {"ignore": [Comment(body_list=[f"@SocketSecurity ignore npm/{package}"]) for package in visible]} assert Comments.remove_alerts(comments, diff.unchanged_alerts) updated = Comments.process_security_comment(Comment(body_list=body.splitlines()), comments) @@ -661,7 +685,7 @@ def test_existing_license_violations_use_the_license_row(): diff = _comment_diff(new=[_issue("alpha")], existing=[license_alert]) comment = Messages.security_comment_template(diff, _config()) - existing = comment[comment.index("Existing alerts"):] + existing = comment[comment.index("Existing alerts") :] assert "gamma@1.0.0 has a License Policy Violation." in existing assert "What is known malware?" not in existing diff --git a/tests/core/test_exit_codes.py b/tests/core/test_exit_codes.py index 22130cd9..c63db246 100644 --- a/tests/core/test_exit_codes.py +++ b/tests/core/test_exit_codes.py @@ -5,6 +5,7 @@ ``--exit-code-on-api-error``. Invalid flags exit 2 like argparse's own usage errors, and Ctrl+C exits 130. See socketsecurity.exit_codes. """ + import sys from contextlib import nullcontext from types import SimpleNamespace @@ -67,10 +68,17 @@ def test_keyboard_interrupt_with_disable_blocking_exits_0(monkeypatch): def test_invalid_flags_exit_2_even_with_disable_blocking(): """A misconfigured run never scanned anything, so --disable-blocking doesn't apply.""" with pytest.raises(SystemExit) as exc_info: - CliConfig.from_args([ - "--api-token", "test", "--disable-blocking", - "--base-scan-id", "a", "--base-commit-sha", "b", - ]) + CliConfig.from_args( + [ + "--api-token", + "test", + "--disable-blocking", + "--base-scan-id", + "a", + "--base-commit-sha", + "b", + ] + ) assert exc_info.value.code == 2 @@ -173,18 +181,20 @@ def test_incomplete_comparison_does_not_fall_back_to_streaming(core, incomplete_ core.sdk.fullscans.stream_diff.assert_not_called() -@pytest.fixture(params=[ - pytest.param({"incomplete": False, "artifacts": None}, id="null-artifacts-complete"), - pytest.param({"artifacts": None}, id="null-artifacts-flag-unset"), - pytest.param({}, id="artifacts-absent-flag-unset"), - pytest.param({"artifacts": []}, id="artifacts-not-an-object"), - pytest.param({"artifacts": {}}, id="empty-artifacts-object"), - pytest.param({"artifacts": {**EMPTY_ARTIFACTS, "added": None}}, id="null-added"), - pytest.param({"artifacts": {**EMPTY_ARTIFACTS, "unchanged": None}}, id="null-unchanged"), - pytest.param({"artifacts": {**EMPTY_ARTIFACTS, "removed": {}}}, id="removed-not-a-list"), - pytest.param({"artifacts": {**EMPTY_ARTIFACTS, "updated": "invalid"}}, id="updated-not-a-list"), - pytest.param({"artifacts": {key: [] for key in EMPTY_ARTIFACTS if key != "replaced"}}, id="missing-replaced"), -]) +@pytest.fixture( + params=[ + pytest.param({"incomplete": False, "artifacts": None}, id="null-artifacts-complete"), + pytest.param({"artifacts": None}, id="null-artifacts-flag-unset"), + pytest.param({}, id="artifacts-absent-flag-unset"), + pytest.param({"artifacts": []}, id="artifacts-not-an-object"), + pytest.param({"artifacts": {}}, id="empty-artifacts-object"), + pytest.param({"artifacts": {**EMPTY_ARTIFACTS, "added": None}}, id="null-added"), + pytest.param({"artifacts": {**EMPTY_ARTIFACTS, "unchanged": None}}, id="null-unchanged"), + pytest.param({"artifacts": {**EMPTY_ARTIFACTS, "removed": {}}}, id="removed-not-a-list"), + pytest.param({"artifacts": {**EMPTY_ARTIFACTS, "updated": "invalid"}}, id="updated-not-a-list"), + pytest.param({"artifacts": {key: [] for key in EMPTY_ARTIFACTS if key != "replaced"}}, id="missing-replaced"), + ] +) def invalid_artifacts_response(request): return {"diff_scan": {"id": "diff-scan-1", **request.param}} @@ -199,12 +209,15 @@ def test_invalid_artifacts_do_not_fall_back_to_streaming(core, invalid_artifacts core.sdk.fullscans.stream_diff.assert_not_called() -@pytest.mark.parametrize("argv, expected", [ - ([], 3), - (["--exit-code-on-api-error", "42"], 42), - (["--disable-blocking"], 0), - (["--disable-blocking", "--exit-code-on-api-error", "42"], 0), -]) +@pytest.mark.parametrize( + "argv, expected", + [ + ([], 3), + (["--exit-code-on-api-error", "42"], 42), + (["--disable-blocking"], 0), + (["--disable-blocking", "--exit-code-on-api-error", "42"], 0), + ], +) @pytest.mark.parametrize("strict", [[], ["--strict-blocking"]], ids=["standard", "strict"]) def test_invalid_artifacts_follow_exit_policy(monkeypatch, caplog, argv, expected, strict): sdk = MagicMock() @@ -218,11 +231,30 @@ def test_invalid_artifacts_follow_exit_policy(monkeypatch, caplog, argv, expecte monkeypatch.setattr(Core, "create_full_scan", lambda *args, **kwargs: SimpleNamespace(id="new")) report = MagicMock() monkeypatch.setattr(socketcli.OutputHandler, "handle_output", report) - monkeypatch.setattr(sys, "argv", [ - "socketcli", "--api-token", "test", "--scm", "api", "--integration", "api", - "--repo", "repo", "--branch", "feature", "--enable-diff", "--base-scan-id", "head", - "--files", '["package.json"]', *strict, *argv, - ]) + monkeypatch.setattr( + sys, + "argv", + [ + "socketcli", + "--api-token", + "test", + "--scm", + "api", + "--integration", + "api", + "--repo", + "repo", + "--branch", + "feature", + "--enable-diff", + "--base-scan-id", + "head", + "--files", + '["package.json"]', + *strict, + *argv, + ], + ) with pytest.raises(SystemExit) as result: socketcli.cli() @@ -238,11 +270,14 @@ class StreamingFallback(Exception): """Sentinel for a streaming comparison call.""" -@pytest.mark.parametrize("response", [ - pytest.param({}, id="empty-dict"), - pytest.param({"diff_scan": None}, id="diff-scan-null"), - pytest.param({"diff_scan": []}, id="diff-scan-not-an-object"), -]) +@pytest.mark.parametrize( + "response", + [ + pytest.param({}, id="empty-dict"), + pytest.param({"diff_scan": None}, id="diff-scan-null"), + pytest.param({"diff_scan": []}, id="diff-scan-not-an-object"), + ], +) def test_response_without_diff_scan_object_falls_back_to_streaming(core, response): core.sdk.diffscans.create_from_ids.return_value = {"diff_scan": {"id": "diff-scan-1"}} core.sdk.diffscans.get.return_value = response @@ -274,10 +309,13 @@ def test_http_204_through_the_sdk_falls_back_to_streaming(core): def test_omitted_unchanged_bucket_is_still_a_result(core): core.cli_config = CliConfig(api_token="test", repo="repo") core.sdk.diffscans.create_from_ids.return_value = {"diff_scan": {"id": "diff-scan-1"}} - core.sdk.diffscans.get.return_value = {"diff_scan": { - "id": "diff-scan-1", "incomplete": False, - "artifacts": {**EMPTY_ARTIFACTS, "unchanged": None}, - }} + core.sdk.diffscans.get.return_value = { + "diff_scan": { + "id": "diff-scan-1", + "incomplete": False, + "artifacts": {**EMPTY_ARTIFACTS, "unchanged": None}, + } + } artifacts = core.get_diff_scan_artifacts("head", "new") diff --git a/tests/core/test_facts_compression.py b/tests/core/test_facts_compression.py index 0e71cdc7..cf115d91 100644 --- a/tests/core/test_facts_compression.py +++ b/tests/core/test_facts_compression.py @@ -4,6 +4,7 @@ `.socket.facts.json.br`, so the CLI compresses the facts file before uploading it. These tests cover the helpers in `Core` that do that rewriting. """ + import json import os diff --git a/tests/core/test_full_scan_outputs.py b/tests/core/test_full_scan_outputs.py index e01682e1..6c2d53c6 100644 --- a/tests/core/test_full_scan_outputs.py +++ b/tests/core/test_full_scan_outputs.py @@ -4,6 +4,7 @@ against: API mode and SCM branch pipelines. Fetching the SBOM is the expensive part, so it is gated on the enabled outputs -- these pin which outputs need it. """ + import pytest from socketdev.fullscans import FullScanParams @@ -41,9 +42,7 @@ def test_license_generation_gets_the_package_list(sdk, params): """ core = _core(sdk, generate_license=True) - diff = core.create_full_scan_with_report_url( - ["."], params, explicit_files=["package.json"] - ) + diff = core.create_full_scan_with_report_url(["."], params, explicit_files=["package.json"]) assert diff.packages # No alert-bearing output format is enabled, so alerts stay unfetched. @@ -53,9 +52,7 @@ def test_license_generation_gets_the_package_list(sdk, params): def test_license_details_are_requested_for_the_scanned_packages(sdk, params): core = _core(sdk, generate_license=True) - core.create_full_scan_with_report_url( - ["."], params, explicit_files=["package.json"] - ) + core.create_full_scan_with_report_url(["."], params, explicit_files=["package.json"]) components = sdk.purl.post.call_args.kwargs["components"] # Keyed the way the PURL endpoint echoes results back, not by artifact id. @@ -88,12 +85,7 @@ def test_license_details_preserve_package_namespace(sdk): packages = core._add_license_details({package.id: package}) assert sdk.purl.post.call_args.kwargs["components"] == [ - { - "purl": ( - "pkg:/maven/org.apache.logging.log4j/" - "log4j-core@2.24.3" - ) - } + {"purl": ("pkg:/maven/org.apache.logging.log4j/log4j-core@2.24.3")} ] assert packages[package.id].licenseDetails == [{"license": "Apache-2.0"}] @@ -101,9 +93,7 @@ def test_license_details_preserve_package_namespace(sdk): def test_alert_formats_still_fetch_the_sbom(sdk, params): core = _core(sdk, enable_json=True) - diff = core.create_full_scan_with_report_url( - ["."], params, explicit_files=["package.json"] - ) + diff = core.create_full_scan_with_report_url(["."], params, explicit_files=["package.json"]) assert diff.packages # Alert-only outputs do not pay for the license lookup. (The scan fixture's @@ -114,9 +104,7 @@ def test_alert_formats_still_fetch_the_sbom(sdk, params): def test_console_only_run_skips_the_sbom_fetch(sdk, params): core = _core(sdk) - diff = core.create_full_scan_with_report_url( - ["."], params, explicit_files=["package.json"] - ) + diff = core.create_full_scan_with_report_url(["."], params, explicit_files=["package.json"]) assert diff.packages == {} assert diff.new_alerts == [] diff --git a/tests/core/test_invalid_facts_marker.py b/tests/core/test_invalid_facts_marker.py index 87b9005c..38e51f93 100644 --- a/tests/core/test_invalid_facts_marker.py +++ b/tests/core/test_invalid_facts_marker.py @@ -8,6 +8,7 @@ These tests cover both the placeholder (`empty_head_scan_file`) and the marker filtering. """ + import copy import json import os @@ -135,9 +136,7 @@ def test_is_invalid_facts_marker_ignores_version(): class Versioned(FakeArtifact): version = "9.9.9" - assert Core.is_invalid_facts_marker( - Versioned(INVALID_FACTS_MARKER_TYPE, INVALID_FACTS_MARKER_NAME) - ) + assert Core.is_invalid_facts_marker(Versioned(INVALID_FACTS_MARKER_TYPE, INVALID_FACTS_MARKER_NAME)) # --- Filtering: full-scan SBOM path ------------------------------------------------------- @@ -149,11 +148,13 @@ def test_get_sbom_data_drops_marker(core, data_dir, load_json, caplog): artifacts = copy.deepcopy(json_data["artifacts"]) artifacts["invalid-facts-1"] = make_marker_artifact() core.sdk.fullscans.stream.side_effect = None - core.sdk.fullscans.stream.return_value = FullScanStreamResponse.from_dict({ - "success": True, - "status": 200, - "artifacts": artifacts, - }) + core.sdk.fullscans.stream.return_value = FullScanStreamResponse.from_dict( + { + "success": True, + "status": 200, + "artifacts": artifacts, + } + ) with caplog.at_level("WARNING"): result = core.get_sbom_data("head") @@ -178,14 +179,14 @@ def _diff_response_with_marker(data_dir, load_json, buckets=("added",)): json_data = load_json(data_dir / "fullscans" / "diff" / "stream_diff.json") artifacts = copy.deepcopy(json_data["data"]["artifacts"]) for index, bucket in enumerate(buckets): - artifacts[bucket].append( - make_marker_artifact(diff_type=bucket, artifact_id=f"invalid-facts-{index}") - ) - return StreamDiffResponse.from_dict({ - "success": json_data["success"], - "status": json_data["status"], - "data": {**json_data["data"], "artifacts": artifacts}, - }) + artifacts[bucket].append(make_marker_artifact(diff_type=bucket, artifact_id=f"invalid-facts-{index}")) + return StreamDiffResponse.from_dict( + { + "success": json_data["success"], + "status": json_data["status"], + "data": {**json_data["data"], "artifacts": artifacts}, + } + ) def test_diff_drops_marker_from_added_packages(core, data_dir, load_json, caplog): @@ -195,9 +196,7 @@ def test_diff_drops_marker_from_added_packages(core, data_dir, load_json, caplog developer never added. """ core.sdk.fullscans.stream_diff.side_effect = None - core.sdk.fullscans.stream_diff.return_value = _diff_response_with_marker( - data_dir, load_json - ) + core.sdk.fullscans.stream_diff.return_value = _diff_response_with_marker(data_dir, load_json) # Force the legacy streaming diff so the fixture above is the artifact source. core.sdk.diffscans.create_from_ids.side_effect = Exception("diff-scans unavailable") @@ -240,14 +239,10 @@ def test_diff_artifact_counts_exclude_marker(core, data_dir, load_json, caplog): looking for a package that was never there. """ core.sdk.fullscans.stream_diff.side_effect = None - core.sdk.fullscans.stream_diff.return_value = _diff_response_with_marker( - data_dir, load_json - ) + core.sdk.fullscans.stream_diff.return_value = _diff_response_with_marker(data_dir, load_json) core.sdk.diffscans.create_from_ids.side_effect = Exception("diff-scans unavailable") unfiltered_added = len( - load_json(data_dir / "fullscans" / "diff" / "stream_diff.json")["data"]["artifacts"][ - "added" - ] + load_json(data_dir / "fullscans" / "diff" / "stream_diff.json")["data"]["artifacts"]["added"] ) with caplog.at_level("INFO"): @@ -261,16 +256,12 @@ def test_diff_keeps_real_packages(core, data_dir, load_json): """Filtering the marker leaves genuine packages untouched.""" core.sdk.fullscans.stream_diff.side_effect = None unfiltered = load_json(data_dir / "fullscans" / "diff" / "stream_diff.json") - core.sdk.fullscans.stream_diff.return_value = _diff_response_with_marker( - data_dir, load_json - ) + core.sdk.fullscans.stream_diff.return_value = _diff_response_with_marker(data_dir, load_json) core.sdk.diffscans.create_from_ids.side_effect = Exception("diff-scans unavailable") added, removed, _ = core.get_added_and_removed_packages("head", "new") - expected_added = len(unfiltered["data"]["artifacts"]["added"]) + len( - unfiltered["data"]["artifacts"]["updated"] - ) + expected_added = len(unfiltered["data"]["artifacts"]["added"]) + len(unfiltered["data"]["artifacts"]["updated"]) expected_removed = len(unfiltered["data"]["artifacts"]["removed"]) + len( unfiltered["data"]["artifacts"]["replaced"] ) diff --git a/tests/core/test_package_and_alerts.py b/tests/core/test_package_and_alerts.py index 0e096621..7463d691 100644 --- a/tests/core/test_package_and_alerts.py +++ b/tests/core/test_package_and_alerts.py @@ -10,6 +10,17 @@ from socketsecurity.core.socket_config import SocketConfig +@pytest.mark.parametrize( + "raw,expected", + [ + ("Tue 10 Nov 2026 12:00:00 GMT (Coordinated Universal Time)", "Tue 10 Nov 2026 12:00:00 GMT"), + ("Tue 10 Nov 2026 12:00:00 GMT", "Tue 10 Nov 2026 12:00:00 GMT"), + ], +) +def test_issue_timestamp_removes_only_the_timezone_suffix(raw, expected): + assert Issue(created_at=raw).created_at == expected + + @dataclass class MockArtifact: id: str @@ -28,17 +39,17 @@ class MockArtifact: class TestPackageAndAlerts: @staticmethod def make_package(**overrides): - base = dict( - id="pkg:npm/test@1.0.0", - name="test", - version="1.0.0", - type="npm", - release="tar-gz", - diffType="added", - score={}, - alerts=[], - topLevelAncestors=[], - ) + base = { + "id": "pkg:npm/test@1.0.0", + "name": "test", + "version": "1.0.0", + "type": "npm", + "release": "tar-gz", + "diffType": "added", + "score": {}, + "alerts": [], + "topLevelAncestors": [], + } base.update(overrides) return Package(**base) @@ -47,14 +58,8 @@ def mock_sdk(self): mock = Mock(spec=socketdev) # Set up org.get() to return expected data mock.org = Mock() - mock.org.get = Mock(return_value={ - "organizations": { - "test-org-id": { - "slug": "test-org" - } - } - }) - + mock.org.get = Mock(return_value={"organizations": {"test-org-id": {"slug": "test-org"}}}) + # Set up settings.get() to return empty response mock.settings = Mock() settings_response = Mock() @@ -64,17 +69,13 @@ def mock_sdk(self): # Set up licensemetadata.post() used by create_packages_dict() mock.licensemetadata = Mock() mock.licensemetadata.post = Mock(return_value=[{"text": ""}]) - + return mock - + @pytest.fixture def config(self): - config = SocketConfig( - api_key="test-key", - allow_unverified_ssl=False - ) - return config - + return SocketConfig(api_key="test-key", allow_unverified_ssl=False) + @pytest.fixture def core(self, mock_sdk, config): return Core(config=config, sdk=mock_sdk) @@ -93,12 +94,12 @@ def test_create_packages_dict_basic(self, core): score={}, alerts=[], direct=True, - topLevelAncestors=[] + topLevelAncestors=[], ) ] - + packages = core.create_packages_dict(mock_artifacts) - + assert len(packages) == 1 pkg = packages["pkg:npm/test@1.0.0"] assert pkg.name == "test" @@ -106,46 +107,45 @@ def test_create_packages_dict_basic(self, core): assert pkg.transitives == 0 def test_full_scan_package_normalizes_enum_type_and_namespace_url(self): - artifact = SocketArtifact.from_dict({ - "id": "pkg:maven/com.example/example-core@1.2.3", - "type": "maven", - "namespace": "com.example", - "name": "example-core", - "version": "1.2.3", - "direct": True, - "topLevelAncestors": [], - "manifestFiles": [{"file": "pom.xml"}], - "alerts": [], - }) + artifact = SocketArtifact.from_dict( + { + "id": "pkg:maven/com.example/example-core@1.2.3", + "type": "maven", + "namespace": "com.example", + "name": "example-core", + "version": "1.2.3", + "direct": True, + "topLevelAncestors": [], + "manifestFiles": [{"file": "pom.xml"}], + "alerts": [], + } + ) package = Package.from_socket_artifact(asdict(artifact)) assert package.type == "maven" assert package.purl == "maven/com.example/example-core@1.2.3" - assert package.url == ( - "https://socket.dev/maven/package/com.example/example-core/overview/1.2.3" - ) + assert package.url == ("https://socket.dev/maven/package/com.example/example-core/overview/1.2.3") def test_maven_package_url_separates_group_and_artifact(self): """groupId and artifactId are distinct path segments, not one fused string""" - artifact = SocketArtifact.from_dict({ - "id": "pkg:maven/org.apache.logging.log4j/log4j-api@2.17.2", - "type": "maven", - "namespace": "org.apache.logging.log4j", - "name": "log4j-api", - "version": "2.17.2", - "direct": True, - "topLevelAncestors": [], - "manifestFiles": [{"file": "pom.xml"}], - "alerts": [], - }) + artifact = SocketArtifact.from_dict( + { + "id": "pkg:maven/org.apache.logging.log4j/log4j-api@2.17.2", + "type": "maven", + "namespace": "org.apache.logging.log4j", + "name": "log4j-api", + "version": "2.17.2", + "direct": True, + "topLevelAncestors": [], + "manifestFiles": [{"file": "pom.xml"}], + "alerts": [], + } + ) package = Package.from_socket_artifact(asdict(artifact)) - assert package.url == ( - "https://socket.dev/maven/package/org.apache.logging.log4j/log4j-api" - "/overview/2.17.2" - ) + assert package.url == ("https://socket.dev/maven/package/org.apache.logging.log4j/log4j-api/overview/2.17.2") # The purl keeps the "/" form, which is what the purl spec and the purl API want. assert package.purl == "maven/org.apache.logging.log4j/log4j-api@2.17.2" @@ -188,9 +188,7 @@ def test_diff_path_builds_the_same_maven_url_as_the_full_scan_path(self): package = Core.update_package_values(package) - assert package.url == ( - "https://socket.dev/maven/package/com.google.code.gson/gson/overview/2.8.6" - ) + assert package.url == ("https://socket.dev/maven/package/com.google.code.gson/gson/overview/2.8.6") def test_create_packages_dict_with_transitives(self, core): """Test package dictionary creation with transitive dependencies""" @@ -206,7 +204,7 @@ def test_create_packages_dict_with_transitives(self, core): score={}, alerts=[], direct=True, - topLevelAncestors=[] + topLevelAncestors=[], ), MockArtifact( id="pkg:npm/child@1.0.0", @@ -219,12 +217,12 @@ def test_create_packages_dict_with_transitives(self, core): score={}, alerts=[], direct=False, - topLevelAncestors=["pkg:npm/parent@1.0.0"] - ) + topLevelAncestors=["pkg:npm/parent@1.0.0"], + ), ] - + packages = core.create_packages_dict(mock_artifacts) - + assert len(packages) == 2 parent = packages["pkg:npm/parent@1.0.0"] child = packages["pkg:npm/child@1.0.0"] @@ -235,19 +233,14 @@ def test_create_packages_dict_with_transitives(self, core): def test_add_package_alerts_basic(self, core): """Test adding basic alerts to collection""" package = self.make_package( - alerts=[{ - "type": "networkAccess", - "key": "test-alert", - "severity": "high" - }], - topLevelAncestors=[] + alerts=[{"type": "networkAccess", "key": "test-alert", "severity": "high"}], topLevelAncestors=[] ) - + alerts_collection = {} packages = {package.id: package} - + result = core.add_package_alerts_to_collection(package, alerts_collection, packages) - + assert len(result) == 1 assert "test-alert" in result alert = result["test-alert"][0] @@ -257,17 +250,17 @@ def test_add_package_alerts_basic(self, core): def test_gpt_did_you_mean_gets_typosquat_title(self, core): """gptDidYouMean alerts must render a non-empty title (CUS2-2).""" package = self.make_package( - alerts=[{ - "type": "gptDidYouMean", - "key": "gpt-did-you-mean-alert", - "severity": "middle", - }], + alerts=[ + { + "type": "gptDidYouMean", + "key": "gpt-did-you-mean-alert", + "severity": "middle", + } + ], topLevelAncestors=[], ) - result = core.add_package_alerts_to_collection( - package, alerts_collection={}, packages={package.id: package} - ) + result = core.add_package_alerts_to_collection(package, alerts_collection={}, packages={package.id: package}) alert = result["gpt-did-you-mean-alert"][0] assert alert.type == "gptDidYouMean" @@ -277,17 +270,17 @@ def test_gpt_did_you_mean_gets_typosquat_title(self, core): def test_unknown_alert_type_falls_back_to_humanized_title(self, core): """Any alert type not present in the SDK should still render a non-empty title.""" package = self.make_package( - alerts=[{ - "type": "someBrandNewAlertType", - "key": "future-alert", - "severity": "low", - }], + alerts=[ + { + "type": "someBrandNewAlertType", + "key": "future-alert", + "severity": "low", + } + ], topLevelAncestors=[], ) - result = core.add_package_alerts_to_collection( - package, alerts_collection={}, packages={package.id: package} - ) + result = core.add_package_alerts_to_collection(package, alerts_collection={}, packages={package.id: package}) alert = result["future-alert"][0] assert alert.title == "Some Brand New Alert Type" @@ -295,36 +288,31 @@ def test_unknown_alert_type_falls_back_to_humanized_title(self, core): def test_license_spdx_disj_keeps_explicit_title(self, core): """licenseSpdxDisj must keep its hard-coded fallback (regression guard for CUS2-2 fix).""" package = self.make_package( - alerts=[{ - "type": "licenseSpdxDisj", - "key": "license-alert", - "severity": "high", - }], + alerts=[ + { + "type": "licenseSpdxDisj", + "key": "license-alert", + "severity": "high", + } + ], topLevelAncestors=[], ) - result = core.add_package_alerts_to_collection( - package, alerts_collection={}, packages={package.id: package} - ) + result = core.add_package_alerts_to_collection(package, alerts_collection={}, packages={package.id: package}) alert = result["license-alert"][0] assert alert.title == "License Policy Violation" - - def test_get_capabilities_for_added_packages(self, core): """Test capability extraction from package alerts""" added_packages = { "pkg:npm/test@1.0.0": self.make_package( - alerts=[{ - "type": "networkAccess", - "key": "test-alert" - }], + alerts=[{"type": "networkAccess", "key": "test-alert"}], ) } - + capabilities = Core.get_capabilities_for_added_packages(added_packages) - + assert len(capabilities) == 1 assert "pkg:npm/test@1.0.0" in capabilities assert "Network Access" in capabilities["pkg:npm/test@1.0.0"] @@ -332,21 +320,23 @@ def test_get_capabilities_for_added_packages(self, core): def test_get_new_alerts_basic(self): """Test identification of new alerts""" added_alerts = { - "test-alert": [Issue( - key="test-alert", - type="networkAccess", - error=True, - pkg_type="npm", - pkg_name="test-package", - pkg_version="1.0.0", - purl="pkg:npm/test-package@1.0.0", - manifests="" # Required by get_new_alerts - )] + "test-alert": [ + Issue( + key="test-alert", + type="networkAccess", + error=True, + pkg_type="npm", + pkg_name="test-package", + pkg_version="1.0.0", + purl="pkg:npm/test-package@1.0.0", + manifests="", # Required by get_new_alerts + ) + ] } removed_alerts = {} - + new_alerts = Core.get_new_alerts(added_alerts, removed_alerts) - + assert len(new_alerts) == 1 assert new_alerts[0].key == "test-alert" assert new_alerts[0].error is True @@ -361,15 +351,15 @@ def test_get_new_alerts_with_readded(self): pkg_name="test-package", pkg_version="1.0.0", purl="pkg:npm/test-package@1.0.0", - manifests="" # Required by get_new_alerts + manifests="", # Required by get_new_alerts ) added_alerts = {"test-alert": [alert]} removed_alerts = {"test-alert": [alert]} - + # With ignore_readded=True (default) new_alerts = Core.get_new_alerts(added_alerts, removed_alerts) assert len(new_alerts) == 0 - + # With ignore_readded=False new_alerts = Core.get_new_alerts(added_alerts, removed_alerts, ignore_readded=False) assert len(new_alerts) == 1 diff --git a/tests/core/test_sdk_methods.py b/tests/core/test_sdk_methods.py index b69d57a1..4a4d510f 100644 --- a/tests/core/test_sdk_methods.py +++ b/tests/core/test_sdk_methods.py @@ -41,14 +41,14 @@ def make_full_scan_params(**overrides): def test_get_repo_info(core, mock_sdk_with_responses): """Test getting repository information""" repo_info = core.get_repo_info("test") - + # Assert SDK called correctly mock_sdk_with_responses.repos.repo.assert_called_once_with( core.config.org_slug, "test", use_types=True, ) - + # Assert response processed correctly assert repo_info.id == "f639d6c9-acc3-4d8a-9fb5-2090ad651c7e" assert repo_info.head_full_scan_id == "head" @@ -68,7 +68,9 @@ def test_get_repo_info_logs_why_repo_creation_failed(core, mock_sdk_with_respons messages = [record.getMessage() for record in caplog.records] assert "Failed to get repository new-repo, attempting to create it" in messages - assert "API failure while creating repository new-repo (HTTP 403): Insufficient permissions" in str(error_info.value) + assert "API failure while creating repository new-repo (HTTP 403): Insufficient permissions" in str( + error_info.value + ) assert "repo:create" in str(error_info.value) @@ -80,7 +82,7 @@ def test_get_repo_info_logs_why_repo_creation_failed(core, mock_sdk_with_respons ], ) def test_get_repo_info_repo_creation_failure_reason( - core, mock_sdk_with_responses, caplog, error, expected_reason, expects_scope_hint + core, mock_sdk_with_responses, caplog, error, expected_reason, expects_scope_hint ): """Message-less SDK errors still name a reason, and only permission 403s get the scope hint""" mock_sdk_with_responses.repos.repo.side_effect = APIResourceNotFound(status_code=404) @@ -95,7 +97,7 @@ def test_get_repo_info_repo_creation_failure_reason( def test_get_repo_info_restores_log_level_after_creating_repo( - core, mock_sdk_with_responses, repo_info_response, caplog + core, mock_sdk_with_responses, repo_info_response, caplog ): """Creating a missing repo must not leave the socketdev logger muted for the rest of the run""" mock_sdk_with_responses.repos.repo.side_effect = [ @@ -114,26 +116,25 @@ def test_get_repo_info_restores_log_level_after_creating_repo( def test_get_head_scan_for_repo(core, mock_sdk_with_responses): """Test getting head scan ID for a repository""" head_scan_id = core.get_head_scan_for_repo("test") - + # Assert SDK method called correctly mock_sdk_with_responses.repos.repo.assert_called_once_with( core.config.org_slug, "test", use_types=True, ) - + # Assert we got the expected head scan ID assert head_scan_id == "head" + def test_get_head_scan_for_repo_no_head(core, mock_sdk_with_responses): """Test getting head scan ID for repo with no head scan""" head_scan_id = core.get_head_scan_for_repo("no-head") assert head_scan_id is None -def test_get_head_scan_for_repo_scopes_workspace_to_default_branch( - core, mock_sdk_with_responses -): +def test_get_head_scan_for_repo_scopes_workspace_to_default_branch(core, mock_sdk_with_responses): mock_sdk_with_responses.fullscans.get.return_value = { "results": [{"id": "workspace-head"}], "nextPage": None, @@ -160,9 +161,7 @@ def test_get_head_scan_for_repo_scopes_workspace_to_default_branch( ) -def test_get_head_scan_for_repo_scopes_scan_type_without_workspace( - core, mock_sdk_with_responses -): +def test_get_head_scan_for_repo_scopes_scan_type_without_workspace(core, mock_sdk_with_responses): """Reachability and standard scans must not share one unscoped head pointer""" mock_sdk_with_responses.fullscans.get.return_value = { "results": [{"id": "standard-head"}], @@ -339,6 +338,7 @@ def test_resolve_base_full_scan_id_scopes_head_to_workspace(core): }, ) + @pytest.mark.parametrize("flags", [(), ("--disable-blocking",)]) def test_resolve_base_full_scan_id_workspace_lookup_failure_fails(core, flags): """A failed workspace lookup fails the run instead of diffing against an empty scan. @@ -372,6 +372,7 @@ def test_resolve_base_full_scan_id_uses_base_scan_id(core): assert core.resolve_base_full_scan_id(make_full_scan_params()) == "explicit-base" core.sdk.repos.repo.assert_not_called() + def test_resolve_base_full_scan_id_uses_base_commit_sha(core): """--base-commit-sha resolves through the full-scans list endpoint""" core.cli_config = make_cli_config("--base-commit-sha", "abc123") @@ -397,18 +398,23 @@ def test_resolve_base_full_scan_id_uses_base_commit_sha(core): }, ) + def test_resolve_base_full_scan_id_falls_back_to_scanned_ancestor(core, monkeypatch): """An unscanned merge base degrades to the nearest scanned ancestor""" core.cli_config = make_cli_config("--base-commit-sha", "unscanned-sha") core.sdk.fullscans.get.side_effect = [ - {"results": [], "nextPage": None}, # exact commit - {"results": [ # recent scans - {"id": "tmp-scan", "commit_hash": "ancestor-1", "tmp": True}, - {"id": "ancestor-scan", "commit_hash": "ancestor-2"}, - ], "nextPage": None}, + {"results": [], "nextPage": None}, # exact commit + { + "results": [ # recent scans + {"id": "tmp-scan", "commit_hash": "ancestor-1", "tmp": True}, + {"id": "ancestor-scan", "commit_hash": "ancestor-2"}, + ], + "nextPage": None, + }, ] monkeypatch.setattr( - Core, "first_parent_commits", + Core, + "first_parent_commits", lambda self, sha, depth: ["unscanned-sha", "ancestor-1", "ancestor-2"], ) @@ -416,9 +422,7 @@ def test_resolve_base_full_scan_id_falls_back_to_scanned_ancestor(core, monkeypa assert core.resolve_base_full_scan_id(params) == "ancestor-scan" -def test_find_baseline_scan_for_ancestor_paginates_and_selects_nearest( - core, monkeypatch -): +def test_find_baseline_scan_for_ancestor_paginates_and_selects_nearest(core, monkeypatch): """Reruns can fill page one while a closer scanned ancestor is on page two""" first_page = [ {"id": "farther-scan", "commit_hash": "ancestor-2"}, @@ -448,9 +452,7 @@ def test_find_baseline_scan_for_ancestor_paginates_and_selects_nearest( assert core.sdk.fullscans.get.call_args_list[1].args[1]["page"] == 2 -def test_resolve_base_full_scan_id_exact_lookup_failure_does_not_fallback( - core, monkeypatch -): +def test_resolve_base_full_scan_id_exact_lookup_failure_does_not_fallback(core, monkeypatch): core.cli_config = make_cli_config("--base-commit-sha", "abc123") core.sdk.fullscans.get.return_value = {} fallback_calls = [] @@ -473,7 +475,8 @@ def test_resolve_base_full_scan_id_ancestor_fallback_skips_temporary_scans(core, {"results": [{"id": "tmp-scan", "commit_hash": "ancestor-1", "tmp": True}], "nextPage": None}, ] monkeypatch.setattr( - Core, "first_parent_commits", + Core, + "first_parent_commits", lambda self, sha, depth: ["unscanned-sha", "ancestor-1"], ) @@ -503,10 +506,11 @@ def test_resolve_base_full_scan_id_commit_sha_not_found_fails(core, flags): with pytest.raises(InfrastructureError, match="No full scan found for commit abc123"): core.resolve_base_full_scan_id(make_full_scan_params()) + def test_get_full_scan(core, mock_sdk_with_responses, head_scan_metadata, head_scan_stream): """Test getting an existing full scan""" full_scan = core.get_full_scan("head") - + # Assert SDK methods called correctly mock_sdk_with_responses.fullscans.metadata.assert_called_once_with( core.config.org_slug, @@ -518,13 +522,14 @@ def test_get_full_scan(core, mock_sdk_with_responses, head_scan_metadata, head_s "head", use_types=True, ) - + # Assert response processed correctly assert full_scan.id == head_scan_metadata["data"]["id"] assert len(full_scan.sbom_artifacts) == len(head_scan_stream.artifacts) assert len(full_scan.packages) == len(head_scan_stream.artifacts) assert full_scan.packages["dp1"].transitives == 2 + def test_create_full_scan(core, mock_sdk_with_responses, new_scan_metadata): """Test creating a new full scan""" # Setup test data @@ -534,10 +539,10 @@ def test_create_full_scan(core, mock_sdk_with_responses, new_scan_metadata): branch="main", commit_hash="abc123", ) - + # Create the full scan full_scan = core.create_full_scan(files, params) - + # Verify the response assert full_scan.id == new_scan_metadata["data"]["id"] mock_sdk_with_responses.fullscans.post.assert_called_once_with( @@ -549,6 +554,7 @@ def test_create_full_scan(core, mock_sdk_with_responses, new_scan_metadata): base_paths=None, ) + def test_get_added_and_removed_packages(core): """Test getting added and removed packages between two scans""" # Get two different scans to compare @@ -574,19 +580,20 @@ def test_get_added_and_removed_packages(core): params={"cached": "true"}, ) core.sdk.fullscans.stream_diff.assert_not_called() - + # Verify the results # Added packages assert len(added) > 0 # We should have some added packages assert "dp3" in added # Verify specific package we know was added assert "dp4" in added - + # Removed packages assert len(removed) > 0 # We should have some removed packages assert "dp2" in removed # Verify specific package we know was removed assert "dp2_t1" in removed # Verify transitive dependencies are also tracked assert "pypi/direct_package_1@1.6.0" in all_packages # Unchanged package is in full package map + def test_get_added_and_removed_packages_license_override(core): """include_license_details only governs the legacy fallback path now: the diff-scans path always receives embedded license details (the API ignores @@ -605,6 +612,7 @@ def test_get_added_and_removed_packages_license_override(core): include_license_details="true", ) + def test_get_sbom_data_failure_raises(core): """A failed SBOM stream fetch raises instead of returning {}. @@ -613,24 +621,27 @@ def test_get_sbom_data_failure_raises(core): handling instead. """ core.sdk.fullscans.stream.side_effect = None - core.sdk.fullscans.stream.return_value = FullScanStreamResponse.from_dict({ - "success": False, - "status": 200, - "message": "Error parsing stream response", - }) + core.sdk.fullscans.stream.return_value = FullScanStreamResponse.from_dict( + { + "success": False, + "status": 200, + "message": "Error parsing stream response", + } + ) with pytest.raises(APIFailure, match="Failed to get SBOM data"): core.get_sbom_data("head") + def test_empty_alerts_preserved(core): """Test that empty alerts arrays stay as empty arrays and don't become None""" # Get the scan that contains dp2 (which has empty alerts array) head_scan = core.get_full_scan("head") - + # Check the raw artifact first artifacts = core.get_sbom_data("head") assert artifacts["dp2"].alerts == [] # Should be empty list, not None - + # Check the final package assert head_scan.packages["dp2"].alerts == [] # Should still be empty list @@ -644,10 +655,7 @@ def test_repository_head_baseline_log(core, caplog): with caplog.at_level("INFO", logger="socketdev"): assert core.resolve_base_full_scan_id(make_full_scan_params()) == "standard-head" - assert ( - 'Baseline selected: source=repository-head scan_id="standard-head"' - in caplog.messages - ) + assert 'Baseline selected: source=repository-head scan_id="standard-head"' in caplog.messages def test_explicit_scan_baseline_log(core, caplog): @@ -669,7 +677,4 @@ def test_explicit_commit_baseline_log(core, caplog): with caplog.at_level("INFO", logger="socketdev"): assert core.resolve_base_full_scan_id(make_full_scan_params()) == "merge-base-scan" - assert ( - 'Baseline selected: source=explicit-commit scan_id="merge-base-scan" ' - 'commit="abc123"' - ) in caplog.messages + assert ('Baseline selected: source=explicit-commit scan_id="merge-base-scan" commit="abc123"') in caplog.messages diff --git a/tests/core/test_strict_blocking_duplicates.py b/tests/core/test_strict_blocking_duplicates.py index da6a7a53..83e65df4 100644 --- a/tests/core/test_strict_blocking_duplicates.py +++ b/tests/core/test_strict_blocking_duplicates.py @@ -8,6 +8,7 @@ These tests run `Core.create_new_diff` against a mocked diff response, with the scan upload mocked out, then check what the output layer renders. """ + import json from pathlib import Path from types import SimpleNamespace @@ -72,11 +73,13 @@ def _blocking_alert(key, alert_type="malware"): def _diff_response(**buckets): raw = json.loads((Path(__file__).parent.parent / "data/fullscans/diff/stream_diff.json").read_text()) artifacts = {name: buckets.get(name, []) for name in BUCKETS} - return StreamDiffResponse.from_dict({ - "success": raw["success"], - "status": raw["status"], - "data": {**raw["data"], "artifacts": artifacts}, - }) + return StreamDiffResponse.from_dict( + { + "success": raw["success"], + "status": raw["status"], + "data": {**raw["data"], "artifacts": artifacts}, + } + ) def _build_diff(core, response, *, baseline="head"): @@ -89,7 +92,9 @@ def _build_diff(core, response, *, baseline="head"): params = FullScanParams(repo="repo", branch="feature") params.include_license_details = True return core.create_new_diff( - ["/repo"], params, explicit_files=["/repo/package.json"], + ["/repo"], + params, + explicit_files=["/repo/package.json"], ) @@ -108,10 +113,16 @@ def _handler(strict_blocking=True): def test_empty_baseline_lists_added_alerts_once(core): """Against an empty baseline every package is added and none is unchanged.""" core.cli_config = CliConfig.from_args(["--api-token", "test", "--strict-blocking"]) - diff = _build_diff(core, _diff_response(added=[ - _artifact("added", "a1", "alpha", [_blocking_alert("k1")]), - _artifact("added", "a2", "beta", [_blocking_alert("k2")]), - ]), baseline=None) + diff = _build_diff( + core, + _diff_response( + added=[ + _artifact("added", "a1", "alpha", [_blocking_alert("k1")]), + _artifact("added", "a2", "beta", [_blocking_alert("k2")]), + ] + ), + baseline=None, + ) assert len(diff.new_alerts) == 2 assert diff.unchanged_alerts == [] @@ -129,10 +140,13 @@ def test_empty_baseline_lists_added_alerts_once(core): def test_real_baseline_lists_new_and_existing_alerts_once_each(core): """With a baseline, added alerts are new and unchanged alerts are existing.""" - diff = _build_diff(core, _diff_response( - added=[_artifact("added", "a1", "alpha", [_blocking_alert("k1")])], - unchanged=[_artifact("unchanged", "u1", "gamma", [_blocking_alert("k3")])], - )) + diff = _build_diff( + core, + _diff_response( + added=[_artifact("added", "a1", "alpha", [_blocking_alert("k1")])], + unchanged=[_artifact("unchanged", "u1", "gamma", [_blocking_alert("k3")])], + ), + ) assert [a.pkg_name for a in diff.new_alerts] == ["alpha"] assert [a.pkg_name for a in diff.unchanged_alerts] == ["gamma"] @@ -149,9 +163,12 @@ def test_real_baseline_lists_new_and_existing_alerts_once_each(core): def test_real_baseline_fails_on_existing_alerts_alone(core): """An unchanged blocking alert fails the run when the API returns it.""" - diff = _build_diff(core, _diff_response( - unchanged=[_artifact("unchanged", "u1", "gamma", [_blocking_alert("k3")])], - )) + diff = _build_diff( + core, + _diff_response( + unchanged=[_artifact("unchanged", "u1", "gamma", [_blocking_alert("k3")])], + ), + ) assert diff.new_alerts == [] assert not _handler(strict_blocking=True).report_pass(diff) @@ -159,10 +176,13 @@ def test_real_baseline_fails_on_existing_alerts_alone(core): def test_without_strict_blocking_output_is_unchanged(core): - diff = _build_diff(core, _diff_response( - added=[_artifact("added", "a1", "alpha", [_blocking_alert("k1")])], - unchanged=[_artifact("unchanged", "u1", "gamma", [_blocking_alert("k3")])], - )) + diff = _build_diff( + core, + _diff_response( + added=[_artifact("added", "a1", "alpha", [_blocking_alert("k1")])], + unchanged=[_artifact("unchanged", "u1", "gamma", [_blocking_alert("k3")])], + ), + ) report = _handler(strict_blocking=False).build_json_report(diff) assert [a["pkg_name"] for a in report["new_alerts"]] == ["alpha"] @@ -170,13 +190,22 @@ def test_without_strict_blocking_output_is_unchanged(core): def test_unchanged_packages_are_keyed_by_artifact_id(core): """Transitive unchanged alerts resolve their introducer through the ancestor ID.""" - diff = _build_diff(core, _diff_response(unchanged=[ - _artifact("unchanged", "top", "parent"), - _artifact( - "unchanged", "dep", "child", [_blocking_alert("k5")], - direct=False, ancestors=["top"], + diff = _build_diff( + core, + _diff_response( + unchanged=[ + _artifact("unchanged", "top", "parent"), + _artifact( + "unchanged", + "dep", + "child", + [_blocking_alert("k5")], + direct=False, + ancestors=["top"], + ), + ] ), - ])) + ) assert diff.unchanged_alerts[0].introduced_by == [("npm/parent@1.0.0", "package.json")] diff --git a/tests/core/test_strict_blocking_no_manifest_change.py b/tests/core/test_strict_blocking_no_manifest_change.py index d2ab41bc..03f286ed 100644 --- a/tests/core/test_strict_blocking_no_manifest_change.py +++ b/tests/core/test_strict_blocking_no_manifest_change.py @@ -76,12 +76,8 @@ def cli_runtime(monkeypatch): sdk = MagicMock() monkeypatch.setattr(socketcli, "build_socket_sdk", Mock(return_value=sdk)) monkeypatch.setattr(socketcli, "CliClient", Mock()) - monkeypatch.setattr( - socketcli, "StreamingLogs", lambda **kwargs: nullcontext(Mock()) - ) - git_repo = SimpleNamespace( - changed_files=["README.md"], is_default_branch=False, remote_url=None - ) + monkeypatch.setattr(socketcli, "StreamingLogs", lambda **kwargs: nullcontext(Mock())) + git_repo = SimpleNamespace(changed_files=["README.md"], is_default_branch=False, remote_url=None) in_git_repo = {"value": True} def apply_git_context(config): @@ -94,9 +90,7 @@ def apply_git_context(config): monkeypatch.setattr( Core, "has_manifest_files", - lambda self, files: any( - f.endswith(("package.json", "package-lock.json")) for f in files - ), + lambda self, files: any(f.endswith(("package.json", "package-lock.json")) for f in files), ) monkeypatch.setattr(Core, "find_files", Mock(return_value=["package.json"])) diff = Diff(id="compared") @@ -158,20 +152,13 @@ def test_no_existing_blocker_passes_a_change_without_manifests(cli_runtime, mode def test_disable_blocking_still_wins(cli_runtime): cli_runtime.diff.unchanged_alerts = [_existing_blocker()] - assert ( - cli_runtime.run(["--enable-diff", "--strict-blocking", "--disable-blocking"]) - == 0 - ) + assert cli_runtime.run(["--enable-diff", "--strict-blocking", "--disable-blocking"]) == 0 cli_runtime.compare.assert_called_once() @pytest.mark.parametrize("mode, git", MODES) -def test_without_strict_blocking_the_full_scan_fallback_is_unchanged( - cli_runtime, mode, git -): - cli_runtime.full_scan.return_value = Diff( - id="full", report_url="", diff_url="", new_alerts=[_existing_blocker()] - ) +def test_without_strict_blocking_the_full_scan_fallback_is_unchanged(cli_runtime, mode, git): + cli_runtime.full_scan.return_value = Diff(id="full", report_url="", diff_url="", new_alerts=[_existing_blocker()]) assert cli_runtime.run(mode, git=git) == 0 cli_runtime.full_scan.assert_called_once() @@ -201,17 +188,11 @@ def test_changed_manifest_still_compares(cli_runtime): def comparison(cli_runtime, monkeypatch): monkeypatch.setattr(Core, "create_new_diff", cli_runtime.create_new_diff) monkeypatch.setattr(Core, "get_org_id_slug", Mock(return_value=("org-id", "acme"))) - monkeypatch.setattr( - Core, "resolve_base_full_scan_id", Mock(return_value="baseline") - ) + monkeypatch.setattr(Core, "resolve_base_full_scan_id", Mock(return_value="baseline")) upload = Mock(return_value=SimpleNamespace(id="head")) monkeypatch.setattr(Core, "create_full_scan", upload) - monkeypatch.setattr( - Core, "find_files", Mock(return_value=["package.json", "package-lock.json"]) - ) - cli_runtime.sdk.diffscans.create_from_ids.return_value = { - "diff_scan": {"id": "comparison"} - } + monkeypatch.setattr(Core, "find_files", Mock(return_value=["package.json", "package-lock.json"])) + cli_runtime.sdk.diffscans.create_from_ids.return_value = {"diff_scan": {"id": "comparison"}} cli_runtime.sdk.diffscans.get.return_value = { "diff_scan": { "artifacts": { @@ -240,9 +221,7 @@ def github_pull_request(cli_runtime, monkeypatch): "event, extra", [ pytest.param("pull_request", [], id="pull-request"), - pytest.param( - "pull_request", ["--ignore-commit-files"], id="ignore-commit-files" - ), + pytest.param("pull_request", ["--ignore-commit-files"], id="ignore-commit-files"), pytest.param("push", [], id="push-with-pr-number"), ], ) @@ -278,22 +257,15 @@ def test_code_only_pull_request_maps_comparison_failures( if failure == "incomplete-comparison": cli_runtime.sdk.diffscans.get.return_value = {"diff_scan": {"incomplete": True}} else: - cli_runtime.sdk.fullscans.stream.return_value = SimpleNamespace( - success=True, artifacts={} - ) + cli_runtime.sdk.fullscans.stream.return_value = SimpleNamespace(success=True, artifacts={}) - assert ( - cli_runtime.run(["--scm", "github", "--strict-blocking", *policy]) - == infrastructure_code - ) + assert cli_runtime.run(["--scm", "github", "--strict-blocking", *policy]) == infrastructure_code comparison.assert_called_once() cli_runtime.sdk.fullscans.stream_diff.assert_not_called() github_pull_request.assert_not_called() -def test_code_only_pull_request_without_strict_blocking_skips_the_comment( - cli_runtime, github_pull_request -): +def test_code_only_pull_request_without_strict_blocking_skips_the_comment(cli_runtime, github_pull_request): assert cli_runtime.run(["--scm", "github"]) == 0 cli_runtime.full_scan.assert_called_once() cli_runtime.compare.assert_not_called() @@ -305,14 +277,9 @@ def test_branch_pipeline_still_creates_a_full_scan(cli_runtime, monkeypatch, cap monkeypatch.setenv("GITHUB_EVENT_NAME", "push") monkeypatch.setenv("GITHUB_REPOSITORY", "acme/repo") monkeypatch.delenv("PR_NUMBER", raising=False) - cli_runtime.full_scan.return_value = Diff( - id="full", report_url="", diff_url="", new_alerts=[_existing_blocker()] - ) + cli_runtime.full_scan.return_value = Diff(id="full", report_url="", diff_url="", new_alerts=[_existing_blocker()]) - assert ( - cli_runtime.run(["--scm", "github", "--pr-number", "0", "--strict-blocking"]) - == 0 - ) + assert cli_runtime.run(["--scm", "github", "--pr-number", "0", "--strict-blocking"]) == 0 cli_runtime.full_scan.assert_called_once() cli_runtime.compare.assert_not_called() assert STRICT_COMPARISON_LOG not in caplog.text @@ -336,9 +303,7 @@ def test_comparison_is_logged_when_it_runs(cli_runtime, caplog): assert STRICT_COMPARISON_LOG in caplog.text -def test_skipped_pull_request_event_logs_no_comparison( - cli_runtime, monkeypatch, caplog -): +def test_skipped_pull_request_event_logs_no_comparison(cli_runtime, monkeypatch, caplog): monkeypatch.setenv("GH_API_TOKEN", "test") monkeypatch.setenv("GITHUB_EVENT_NAME", "pull_request") monkeypatch.setenv("EVENT_ACTION", "closed") @@ -364,9 +329,7 @@ def gitlab_pipeline(cli_runtime, monkeypatch): return add_comments -def test_code_only_merge_request_comments_on_existing_blockers( - cli_runtime, gitlab_pipeline, monkeypatch -): +def test_code_only_merge_request_comments_on_existing_blockers(cli_runtime, gitlab_pipeline, monkeypatch): monkeypatch.setenv("CI_PIPELINE_SOURCE", "merge_request_event") monkeypatch.setenv("CI_MERGE_REQUEST_IID", "7") monkeypatch.setenv("CI_MERGE_REQUEST_PROJECT_ID", "42") @@ -383,13 +346,9 @@ def test_code_only_merge_request_comments_on_existing_blockers( assert "Existing alerts" in security_comment -def test_gitlab_branch_pipeline_still_creates_a_full_scan( - cli_runtime, gitlab_pipeline, monkeypatch, caplog -): +def test_gitlab_branch_pipeline_still_creates_a_full_scan(cli_runtime, gitlab_pipeline, monkeypatch, caplog): monkeypatch.setenv("CI_PIPELINE_SOURCE", "push") - cli_runtime.full_scan.return_value = Diff( - id="full", report_url="", diff_url="", new_alerts=[_existing_blocker()] - ) + cli_runtime.full_scan.return_value = Diff(id="full", report_url="", diff_url="", new_alerts=[_existing_blocker()]) assert cli_runtime.run(["--scm", "gitlab", "--strict-blocking"]) == 0 cli_runtime.full_scan.assert_called_once() diff --git a/tests/core/test_supporting_methods.py b/tests/core/test_supporting_methods.py index 1e1fb91d..4cca436a 100644 --- a/tests/core/test_supporting_methods.py +++ b/tests/core/test_supporting_methods.py @@ -3,24 +3,24 @@ def make_package(**overrides): - base = dict( - id="pkg:npm/test-package@1.0.0", - name="test-package", - version="1.0.0", - type="npm", - release="tar-gz", - diffType="added", - score={}, - alerts=[], - direct=True, - manifestFiles=[{"file": "package.json"}], - topLevelAncestors=[], - author=["test-author"], - size=1000, - transitives=0, - purl="pkg:npm/test-package@1.0.0", - url="https://socket.dev/npm/package/test-package/overview/1.0.0", - ) + base = { + "id": "pkg:npm/test-package@1.0.0", + "name": "test-package", + "version": "1.0.0", + "type": "npm", + "release": "tar-gz", + "diffType": "added", + "score": {}, + "alerts": [], + "direct": True, + "manifestFiles": [{"file": "package.json"}], + "topLevelAncestors": [], + "author": ["test-author"], + "size": 1000, + "transitives": 0, + "purl": "pkg:npm/test-package@1.0.0", + "url": "https://socket.dev/npm/package/test-package/overview/1.0.0", + } base.update(overrides) return Package(**base) @@ -31,21 +31,21 @@ def test_create_purl(): pkg_type = "npm" pkg_name = "test-package" pkg_version = "1.0.0" - + packages = { "test_pkg": make_package( id="test_pkg", name=pkg_name, version=pkg_version, type=pkg_type, - purl=f"pkg:{pkg_type}/{pkg_name}@{pkg_version}" + purl=f"pkg:{pkg_type}/{pkg_name}@{pkg_version}", ) } - + # Create PURL core = Core.__new__(Core) purl = core.create_purl("test_pkg", packages) - + # Verify PURL properties assert purl.id == "test_pkg" assert purl.name == pkg_name @@ -57,7 +57,7 @@ def test_create_purl(): assert purl.size == 1000 assert purl.transitives == 0 assert purl.url == f"https://socket.dev/{pkg_type}/package/{pkg_name}/overview/{pkg_version}" - assert purl.purl == f"pkg:{pkg_type}/{pkg_name}@{pkg_version}" + assert purl.purl == f"pkg:{pkg_type}/{pkg_name}@{pkg_version}" def test_get_source_data(): @@ -69,13 +69,11 @@ def test_get_source_data(): version="1.0.0", type="npm", direct=True, - manifestFiles=[ - {"file": "package.json", "start": 10, "end": 20} - ], + manifestFiles=[{"file": "package.json", "start": 10, "end": 20}], topLevelAncestors=[], - transitives=1 + transitives=1, ) - + transitive_pkg = make_package( id="t_pkg", name="transitive-package", @@ -86,21 +84,18 @@ def test_get_source_data(): topLevelAncestors=["direct_pkg"], author=["other-author"], size=500, - transitives=0 + transitives=0, ) - - packages = { - "direct_pkg": direct_pkg, - "t_pkg": transitive_pkg - } - + + packages = {"direct_pkg": direct_pkg, "t_pkg": transitive_pkg} + # Test direct package direct_source = Core.get_source_data(direct_pkg, packages) assert direct_source == [("direct", "package.json")] - + # Test transitive package trans_source = Core.get_source_data(transitive_pkg, packages) - assert trans_source == [("npm/direct-package@1.0.0", "package.json")] + assert trans_source == [("npm/direct-package@1.0.0", "package.json")] def test_get_capabilities_for_added_packages(): @@ -118,16 +113,16 @@ def test_get_capabilities_for_added_packages(): "type": "filesystemAccess", "severity": "low", "category": "supplyChainRisk", - "file": "index.js" + "file": "index.js", }, { "key": "alert2", "type": "networkAccess", "severity": "middle", "category": "supplyChainRisk", - "file": "lib.js" - } - ] + "file": "lib.js", + }, + ], ), "pkg2": make_package( id="pkg2", @@ -140,27 +135,27 @@ def test_get_capabilities_for_added_packages(): "type": "usesEval", "severity": "high", "category": "supplyChainRisk", - "file": "main.js" + "file": "main.js", } - ] - ) + ], + ), } - + # Get capabilities for these packages capabilities = Core.get_capabilities_for_added_packages(packages) - + # Verify the returned dictionary structure assert "pkg1" in capabilities assert "pkg2" in capabilities - + # Verify capabilities for pkg1 (has both filesystem and network access) assert "File System Access" in capabilities["pkg1"] assert "Network Access" in capabilities["pkg1"] assert len(capabilities["pkg1"]) == 2 - + # Verify capabilities for pkg2 (has eval) assert "Uses Eval" in capabilities["pkg2"] - assert len(capabilities["pkg2"]) == 1 + assert len(capabilities["pkg2"]) == 1 def test_get_new_alerts(): @@ -178,7 +173,7 @@ def test_get_new_alerts(): severity="high", error=True, purl="pkg:npm/pkg1@1.0.0", - manifests="package.json" + manifests="package.json", ) ], "key2": [ # Existing alert type but new instance @@ -192,7 +187,7 @@ def test_get_new_alerts(): severity="medium", warn=True, purl="pkg:npm/pkg2@1.0.0", - manifests="package.json" + manifests="package.json", ) ], "key3": [ # Alert that should be ignored (no error/warn) @@ -206,11 +201,11 @@ def test_get_new_alerts(): severity="low", monitor=True, purl="pkg:npm/pkg3@1.0.0", - manifests="package.json" + manifests="package.json", ) - ] + ], } - + removed_alerts = { "key2": [ # Existing alert with different package Issue( @@ -223,36 +218,36 @@ def test_get_new_alerts(): severity="medium", warn=True, purl="pkg:npm/old-pkg@0.9.0", - manifests="package.json" + manifests="package.json", ) ] } - + # Test with ignore_readded=True (default) new_alerts = Core.get_new_alerts(added_alerts, removed_alerts) - + # Verify results assert len(new_alerts) == 2 # Should only include key1 and key2 alerts - + # Verify the completely new alert (key1) is included key1_alerts = [a for a in new_alerts if a.key == "key1"] assert len(key1_alerts) == 1 assert key1_alerts[0].type == "filesystemAccess" assert key1_alerts[0].error is True - + # Verify the new instance of existing alert (key2) is included key2_alerts = [a for a in new_alerts if a.key == "key2"] assert len(key2_alerts) == 1 assert key2_alerts[0].type == "networkAccess" assert key2_alerts[0].warn is True - + # Verify the monitor-only alert (key3) is not included key3_alerts = [a for a in new_alerts if a.key == "key3"] assert len(key3_alerts) == 0 - + # Test with ignore_readded=False all_alerts = Core.get_new_alerts(added_alerts, removed_alerts, ignore_readded=False) - assert len(all_alerts) == 2 # Should still be 2 since key3 is still monitor-only + assert len(all_alerts) == 2 # Should still be 2 since key3 is still monitor-only def test_add_purl_capabilities(): @@ -272,7 +267,7 @@ def test_add_purl_capabilities(): size=1000, transitives=0, url="https://socket.dev/npm/package/package-1/overview/1.0.0", - purl="pkg:npm/package-1@1.0.0" + purl="pkg:npm/package-1@1.0.0", ), Purl( id="pkg2", @@ -285,26 +280,26 @@ def test_add_purl_capabilities(): size=500, transitives=0, url="https://socket.dev/npm/package/package-2/overview/2.0.0", - purl="pkg:npm/package-2@2.0.0" - ) + purl="pkg:npm/package-2@2.0.0", + ), ], new_capabilities={ "pkg1": ["File System Access", "Network Access"], # pkg2 intentionally has no capabilities - } + }, ) - + # Add capabilities to purls Core.add_purl_capabilities(diff) - + # Verify results assert len(diff.new_packages) == 2 - + # Check package with capabilities pkg1 = next(p for p in diff.new_packages if p.id == "pkg1") assert hasattr(pkg1, "capabilities") assert pkg1.capabilities == ["File System Access", "Network Access"] - + # Check package without capabilities pkg2 = next(p for p in diff.new_packages if p.id == "pkg2") assert pkg2.capabilities == [] diff --git a/tests/e2e/reach_facts.py b/tests/e2e/reach_facts.py index abb6d25a..ffb09d4f 100644 --- a/tests/e2e/reach_facts.py +++ b/tests/e2e/reach_facts.py @@ -37,11 +37,7 @@ def alert_states(fixture: str) -> Counter: components = load_components_with_alerts(fixture, FACTS_FILE) or [] - return Counter( - alert["props"]["reachability"] - for component in components - for alert in component["alerts"] - ) + return Counter(alert["props"]["reachability"] for component in components for alert in component["alerts"]) def nothing_to_analyze(log: str) -> bool: @@ -75,9 +71,7 @@ def validate_analyzed(fixture: str, log: str) -> bool: f"::warning title=reachability analysis errors::{states['error']} vulnerabilities in {fixture} ended in error" ) if not any(states[state] for state in ANALYZED): - print( - f"FAIL: Coana analyzed no vulnerability in {fixture}; check the toolchain errors in the CLI output" - ) + print(f"FAIL: Coana analyzed no vulnerability in {fixture}; check the toolchain errors in the CLI output") return False print(f"PASS: Coana analyzed vulnerabilities in {fixture}") return True @@ -96,9 +90,7 @@ def main() -> int: return 0 if alert_states(args.fixture) else 1 if args.inconclusive: return 0 if nothing_to_analyze(args.inconclusive.read_text()) else 1 - return ( - 0 if validate_analyzed(args.fixture, args.validate_analyzed.read_text()) else 1 - ) + return 0 if validate_analyzed(args.fixture, args.validate_analyzed.read_text()) else 1 if __name__ == "__main__": diff --git a/tests/unit/test_alert_selection.py b/tests/unit/test_alert_selection.py index d7a63c7b..7a59ca86 100644 --- a/tests/unit/test_alert_selection.py +++ b/tests/unit/test_alert_selection.py @@ -44,40 +44,51 @@ def test_select_diff_alerts_includes_unchanged_with_strict(): def test_filter_alerts_by_reachability_supports_reachability_selectors(tmp_path): facts_path = tmp_path / ".socket.facts.json" - facts_path.write_text(json.dumps({ - "components": [ + facts_path.write_text( + json.dumps( { - "type": "npm", - "name": "reachable-pkg", - "version": "1.0.0", - "vulnerabilities": [{"ghsaId": "GHSA-AAAA-BBBB-CCCC", "severity": "HIGH"}], - "reachability": [{ - "ghsa_id": "GHSA-AAAA-BBBB-CCCC", - "reachability": [{"type": "reachable"}], - }], - }, - { - "type": "npm", - "name": "potential-pkg", - "version": "1.0.0", - "vulnerabilities": [{"ghsaId": "GHSA-DDDD-EEEE-FFFF", "severity": "HIGH"}], - "reachability": [{ - "ghsa_id": "GHSA-DDDD-EEEE-FFFF", - "reachability": [{"type": "potentially_reachable"}], - }], - }, - { - "type": "npm", - "name": "unreachable-pkg", - "version": "1.0.0", - "vulnerabilities": [{"ghsaId": "GHSA-GGGG-HHHH-IIII", "severity": "HIGH"}], - "reachability": [{ - "ghsa_id": "GHSA-GGGG-HHHH-IIII", - "reachability": [{"type": "unreachable"}], - }], - }, - ], - }), encoding="utf-8") + "components": [ + { + "type": "npm", + "name": "reachable-pkg", + "version": "1.0.0", + "vulnerabilities": [{"ghsaId": "GHSA-AAAA-BBBB-CCCC", "severity": "HIGH"}], + "reachability": [ + { + "ghsa_id": "GHSA-AAAA-BBBB-CCCC", + "reachability": [{"type": "reachable"}], + } + ], + }, + { + "type": "npm", + "name": "potential-pkg", + "version": "1.0.0", + "vulnerabilities": [{"ghsaId": "GHSA-DDDD-EEEE-FFFF", "severity": "HIGH"}], + "reachability": [ + { + "ghsa_id": "GHSA-DDDD-EEEE-FFFF", + "reachability": [{"type": "potentially_reachable"}], + } + ], + }, + { + "type": "npm", + "name": "unreachable-pkg", + "version": "1.0.0", + "vulnerabilities": [{"ghsaId": "GHSA-GGGG-HHHH-IIII", "severity": "HIGH"}], + "reachability": [ + { + "ghsa_id": "GHSA-GGGG-HHHH-IIII", + "reachability": [{"type": "unreachable"}], + } + ], + }, + ], + } + ), + encoding="utf-8", + ) alerts = [ _issue("reachable-pkg", "GHSA-AAAA-BBBB-CCCC"), @@ -85,14 +96,10 @@ def test_filter_alerts_by_reachability_supports_reachability_selectors(tmp_path) _issue("unreachable-pkg", "GHSA-GGGG-HHHH-IIII"), ] - reachable = filter_alerts_by_reachability( - alerts, "reachable", str(tmp_path), ".socket.facts.json" - ) + reachable = filter_alerts_by_reachability(alerts, "reachable", str(tmp_path), ".socket.facts.json") assert [a.pkg_name for a in reachable] == ["reachable-pkg"] - potentially = filter_alerts_by_reachability( - alerts, "potentially", str(tmp_path), ".socket.facts.json" - ) + potentially = filter_alerts_by_reachability(alerts, "potentially", str(tmp_path), ".socket.facts.json") assert [a.pkg_name for a in potentially] == ["potential-pkg"] reachable_or_potentially = filter_alerts_by_reachability( diff --git a/tests/unit/test_cli_config.py b/tests/unit/test_cli_config.py index 636ee9d3..5c64e04c 100644 --- a/tests/unit/test_cli_config.py +++ b/tests/unit/test_cli_config.py @@ -9,15 +9,11 @@ def test_default_is_3(self): assert config.exit_code_on_api_error == 3 def test_custom_value(self): - config = CliConfig.from_args( - ["--api-token", "test", "--exit-code-on-api-error", "100"] - ) + config = CliConfig.from_args(["--api-token", "test", "--exit-code-on-api-error", "100"]) assert config.exit_code_on_api_error == 100 def test_zero_value(self): - config = CliConfig.from_args( - ["--api-token", "test", "--exit-code-on-api-error", "0"] - ) + config = CliConfig.from_args(["--api-token", "test", "--exit-code-on-api-error", "0"]) assert config.exit_code_on_api_error == 0 @@ -28,17 +24,13 @@ def test_passes_through_under_limit(self): assert config.commit_message == msg def test_truncated_above_limit(self): - config = CliConfig.from_args( - ["--api-token", "test", "--commit-message", "a" * 250] - ) + config = CliConfig.from_args(["--api-token", "test", "--commit-message", "a" * 250]) assert config.commit_message == "a" * 197 + "..." assert len(config.commit_message) == 200 def test_quote_strip_runs_before_truncation(self): quoted = '"' + ("b" * 250) + '"' - config = CliConfig.from_args( - ["--api-token", "test", "--commit-message", quoted] - ) + config = CliConfig.from_args(["--api-token", "test", "--commit-message", quoted]) assert config.commit_message == "b" * 197 + "..." @@ -76,59 +68,85 @@ def test_scm_infers_scan_integration_when_integration_is_not_explicit(self, scm) assert config.integration_type == scm def test_explicit_api_integration_wins_over_scm_inference(self): - config = CliConfig.from_args([ - "--api-token", "test", - "--scm", "github", - "--integration", "api", - ]) + config = CliConfig.from_args( + [ + "--api-token", + "test", + "--scm", + "github", + "--integration", + "api", + ] + ) assert config.integration_type == "api" def test_abbreviated_integration_is_still_treated_as_explicit(self): - config = CliConfig.from_args([ - "--api-token", "test", - "--scm", "github", - "--integ", "api", - ]) + config = CliConfig.from_args( + [ + "--api-token", + "test", + "--scm", + "github", + "--integ", + "api", + ] + ) assert config.integration_type == "api" def test_pr_number_tracks_whether_it_was_explicit(self): inferred = CliConfig.from_args(["--api-token", "test"]) - explicit = CliConfig.from_args([ - "--api-token", "test", "--pr-number", "0", - ]) + explicit = CliConfig.from_args( + [ + "--api-token", + "test", + "--pr-number", + "0", + ] + ) assert inferred.pr_number_explicit is False assert explicit.pr_number_explicit is True def test_abbreviated_pr_number_is_still_treated_as_explicit(self): - config = CliConfig.from_args([ - "--api-token", "test", "--pr-n", "0", - ]) + config = CliConfig.from_args( + [ + "--api-token", + "test", + "--pr-n", + "0", + ] + ) assert config.pr_number == "0" assert config.pr_number_explicit is True def test_config_file_values_are_treated_as_explicit(self, tmp_path): config_path = tmp_path / "socketcli.json" - config_path.write_text( - '{"socketcli":{"scm":"github","integration":"api","pr_number":"0"}}' - ) + config_path.write_text('{"socketcli":{"scm":"github","integration":"api","pr_number":"0"}}') - config = CliConfig.from_args([ - "--api-token", "test", "--config", str(config_path), - ]) + config = CliConfig.from_args( + [ + "--api-token", + "test", + "--config", + str(config_path), + ] + ) assert config.integration_type == "api" assert config.pr_number_explicit is True - @pytest.mark.parametrize("flag,attr", [ - ("--enable-debug", "enable_debug"), - ("--disable-blocking", "disable_blocking"), - ("--allow-unverified", "allow_unverified"), - ("--enable-diff", "enable_diff") - ]) + @pytest.mark.parametrize( + "flag,attr", + [ + ("--enable-debug", "enable_debug"), + ("--disable-blocking", "disable_blocking"), + ("--allow-unverified", "allow_unverified"), + ("--enable-diff", "enable_diff"), + ], + ) def test_boolean_flags(self, flag, attr): config = CliConfig.from_args(["--api-token", "test", flag]) assert getattr(config, attr) is True @@ -156,11 +174,7 @@ def test_strict_blocking_default_false(self): def test_strict_blocking_with_disable_blocking(self): """Test that both flags can be set (disable-blocking should win)""" - config = CliConfig.from_args([ - "--api-token", "test", - "--strict-blocking", - "--disable-blocking" - ]) + config = CliConfig.from_args(["--api-token", "test", "--strict-blocking", "--disable-blocking"]) assert config.strict_blocking is True assert config.disable_blocking is True @@ -176,12 +190,18 @@ def test_workspace_default_is_none(self): def test_workspace_is_independent_of_workspace_name(self): """--workspace and --workspace-name are distinct flags with distinct purposes.""" - config = CliConfig.from_args([ - "--api-token", "test", - "--workspace", "my-workspace", - "--sub-path", ".", - "--workspace-name", "monorepo-suffix", - ]) + config = CliConfig.from_args( + [ + "--api-token", + "test", + "--workspace", + "my-workspace", + "--sub-path", + ".", + "--workspace-name", + "monorepo-suffix", + ] + ) assert config.workspace == "my-workspace" assert config.workspace_name == "monorepo-suffix" @@ -197,15 +217,23 @@ def test_legal_flag_sets_default_artifact_files(self): assert config.license_file_name == "socket-license.json" def test_legal_flag_preserves_explicit_file_paths(self): - config = CliConfig.from_args([ - "--api-token", "test", - "--legal", - "--json-file", "custom-report.json", - "--summary-file", "custom-summary.txt", - "--report-link-file", "custom-link.txt", - "--sbom-file", "custom-sbom.json", - "--license-file-name", "custom-license.json", - ]) + config = CliConfig.from_args( + [ + "--api-token", + "test", + "--legal", + "--json-file", + "custom-report.json", + "--summary-file", + "custom-summary.txt", + "--report-link-file", + "custom-link.txt", + "--sbom-file", + "custom-sbom.json", + "--license-file-name", + "custom-license.json", + ] + ) assert config.json_file == "custom-report.json" assert config.summary_file == "custom-summary.txt" assert config.report_link_file == "custom-link.txt" diff --git a/tests/unit/test_cli_run.py b/tests/unit/test_cli_run.py index 82754e1a..08897408 100644 --- a/tests/unit/test_cli_run.py +++ b/tests/unit/test_cli_run.py @@ -14,15 +14,17 @@ def _resp(payload): def test_register_cli_run_returns_run_id_when_enabled(): client = Mock(spec=CliClient) - client.request.return_value = _resp({ - "log_streaming_enabled": True, - "run_id": "srv-issued-123", - }) + client.request.return_value = _resp( + { + "log_streaming_enabled": True, + "run_id": "srv-issued-123", + } + ) run_id = register_cli_run(client, client_version="1.2.3", upload_logs=True) assert run_id == "srv-issued-123" - args, kwargs = client.request.call_args + _args, kwargs = client.request.call_args assert kwargs["path"] == "python-cli-runs" assert kwargs["method"] == "POST" body = json.loads(kwargs["payload"]) @@ -31,10 +33,12 @@ def test_register_cli_run_returns_run_id_when_enabled(): def test_register_cli_run_returns_none_when_disabled_by_server(): client = Mock(spec=CliClient) - client.request.return_value = _resp({ - "log_streaming_enabled": False, - "run_id": None, - }) + client.request.return_value = _resp( + { + "log_streaming_enabled": False, + "run_id": None, + } + ) assert register_cli_run(client, client_version="1.0.0", upload_logs=None) is None @@ -104,7 +108,7 @@ def test_finalize_cli_run_posts_status_and_null_report_run_id_by_default(): client = Mock(spec=CliClient) finalize_cli_run(client, "run-x", status="failure") - args, kwargs = client.request.call_args + _args, kwargs = client.request.call_args assert kwargs["path"] == "python-cli-runs/run-x/finalize" assert kwargs["method"] == "POST" assert json.loads(kwargs["payload"]) == {"status": "failure", "report_run_id": None} diff --git a/tests/unit/test_client.py b/tests/unit/test_client.py index 1965d59f..9fff9312 100644 --- a/tests/unit/test_client.py +++ b/tests/unit/test_client.py @@ -10,24 +10,23 @@ @pytest.fixture def config(): - return SocketConfig( - api_key="test_key", - timeout=30, - allow_unverified_ssl=False - ) + return SocketConfig(api_key="test_key", timeout=30, allow_unverified_ssl=False) + @pytest.fixture def client(config): return CliClient(config) + def test_encode_key(): """Test the static key encoding method""" encoded = CliClient._encode_key("test_key") assert encoded == "dGVzdF9rZXk6" # base64 of "test_key:" + def test_request_builds_correct_url(client): """Test URL construction""" - with patch('requests.request') as mock_request: + with patch("requests.request") as mock_request: mock_response = Mock() mock_response.status_code = 200 mock_request.return_value = mock_response @@ -35,12 +34,13 @@ def test_request_builds_correct_url(client): client.request("test/path") mock_request.assert_called_once() - args, kwargs = mock_request.call_args - assert kwargs['url'] == "https://api.socket.dev/v0/test/path" + _args, kwargs = mock_request.call_args + assert kwargs["url"] == "https://api.socket.dev/v0/test/path" + def test_request_uses_config_timeout(client): """Test timeout is passed from config""" - with patch('requests.request') as mock_request: + with patch("requests.request") as mock_request: mock_response = Mock() mock_response.status_code = 200 mock_request.return_value = mock_response @@ -48,15 +48,16 @@ def test_request_uses_config_timeout(client): client.request("test/path") mock_request.assert_called_once() - args, kwargs = mock_request.call_args - assert kwargs['timeout'] == 30 + _args, kwargs = mock_request.call_args + assert kwargs["timeout"] == 30 + def test_request_handles_api_error(): """Test error handling""" config = SocketConfig(api_key="test_key") client = CliClient(config) - with patch('requests.request') as mock_request: + with patch("requests.request") as mock_request: mock_response = Mock() mock_response.status_code = 400 mock_response.raise_for_status.side_effect = requests.exceptions.RequestException("Test error") @@ -65,86 +66,96 @@ def test_request_handles_api_error(): with pytest.raises(APIFailure): client.request("test/path") + def test_request_failure_carries_the_api_error_message(client): response = requests.Response() response.status_code = 404 response._content = b'{"error": {"message": "need an older Socket CLI"}}' - with patch('requests.request', return_value=response): - with pytest.raises(APIFailure, match="404 Client Error.*: need an older Socket CLI") as exc_info: - client.request("test/path") + with ( + patch("requests.request", return_value=response), + pytest.raises(APIFailure, match=r"404 Client Error.*: need an older Socket CLI") as exc_info, + ): + client.request("test/path") assert exc_info.value.status_code == 404 + def test_request_failure_without_an_api_error_message(client): response = requests.Response() response.status_code = 502 - response._content = b'Bad Gateway' + response._content = b"Bad Gateway" + + with ( + patch("requests.request", return_value=response), + pytest.raises(APIFailure, match=r"502 Server Error: None for url: None$"), + ): + client.request("test/path") - with patch('requests.request', return_value=response): - with pytest.raises(APIFailure, match=r"502 Server Error: None for url: None$"): - client.request("test/path") def test_request_uses_custom_headers(client): """Test that custom headers override defaults""" custom_headers = {"Authorization": "Bearer token", "Custom": "Value"} - with patch('requests.request') as mock_request: + with patch("requests.request") as mock_request: mock_response = Mock() mock_response.status_code = 200 mock_request.return_value = mock_response client.request("test/path", headers=custom_headers) - args, kwargs = mock_request.call_args - assert kwargs['headers'] == custom_headers + _args, kwargs = mock_request.call_args + assert kwargs["headers"] == custom_headers + def test_request_uses_custom_base_url(client): """Test that custom base_url overrides default""" custom_base = "https://custom.api.com" - with patch('requests.request') as mock_request: + with patch("requests.request") as mock_request: mock_response = Mock() mock_response.status_code = 200 mock_request.return_value = mock_response client.request("test/path", base_url=custom_base) - args, kwargs = mock_request.call_args - assert kwargs['url'] == f"{custom_base}/test/path" + _args, kwargs = mock_request.call_args + assert kwargs["url"] == f"{custom_base}/test/path" + def test_request_ssl_verification(client): """Test SSL verification setting from config""" - with patch('requests.request') as mock_request: + with patch("requests.request") as mock_request: mock_response = Mock() mock_response.status_code = 200 mock_request.return_value = mock_response client.request("test/path") - args, kwargs = mock_request.call_args - assert kwargs['verify'] # Default is True + _args, kwargs = mock_request.call_args + assert kwargs["verify"] # Default is True # Test with SSL verification disabled client.config.allow_unverified_ssl = True client.request("test/path") - args, kwargs = mock_request.call_args - assert not kwargs['verify'] + _args, kwargs = mock_request.call_args + assert not kwargs["verify"] + def test_request_with_payload(client): """Test request with payload data""" payload = {"key": "value"} - with patch('requests.request') as mock_request: + with patch("requests.request") as mock_request: mock_response = Mock() mock_response.status_code = 200 mock_request.return_value = mock_response client.request("test/path", method="POST", payload=payload) - args, kwargs = mock_request.call_args - assert kwargs['method'] == "POST" - assert kwargs['data'] == payload + _args, kwargs = mock_request.call_args + assert kwargs["method"] == "POST" + assert kwargs["data"] == payload def test_post_telemetry_events_sends_individually(client): @@ -156,7 +167,7 @@ def test_post_telemetry_events_sends_individually(client): {"event_kind": "user-action", "client_action": "ignore_alerts", "artifact_purl": "pkg:npm/bar@2.0.0"}, ] - with patch('requests.request') as mock_request: + with patch("requests.request") as mock_request: mock_response = Mock() mock_response.status_code = 201 mock_request.return_value = mock_response @@ -166,12 +177,12 @@ def test_post_telemetry_events_sends_individually(client): assert mock_request.call_count == 2 first_call = mock_request.call_args_list[0] - assert first_call.kwargs['url'] == "https://api.socket.dev/v0/orgs/test-org/telemetry" - assert first_call.kwargs['method'] == "POST" - assert first_call.kwargs['data'] == json.dumps(events[0]) + assert first_call.kwargs["url"] == "https://api.socket.dev/v0/orgs/test-org/telemetry" + assert first_call.kwargs["method"] == "POST" + assert first_call.kwargs["data"] == json.dumps(events[0]) second_call = mock_request.call_args_list[1] - assert second_call.kwargs['data'] == json.dumps(events[1]) + assert second_call.kwargs["data"] == json.dumps(events[1]) def test_post_telemetry_events_continues_on_failure(client): @@ -182,7 +193,7 @@ def test_post_telemetry_events_continues_on_failure(client): {"event_kind": "user-action", "artifact_purl": "pkg:npm/bar@2.0.0"}, ] - with patch('requests.request') as mock_request: + with patch("requests.request") as mock_request: mock_response = Mock() mock_response.status_code = 201 mock_request.side_effect = [ @@ -205,7 +216,7 @@ def test_request_preserves_the_http_status_on_failure(): config = SocketConfig(api_key="test_key") client = CliClient(config) - with patch('requests.request') as mock_request: + with patch("requests.request") as mock_request: mock_response = Mock() mock_response.status_code = 401 error = requests.exceptions.HTTPError("401 Client Error") @@ -224,7 +235,7 @@ def test_request_tolerates_a_failure_with_no_response(): config = SocketConfig(api_key="test_key") client = CliClient(config) - with patch('requests.request') as mock_request: + with patch("requests.request") as mock_request: mock_request.side_effect = requests.exceptions.ConnectionError("no route") with pytest.raises(APIFailure) as exc_info: @@ -241,7 +252,7 @@ def test_a_handler_written_against_the_sdk_exception_catches_client_failures(): config = SocketConfig(api_key="test_key") client = CliClient(config) - with patch('requests.request') as mock_request: + with patch("requests.request") as mock_request: mock_request.side_effect = requests.exceptions.ConnectionError("no route") with pytest.raises(SdkAPIFailure): diff --git a/tests/unit/test_comment_event_flow.py b/tests/unit/test_comment_event_flow.py index 3bf52604..d8691dbd 100644 --- a/tests/unit/test_comment_event_flow.py +++ b/tests/unit/test_comment_event_flow.py @@ -12,19 +12,7 @@ from socketsecurity.core.scm.gitlab import Gitlab, GitlabConfig from socketsecurity.core.scm_comments import Comments -SECURITY_COMMENT = "\n".join([ - "", - "

    Socket Security: Pull Request Alerts

    ", - "", - "", - "", - "", - "", - "", - "", - "
    npm/lodash@4.17.11 - Prototype Pollution
    npm/handlebars@4.0.11 - Remote Code Execution
    ", - "[View full report](https://socket.dev/dashboard/org/acme/diff/abc?foo=bar)", -]) +SECURITY_COMMENT = "\n

    Socket Security: Pull Request Alerts

    \n\n\n\n\n\n\n\n
    npm/lodash@4.17.11 - Prototype Pollution
    npm/handlebars@4.0.11 - Remote Code Execution
    \n[View full report](https://socket.dev/dashboard/org/acme/diff/abc?foo=bar)" GITHUB_COMMENTS_PATH = "repos/acme/repo/issues/42/comments" GITHUB_PERMISSION_PATH = "repos/acme/repo/collaborators/maintainer/permission" @@ -41,14 +29,25 @@ def _comment(body: str, comment_id: int) -> Comment: def _run_comment_event(monkeypatch, raw_comments, *, permission="write", extra_args=()): argv = [ - "socketcli", "--api-token", "test", "--scm", "github", - "--repo", "repo", "--branch", "feature", "--pr-number", "42", + "socketcli", + "--api-token", + "test", + "--scm", + "github", + "--repo", + "repo", + "--branch", + "feature", + "--pr-number", + "42", *extra_args, ] monkeypatch.setattr(sys, "argv", argv) for key, value in { - "GH_API_TOKEN": "test", "GITHUB_EVENT_NAME": "issue_comment", - "EVENT_ACTION": "created", "GITHUB_REPOSITORY": "acme/repo", + "GH_API_TOKEN": "test", + "GITHUB_EVENT_NAME": "issue_comment", + "EVENT_ACTION": "created", + "GITHUB_REPOSITORY": "acme/repo", "DEFAULT_BRANCH": "false", }.items(): monkeypatch.setenv(key, value) @@ -95,14 +94,19 @@ def _security_and(*bodies): class TestCliCommentEvent: - @pytest.mark.parametrize("body", [ - "LGTM, merging after CI", - "", - "Can we ignore this one? @SocketSecurity please look", - ]) + @pytest.mark.parametrize( + "body", + [ + "LGTM, merging after CI", + "", + "Can we ignore this one? @SocketSecurity please look", + ], + ) def test_ordinary_comment_exits_0_and_leaves_security_comment(self, monkeypatch, body): code, get_comments, update_comment, post_reaction, client = _run_comment_event( - monkeypatch, _security_and(body), extra_args=("--strict-blocking",), + monkeypatch, + _security_and(body), + extra_args=("--strict-blocking",), ) assert code == 0 @@ -116,7 +120,8 @@ def test_ordinary_comment_exits_0_and_leaves_security_comment(self, monkeypatch, def test_ordinary_comment_without_security_comment_exits_0(self, monkeypatch): code, _, update_comment, _, _ = _run_comment_event( - monkeypatch, {5: _comment("ship it", 5)}, + monkeypatch, + {5: _comment("ship it", 5)}, ) assert code == 0 @@ -140,7 +145,8 @@ def test_ignore_command_removes_only_that_package(self, monkeypatch): def test_ignore_all_clears_the_table(self, monkeypatch): code, _, update_comment, post_reaction, client = _run_comment_event( - monkeypatch, _security_and("@SocketSecurity ignore-all"), + monkeypatch, + _security_and("@SocketSecurity ignore-all"), ) assert code == 0 @@ -151,12 +157,19 @@ def test_ignore_all_clears_the_table(self, monkeypatch): events = client.post_telemetry_events.call_args.args[1] assert len(events) == 1 and events[0]["ignore_all"] is True - @pytest.mark.parametrize("command", [ - "@SocketSecurity ignore npm/lodash@4.17.11", "@SocketSecurity ignore-all", "LGTM", - ]) + @pytest.mark.parametrize( + "command", + [ + "@SocketSecurity ignore npm/lodash@4.17.11", + "@SocketSecurity ignore-all", + "LGTM", + ], + ) def test_disable_ignore_skips_comment_processing(self, monkeypatch, command): code, get_comments, update_comment, post_reaction, client = _run_comment_event( - monkeypatch, _security_and(command), extra_args=("--disable-ignore",), + monkeypatch, + _security_and(command), + extra_args=("--disable-ignore",), ) assert code == 0 @@ -183,12 +196,15 @@ def test_unauthorized_ignore_is_dropped_without_crashing(self, monkeypatch): post_reaction.assert_not_called() client.post_telemetry_events.assert_not_called() - @pytest.mark.parametrize("command", [ - "@SocketSecurity ignore", - "@SocketSecurity ignore lodash", - "@SocketSecurity ignore @4.17.11", - "@SocketSecurity ignore npm/lodash@", - ]) + @pytest.mark.parametrize( + "command", + [ + "@SocketSecurity ignore", + "@SocketSecurity ignore lodash", + "@SocketSecurity ignore @4.17.11", + "@SocketSecurity ignore npm/lodash@", + ], + ) def test_malformed_ignore_command_keeps_every_alert(self, monkeypatch, command): code, _, update_comment, _, _ = _run_comment_event(monkeypatch, _security_and(command)) @@ -220,11 +236,20 @@ def _github(self): def _gitlab(self): config = GitlabConfig( - commit_sha="abc", api_url="https://gitlab.example.com/api/v4", - project_dir=".", mr_source_branch="feature", mr_iid="7", - mr_project_id=1, commit_message="", default_branch="main", - project_name="repo", pipeline_source="merge_request_event", - commit_author="dev", token="t", repository="repo", is_default_branch=False, + commit_sha="abc", + api_url="https://gitlab.example.com/api/v4", + project_dir=".", + mr_source_branch="feature", + mr_iid="7", + mr_project_id=1, + commit_message="", + default_branch="main", + project_name="repo", + pipeline_source="merge_request_event", + commit_author="dev", + token="t", + repository="repo", + is_default_branch=False, headers={}, ) gl = Gitlab(client=MagicMock(), config=config) @@ -243,10 +268,12 @@ def test_no_ignore_comments_leaves_security_comment(self, make): @pytest.mark.parametrize("make", ["_github", "_gitlab"]) def test_ignore_comment_rewrites_security_comment(self, make): scm = getattr(self, make)() - comments = Comments.check_for_socket_comments({ - 1: _comment(SECURITY_COMMENT, 1), - 2: _comment("@SocketSecurity ignore npm/handlebars@4.0.11", 2), - }) + comments = Comments.check_for_socket_comments( + { + 1: _comment(SECURITY_COMMENT, 1), + 2: _comment("@SocketSecurity ignore npm/handlebars@4.0.11", 2), + } + ) scm.remove_comment_alerts(comments) body, comment_id = scm.update_comment.call_args.args diff --git a/tests/unit/test_comment_package_links.py b/tests/unit/test_comment_package_links.py index 68c1a73a..46ec6841 100644 --- a/tests/unit/test_comment_package_links.py +++ b/tests/unit/test_comment_package_links.py @@ -21,35 +21,35 @@ class _FakeConfig: ECOSYSTEMS = { "npm": ( - dict(type="npm", name="handlebars", version="4.0.11"), + {"type": "npm", "name": "handlebars", "version": "4.0.11"}, "https://socket.dev/npm/package/handlebars/overview/4.0.11", ), "npm-scoped": ( - dict(type="npm", namespace="@babel", name="traverse", version="7.22.5"), + {"type": "npm", "namespace": "@babel", "name": "traverse", "version": "7.22.5"}, "https://socket.dev/npm/package/@babel/traverse/overview/7.22.5", ), "pypi": ( - dict(type="pypi", name="django", version="2.2"), + {"type": "pypi", "name": "django", "version": "2.2"}, "https://socket.dev/pypi/package/django/overview/2.2", ), "maven": ( - dict(type="maven", namespace="org.apache.logging.log4j", name="log4j-core", version="2.14.1"), + {"type": "maven", "namespace": "org.apache.logging.log4j", "name": "log4j-core", "version": "2.14.1"}, "https://socket.dev/maven/package/org.apache.logging.log4j/log4j-core/overview/2.14.1", ), "golang": ( - dict(type="golang", namespace="github.com/gin-gonic", name="gin", version="v1.6.0"), + {"type": "golang", "namespace": "github.com/gin-gonic", "name": "gin", "version": "v1.6.0"}, "https://socket.dev/golang/package/github.com/gin-gonic/gin/overview/v1.6.0", ), "nuget": ( - dict(type="nuget", name="Newtonsoft.Json", version="12.0.1"), + {"type": "nuget", "name": "Newtonsoft.Json", "version": "12.0.1"}, "https://socket.dev/nuget/package/Newtonsoft.Json/overview/12.0.1", ), "gem": ( - dict(type="gem", name="rails", version="5.2.0"), + {"type": "gem", "name": "rails", "version": "5.2.0"}, "https://socket.dev/gem/package/rails/overview/5.2.0", ), "cargo": ( - dict(type="cargo", name="smallvec", version="0.6.9"), + {"type": "cargo", "name": "smallvec", "version": "0.6.9"}, "https://socket.dev/cargo/package/smallvec/overview/0.6.9", ), } @@ -59,15 +59,17 @@ class _FakeConfig: def _issues(artifact: dict, alert: dict) -> list: - package = Package.from_diff_artifact({ - "id": f"{artifact['type']}-{artifact['name']}", - "score": {}, - "topLevelAncestors": [], - "direct": True, - "manifestFiles": [{"file": "manifest"}], - "alerts": [alert], - **artifact, - }) + package = Package.from_diff_artifact( + { + "id": f"{artifact['type']}-{artifact['name']}", + "score": {}, + "topLevelAncestors": [], + "direct": True, + "manifestFiles": [{"file": "manifest"}], + "alerts": [alert], + **artifact, + } + ) package = Core.update_package_values(package) core = Core.__new__(Core) core.config = SimpleNamespace(all_issues=SimpleNamespace()) @@ -125,7 +127,7 @@ def test_existing_alerts_table_links_the_package_page(alert): def test_rows_keep_package_namespaces_distinct(section, alert): issues = [] for scope in ("@alpha", "@beta"): - artifact = dict(type="npm", namespace=scope, name="widgets", version="1.0.0") + artifact = {"type": "npm", "namespace": scope, "name": "widgets", "version": "1.0.0"} issues += _issues(artifact, alert) diff = _diff([]) setattr(diff, section, issues) @@ -153,15 +155,12 @@ def test_rows_keep_package_namespaces_distinct(section, alert): @pytest.mark.parametrize("with_existing", [False, True]) def test_large_comments_keep_omission_counts_and_the_full_report(with_existing): - new_issues = [ - _issues(dict(type="npm", name=f"widget-{i}", version="1.0.0"), CVE_ALERT)[0] - for i in range(60) - ] + new_issues = [_issues({"type": "npm", "name": f"widget-{i}", "version": "1.0.0"}, CVE_ALERT)[0] for i in range(60)] for issue in new_issues: issue.description = "่ชฌๆ˜Ž" * 200 diff = _diff(new_issues) if with_existing: - artifact = dict(type="npm", name="existing-widget", version="1.0.0") + artifact = {"type": "npm", "name": "existing-widget", "version": "1.0.0"} diff.unchanged_alerts = _issues(artifact, CVE_ALERT) diff.unchanged_alerts[0].description = "่ชฌๆ˜Ž" * 500 @@ -181,10 +180,7 @@ def test_large_comments_keep_omission_counts_and_the_full_report(with_existing): assert len(diff.unchanged_alerts) == int(with_existing) comment = Comment(body_list=body.splitlines()) - individual_ignores = [ - Comment(body_list=[f"@SocketSecurity ignore npm/{coordinate}"]) - for coordinate in visible - ] + individual_ignores = [Comment(body_list=[f"@SocketSecurity ignore npm/{coordinate}"]) for coordinate in visible] updated = Comments.process_security_comment(comment, {"ignore": individual_ignores}) assert "more new alert(s) are not shown" in updated assert "No dependency alerts to report" not in updated @@ -212,11 +208,9 @@ def test_no_relative_package_links_on_either_scm(scm): def test_package_url_is_attribute_escaped(): - artifact = dict(type="npm", name='evil">