Skip to content

Commit d71b14d

Browse files
dc-larsenlelia
andauthored
Update tracked branch heads from full scans (#479)
* Check --branch and --commit-sha before marking a scan as the default branch Default-branch detection read only the CI variables. On GitHub Actions it compared GITHUB_REF to the repository's default branch and checked that the GITHUB_SHA commit is on it; --branch and --commit-sha were never consulted. A workflow_run job triggered by develop (the default branch) that checks out a release tag on main and passes --branch main --commit-sha <tag> was detected as a default-branch scan. The full scan was created with make_default_branch=true and set_as_pending_head=true, which moved the repository's default branch to main, and with develop's commit message. Without --scm, DEFAULT_BRANCH=false did not help, and nothing could turn --default-branch detection off. When --branch or --commit-sha names a different ref than the CI variables, the scan is no longer treated as the default branch unless that branch is the default branch and that commit is on it. A commit missing from the checkout cannot be checked, so it is not treated as the default branch either. The check can only turn detection off; --default-branch still marks a scan explicitly. The commit message and the committer fallback now come from the --commit-sha commit when the checkout has it. Changed-file detection still reads the CI variables. Add --no-default-branch, which forces make_default_branch and set_as_pending_head off whatever git or the CI environment says. It is mutually exclusive with --default-branch, on the command line and in a --config file. Set the version to 2.16.0. * Clear CI committer usernames in git interface tests GitHub Actions sets GITHUB_ACTOR, which get_formatted_committer prefers over the commit's committer, so the --commit-sha committer test failed in CI. * Apply the explicit-ref check to the combined default-branch detection With --scm github, the SCM adapter's is_default_branch was copied into config.default_branch, so DEFAULT_BRANCH=true restored default-branch status after git had rejected a mismatched --branch or --commit-sha. resolve_default_branch() now makes the decision in one place: --no-default-branch and --default-branch are authoritative, and otherwise the SCM and git detection results are combined before the explicit-ref check runs. Git.apply_explicit_ref() only records the named ref and switches the commit details; explicit_ref_allows_default_branch() does the check. Adds CLI-path tests with SCM detection enabled covering both outgoing flags, the explicit overrides, and the commit message and committer fallback. Sets the release to 2.16.0 and updates the CLI reference, README and CHANGELOG. * Compare --commit-sha with the commit CI names When the clone lacks the CI commit, Git falls back to HEAD. A --commit-sha naming that checkout then matched self.commit and was not treated as an explicit ref, so the reachability check never ran and DEFAULT_BRANCH=true with --scm github could still mark a scan of another ref as the default branch. Compare with the CI SHA when there is one. * 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. * Keep incomplete branch refs from falling back to the default branch --------- Co-authored-by: lelia <2418071+lelia@users.noreply.github.com>
1 parent a326ec8 commit d71b14d

11 files changed

Lines changed: 239 additions & 8 deletions

‎CHANGELOG.md‎

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

11+
### Changed
12+
13+
- Full scans of tracked branches can update branch heads, so findings from
14+
those branches can appear on the organization Alerts page after upgrade.
15+
Use `--no-default-branch` to opt a scan out.
16+
1117
### Fixed
1218

1319
- Automatic default-branch detection checks explicit scan refs against the

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

217219
```yaml

‎docs/cli-reference.md‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -749,7 +749,16 @@ Example: a GitHub Actions job that runs on `develop`, the default branch, after
749749
750750
`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`.
751751

752-
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.
752+
#### Branch heads
753+
754+
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.
755+
756+
- A pull request or merge request scan of a non-default branch doesn't ask, even when no PR number is available.
757+
- 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.
758+
- If a Git checkout lacks the commit named by `--commit-sha`, the scan only requests a head update when `--default-branch` explicitly marks it.
759+
- `--no-default-branch` never asks. Use it for a scan of a tracked branch that shouldn't update that branch's head.
760+
761+
`--pending-head` is deprecated and has no effect: it is still accepted so existing pipelines keep working, but it logs a warning.
753762
754763
## Who can ignore an alert
755764

‎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/git_interface.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -564,14 +564,19 @@ def apply_explicit_ref(self, branch: str | None, commit_sha: str | None) -> None
564564
self.commit_message = commit.message
565565
self.committer = commit.committer
566566

567+
@property
568+
def explicit_commit_is_missing(self) -> bool:
569+
"""Whether the requested commit could not be resolved in the checkout."""
570+
return bool(self._explicit_commit_sha and not self._explicit_commit_found)
571+
567572
def explicit_ref_allows_default_branch(self) -> bool:
568573
"""
569574
Whether the ref recorded by apply_explicit_ref can be the default branch:
570575
the named branch must be the default branch and the named commit must be
571576
in the checkout and on the default branch.
572577
"""
573578
commit_sha = self._explicit_commit_sha
574-
if commit_sha and not self._explicit_commit_found:
579+
if self.explicit_commit_is_missing:
575580
log.info(
576581
f"--commit-sha {commit_sha} is not in the local checkout, so the scan "
577582
"is not treated as the default branch. Pass --default-branch to mark it."

‎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: 27 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,
@@ -265,6 +266,23 @@ def resolve_default_branch(config: CliConfig, scm, git_repo: Optional[Git]) -> b
265266
return detected and git_repo.explicit_ref_allows_default_branch()
266267

267268

269+
def request_branch_head(
270+
config: CliConfig, is_default_branch: bool, pull_request_run: bool, git_repo: Optional[Git]
271+
) -> bool:
272+
"""
273+
Whether the scan asks the API to make it its branch's head (set_as_pending_head).
274+
275+
The API promotes a scan only on the repository's default branch or a branch
276+
matching the organization's tracked branch patterns, and ignores the request
277+
on any other branch.
278+
"""
279+
if config.no_default_branch:
280+
return False
281+
if is_default_branch:
282+
return True
283+
return not pull_request_run and not (git_repo is not None and git_repo.explicit_commit_is_missing)
284+
285+
268286
def build_socket_sdk(config: CliConfig) -> socketdev:
269287
cli_user_agent_string = f"{USER_AGENT_NAME}/{config.version}"
270288
return socketdev(
@@ -721,6 +739,12 @@ def main_code(config: Optional[CliConfig] = None):
721739
)
722740

723741
is_default_branch = resolve_default_branch(config, scm, git_repo if is_repo else None)
742+
scm_event_type = scm.check_event_type() if scm is not None else None
743+
pull_request_run = bool(
744+
pr_number
745+
or scm_event_type in ("diff", "comment")
746+
or is_pull_request_environment(os.environ)
747+
)
724748

725749
params = FullScanParams(
726750
org_slug=org_slug,
@@ -733,7 +757,9 @@ def main_code(config: Optional[CliConfig] = None):
733757
pull_request=pr_number,
734758
committers=config.committers,
735759
make_default_branch=is_default_branch,
736-
set_as_pending_head=is_default_branch,
760+
set_as_pending_head=request_branch_head(
761+
config, is_default_branch, pull_request_run, git_repo
762+
),
737763
tmp=False,
738764
scan_type='socket_tier1' if config.reach else 'socket',
739765
workspace=config.workspace or None,
@@ -766,7 +792,6 @@ def _is_unprocessed(c):
766792
return False
767793
return True
768794

769-
scm_event_type = scm.check_event_type() if scm is not None else None
770795
if strict_forced_comparison and scm_event_type in (None, "diff"):
771796
log.info(
772797
"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
@@ -91,7 +91,8 @@ def test_scm_detection_honors_an_explicit_ref_off_the_default_branch(
9191

9292
assert github_dispatch_on_develop(flags) == 0
9393

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

9697

9798
def test_scm_detection_honors_an_explicit_commit_when_the_ci_commit_is_not_cloned(
@@ -101,7 +102,7 @@ def test_scm_detection_honors_an_explicit_commit_when_the_ci_commit_is_not_clone
101102

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

104-
assert _flags(_scan_params(cli_runtime)) == (False, False)
105+
assert _flags(_scan_params(cli_runtime)) == (False, True)
105106

106107

107108
def test_scm_detection_requires_explicit_ci_commit_in_checkout(
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
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+
assert cli_runtime.run(["--pr-number", "42", "--default-branch"]) == 0
98+
99+
params = _scan_params(cli_runtime)
100+
assert params.set_as_pending_head is True
101+
assert params.make_default_branch is True
102+
103+
104+
@pytest.mark.parametrize("detected_default", [True, False], ids=["default-branch", "tracked-branch"])
105+
def test_no_default_branch_does_not_request_the_head(cli_runtime, detected_default): # noqa: F811
106+
cli_runtime.git_repo.is_default_branch = detected_default
107+
108+
assert cli_runtime.run(["--branch", "release/1.0", "--no-default-branch"]) == 0
109+
110+
params = _scan_params(cli_runtime)
111+
assert params.set_as_pending_head is False
112+
assert params.make_default_branch is False
113+
114+
115+
@pytest.mark.parametrize("force_default", [False, True], ids=["automatic", "explicit"])
116+
def test_missing_explicit_commit_requires_a_default_branch_override_to_request_the_head(
117+
cli_runtime, force_default # noqa: F811
118+
):
119+
cli_runtime.git_repo.explicit_commit_is_missing = True
120+
cli_runtime.git_repo.explicit_ref_allows_default_branch = lambda: False
121+
flags = ["--branch", "release/1.0"]
122+
if force_default:
123+
flags.append("--default-branch")
124+
125+
assert cli_runtime.run(flags) == 0
126+
127+
params = _scan_params(cli_runtime)
128+
assert params.make_default_branch is force_default
129+
assert params.set_as_pending_head is force_default

‎tests/core/test_strict_blocking_no_manifest_change.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ def cli_runtime(monkeypatch):
8484
is_default_branch=False,
8585
remote_url=None,
8686
explicit_ref_allows_default_branch=lambda: True,
87+
explicit_commit_is_missing=False,
8788
)
8889
in_git_repo = {"value": True}
8990

0 commit comments

Comments
 (0)