diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a3c0b6..0af5d21 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,14 @@ branch or updating a branch head, whatever git or the CI environment detects. It is mutually exclusive with `--default-branch`. +### Changed + +- Full scans of branches that match an organization's tracked branch patterns + can update those branch heads, so findings from those branches can appear on + the organization Alerts page after upgrade. Untracked branches are not + eligible, pull request and merge request scans of a non-default branch don't + request it, and `--no-default-branch` opts a scan out. + ### Fixed - Automatic default-branch detection honors an explicitly scanned ref. When diff --git a/README.md b/README.md index 7e839ea..bb5ae95 100644 --- a/README.md +++ b/README.md @@ -212,6 +212,8 @@ Prebuilt workflow examples: When a job scans a different ref than the one that triggered it, such as a release tag, pass `--branch` and `--commit-sha` for that ref. [Default Branch Detection](https://github.com/SocketDev/socket-python-cli/blob/main/docs/cli-reference.md#default-branch-detection) covers when to add `--no-default-branch`. +Full scans of branches that match your organization's tracked branch patterns update those branch heads, so their findings appear on the Alerts page. See [Branch heads](https://github.com/SocketDev/socket-python-cli/blob/main/docs/cli-reference.md#branch-heads). + Minimal pattern: ```yaml diff --git a/docs/cli-reference.md b/docs/cli-reference.md index ace1aa5..1b60d98 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -747,7 +747,15 @@ Example: a GitHub Actions job that runs on `develop`, the default branch, after `GITHUB_REF` and `GITHUB_SHA` describe `develop`, so without `--branch` and `--commit-sha` the scan would be marked as the default branch with `develop`'s commit message. With them, the scan is recorded on `main` with the tag's commit message and is not marked, because `main` is not the default branch. A job that passes only `--commit-sha` gets the reachability check alone; if the tag commit is also in `develop`'s history, that scan still qualifies, so add `--no-default-branch`. -A scan on the default branch also becomes that branch's head scan. `--pending-head` is deprecated and has no effect: it is still accepted so existing pipelines keep working, but it logs a warning. Use `--default-branch` instead. +#### Branch heads + +The organization Alerts page shows each repository's branch head scans. A full scan asks to become its branch's head, and the API grants it only on the repository's default branch or a branch that matches the organization's tracked branch patterns (**Settings > Alerts > Scans**). The CLI doesn't know which branches are tracked, so it asks on every eligible run and the API decides. Full scans of untracked branches don't become heads. + +- A pull request or merge request scan of a non-default branch doesn't ask, even when no PR number is available. +- A scan marked as the default branch asks on any run, including a pull request run with an explicit `--default-branch`, as in earlier releases. +- `--no-default-branch` never asks. Use it for a scan of a tracked branch that shouldn't update that branch's head. + +`--pending-head` is deprecated and has no effect: it is still accepted so existing pipelines keep working, but it logs a warning. ## Who can ignore an alert diff --git a/socketsecurity/config.py b/socketsecurity/config.py index c33306b..245625d 100644 --- a/socketsecurity/config.py +++ b/socketsecurity/config.py @@ -504,8 +504,9 @@ def _from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig': if args.pending_head: logging.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." + "--pending-head is deprecated and has no effect. Full scans ask to become their " + "branch's head, which the API grants on the default branch and on tracked " + "branches (Settings > Alerts > Scans). Use --no-default-branch to opt out." ) # argparse only enforces the mutually exclusive group for real CLI args; diff --git a/socketsecurity/core/pull_request.py b/socketsecurity/core/pull_request.py index 1804dd6..de04e6b 100644 --- a/socketsecurity/core/pull_request.py +++ b/socketsecurity/core/pull_request.py @@ -27,6 +27,25 @@ def parse_pull_request_number(value) -> int: return parsed if parsed > 0 else 0 +def is_pull_request_environment(env: Mapping[str, str]) -> bool: + """Whether the CI environment describes a pull or merge request run. + + This holds even when no PR number is available, for example with an + explicit ``--pr-number 0``. + """ + if env.get("GITHUB_EVENT_NAME", "").lower() in ("pull_request", "pull_request_target"): + return True + if env.get("GITHUB_REF", "").startswith("refs/pull/"): + return True + if env.get("CI_MERGE_REQUEST_IID") or env.get("CI_PIPELINE_SOURCE", "").lower() == "merge_request_event": + return True + if env.get("BITBUCKET_PR_ID") or parse_pull_request_number(env.get("BUILDKITE_PULL_REQUEST")): + return True + return env.get("BUILD_REASON", "").lower() == "pullrequest" or bool( + env.get("SYSTEM_PULLREQUEST_PULLREQUESTID") + ) + + def _http_url(value: Optional[str]) -> Optional[str]: """Return ``value`` if it is an http(s) URL with a host, else ``None``. diff --git a/socketsecurity/socketcli.py b/socketsecurity/socketcli.py index 3f2bd21..b390657 100644 --- a/socketsecurity/socketcli.py +++ b/socketsecurity/socketcli.py @@ -22,6 +22,7 @@ from socketsecurity.core.logging import initialize_logging, set_debug_mode from socketsecurity.core.messages import Messages from socketsecurity.core.pull_request import ( + is_pull_request_environment, parse_pull_request_number, repository_owner, resolve_pull_request_context, @@ -263,6 +264,19 @@ def resolve_default_branch(config: CliConfig, scm, git_repo: Optional[Git]) -> b return detected and git_repo.explicit_ref_allows_default_branch() +def request_branch_head(config: CliConfig, is_default_branch: bool, pull_request_run: bool) -> bool: + """ + Whether the scan asks the API to make it its branch's head (set_as_pending_head). + + The API promotes a scan only on the repository's default branch or a branch + matching the organization's tracked branch patterns, and ignores the request + on any other branch. + """ + if config.no_default_branch: + return False + return is_default_branch or not pull_request_run + + def build_socket_sdk(config: CliConfig) -> socketdev: cli_user_agent_string = f"{USER_AGENT_NAME}/{config.version}" return socketdev( @@ -719,6 +733,12 @@ def main_code(config: Optional[CliConfig] = None): ) is_default_branch = resolve_default_branch(config, scm, git_repo if is_repo else None) + scm_event_type = scm.check_event_type() if scm is not None else None + pull_request_run = bool( + pr_number + or scm_event_type in ("diff", "comment") + or is_pull_request_environment(os.environ) + ) params = FullScanParams( org_slug=org_slug, @@ -731,7 +751,7 @@ def main_code(config: Optional[CliConfig] = None): pull_request=pr_number, committers=config.committers, make_default_branch=is_default_branch, - set_as_pending_head=is_default_branch, + set_as_pending_head=request_branch_head(config, is_default_branch, pull_request_run), tmp=False, scan_type='socket_tier1' if config.reach else 'socket', workspace=config.workspace or None, @@ -764,7 +784,6 @@ def _is_unprocessed(c): return False return True - 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"): log.info( "No supported manifest triggered a comparison. " diff --git a/tests/core/test_default_branch_flags.py b/tests/core/test_default_branch_flags.py index 19852f7..b404c97 100644 --- a/tests/core/test_default_branch_flags.py +++ b/tests/core/test_default_branch_flags.py @@ -90,7 +90,8 @@ def test_scm_detection_honors_an_explicit_ref_off_the_default_branch( assert github_dispatch_on_develop(flags) == 0 - assert _flags(_scan_params(cli_runtime)) == (False, False) + # Not the default branch, but still a branch run that can update a tracked branch head. + assert _flags(_scan_params(cli_runtime)) == (False, True) def test_scm_detection_honors_an_explicit_commit_when_the_ci_commit_is_not_cloned( @@ -100,7 +101,7 @@ def test_scm_detection_honors_an_explicit_commit_when_the_ci_commit_is_not_clone assert github_dispatch_on_develop(["--commit-sha", release_tag_checkout.release_sha]) == 0 - assert _flags(_scan_params(cli_runtime)) == (False, False) + assert _flags(_scan_params(cli_runtime)) == (False, True) def test_scm_detection_still_marks_the_default_branch_run( diff --git a/tests/core/test_pending_head_params.py b/tests/core/test_pending_head_params.py new file mode 100644 index 0000000..e8e15d8 --- /dev/null +++ b/tests/core/test_pending_head_params.py @@ -0,0 +1,113 @@ +"""Which full scans ask the API to become their branch's head scan.""" + +import pytest + +from socketsecurity.core import Core +from socketsecurity.core.scm.github import Github +from tests.core.test_strict_blocking_no_manifest_change import cli_runtime # noqa: F401 + +PULL_REQUEST_ENVIRONMENT = ( + "GITHUB_EVENT_NAME", + "GITHUB_EVENT_PATH", + "GITHUB_REF", + "PR_NUMBER", + "EVENT_ACTION", + "CI_MERGE_REQUEST_IID", + "CI_PIPELINE_SOURCE", + "BITBUCKET_PR_ID", + "BUILDKITE_PULL_REQUEST", + "BUILD_REASON", + "SYSTEM_PULLREQUEST_PULLREQUESTID", +) + + +@pytest.fixture(autouse=True) +def branch_push_environment(monkeypatch): + # The suite itself runs on pull_request events in CI. + for name in PULL_REQUEST_ENVIRONMENT: + monkeypatch.delenv(name, raising=False) + + +def _scan_params(runtime): + runtime.full_scan.assert_called_once() + return runtime.full_scan.call_args.args[1] + + +def test_branch_scan_asks_to_be_the_branch_head(cli_runtime): # noqa: F811 + assert cli_runtime.run(["--branch", "release/1.0"]) == 0 + + params = _scan_params(cli_runtime) + assert params.branch == "release/1.0" + assert params.set_as_pending_head is True + assert params.make_default_branch is False + + +def test_default_branch_scan_is_the_head_and_the_default_branch(cli_runtime): # noqa: F811 + cli_runtime.git_repo.is_default_branch = True + + assert cli_runtime.run() == 0 + + params = _scan_params(cli_runtime) + assert params.set_as_pending_head is True + assert params.make_default_branch is True + + +def test_pull_request_scan_of_a_non_default_branch_does_not_request_the_head(cli_runtime): # noqa: F811 + assert cli_runtime.run(["--pr-number", "42"]) == 0 + + params = _scan_params(cli_runtime) + assert params.set_as_pending_head is False + assert params.make_default_branch is False + + +def test_pull_request_event_without_a_pr_number_does_not_request_the_head( + cli_runtime, monkeypatch # noqa: F811 +): + monkeypatch.setenv("GITHUB_EVENT_NAME", "pull_request") + monkeypatch.setenv("GITHUB_REF", "refs/pull/7/merge") + + assert cli_runtime.run(["--pr-number", "0"]) == 0 + + params = _scan_params(cli_runtime) + assert params.pull_request == 0 + assert params.set_as_pending_head is False + + +def test_scm_comparison_without_a_pr_number_does_not_request_the_head( + cli_runtime, monkeypatch, mocker # noqa: F811 +): + monkeypatch.setenv("GITHUB_EVENT_NAME", "pull_request") + monkeypatch.setenv("EVENT_ACTION", "synchronize") + monkeypatch.setenv("GITHUB_REPOSITORY", "example/widgets") + monkeypatch.setenv("GH_API_TOKEN", "test") + mocker.patch.object(Github, "get_comments_for_pr", return_value={}) + mocker.patch.object(Github, "add_socket_comments") + mocker.patch.object(Github, "set_commit_status", create=True) + # A manifest change keeps the run on the SCM comparison path. + monkeypatch.setattr(Core, "has_manifest_files", lambda self, files: True) + + assert cli_runtime.run(["--scm", "github", "--pr-number", "0"]) == 0 + + cli_runtime.full_scan.assert_not_called() + cli_runtime.compare.assert_called_once() + assert cli_runtime.compare.call_args.args[1].set_as_pending_head is False + + +def test_explicit_default_branch_on_a_pull_request_still_requests_the_head(cli_runtime): # noqa: F811 + # Unchanged from earlier releases: --default-branch marks the scan on any run. + assert cli_runtime.run(["--pr-number", "42", "--default-branch"]) == 0 + + params = _scan_params(cli_runtime) + assert params.set_as_pending_head is True + assert params.make_default_branch is True + + +@pytest.mark.parametrize("detected_default", [True, False], ids=["default-branch", "tracked-branch"]) +def test_no_default_branch_does_not_request_the_head(cli_runtime, detected_default): # noqa: F811 + cli_runtime.git_repo.is_default_branch = detected_default + + assert cli_runtime.run(["--branch", "release/1.0", "--no-default-branch"]) == 0 + + params = _scan_params(cli_runtime) + assert params.set_as_pending_head is False + assert params.make_default_branch is False diff --git a/tests/unit/test_pull_request_context.py b/tests/unit/test_pull_request_context.py index b1a6dd8..9c68561 100644 --- a/tests/unit/test_pull_request_context.py +++ b/tests/unit/test_pull_request_context.py @@ -1,6 +1,7 @@ import pytest from socketsecurity.core.pull_request import ( + is_pull_request_environment, parse_pull_request_number, repository_owner, resolve_pull_request_context, @@ -334,3 +335,35 @@ def test_resolve_repository_url(scm, env, remote_url, expected): ) def test_repository_owner(url, owner): assert repository_owner(url) == owner + + +@pytest.mark.parametrize( + "env", + [ + {"GITHUB_EVENT_NAME": "pull_request"}, + {"GITHUB_EVENT_NAME": "pull_request_target"}, + {"GITHUB_REF": "refs/pull/7/merge"}, + {"CI_MERGE_REQUEST_IID": "3"}, + {"CI_PIPELINE_SOURCE": "merge_request_event"}, + {"BITBUCKET_PR_ID": "12"}, + {"BUILDKITE_PULL_REQUEST": "42"}, + {"BUILD_REASON": "PullRequest"}, + {"SYSTEM_PULLREQUEST_PULLREQUESTID": "9"}, + ], +) +def test_pull_request_environments_are_detected_without_a_number(env): + assert is_pull_request_environment(env) is True + + +@pytest.mark.parametrize( + "env", + [ + {}, + {"GITHUB_EVENT_NAME": "push", "GITHUB_REF": "refs/heads/release/1.0"}, + {"CI_PIPELINE_SOURCE": "push"}, + {"BUILDKITE_PULL_REQUEST": "false"}, + {"BUILD_REASON": "IndividualCI"}, + ], +) +def test_branch_environments_are_not_pull_requests(env): + assert is_pull_request_environment(env) is False