Skip to content

Commit 29b1612

Browse files
committed
Update tracked branch heads from full scans
Full scans sent set_as_pending_head=is_default_branch, so only a default-branch scan could become a head. The API also makes a scan the head of a branch that matches the organization's tracked branch patterns (Settings > Alerts > Scans), but only when the request sets set_as_pending_head, and it ignores the flag on branches it doesn't track. Python CLI scans of a tracked branch were never that branch's head, so their findings never reached the organization Alerts page. Branch runs now send set_as_pending_head=true and let the API decide. make_default_branch is unchanged. A run counts as a pull or merge request when it has a PR number, when the SCM adapter selected the comparison flow, or when the CI environment describes a PR or MR event, so a PR run with --pr-number 0 stays out of the new path. A scan marked as the default branch, including one with an explicit --default-branch on a PR, still requests it as before, and --no-default-branch keeps it off. --pending-head stays a deprecated no-op. Its warning, the CLI reference, the README and the CHANGELOG describe the new behavior. Shares the 2.16.0 version set in #478.
1 parent 70672fa commit 29b1612

9 files changed

Lines changed: 211 additions & 7 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,14 @@
88
branch or updating a branch head, whatever git or the CI environment detects.
99
It is mutually exclusive with `--default-branch`.
1010

11+
### Changed
12+
13+
- Full scans of branches that match an organization's tracked branch patterns
14+
can update those branch heads, so findings from those branches can appear on
15+
the organization Alerts page after upgrade. Untracked branches are not
16+
eligible, pull request and merge request scans of a non-default branch don't
17+
request it, and `--no-default-branch` opts a scan out.
18+
1119
### Fixed
1220

1321
- Automatic default-branch detection honors an explicitly scanned ref. When

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,8 @@ Prebuilt workflow examples:
212212

213213
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`.
214214

215+
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).
216+
215217
Minimal pattern:
216218

217219
```yaml

‎docs/cli-reference.md‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -747,7 +747,15 @@ Example: a GitHub Actions job that runs on `develop`, the default branch, after
747747
748748
`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`.
749749

750-
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.
750+
#### Branch heads
751+
752+
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.
753+
754+
- A pull request or merge request scan of a non-default branch doesn't ask, even when no PR number is available.
755+
- 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.
756+
- `--no-default-branch` never asks. Use it for a scan of a tracked branch that shouldn't update that branch's head.
757+
758+
`--pending-head` is deprecated and has no effect: it is still accepted so existing pipelines keep working, but it logs a warning.
751759
752760
## Who can ignore an alert
753761

‎socketsecurity/config.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -504,8 +504,9 @@ def _from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig':
504504

505505
if args.pending_head:
506506
logging.warning(
507-
"--pending-head is deprecated and has no effect. A scan becomes the head scan "
508-
"when it runs on the default branch; use --default-branch to mark it as such."
507+
"--pending-head is deprecated and has no effect. Full scans ask to become their "
508+
"branch's head, which the API grants on the default branch and on tracked "
509+
"branches (Settings > Alerts > Scans). Use --no-default-branch to opt out."
509510
)
510511

511512
# argparse only enforces the mutually exclusive group for real CLI args;

‎socketsecurity/core/pull_request.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,25 @@ def parse_pull_request_number(value) -> int:
2727
return parsed if parsed > 0 else 0
2828

2929

30+
def is_pull_request_environment(env: Mapping[str, str]) -> bool:
31+
"""Whether the CI environment describes a pull or merge request run.
32+
33+
This holds even when no PR number is available, for example with an
34+
explicit ``--pr-number 0``.
35+
"""
36+
if env.get("GITHUB_EVENT_NAME", "").lower() in ("pull_request", "pull_request_target"):
37+
return True
38+
if env.get("GITHUB_REF", "").startswith("refs/pull/"):
39+
return True
40+
if env.get("CI_MERGE_REQUEST_IID") or env.get("CI_PIPELINE_SOURCE", "").lower() == "merge_request_event":
41+
return True
42+
if env.get("BITBUCKET_PR_ID") or parse_pull_request_number(env.get("BUILDKITE_PULL_REQUEST")):
43+
return True
44+
return env.get("BUILD_REASON", "").lower() == "pullrequest" or bool(
45+
env.get("SYSTEM_PULLREQUEST_PULLREQUESTID")
46+
)
47+
48+
3049
def _http_url(value: Optional[str]) -> Optional[str]:
3150
"""Return ``value`` if it is an http(s) URL with a host, else ``None``.
3251

‎socketsecurity/socketcli.py‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
from socketsecurity.core.logging import initialize_logging, set_debug_mode
2323
from socketsecurity.core.messages import Messages
2424
from socketsecurity.core.pull_request import (
25+
is_pull_request_environment,
2526
parse_pull_request_number,
2627
repository_owner,
2728
resolve_pull_request_context,
@@ -263,6 +264,19 @@ def resolve_default_branch(config: CliConfig, scm, git_repo: Optional[Git]) -> b
263264
return detected and git_repo.explicit_ref_allows_default_branch()
264265

265266

267+
def request_branch_head(config: CliConfig, is_default_branch: bool, pull_request_run: bool) -> bool:
268+
"""
269+
Whether the scan asks the API to make it its branch's head (set_as_pending_head).
270+
271+
The API promotes a scan only on the repository's default branch or a branch
272+
matching the organization's tracked branch patterns, and ignores the request
273+
on any other branch.
274+
"""
275+
if config.no_default_branch:
276+
return False
277+
return is_default_branch or not pull_request_run
278+
279+
266280
def build_socket_sdk(config: CliConfig) -> socketdev:
267281
cli_user_agent_string = f"{USER_AGENT_NAME}/{config.version}"
268282
return socketdev(
@@ -719,6 +733,12 @@ def main_code(config: Optional[CliConfig] = None):
719733
)
720734

721735
is_default_branch = resolve_default_branch(config, scm, git_repo if is_repo else None)
736+
scm_event_type = scm.check_event_type() if scm is not None else None
737+
pull_request_run = bool(
738+
pr_number
739+
or scm_event_type in ("diff", "comment")
740+
or is_pull_request_environment(os.environ)
741+
)
722742

723743
params = FullScanParams(
724744
org_slug=org_slug,
@@ -731,7 +751,7 @@ def main_code(config: Optional[CliConfig] = None):
731751
pull_request=pr_number,
732752
committers=config.committers,
733753
make_default_branch=is_default_branch,
734-
set_as_pending_head=is_default_branch,
754+
set_as_pending_head=request_branch_head(config, is_default_branch, pull_request_run),
735755
tmp=False,
736756
scan_type='socket_tier1' if config.reach else 'socket',
737757
workspace=config.workspace or None,
@@ -764,7 +784,6 @@ def _is_unprocessed(c):
764784
return False
765785
return True
766786

767-
scm_event_type = scm.check_event_type() if scm is not None else None
768787
if strict_forced_comparison and scm_event_type in (None, "diff"):
769788
log.info(
770789
"No supported manifest triggered a comparison. "

‎tests/core/test_default_branch_flags.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,8 @@ def test_scm_detection_honors_an_explicit_ref_off_the_default_branch(
9090

9191
assert github_dispatch_on_develop(flags) == 0
9292

93-
assert _flags(_scan_params(cli_runtime)) == (False, False)
93+
# Not the default branch, but still a branch run that can update a tracked branch head.
94+
assert _flags(_scan_params(cli_runtime)) == (False, True)
9495

9596

9697
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
100101

101102
assert github_dispatch_on_develop(["--commit-sha", release_tag_checkout.release_sha]) == 0
102103

103-
assert _flags(_scan_params(cli_runtime)) == (False, False)
104+
assert _flags(_scan_params(cli_runtime)) == (False, True)
104105

105106

106107
def test_scm_detection_still_marks_the_default_branch_run(
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
"""Which full scans ask the API to become their branch's head scan."""
2+
3+
import pytest
4+
5+
from socketsecurity.core import Core
6+
from socketsecurity.core.scm.github import Github
7+
from tests.core.test_strict_blocking_no_manifest_change import cli_runtime # noqa: F401
8+
9+
PULL_REQUEST_ENVIRONMENT = (
10+
"GITHUB_EVENT_NAME",
11+
"GITHUB_EVENT_PATH",
12+
"GITHUB_REF",
13+
"PR_NUMBER",
14+
"EVENT_ACTION",
15+
"CI_MERGE_REQUEST_IID",
16+
"CI_PIPELINE_SOURCE",
17+
"BITBUCKET_PR_ID",
18+
"BUILDKITE_PULL_REQUEST",
19+
"BUILD_REASON",
20+
"SYSTEM_PULLREQUEST_PULLREQUESTID",
21+
)
22+
23+
24+
@pytest.fixture(autouse=True)
25+
def branch_push_environment(monkeypatch):
26+
# The suite itself runs on pull_request events in CI.
27+
for name in PULL_REQUEST_ENVIRONMENT:
28+
monkeypatch.delenv(name, raising=False)
29+
30+
31+
def _scan_params(runtime):
32+
runtime.full_scan.assert_called_once()
33+
return runtime.full_scan.call_args.args[1]
34+
35+
36+
def test_branch_scan_asks_to_be_the_branch_head(cli_runtime): # noqa: F811
37+
assert cli_runtime.run(["--branch", "release/1.0"]) == 0
38+
39+
params = _scan_params(cli_runtime)
40+
assert params.branch == "release/1.0"
41+
assert params.set_as_pending_head is True
42+
assert params.make_default_branch is False
43+
44+
45+
def test_default_branch_scan_is_the_head_and_the_default_branch(cli_runtime): # noqa: F811
46+
cli_runtime.git_repo.is_default_branch = True
47+
48+
assert cli_runtime.run() == 0
49+
50+
params = _scan_params(cli_runtime)
51+
assert params.set_as_pending_head is True
52+
assert params.make_default_branch is True
53+
54+
55+
def test_pull_request_scan_of_a_non_default_branch_does_not_request_the_head(cli_runtime): # noqa: F811
56+
assert cli_runtime.run(["--pr-number", "42"]) == 0
57+
58+
params = _scan_params(cli_runtime)
59+
assert params.set_as_pending_head is False
60+
assert params.make_default_branch is False
61+
62+
63+
def test_pull_request_event_without_a_pr_number_does_not_request_the_head(
64+
cli_runtime, monkeypatch # noqa: F811
65+
):
66+
monkeypatch.setenv("GITHUB_EVENT_NAME", "pull_request")
67+
monkeypatch.setenv("GITHUB_REF", "refs/pull/7/merge")
68+
69+
assert cli_runtime.run(["--pr-number", "0"]) == 0
70+
71+
params = _scan_params(cli_runtime)
72+
assert params.pull_request == 0
73+
assert params.set_as_pending_head is False
74+
75+
76+
def test_scm_comparison_without_a_pr_number_does_not_request_the_head(
77+
cli_runtime, monkeypatch, mocker # noqa: F811
78+
):
79+
monkeypatch.setenv("GITHUB_EVENT_NAME", "pull_request")
80+
monkeypatch.setenv("EVENT_ACTION", "synchronize")
81+
monkeypatch.setenv("GITHUB_REPOSITORY", "example/widgets")
82+
monkeypatch.setenv("GH_API_TOKEN", "test")
83+
mocker.patch.object(Github, "get_comments_for_pr", return_value={})
84+
mocker.patch.object(Github, "add_socket_comments")
85+
mocker.patch.object(Github, "set_commit_status", create=True)
86+
# A manifest change keeps the run on the SCM comparison path.
87+
monkeypatch.setattr(Core, "has_manifest_files", lambda self, files: True)
88+
89+
assert cli_runtime.run(["--scm", "github", "--pr-number", "0"]) == 0
90+
91+
cli_runtime.full_scan.assert_not_called()
92+
cli_runtime.compare.assert_called_once()
93+
assert cli_runtime.compare.call_args.args[1].set_as_pending_head is False
94+
95+
96+
def test_explicit_default_branch_on_a_pull_request_still_requests_the_head(cli_runtime): # noqa: F811
97+
# Unchanged from earlier releases: --default-branch marks the scan on any run.
98+
assert cli_runtime.run(["--pr-number", "42", "--default-branch"]) == 0
99+
100+
params = _scan_params(cli_runtime)
101+
assert params.set_as_pending_head is True
102+
assert params.make_default_branch is True
103+
104+
105+
@pytest.mark.parametrize("detected_default", [True, False], ids=["default-branch", "tracked-branch"])
106+
def test_no_default_branch_does_not_request_the_head(cli_runtime, detected_default): # noqa: F811
107+
cli_runtime.git_repo.is_default_branch = detected_default
108+
109+
assert cli_runtime.run(["--branch", "release/1.0", "--no-default-branch"]) == 0
110+
111+
params = _scan_params(cli_runtime)
112+
assert params.set_as_pending_head is False
113+
assert params.make_default_branch is False

‎tests/unit/test_pull_request_context.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import pytest
22

33
from socketsecurity.core.pull_request import (
4+
is_pull_request_environment,
45
parse_pull_request_number,
56
repository_owner,
67
resolve_pull_request_context,
@@ -334,3 +335,35 @@ def test_resolve_repository_url(scm, env, remote_url, expected):
334335
)
335336
def test_repository_owner(url, owner):
336337
assert repository_owner(url) == owner
338+
339+
340+
@pytest.mark.parametrize(
341+
"env",
342+
[
343+
{"GITHUB_EVENT_NAME": "pull_request"},
344+
{"GITHUB_EVENT_NAME": "pull_request_target"},
345+
{"GITHUB_REF": "refs/pull/7/merge"},
346+
{"CI_MERGE_REQUEST_IID": "3"},
347+
{"CI_PIPELINE_SOURCE": "merge_request_event"},
348+
{"BITBUCKET_PR_ID": "12"},
349+
{"BUILDKITE_PULL_REQUEST": "42"},
350+
{"BUILD_REASON": "PullRequest"},
351+
{"SYSTEM_PULLREQUEST_PULLREQUESTID": "9"},
352+
],
353+
)
354+
def test_pull_request_environments_are_detected_without_a_number(env):
355+
assert is_pull_request_environment(env) is True
356+
357+
358+
@pytest.mark.parametrize(
359+
"env",
360+
[
361+
{},
362+
{"GITHUB_EVENT_NAME": "push", "GITHUB_REF": "refs/heads/release/1.0"},
363+
{"CI_PIPELINE_SOURCE": "push"},
364+
{"BUILDKITE_PULL_REQUEST": "false"},
365+
{"BUILD_REASON": "IndividualCI"},
366+
],
367+
)
368+
def test_branch_environments_are_not_pull_requests(env):
369+
assert is_pull_request_environment(env) is False

0 commit comments

Comments
 (0)