diff --git a/CHANGELOG.md b/CHANGELOG.md index e7d7f13..fa8a070 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,6 +54,11 @@ - The [CI guide](docs/ci-cd.md#required-github-checks) describes GitHub required checks and the GitHub Actions workflow migration. +- The README's upgrade notes for 2.13 and 2.14 are combined into one short + [section](README.md#upgrading-from-212-or-earlier). +- Clarified that `--include-module-folders` discovers dependency manifests. + Added a guide to scanning packages installed outside the lockfile with a + CycloneDX SBOM. ## 2.13.2 diff --git a/README.md b/README.md index 70152cf..a143c62 100644 --- a/README.md +++ b/README.md @@ -268,27 +268,29 @@ scan exit `0` on *both* findings and outages — the `soft_fail: 100` rule would never match, and real findings would stop blocking. That's usually not what you want. -### Upgrading to 2.13.0 - -Update pipeline rules and wrapper scripts that match specific exit codes: - -| Outcome | Before 2.13.0 | From 2.13.0 | -|---------|---------------|-------------| -| Invalid flags or configuration | CLI validation: `1`; argparse: `2` | `2` for both; never suppressed by `--disable-blocking` | -| Ctrl+C | `2` | `130`, or `0` with `--disable-blocking` | -| Missing token or other setup failure | Fixed `2` or `3`, depending on the failure | Infrastructure-error code (`3` by default); both exit-code flags now apply | - -Blocking findings still exit `1`. With `--strict-blocking`, existing blocking -alerts can now fail jobs that previously passed. GitLab report findings also get -new IDs once; see the [release notes](CHANGELOG.md#2130). - -Configuration is validated before credentials or network setup. Use native -JSON/TOML booleans such as `false`, a positive integer `timeout`, and an array of -file paths for `files`. Invalid or unreadable configuration exits `2` even when -credentials are missing or blocking is disabled. - -For a compact comparison of failure-handling policies, see -[Exit codes in CI](docs/ci-cd.md#exit-codes-in-ci). +### Upgrading from 2.12 or earlier + +2.13 and 2.14 change exit codes and what `--strict-blocking` checks: + +- **Exit codes:** invalid flags or configuration exit `2`, Ctrl+C exits `130`, + and setup failures such as a missing token use the infrastructure-error code + (`3` by default). Blocking findings still exit `1`. See + [Exit codes in CI](docs/ci-cd.md#exit-codes-in-ci). +- **Config files** are validated before credentials or network setup. Use native + JSON/TOML booleans, a positive integer `timeout` and an array for `files`. +- **`--strict-blocking`** fails on existing Block alerts, counts each advisory + separately, and compares code-only changes too, so pipelines can fail on + alerts they used to pass. Without `--scm github` or `--scm gitlab`, that + includes default-branch pushes, which need the `full-scans:list` and + `repo:list` token scopes; see + [API token permissions](docs/troubleshooting.md#api-token-permissions). +- **GitHub Actions example:** if you copied it, put the + [PR workflow](workflows/github-actions.yml) at the existing path and add the + [push workflow](workflows/github-actions-push.yml) in the same change. See + [Required GitHub checks](docs/ci-cd.md#required-github-checks). + +GitLab report findings get new IDs once. The [release notes](CHANGELOG.md) have +the details. ## Common gotchas diff --git a/docs/ci-cd.md b/docs/ci-cd.md index 7c22a81..1c53760 100644 --- a/docs/ci-cd.md +++ b/docs/ci-cd.md @@ -90,7 +90,7 @@ validating a new workflow. The CLI treats comparisons marked incomplete or returned with missing or invalid package lists as infrastructure failures. With `--strict-blocking`, incomplete existing-alert data is also an infrastructure failure. See the -[2.13.0 migration table](../README.md#upgrading-to-2130) when updating existing CI rules. +[upgrade notes](../README.md#upgrading-from-212-or-earlier) when updating existing CI rules. ## Config file usage in CI diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 29939bd..8e0704c 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -324,7 +324,7 @@ docs.socket.dev use `SOCKET_SECURITY_API_KEY`. Either works. If both are set, | Parameter | Required | Default | Description | |:-------------------------|:---------|:--------|:------------------------------------------------------------------------------------------------------| | `--default-branch` | False | *auto* | Make this branch the default branch (auto-detected from git and CI environment when not specified) | -| `--include-module-folders` | False | False | If enabled, re-includes the JS/TS module folders (`node_modules`, `bower_components`, `jspm_packages`) in manifest discovery. For other excluded directories, use `--include-dirs`. | +| `--include-module-folders` | False | False | Includes supported manifests found under `node_modules`, `bower_components`, and `jspm_packages` in manifest discovery. Equivalent to `--include-dirs node_modules,bower_components,jspm_packages`. Other discovery exclusions still apply. For an inventory of installed packages, see [Packages installed outside the lockfile](troubleshooting.md#packages-installed-outside-the-lockfile). | #### Output Configuration | Parameter | Required | Default | Description | diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index e916236..c80a3c6 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -10,7 +10,7 @@ | Exit `0` despite expected blockers | Check `--disable-blocking`, remapping to `0`, and whether the run produced a full scan instead of a diff. Full scans do not gate on findings. | See [Exit codes in CI](ci-cd.md#exit-codes-in-ci) for the flag combinations and -[upgrade guidance](../README.md#upgrading-to-2130) for older pipeline rules. +[upgrade notes](../README.md#upgrading-from-212-or-earlier) for older pipeline rules. ## Repository lookup or creation fails @@ -232,6 +232,27 @@ by the comparison step that follows. - Every vulnerability reported as `INSTALL ERROR`: the engine could not install your dependencies. Allow the ecosystem's package registry, or install dependencies in the target path before running `--reach`. - See **Reachability network access** in the [CLI reference](cli-reference.md) for the full list of hosts. +## Packages installed outside the lockfile + +Packages present only on disk, such as packages that a `postinstall` script adds without updating the lockfile, can be missing from a manifest-based scan. + +`--include-module-folders` lets the CLI discover supported manifests in `node_modules`, `bower_components`, and `jspm_packages`, including nested directories. Other directory and path exclusions still apply, and discovery skips symlinked directories. Socket resolves the dependencies the manifests declare, including `devDependencies`. This can add findings for dependencies absent from your installed tree. With `--reach`, the CLI also includes these files in the manifest upload for reachability analysis. + +For npm projects, generate a CycloneDX software bill of materials (SBOM) from the installed tree. The example uses Node.js 20.18 or newer and npm 9 or newer. Run it from the scan root with a Socket API token configured. + +```bash +npm ci && + npx --yes @cyclonedx/cyclonedx-npm@7.0.1 --omit dev --output-format JSON --output-file installed.cdx.json && + socketcli --target-path . +``` + +The example excludes development dependencies. To include them, remove `--omit dev` and run the install and generator without production-only npm settings or `NODE_ENV=production`. If npm reports a dependency-tree error, inspect it first. Use the generator's `--ignore-npm-errors` option only if the tree npm returns contains the packages you intend to scan. + +The CLI discovers CycloneDX files such as `bom.json`, `*.cdx.json`, and `*.cyclonedx.json` (or their `.xml` equivalents) alongside the lockfile. Leave `--include-module-folders` off when you only want to add the SBOM. + +- For PR comparisons, generate the SBOM with the same settings before the default-branch and PR scans. Add `--ignore-commit-files` to the PR scan so it runs a comparison even on commits that change no tracked manifest. A generated SBOM outside the Git diff does not trigger comparison mode on its own. +- The SBOM covers packages present when it is generated. Packages fetched later or installed outside the tree, such as tools fetched into the npm cache by `npx`, are outside its scope. + ## Dashboard vs CLI result counts Differences in result counts can be valid, even when filtering appears similar. diff --git a/socketsecurity/config.py b/socketsecurity/config.py index d2a8322..a5ceadc 100644 --- a/socketsecurity/config.py +++ b/socketsecurity/config.py @@ -1120,7 +1120,9 @@ def create_argument_parser() -> argparse.ArgumentParser: dest="include_module_folders", action="store_true", default=False, - help="Enabling including module folders like node_modules" + 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" ) # Reachability Configuration diff --git a/tests/unit/test_include_dirs.py b/tests/unit/test_include_dirs.py index 5425287..0a607be 100644 --- a/tests/unit/test_include_dirs.py +++ b/tests/unit/test_include_dirs.py @@ -1,11 +1,13 @@ -"""Tests for --include-dirs (and the now-functional --include-module-folders). - -Covers config parsing of the comma-separated directory names and that re-including a -normally-excluded directory (e.g. build) lets Core.find_files discover manifests under it. -""" +"""Test directory selection for manifest discovery.""" +import sys import types +from contextlib import nullcontext +from pathlib import Path from unittest.mock import MagicMock +import pytest + +from socketsecurity import socketcli from socketsecurity.config import CliConfig from socketsecurity.core import Core from socketsecurity.core.socket_config import ( @@ -95,3 +97,53 @@ def test_unexcluding_does_not_mutate_shared_defaults(): assert "build" not in config.excluded_dirs assert default_exclude_dirs == before assert "build" in default_exclude_dirs + + +@pytest.mark.parametrize(("flags", "include_node", "include_other"), [ + pytest.param([], False, False, id="default"), + pytest.param(["--include-module-folders"], True, True, id="module-folders"), + pytest.param(["--include-dirs", "node_modules,bower_components,jspm_packages"], True, True, id="include-dirs"), + pytest.param(["--include-module-folders", "--exclude-paths", "node_modules"], False, True, id="exclude-paths"), +]) +def test_cli_manifest_selection(tmp_path, monkeypatch, mocker, flags, include_node, include_other): + root_files = {"package-lock.json", "installed.cdx.json"} + node_files = { + "node_modules/@scope/parent/package.json", + "node_modules/@scope/parent/node_modules/child/yarn.lock", + "node_modules/@scope/parent/requirements.txt", + } + other_modules = {"bower_components/pkg/package.json", "nested/jspm_packages/pkg/package.json"} + excluded_files = {"node_modules/.package-lock.json", "vendor/requirements.txt", ".venv/requirements.txt"} + for name in root_files | node_files | other_modules | excluded_files: + manifest = tmp_path / name + manifest.parent.mkdir(parents=True, exist_ok=True) + manifest.touch() + + sdk = MagicMock() + sdk.org.get.return_value = {"organizations": {"org-id": {"slug": "test-org", "plan": "enterprise"}}} + sdk.report.supported.return_value = { + "npm": {name: {"pattern": name} for name in ("package.json", "package-lock.json", "yarn.lock")}, + "pypi": {"requirements": {"pattern": "requirements.txt"}}, + "cdx": {"json": {"pattern": "{bom,c{yclone,}dx[-.]*,*[-.]c{yclone,}dx}.json"}}, + } + mocker.patch.object(socketcli, "build_socket_sdk", return_value=sdk) + mocker.patch.object(socketcli, "CliClient") + mocker.patch.object(socketcli, "StreamingLogs", return_value=nullcontext(MagicMock())) + mocker.patch.object(socketcli, "apply_git_context", return_value=(False, None)) + upload = mocker.patch.object(Core, "create_full_scan", return_value=types.SimpleNamespace(id="scan")) + monkeypatch.setattr(sys, "argv", [ + "socketcli", *BASE_ARGS, "--branch", "main", "--target-path", str(tmp_path), *flags, + ]) + + with pytest.raises(SystemExit) as exit_status: + socketcli.cli() + + assert exit_status.value.code == 0 + upload.assert_called_once() + submitted = {Path(path).relative_to(tmp_path).as_posix() for path in upload.call_args.args[0]} + expected = root_files.copy() + if include_other: + expected |= other_modules + if include_node: + expected |= node_files + assert submitted == expected