Skip to content

Commit 0bcb47f

Browse files
committed
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. Bump version to 2.15.8 (2.15.7 is taken by #477).
1 parent 623d909 commit 0bcb47f

11 files changed

Lines changed: 235 additions & 12 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,22 @@
11
# Changelog
22

3+
## 2.15.8
4+
5+
### Added
6+
7+
- `--no-default-branch` keeps a scan from becoming the repository's default
8+
branch or its head scan, whatever the git checkout or CI environment says.
9+
10+
### Fixed
11+
12+
- When `--branch` names a branch other than the repository's default branch, or
13+
`--commit-sha` names a commit that isn't on it, the scan is no longer marked
14+
as the default branch because of the CI variables. A workflow that checks out
15+
another ref, such as a `workflow_run` job that scans a release tag, no longer
16+
changes the repository's default branch.
17+
- With `--commit-sha`, the commit message and committer fallback come from that
18+
commit when it is in the checkout, not from the commit the CI variables name.
19+
320
## 2.15.6
421

522
### Changed: bump pinned Coana CLI to 15.15.8

‎docs/cli-reference.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ socketcli [-h] [--api-token API_TOKEN] [--repo REPO] [--workspace WORKSPACE] [--
212212
[--base-scan-id BASE_SCAN_ID | --base-commit-sha BASE_COMMIT_SHA]
213213
[--target-path TARGET_PATH] [--sbom-file SBOM_FILE] [--license-file-name LICENSE_FILE_NAME] [--save-submitted-files-list SAVE_SUBMITTED_FILES_LIST]
214214
[--save-manifest-tar SAVE_MANIFEST_TAR] [--files FILES] [--sub-path SUB_PATH] [--workspace-name WORKSPACE_NAME]
215-
[--excluded-ecosystems EXCLUDED_ECOSYSTEMS] [--exclude-paths EXCLUDE_PATHS] [--include-dirs INCLUDE_DIRS] [--default-branch] [--generate-license] [--enable-debug]
215+
[--excluded-ecosystems EXCLUDED_ECOSYSTEMS] [--exclude-paths EXCLUDE_PATHS] [--include-dirs INCLUDE_DIRS] [--default-branch | --no-default-branch] [--generate-license] [--enable-debug]
216216
[--enable-json] [--enable-sarif] [--sarif-file <path>] [--sarif-scope {diff,full}] [--sarif-grouping {instance,alert}] [--sarif-reachability {all,reachable,potentially,reachable-or-potentially}] [--enable-gitlab-security] [--gitlab-security-file <path>]
217217
[--disable-overview] [--exclude-license-details] [--allow-unverified] [--disable-security-issue]
218218
[--ignore-commit-files] [--disable-blocking] [--disable-ignore] [--enable-diff] [--scm SCM] [--timeout TIMEOUT] [--include-module-folders]
@@ -324,6 +324,7 @@ docs.socket.dev use `SOCKET_SECURITY_API_KEY`. Either works. If both are set,
324324
| Parameter | Required | Default | Description |
325325
|:-------------------------|:---------|:--------|:------------------------------------------------------------------------------------------------------|
326326
| `--default-branch` | False | *auto* | Make this branch the default branch (auto-detected from git and CI environment when not specified) |
327+
| `--no-default-branch` | False | False | Never make this scan the default branch or its head scan, whatever git or the CI environment says. Mutually exclusive with `--default-branch` |
327328
| `--include-module-folders` | False | False | Includes supported manifests found under `node_modules`, `bower_components`, and `jspm_packages` in manifest discovery. Equivalent to `--include-dirs node_modules,bower_components,jspm_packages`. Other discovery exclusions still apply. For an inventory of installed packages, see [Packages installed outside the lockfile](troubleshooting.md#packages-installed-outside-the-lockfile). |
328329

329330
#### Output Configuration
@@ -721,11 +722,13 @@ The CLI now automatically detects repository information from your git environme
721722
722723
The CLI uses intelligent default branch detection with the following priority:
723724
724-
1. **Explicit `--default-branch` flag**: Takes highest priority when specified
725+
1. **Explicit `--no-default-branch` or `--default-branch` flag**: Takes highest priority when specified
725726
2. **CI environment detection**: Uses CI platform variables (GitHub Actions, GitLab CI, and Bitbucket Pipelines)
726727
3. **Git repository analysis**: Compares current branch with repository's default branch
727728
4. **Fallback**: Defaults to `false` if none of the above methods succeed
728729

730+
When `--branch` or `--commit-sha` names a different ref than the CI variables, git repository analysis also checks the ref you passed: the scan is not treated as the default branch unless that branch is the default branch and that commit is on it. These flags never turn detection on; use `--default-branch` for that. With `--commit-sha`, the commit message and committer come from that commit when it is in the checkout.
731+
729732
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.
730733
731734
## Who can ignore an alert

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ build-backend = "hatchling.build"
66

77
[project]
88
name = "socketsecurity"
9-
version = "2.15.6"
9+
version = "2.15.8"
1010
requires-python = ">= 3.11"
1111
license = {"file" = "LICENSE"}
1212
dependencies = [

‎socketsecurity/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
__author__ = 'socket.dev'
2-
__version__ = '2.15.6'
2+
__version__ = '2.15.8'
33
USER_AGENT_NAME = 'socket-python-cli'
44
USER_AGENT = f'{USER_AGENT_NAME}/{__version__}'

‎socketsecurity/config.py‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,7 @@ class CliConfig:
167167
pr_number_explicit: bool = False
168168
commit_message: Optional[str] = None
169169
default_branch: bool = False
170+
no_default_branch: bool = False
170171
target_path: str = "./"
171172
scm: str = "api"
172173
sbom_file: Optional[str] = None
@@ -345,6 +346,7 @@ def _from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig':
345346
'pr_number_explicit': pr_number_explicit,
346347
'commit_message': commit_message,
347348
'default_branch': args.default_branch,
349+
'no_default_branch': args.no_default_branch,
348350
'target_path': os.path.expanduser(args.target_path),
349351
'scm': args.scm,
350352
'sbom_file': args.sbom_file,
@@ -510,6 +512,8 @@ def _from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig':
510512
# this also catches both values arriving via a --config file.
511513
if args.base_scan_id and args.base_commit_sha:
512514
_usage_error("--base-scan-id and --base-commit-sha are mutually exclusive")
515+
if args.default_branch and args.no_default_branch:
516+
_usage_error("--default-branch and --no-default-branch are mutually exclusive")
513517

514518
if args.sarif_scope == "full" and not args.reach:
515519
_usage_error("--sarif-scope full requires --reach to be specified")
@@ -785,18 +789,26 @@ def create_argument_parser() -> argparse.ArgumentParser:
785789

786790
# Branch and Scan Configuration
787791
config_group = parser.add_argument_group('Branch and Scan Configuration')
788-
config_group.add_argument(
792+
default_branch_group = config_group.add_mutually_exclusive_group()
793+
default_branch_group.add_argument(
789794
"--default-branch",
790795
dest="default_branch",
791796
action="store_true",
792797
help="Make this branch the default branch"
793798
)
794-
config_group.add_argument(
799+
default_branch_group.add_argument(
795800
"--default_branch",
796801
dest="default_branch",
797802
action="store_true",
798803
help=argparse.SUPPRESS
799804
)
805+
default_branch_group.add_argument(
806+
"--no-default-branch",
807+
dest="no_default_branch",
808+
action="store_true",
809+
help="Never make this scan the default branch or its head scan, whatever the git "
810+
"checkout or CI environment says. Mutually exclusive with --default-branch."
811+
)
800812
# Deprecated no-op, still accepted so existing pipelines don't fail to parse.
801813
config_group.add_argument(
802814
"--pending-head",

‎socketsecurity/core/git_interface.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -507,6 +507,44 @@ def _is_commit_and_branch_default(self) -> bool:
507507
log.debug(f"Error determining if commit and branch are default: {error}")
508508
return False
509509

510+
def apply_explicit_ref(self, branch: str | None, commit_sha: str | None) -> None:
511+
"""
512+
Apply the --branch and --commit-sha the caller passed, which can name a
513+
different ref than the CI variables describe (a workflow_run job that
514+
checks out a release tag, for example).
515+
516+
Commit details come from the named commit when the checkout has it.
517+
Default-branch detection can only be turned off here: the scan is not
518+
treated as the default branch unless the named branch is the default
519+
branch and the named commit is on it. Changed-file detection is left as is.
520+
"""
521+
if commit_sha and not self.commit.hexsha.startswith(commit_sha.lower()):
522+
try:
523+
commit = self.repo.commit(
524+
self.repo.git.rev_parse("--verify", f"{commit_sha}^{{commit}}")
525+
)
526+
except Exception as error:
527+
log.debug(f"--commit-sha {commit_sha} is not in the local checkout: {error}")
528+
if self.is_default_branch:
529+
log.info(
530+
f"--commit-sha {commit_sha} is not in the local checkout, so the scan "
531+
"is not treated as the default branch. Pass --default-branch to mark it."
532+
)
533+
self.is_default_branch = False
534+
else:
535+
self.commit = commit
536+
self.author = commit.author
537+
self.commit_sha = commit.binsha
538+
self.commit_message = commit.message
539+
self.committer = commit.committer
540+
if self.is_default_branch and not self.is_commit_on_default_branch():
541+
log.debug(f"--commit-sha {commit_sha} is not on the default branch")
542+
self.is_default_branch = False
543+
544+
if branch and self.is_default_branch and branch != self.get_default_branch_name():
545+
log.debug(f"--branch {branch} is not the default branch {self.get_default_branch_name()}")
546+
self.is_default_branch = False
547+
510548
@property
511549
def commit_str(self) -> str:
512550
"""Return commit SHA as a string"""

‎socketsecurity/socketcli.py‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,7 @@ def apply_git_context(config: CliConfig) -> Tuple[bool, Optional[Git]]:
228228
except NoSuchPathError:
229229
raise Exception(f"Unable to find path {config.target_path}")
230230

231+
git_repo.apply_explicit_ref(config.branch, config.commit_sha)
231232
if not config.repo:
232233
config.repo = git_repo.repo_name
233234
if not config.commit_sha:
@@ -704,11 +705,14 @@ def main_code(config: Optional[CliConfig] = None):
704705

705706
# Determine if this should be treated as default branch
706707
# Priority order:
707-
# 1. If --default-branch flag is explicitly set to True, use that
708-
# 2. If SCM detected it's the default branch, use that
709-
# 3. If it's a git repo, use git_repo.is_default_branch
710-
# 4. Otherwise, default to False
711-
if config.default_branch:
708+
# 1. If --no-default-branch is set, it is not
709+
# 2. If --default-branch flag is explicitly set to True, use that
710+
# 3. If SCM detected it's the default branch, use that
711+
# 4. If it's a git repo, use git_repo.is_default_branch
712+
# 5. Otherwise, default to False
713+
if config.no_default_branch:
714+
is_default_branch = False
715+
elif config.default_branch:
712716
is_default_branch = True
713717
elif scm is not None and hasattr(scm.config, 'is_default_branch') and scm.config.is_default_branch:
714718
is_default_branch = True
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""Which default-branch and head-scan parameters a full scan is created with."""
2+
3+
import pytest
4+
5+
from tests.core.test_strict_blocking_no_manifest_change import cli_runtime # noqa: F401
6+
7+
8+
def _scan_params(runtime):
9+
runtime.full_scan.assert_called_once()
10+
return runtime.full_scan.call_args.args[1]
11+
12+
13+
def test_detected_default_branch_makes_the_scan_the_head(cli_runtime): # noqa: F811
14+
cli_runtime.git_repo.is_default_branch = True
15+
16+
assert cli_runtime.run() == 0
17+
18+
params = _scan_params(cli_runtime)
19+
assert params.make_default_branch is True
20+
assert params.set_as_pending_head is True
21+
22+
23+
@pytest.mark.parametrize("ci_says_default", [True, False])
24+
def test_no_default_branch_wins_over_detection(cli_runtime, ci_says_default): # noqa: F811
25+
cli_runtime.git_repo.is_default_branch = ci_says_default
26+
27+
assert cli_runtime.run(["--no-default-branch"]) == 0
28+
29+
params = _scan_params(cli_runtime)
30+
assert params.make_default_branch is False
31+
assert params.set_as_pending_head is False

‎tests/unit/test_config.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,38 @@ def test_help_hides_pending_head_and_shows_repo_slug(self, capsys):
196196
assert "--repo <repo>" in help_text
197197

198198

199+
class TestDefaultBranchFlags:
200+
"""--no-default-branch is the explicit off switch for --default-branch"""
201+
202+
BASE_ARGS = ["--api-token", "test-token", "--repo", "test-repo"]
203+
204+
def test_defaults_are_off(self):
205+
config = CliConfig.from_args(self.BASE_ARGS)
206+
assert config.default_branch is False
207+
assert config.no_default_branch is False
208+
209+
def test_no_default_branch_parses(self):
210+
config = CliConfig.from_args(self.BASE_ARGS + ["--no-default-branch"])
211+
assert config.no_default_branch is True
212+
assert config.default_branch is False
213+
214+
@pytest.mark.parametrize("flag", ["--default-branch", "--default_branch"])
215+
def test_flags_are_mutually_exclusive(self, flag):
216+
with pytest.raises(SystemExit) as exc_info:
217+
CliConfig.from_args(self.BASE_ARGS + [flag, "--no-default-branch"])
218+
assert exc_info.value.code == 2
219+
220+
def test_config_file_values_are_mutually_exclusive(self, tmp_path):
221+
config_path = tmp_path / "socketcli.toml"
222+
config_path.write_text(
223+
"[socketcli]\ndefault_branch = true\nno_default_branch = true\n",
224+
encoding="utf-8",
225+
)
226+
with pytest.raises(SystemExit) as exc_info:
227+
CliConfig.from_args(self.BASE_ARGS + ["--config", str(config_path)])
228+
assert exc_info.value.code == 2
229+
230+
199231
class TestBaseScanFlags:
200232
"""Tests for the --base-scan-id / --base-commit-sha diff baseline overrides."""
201233

‎tests/unit/test_git_interface.py‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -529,3 +529,89 @@ def test_windows_timeout_kills_the_whole_process_tree(monkeypatch, mocker):
529529

530530
assert run.call_args.args[0] == ["taskkill", "/F", "/T", "/PID", "4321"]
531531
process.wait.assert_called_once()
532+
533+
534+
@pytest.fixture
535+
def release_tag_checkout(tmp_path):
536+
"""A repo whose default branch is develop, checked out at a release commit on main."""
537+
source = tmp_path / "source"
538+
source.mkdir()
539+
_git(source, "init", "-b", "develop")
540+
_git(source, "config", "user.name", "Socket Test")
541+
_git(source, "config", "user.email", "socket@example.com")
542+
(source / "package.json").write_text("{}\n", encoding="utf-8")
543+
_git(source, "add", "package.json")
544+
_git(source, "commit", "-m", "base")
545+
_git(source, "checkout", "-b", "main")
546+
(source / "package.json").write_text('{"version": "1.0.0"}\n', encoding="utf-8")
547+
_git(source, "commit", "-am", "release 1.0", "--author", "Release Bot <release@example.com>")
548+
_git(source, "tag", "v1.0")
549+
_git(source, "checkout", "develop")
550+
(source / "README.md").write_text("dev\n", encoding="utf-8")
551+
_git(source, "add", "README.md")
552+
_git(source, "commit", "-m", "dev work")
553+
checkout = tmp_path / "checkout"
554+
_git(tmp_path, "clone", str(source), str(checkout))
555+
_git(checkout, "checkout", "v1.0")
556+
return SimpleNamespace(
557+
path=checkout,
558+
develop_sha=_git(source, "rev-parse", "develop"),
559+
release_sha=_git(source, "rev-parse", "v1.0"),
560+
)
561+
562+
563+
@pytest.fixture
564+
def workflow_run_on_develop(release_tag_checkout, monkeypatch, mocker):
565+
"""GITHUB_REF and GITHUB_SHA describe develop while the checkout is the release tag."""
566+
monkeypatch.setenv("GITHUB_REF", "refs/heads/develop")
567+
monkeypatch.setenv("GITHUB_SHA", release_tag_checkout.develop_sha)
568+
mocker.patch.object(Git, "ensure_safe_directory")
569+
repository = Git(str(release_tag_checkout.path))
570+
assert repository.is_default_branch is True
571+
return repository
572+
573+
574+
def test_explicit_branch_that_is_not_the_default_branch_is_not_default(workflow_run_on_develop):
575+
workflow_run_on_develop.apply_explicit_ref("main", None)
576+
577+
assert workflow_run_on_develop.is_default_branch is False
578+
579+
580+
def test_explicit_commit_off_the_default_branch_is_not_default_and_supplies_details(
581+
release_tag_checkout, workflow_run_on_develop
582+
):
583+
workflow_run_on_develop.apply_explicit_ref(None, release_tag_checkout.release_sha)
584+
585+
assert workflow_run_on_develop.is_default_branch is False
586+
assert workflow_run_on_develop.commit_str == release_tag_checkout.release_sha
587+
assert workflow_run_on_develop.commit_message.strip() == "release 1.0"
588+
assert workflow_run_on_develop.get_formatted_committer() == "release@example.com"
589+
590+
591+
def test_explicit_ref_naming_the_default_branch_keeps_detection(
592+
release_tag_checkout, workflow_run_on_develop
593+
):
594+
workflow_run_on_develop.apply_explicit_ref("develop", release_tag_checkout.develop_sha[:12])
595+
596+
assert workflow_run_on_develop.is_default_branch is True
597+
assert workflow_run_on_develop.commit_message.strip() == "dev work"
598+
599+
600+
def test_explicit_commit_missing_from_the_checkout_is_not_default(workflow_run_on_develop):
601+
workflow_run_on_develop.apply_explicit_ref(None, "0" * 40)
602+
603+
assert workflow_run_on_develop.is_default_branch is False
604+
assert workflow_run_on_develop.commit_message.strip() == "dev work"
605+
606+
607+
def test_explicit_ref_never_turns_default_branch_detection_on(
608+
release_tag_checkout, monkeypatch, mocker
609+
):
610+
monkeypatch.setenv("GITHUB_REF", "refs/tags/v1.0")
611+
monkeypatch.setenv("GITHUB_SHA", release_tag_checkout.release_sha)
612+
mocker.patch.object(Git, "ensure_safe_directory")
613+
repository = Git(str(release_tag_checkout.path))
614+
615+
repository.apply_explicit_ref("develop", release_tag_checkout.develop_sha)
616+
617+
assert repository.is_default_branch is False

0 commit comments

Comments
 (0)