Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@
default branch or updating a branch head. It is mutually exclusive with
`--default-branch`.

### Changed

- Full scans of tracked branches can update branch heads, so findings from
those branches can appear on the organization Alerts page after upgrade.
Use `--no-default-branch` to opt a scan out.

### Fixed

- Automatic default-branch detection checks explicit scan refs against the
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 tracked branches can update branch heads and show their findings 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
Expand Down
11 changes: 10 additions & 1 deletion docs/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -747,7 +747,16 @@ 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.
- If a Git checkout lacks the commit named by `--commit-sha`, the scan only requests a head update when `--default-branch` explicitly marks it.
- `--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

Expand Down
5 changes: 3 additions & 2 deletions socketsecurity/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
7 changes: 6 additions & 1 deletion socketsecurity/core/git_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -542,14 +542,19 @@ def apply_explicit_ref(self, branch: str | None, commit_sha: str | None) -> None
self.commit_message = commit.message
self.committer = commit.committer

@property
def explicit_commit_is_missing(self) -> bool:
"""Whether the requested commit could not be resolved in the checkout."""
return bool(self._explicit_commit_sha and not self._explicit_commit_found)

def explicit_ref_allows_default_branch(self) -> bool:
"""
Whether the ref recorded by apply_explicit_ref can be the default branch:
the named branch must be the default branch and the named commit must be
in the checkout and on the default branch.
"""
commit_sha = self._explicit_commit_sha
if commit_sha and not self._explicit_commit_found:
if self.explicit_commit_is_missing:
log.info(
f"--commit-sha {commit_sha} is not in the local checkout, so the scan "
"is not treated as the default branch. Pass --default-branch to mark it."
Expand Down
19 changes: 19 additions & 0 deletions socketsecurity/core/pull_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -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``.

Expand Down
29 changes: 27 additions & 2 deletions socketsecurity/socketcli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -263,6 +264,23 @@ 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, git_repo: Optional[Git]
) -> 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
if is_default_branch:
return True
return not pull_request_run and not (git_repo is not None and git_repo.explicit_commit_is_missing)


def build_socket_sdk(config: CliConfig) -> socketdev:
cli_user_agent_string = f"{USER_AGENT_NAME}/{config.version}"
return socketdev(
Expand Down Expand Up @@ -719,6 +737,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,
Expand All @@ -731,7 +755,9 @@ 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, git_repo
),
tmp=False,
scan_type='socket_tier1' if config.reach else 'socket',
workspace=config.workspace or None,
Expand Down Expand Up @@ -764,7 +790,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. "
Expand Down
5 changes: 3 additions & 2 deletions tests/core/test_default_branch_flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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_requires_explicit_ci_commit_in_checkout(
Expand Down
129 changes: 129 additions & 0 deletions tests/core/test_pending_head_params.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
"""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
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


@pytest.mark.parametrize("force_default", [False, True], ids=["automatic", "explicit"])
def test_missing_explicit_commit_requires_a_default_branch_override_to_request_the_head(
cli_runtime, force_default # noqa: F811
):
cli_runtime.git_repo.explicit_commit_is_missing = True
cli_runtime.git_repo.explicit_ref_allows_default_branch = lambda: False
flags = ["--branch", "release/1.0"]
if force_default:
flags.append("--default-branch")

assert cli_runtime.run(flags) == 0

params = _scan_params(cli_runtime)
assert params.make_default_branch is force_default
assert params.set_as_pending_head is force_default
1 change: 1 addition & 0 deletions tests/core/test_strict_blocking_no_manifest_change.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ def cli_runtime(monkeypatch):
is_default_branch=False,
remote_url=None,
explicit_ref_allows_default_branch=lambda: True,
explicit_commit_is_missing=False,
)
in_git_repo = {"value": True}

Expand Down
33 changes: 33 additions & 0 deletions tests/unit/test_pull_request_context.py
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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