diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 34bcd93..f31a774 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -109,9 +109,16 @@ updates: - dependency-name: "ghcr.io/astral-sh/uv" - dependency-name: "trufflesecurity/trufflehog" # Python minors move by hand; see the note on the root entry. + # Node majors move by hand: the Dockerfile and Dockerfile.heavy install + # Node through nodesource, which Dependabot can't see, so all three must + # change together. Dependabot also doesn't know Node's release schedule, + # and would propose odd-numbered majors, which never get LTS. The floating + # node:-slim tag picks up minor and patch releases on every build. ignore: - dependency-name: "python" update-types: ["version-update:semver-minor"] + - dependency-name: "node" + update-types: ["version-update:semver-major"] groups: docker-app-tests-minor-patch: patterns: diff --git a/.github/workflows/core-tool-watch.yml b/.github/workflows/core-tool-watch.yml index 44f4322..84aa2f2 100644 --- a/.github/workflows/core-tool-watch.yml +++ b/.github/workflows/core-tool-watch.yml @@ -36,7 +36,9 @@ concurrency: jobs: analyze: runs-on: ubuntu-latest - timeout-minutes: 15 + # Three scoring attempts can spend 19 minutes on requests and backoff. + # Allow time for setup, release discovery, and report uploads as well. + timeout-minutes: 30 environment: socket-firewall permissions: contents: read diff --git a/CHANGELOG.md b/CHANGELOG.md index e32407f..4f924d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Upgrade notes - **The heavy image's Socket Python CLI changes its exit codes.** It moves from - 2.12.0 to 2.13.1, and 2.13.0 exits `2` for invalid flags (was `1`), `130` for + 2.12.0 to 2.13.2, and 2.13.0 exits `2` for invalid flags (was `1`), `130` for Ctrl+C (was `2`), and applies `--disable-blocking` and `--exit-code-on-api-error` to missing tokens and other setup failures. `--strict-blocking` now also fails on existing blocking alerts. Check any @@ -21,11 +21,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). unchanged. ### Changed -- Bundled tools: Socket Python CLI 2.12.0 -> 2.13.1. -- The bundled Socket Python CLI now pins the Coana reachability engine 15.15.2. - Socket Tier 1 runs through the Socket npm CLI, which still pins 15.15.0. +- The images ship Node.js 24 (LTS, supported until April 2028) instead of + Node.js 22. +- Bundled tools: Socket npm CLI 1.15.0 -> 1.16.0, Socket Python CLI 2.12.0 -> + 2.13.2; TruffleHog 3.99.8 -> 3.99.9 in the socket-basics and heavy images + (#142). +- Socket Tier 1 runs the Coana reachability engine 15.15.2 instead of 15.15.0. + Socket npm CLI 1.16.0 and Socket Python CLI 2.13.2 both pin it. - Socket Python SDK (`socketdev`) 3.6.2 -> 3.6.3, which Socket Python CLI - 2.13.1 pins exactly. Source installs now require `socketdev>=3.6.3`. + 2.13.2 pins exactly. Source installs now require `socketdev>=3.6.3`. ## [3.5.0] - 2026-11-13 diff --git a/Dockerfile b/Dockerfile index 3be1088..386ed9b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -13,7 +13,7 @@ # Dependabot to read, so they keep an ARG pin and are bumped by hand. These # stay overridable: docker build --build-arg OPENGREP_VERSION=v1.33.1 . ARG OPENGREP_VERSION=v1.33.1 -ARG SOCKET_NPM_CLI_VERSION=1.15.0 +ARG SOCKET_NPM_CLI_VERSION=1.16.0 # # 3. Socket-built Trivy, rebuilt from unmodified upstream source and published # by Socket's own release pipeline. Deliberately kept out of Dependabot's @@ -60,7 +60,7 @@ COPY --from=trivy /usr/local/bin/trivy /usr/local/bin/trivy COPY --from=trufflehog /usr/bin/trufflehog /usr/local/bin/trufflehog COPY --from=opengrep-installer /root/.opengrep /root/.opengrep -# System deps + Node.js 22.x + Socket CLI +# System deps + Node.js 24.x + Socket CLI # ca-certificates must be 20250419+deb13u1 or newer, which drops the roots the # compromised eMudhra intermediates chain to. RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \ @@ -73,10 +73,10 @@ RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \ # vendors certifi 2026.10.19. Upgrade it against the system store fixed above. RUN python -m pip install --no-cache-dir --cert /etc/ssl/certs/ca-certificates.crt --upgrade "pip>=26.2.2" \ && python -c 'import sys, pip; sys.exit(tuple(map(int, pip.__version__.split(".")[:3])) < (26, 2, 2))' -# Node rejects the compromised eMudhra intermediates from 22.23.4. -RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \ +# Node rejects the compromised eMudhra intermediates from 24.22.1. +RUN curl -fsSL https://deb.nodesource.com/setup_24.x | bash - \ && apt-get install -y nodejs \ - && node -e 'const [a,b,c]=process.versions.node.split(".").map(Number); process.exit(a>22||(a===22&&(b>23||(b===23&&c>=4)))?0:1)' + && node -e 'const [a,b,c]=process.versions.node.split(".").map(Number); process.exit(a>24||(a===24&&(b>22||(b===22&&c>=1)))?0:1)' ARG SOCKET_NPM_CLI_VERSION RUN --mount=type=cache,target=/root/.npm \ npm install -g "socket@${SOCKET_NPM_CLI_VERSION}" diff --git a/Dockerfile.heavy b/Dockerfile.heavy index 7bcf57b..7fbb703 100644 --- a/Dockerfile.heavy +++ b/Dockerfile.heavy @@ -4,8 +4,8 @@ # installed by a script or package manager keep an ARG pin and are bumped by # hand. See the note at the top of ./Dockerfile for why. ARG OPENGREP_VERSION=v1.33.1 -ARG SOCKET_NPM_CLI_VERSION=1.15.0 -ARG SOCKET_PYTHON_CLI_VERSION=2.13.1 +ARG SOCKET_NPM_CLI_VERSION=1.16.0 +ARG SOCKET_PYTHON_CLI_VERSION=2.13.2 # Socket-built Trivy, pinned by digest — see the note in ./Dockerfile. ARG TRIVY_IMAGE=ghcr.io/socketdev/trivy:0.76.1@sha256:883da3593a60e311b2ed87c3a55241051b27bba15ffc3ce041ae570cd0f00915 @@ -43,10 +43,10 @@ RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \ # vendors certifi 2026.10.19. Upgrade it against the system store fixed above. RUN python -m pip install --no-cache-dir --cert /etc/ssl/certs/ca-certificates.crt --upgrade "pip>=26.2.2" \ && python -c 'import sys, pip; sys.exit(tuple(map(int, pip.__version__.split(".")[:3])) < (26, 2, 2))' -# Node rejects the compromised eMudhra intermediates from 22.23.4. -RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \ +# Node rejects the compromised eMudhra intermediates from 24.22.1. +RUN curl -fsSL https://deb.nodesource.com/setup_24.x | bash - \ && apt-get install -y nodejs \ - && node -e 'const [a,b,c]=process.versions.node.split(".").map(Number); process.exit(a>22||(a===22&&(b>23||(b===23&&c>=4)))?0:1)' + && node -e 'const [a,b,c]=process.versions.node.split(".").map(Number); process.exit(a>24||(a===24&&(b>22||(b===22&&c>=1)))?0:1)' ARG SOCKET_NPM_CLI_VERSION RUN --mount=type=cache,target=/root/.npm \ npm install -g "socket@${SOCKET_NPM_CLI_VERSION}" diff --git a/app_tests/Dockerfile b/app_tests/Dockerfile index 7fbdedc..6d94812 100644 --- a/app_tests/Dockerfile +++ b/app_tests/Dockerfile @@ -9,8 +9,8 @@ # docker build --build-arg OPENGREP_VERSION=v1.33.1 -f app_tests/Dockerfile app_tests ARG GOSEC_VERSION=v2.30.0 ARG OPENGREP_VERSION=v1.33.1 -ARG SOCKET_NPM_CLI_VERSION=1.15.0 -ARG SOCKET_PYTHON_CLI_VERSION=2.13.1 +ARG SOCKET_NPM_CLI_VERSION=1.16.0 +ARG SOCKET_PYTHON_CLI_VERSION=2.13.2 # # Socket-built Trivy, pinned by digest and deliberately kept out of Dependabot's # reach; updated by Socket's trivy-dist release process. See the root @@ -29,7 +29,7 @@ FROM golang:1.27.3 AS golang # ─── Stage: node ────────────────────────────────────────────────────────────── # Node comes from a named stage, not the nodesource install script, so its # version is a FROM tag that Dependabot and the pin checkers can read. -FROM node:22-slim AS node +FROM node:24-slim AS node # ─── Stage: uv ──────────────────────────────────────────────────────────────── # Named stage required — COPY --from does not support ARG variable expansion. diff --git a/docs/local-install-docker.md b/docs/local-install-docker.md index 8d0a017..ed6b456 100644 --- a/docs/local-install-docker.md +++ b/docs/local-install-docker.md @@ -220,7 +220,7 @@ script or package manager are build args and can be overridden: ```bash docker build \ --build-arg OPENGREP_VERSION=v1.33.1 \ - --build-arg SOCKET_NPM_CLI_VERSION=1.15.0 \ + --build-arg SOCKET_NPM_CLI_VERSION=1.16.0 \ -t socket-basics:3.5.0 . ``` @@ -268,6 +268,9 @@ With `--app-tests` to also test the app_tests image (requires full build context ./scripts/smoke-test-docker.sh --app-tests ``` +Use `linux/amd64` or `linux/arm64` for app-tests builds. The Node.js 24 base +image has no `linux/arm/v7` variant for 32-bit ARM. + This builds the image(s) and verifies the currently bundled tools are installed and executable. A GitHub Action runs this on Dockerfile changes and daily. ## Running Scans diff --git a/scripts/check_core_tools.py b/scripts/check_core_tools.py index 57f035d..eb39066 100644 --- a/scripts/check_core_tools.py +++ b/scripts/check_core_tools.py @@ -55,6 +55,7 @@ import os import re import sys +import time import urllib.request from dataclasses import dataclass, field from pathlib import Path @@ -500,6 +501,106 @@ def analyze_purls(purls: list[str], token: str) -> dict[str, dict[str, Any]]: return by_purl +# Backoff before each retry, in addition to the SDK request timeouts. +SCORING_RETRY_DELAYS_SEC = (15, 45) + + +def _is_transient_api_error(exc: BaseException) -> bool: + """Whether socketdev classifies the failure as worth retrying. + + socketdev's APIFailure.is_transient_error() is true for 408/502/503/504, + dropped connections, and client-side timeouts. Anything else, including + 401/403, 429 quota errors, and an empty result, fails the same way again. + """ + check = getattr(exc, "is_transient_error", None) + return bool(callable(check) and check()) + + +def describe_api_error(exc: BaseException) -> str: + """Name the exception, its HTTP status, and the error that caused it. + + socketdev raises several exceptions with no message (APITimeout, + APIConnectionError, APIBadGateway, and the 403/404/429 variants) and logs + the detail instead, so str(exc) alone is often empty. The status code and + the underlying requests error carried on __context__ say what failed + without printing response headers into public CI logs. + """ + parts = [type(exc).__name__] + status = getattr(exc, "status_code", None) + if status is not None: + parts.append(f"HTTP {status}") + if str(exc): + parts.append(str(exc)) + cause = exc.__cause__ or exc.__context__ + if cause is not None: + parts.append(f"caused by {type(cause).__name__}: {cause}") + return " | ".join(parts) + + +def score_purls_with_retry( + purls: list[str], + token: str, + *, + required: frozenset[str] = frozenset(), + analyze: Callable[[list[str], str], dict[str, dict[str, Any]]] = analyze_purls, + sleep: Callable[[float], None] = time.sleep, + delays: tuple[float, ...] = SCORING_RETRY_DELAYS_SEC, +) -> tuple[dict[str, dict[str, Any]], Exception | None]: + """Run analyze_purls, retrying transient failures and pending results. + + Two kinds of attempt are retried: + - a failure socketdev marks transient (see _is_transient_api_error); + - a batch that answered, but with a coordinate in `required` still + pendingScan after the server-side poll. Only those coordinates are + scored again, and their new rows replace the pending ones. + + Coordinates outside `required` (the discovered latest releases, which + only feed drift reporting) never trigger a retry, so a scheduled watch + doesn't wait on a release Socket is still ingesting. + + Both requests behind analyze_purls (the org lookup and the batch purl + POST) only read, so repeating them is safe. Return the accumulated rows + with any terminal API error so the caller can report findings and fail + closed on incomplete scoring. + """ + analyses: dict[str, dict[str, Any]] = {} + to_score = purls + pending: list[str] = [] + for attempt, delay in enumerate((*delays, None), start=1): + try: + rows = analyze(to_score, token) + except Exception as exc: # noqa: BLE001 + if delay is None or not _is_transient_api_error(exc): + return analyses, exc + print( + f" ! Socket scoring attempt {attempt} failed ({describe_api_error(exc)}); " + f"retrying in {delay:g}s", + file=sys.stderr, + ) + sleep(delay) + continue + # Drop stale pending rows only after a rescore succeeds. A normalized + # response key may differ, and the fallback finds the first match. + for p in pending: + stale = _match_analysis(analyses, p) + for key in [k for k, v in analyses.items() if v is stale]: + del analyses[key] + analyses.update(rows) + pending = [ + p for p in sorted(required) if _match_analysis(analyses, p).get("status") == "pending" + ] + if not pending or delay is None: + return analyses, None + print( + f" ! Socket analysis still pending for {len(pending)} pinned coordinate(s) " + f"after attempt {attempt}; rescoring them in {delay:g}s", + file=sys.stderr, + ) + sleep(delay) + to_score = pending + raise AssertionError("unreachable") + + def _match_analysis(analyses: dict[str, dict[str, Any]], purl: str) -> dict[str, Any]: if purl in analyses: return analyses[purl] @@ -634,10 +735,11 @@ def main() -> int: scoring_error = False if token_present and purls: print(f"== Scoring {len(purls)} PURLs through Socket ==") - try: - analyses = analyze_purls(purls, token) - except Exception as exc: # noqa: BLE001 - print(f"! Socket analysis failed: {exc}", file=sys.stderr) + # Only pending rows for covered pins can fail the run. + required = frozenset(t.purl(v) for t in tools if t.socket_coverage for v in t.pinned) + analyses, error = score_purls_with_retry(purls, token, required=required) + if error is not None: + print(f"! Socket analysis failed: {describe_api_error(error)}", file=sys.stderr) scoring_error = True for t in tools: t.analyses = analyses diff --git a/scripts/smoke-test-docker.sh b/scripts/smoke-test-docker.sh index 37691ec..5aae48a 100644 --- a/scripts/smoke-test-docker.sh +++ b/scripts/smoke-test-docker.sh @@ -14,7 +14,7 @@ BUILD_PROGRESS="${SMOKE_TEST_BUILD_PROGRESS:-}" MAIN_TOOLS=( "socket-basics -h" - "command -v socket" + "socket --version" "trivy --version" "trufflehog --version" "opengrep --version" @@ -24,13 +24,13 @@ APP_TESTS_TOOLS=( "trivy --version" "trufflehog --version" "opengrep --version" - "command -v socket" + "socket --version" ) HEAVY_TOOLS=( "socket-basics -h" "socketcli --help" - "command -v socket" + "socket --version" "trivy --version" "trufflehog --version" "opengrep --version" diff --git a/tests/test_check_core_tools.py b/tests/test_check_core_tools.py index 51c4edf..3ee6951 100644 --- a/tests/test_check_core_tools.py +++ b/tests/test_check_core_tools.py @@ -1,4 +1,9 @@ +import json import re +import sys +from functools import partial + +import pytest from scripts import check_core_tools @@ -102,3 +107,216 @@ def test_incomplete_discovery_report_cannot_be_mistaken_for_no_drift(): assert "Latest-version discovery incomplete" in report assert "must not be used to resolve the drift issue" in report + + +def _raise_from(exc, cause): + """Raise exc inside an except block for cause, as socketdev does.""" + try: + raise cause + except type(cause): + try: + raise exc + except type(exc) as raised: + return raised + + +def test_scoring_retries_transient_api_errors_then_succeeds(): + from socketdev.exceptions import APIBadGateway, APIConnectionError + + failures = [APIBadGateway(), APIConnectionError()] + sleeps = [] + + def flaky_analyze(purls, token): + if failures: + raise failures.pop(0) + return {"pkg:npm/socket@1.16.0": {"score": {}}} + + result, error = check_core_tools.score_purls_with_retry( + ["pkg:npm/socket@1.16.0"], "token", analyze=flaky_analyze, sleep=sleeps.append + ) + + assert result == {"pkg:npm/socket@1.16.0": {"score": {}}} + assert error is None + assert sleeps == list(check_core_tools.SCORING_RETRY_DELAYS_SEC) + + +def test_scoring_gives_up_after_the_last_transient_failure(): + from socketdev.exceptions import APITimeout + + calls = [] + + def always_times_out(purls, token): + calls.append(1) + raise APITimeout() + + result, error = check_core_tools.score_purls_with_retry( + ["p"], "token", analyze=always_times_out, sleep=lambda _: None + ) + assert result == {} + assert isinstance(error, APITimeout) + assert len(calls) == len(check_core_tools.SCORING_RETRY_DELAYS_SEC) + 1 + + +@pytest.mark.parametrize( + "error", + [ + "APIAccessDenied", + "APIInsufficientQuota", + "RuntimeError", + ], +) +def test_scoring_does_not_retry_deterministic_errors(error): + import socketdev.exceptions as sdk_errors + + exc_type = getattr(sdk_errors, error, None) or RuntimeError + calls = [] + + def fails(purls, token): + calls.append(1) + raise exc_type("nope") + + result, error = check_core_tools.score_purls_with_retry( + ["p"], "token", analyze=fails, sleep=lambda _: None + ) + assert result == {} + assert isinstance(error, exc_type) + assert len(calls) == 1 + + +def test_describe_api_error_names_messageless_sdk_errors(): + import requests + from socketdev.exceptions import APIBadGateway, APIConnectionError + + assert check_core_tools.describe_api_error(APIBadGateway()) == "APIBadGateway | HTTP 502" + + exc = _raise_from(APIConnectionError(), requests.ConnectionError("Connection reset by peer")) + assert check_core_tools.describe_api_error(exc) == ( + "APIConnectionError | caused by ConnectionError: Connection reset by peer" + ) + + +PINNED = "pkg:npm/socket@1.16.0" +LATEST = "pkg:npm/socket@1.17.0" + + +def _row(status=None): + return {"status": status, "alerts": [], "malware": [], "critical": []} + + +def test_scoring_rescores_only_pending_required_coordinates(): + pending_row = _row("pending") + calls = [] + sleeps = [] + + def analyze(purls, token): + calls.append(list(purls)) + if len(calls) == 1: + # Pending row indexed under two keys, as analyze_purls does. + return {PINNED: pending_row, "pkg:npm/socket@1.16.0#echo": pending_row, LATEST: _row()} + # The rescored row comes back under a different key than the pending one. + return {"npm/socket@1.16.0": _row()} + + result, error = check_core_tools.score_purls_with_retry( + [PINNED, LATEST], + "token", + required=frozenset({PINNED}), + analyze=analyze, + sleep=sleeps.append, + ) + + assert calls == [[PINNED, LATEST], [PINNED]] + assert error is None + assert sleeps == [check_core_tools.SCORING_RETRY_DELAYS_SEC[0]] + assert check_core_tools._match_analysis(result, PINNED)["status"] is None + assert pending_row not in result.values() + assert LATEST in result + + +def test_scoring_returns_pending_rows_after_the_last_attempt(): + calls = [] + + def analyze(purls, token): + calls.append(1) + return {PINNED: _row("pending")} + + result, error = check_core_tools.score_purls_with_retry( + [PINNED], "token", required=frozenset({PINNED}), analyze=analyze, sleep=lambda _: None + ) + + assert len(calls) == len(check_core_tools.SCORING_RETRY_DELAYS_SEC) + 1 + assert error is None + assert result[PINNED]["status"] == "pending" + + +def test_scoring_does_not_wait_on_pending_report_only_coordinates(): + calls = [] + + def analyze(purls, token): + calls.append(1) + return {PINNED: _row(), LATEST: _row("pending")} + + check_core_tools.score_purls_with_retry( + [PINNED, LATEST], + "token", + required=frozenset({PINNED}), + analyze=analyze, + sleep=lambda _: pytest.fail("should not wait"), + ) + + assert len(calls) == 1 + + +def test_build_reports_critical_pin_when_another_pin_exhausts_rescores( + monkeypatch, tmp_path, capsys +): + from socketdev.exceptions import APIBadGateway + + sdk_purl = "pkg:pypi/socketdev@3.6.3" + tools = [ + check_core_tools.Tool( + "npm", "Socket npm CLI", lambda: ["1.16.0"], lambda: None, lambda _: PINNED + ), + check_core_tools.Tool( + "sdk", "Socket SDK", lambda: ["3.6.3"], lambda: None, lambda _: sdk_purl + ), + ] + calls = [] + + def analyze(purls, token): + calls.append(purls) + if len(calls) == 1: + return {PINNED: _row("pending"), sdk_purl: {**_row(), "critical": ["test-alert"]}} + raise APIBadGateway() + + report = tmp_path / "report.json" + output = tmp_path / "github-output" + retry = partial(check_core_tools.score_purls_with_retry, analyze=analyze, sleep=lambda _: None) + monkeypatch.setattr(check_core_tools, "score_purls_with_retry", retry) + monkeypatch.setattr(check_core_tools, "build_tools", lambda: tools) + monkeypatch.setenv("SOCKET_API_TOKEN", "test-token") + monkeypatch.setattr( + sys, + "argv", + [ + "check_core_tools.py", + "--mode", + "build", + "--fail-on-malware", + "--json-out", + str(report), + "--github-output", + str(output), + ], + ) + + assert check_core_tools.main() == 1 + assert calls == [[PINNED, sdk_purl], [PINNED], [PINNED]] + stdout, stderr = capsys.readouterr() + assert "test-alert" in stdout + assert "analysis pending upstream" in stdout + assert "Socket analysis failed: APIBadGateway | HTTP 502" in stderr + analysis_report = json.loads(report.read_text()) + assert analysis_report["scoring_error"] is True + assert analysis_report["pending"] == [f"npm {PINNED}"] + assert analysis_report["findings"][1]["analyses"]["3.6.3"]["critical"] == ["test-alert"] + assert "critical=true" in output.read_text().splitlines()