Skip to content

Commit a326ec8

Browse files
dc-larsenlelia
andauthored
Honor explicit scan refs in default-branch detection (#478)
* 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. * Keep incomplete branch refs from falling back to the default branch --------- Co-authored-by: lelia <2418071+lelia@users.noreply.github.com>
1 parent 2ab48d9 commit a326ec8

13 files changed

Lines changed: 542 additions & 31 deletions

‎CHANGELOG.md‎

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

3+
## 2.16.0
4+
5+
### Added
6+
7+
- Use `--no-default-branch` to prevent a scan from changing the repository's
8+
default branch or updating a branch head. It is mutually exclusive with
9+
`--default-branch`.
10+
11+
### Fixed
12+
13+
- Automatic default-branch detection checks explicit scan refs against the
14+
default branch, including qualified branch refs such as `refs/heads/main`.
15+
An explicit commit must be available in the checkout for automatic promotion.
16+
The selected commit supplies the commit message and Git committer fallback
17+
when available. CI actor settings retain precedence.
18+
319
## 2.15.10
420

521
### Added

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,8 @@ Prebuilt workflow examples:
210210
- [GitLab CI](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/gitlab-ci.yml)
211211
- [Bitbucket Pipelines](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/bitbucket-pipelines.yml)
212212

213+
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`.
214+
213215
Minimal pattern:
214216

215217
```yaml

‎docs/cli-reference.md‎

Lines changed: 29 additions & 6 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 | Prevent the scan from changing the repository's default branch or updating a branch head, whatever git or the CI environment detects. Mutually exclusive with `--default-branch`. See [Default Branch Detection](#default-branch-detection) |
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
@@ -719,12 +720,34 @@ The CLI now automatically detects repository information from your git environme
719720
> For *octopus merges* (three or more parents), Git only reports changes relative to the first parent. This can lead to incomplete or empty file lists if changes only exist relative to other parents. In these cases, differential scanning may be skipped. To ensure coverage, use `--ignore-commit-files` to compare regardless of the detected changes, or specify files explicitly with `--files`.
720721
### Default Branch Detection
721722

722-
The CLI uses intelligent default branch detection with the following priority:
723+
`--default-branch` always marks the scan as the repository's default branch. `--no-default-branch` never does, and the scan does not update a branch head. The two flags are mutually exclusive, on the command line and in a `--config` file.
723724
724-
1. **Explicit `--default-branch` flag**: Takes highest priority when specified
725-
2. **CI environment detection**: Uses CI platform variables (GitHub Actions, GitLab CI, and Bitbucket Pipelines)
726-
3. **Git repository analysis**: Compares current branch with repository's default branch
727-
4. **Fallback**: Defaults to `false` if none of the above methods succeed
725+
Without either flag, the CLI marks the scan when automatic detection finds the default branch: CI platform variables (GitHub Actions, GitLab CI, Bitbucket Pipelines and Buildkite), the `DEFAULT_BRANCH` variable with `--scm github`, or, outside CI, the local checkout. Otherwise the scan is not marked.
726+
727+
#### Scanning a different ref than the CI run
728+
729+
When `--branch` or `--commit-sha` names a different ref than the CI variables, automatic detection also checks the ref you passed. The scan is marked only when that branch is the default branch and that commit is in the checkout and reachable from the default branch. An explicit commit that is missing from the checkout disqualifies automatic detection, even when it matches the SHA reported by CI. These flags never turn detection on.
730+
731+
In a Git checkout, `--branch refs/heads/main` and `--branch refs/remotes/origin/main` are recorded as `main`. The shorthand `origin/main` also resolves to `main` when Git recognizes it as the remote-tracking branch. A branch literally named `origin/main` keeps its name.
732+
733+
The commit check is reachability, so an older commit already in the default branch's history can still qualify: for example, a release tag that was merged back into the default branch, scanned with `--commit-sha` and no `--branch`. Pass `--no-default-branch` when a scan of such a ref must not change the default branch.
734+
735+
With `--commit-sha`, that commit supplies the commit message (unless `--commit-message` is set) and the git fallback for the committer, when the checkout has it. `--committers` and CI actor values (`GITHUB_ACTOR`, `GITLAB_USER_LOGIN`, `BITBUCKET_STEP_TRIGGERER_UUID`) still take precedence over the commit's committer.
736+
737+
Example: a GitHub Actions job that runs on `develop`, the default branch, after a release and scans the release tag on `main`:
738+
739+
```yaml
740+
- uses: actions/checkout@v4
741+
with:
742+
ref: v1.2.0
743+
fetch-depth: 0
744+
- name: Scan the release tag
745+
run: socketcli --target-path . --branch main --commit-sha "$(git rev-parse HEAD)"
746+
env:
747+
SOCKET_SECURITY_API_TOKEN: ${{ secrets.SOCKET_SECURITY_API_TOKEN }}
748+
```
749+
750+
`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`.
728751

729752
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.
730753

‎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.10"
9+
version = "2.16.0"
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.10'
2+
__version__ = '2.16.0'
33
USER_AGENT_NAME = 'socket-python-cli'
44
USER_AGENT = f'{USER_AGENT_NAME}/{__version__}'

‎socketsecurity/config.py‎

Lines changed: 15 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,27 @@ 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="Prevent the scan from changing the repository's default branch or updating a "
810+
"branch head, whatever git or the CI environment detects. Mutually exclusive "
811+
"with --default-branch."
812+
)
800813
# Deprecated no-op, still accepted so existing pipelines don't fail to parse.
801814
config_group.add_argument(
802815
"--pending-head",

‎socketsecurity/core/git_interface.py‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ def __init__(self, path: str, base_commit_sha: str | None = None):
3434
self.base_commit_sha = base_commit_sha
3535
self._fetched_ref_commits = {}
3636
self._default_branch_name: str | None = None
37+
self._explicit_branch: str | None = None
38+
self._explicit_commit_sha: str | None = None
39+
self._explicit_commit_found = False
3740
self.ensure_safe_directory(path)
3841
self.repo = Repo(path)
3942
assert self.repo
@@ -54,6 +57,7 @@ def __init__(self, path: str, base_commit_sha: str | None = None):
5457
((source, sha) for source, sha in ci_commits if sha),
5558
(None, None),
5659
)
60+
self._ci_sha = ci_sha
5761

5862
if ci_sha:
5963
try:
@@ -507,6 +511,87 @@ def _is_commit_and_branch_default(self) -> bool:
507511
log.debug(f"Error determining if commit and branch are default: {error}")
508512
return False
509513

514+
def scan_branch_name(self, branch: str) -> str:
515+
"""Resolve a qualified branch ref to the branch name used by scan requests."""
516+
for prefix in ("refs/heads/", "refs/remotes/origin/"):
517+
if branch.startswith(prefix):
518+
return branch.removeprefix(prefix) or branch
519+
520+
if not branch.startswith("origin/"):
521+
return branch
522+
523+
# Shorthand can also be a literal branch name, such as origin/main.
524+
if (
525+
branch == self.branch
526+
or branch in self.repo.heads
527+
or self._resolve_ref(f"refs/remotes/origin/{branch}")
528+
):
529+
return branch
530+
531+
name = branch.removeprefix("origin/")
532+
if name == self.branch or self._resolve_ref(f"refs/remotes/{branch}"):
533+
return name
534+
return branch
535+
536+
def apply_explicit_ref(self, branch: str | None, commit_sha: str | None) -> None:
537+
"""Record explicit scan refs and use the selected commit's local metadata."""
538+
self._explicit_branch = branch if branch and branch != self.branch else None
539+
self._explicit_commit_sha = None
540+
self._explicit_commit_found = False
541+
if not commit_sha:
542+
return
543+
544+
requested_sha = commit_sha.lower()
545+
selected_sha = self.commit.hexsha
546+
ci_sha = (self._ci_sha or selected_sha).lower()
547+
# Git can fall back to HEAD when the commit named by CI is unavailable.
548+
if ci_sha.startswith(requested_sha) and selected_sha.startswith(requested_sha):
549+
return
550+
551+
self._explicit_commit_sha = commit_sha
552+
try:
553+
commit = self.repo.commit(
554+
self.repo.git.rev_parse("--verify", f"{commit_sha}^{{commit}}")
555+
)
556+
except Exception as error:
557+
log.debug(f"--commit-sha {commit_sha} is not in the local checkout: {error}")
558+
return
559+
560+
self._explicit_commit_found = True
561+
self.commit = commit
562+
self.author = commit.author
563+
self.commit_sha = commit.binsha
564+
self.commit_message = commit.message
565+
self.committer = commit.committer
566+
567+
def explicit_ref_allows_default_branch(self) -> bool:
568+
"""
569+
Whether the ref recorded by apply_explicit_ref can be the default branch:
570+
the named branch must be the default branch and the named commit must be
571+
in the checkout and on the default branch.
572+
"""
573+
commit_sha = self._explicit_commit_sha
574+
if commit_sha and not self._explicit_commit_found:
575+
log.info(
576+
f"--commit-sha {commit_sha} is not in the local checkout, so the scan "
577+
"is not treated as the default branch. Pass --default-branch to mark it."
578+
)
579+
return False
580+
if commit_sha and not self.is_commit_on_default_branch():
581+
log.info(
582+
f"--commit-sha {commit_sha} is not on the default branch, so the scan "
583+
"is not treated as the default branch"
584+
)
585+
return False
586+
branch = self._explicit_branch
587+
if branch and branch != self.get_default_branch_name():
588+
log.info(
589+
f"--branch {branch} is not the default branch "
590+
f"{self.get_default_branch_name()}, so the scan is not treated as the default branch"
591+
)
592+
return False
593+
return True
594+
510595
@property
511596
def commit_str(self) -> str:
512597
"""Return commit SHA as a string"""

‎socketsecurity/socketcli.py‎

Lines changed: 24 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,9 @@ 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+
if config.branch:
232+
config.branch = git_repo.scan_branch_name(config.branch)
233+
git_repo.apply_explicit_ref(config.branch, config.commit_sha)
231234
if not config.repo:
232235
config.repo = git_repo.repo_name
233236
if not config.commit_sha:
@@ -242,6 +245,26 @@ def apply_git_context(config: CliConfig) -> Tuple[bool, Optional[Git]]:
242245
return True, git_repo
243246

244247

248+
def resolve_default_branch(config: CliConfig, scm, git_repo: Optional[Git]) -> bool:
249+
"""
250+
Whether the scan should become the repository's default branch and head scan.
251+
252+
--no-default-branch and --default-branch decide on their own. Otherwise the
253+
scan qualifies when the SCM adapter or git detects the default branch, and a
254+
--branch or --commit-sha that names a different ref than CI must also be the
255+
default branch.
256+
"""
257+
if config.no_default_branch:
258+
return False
259+
if config.default_branch:
260+
return True
261+
detected = bool(scm is not None and getattr(scm.config, "is_default_branch", False))
262+
if git_repo is None:
263+
return detected
264+
detected = detected or bool(git_repo.is_default_branch)
265+
return detected and git_repo.explicit_ref_allows_default_branch()
266+
267+
245268
def build_socket_sdk(config: CliConfig) -> socketdev:
246269
cli_user_agent_string = f"{USER_AGENT_NAME}/{config.version}"
247270
return socketdev(
@@ -584,11 +607,6 @@ def main_code(config: Optional[CliConfig] = None):
584607
os.environ,
585608
remote_url=getattr(git_repo, "remote_url", None) if is_repo else None,
586609
)
587-
# Don't override config.default_branch if it was explicitly set via --default-branch flag
588-
# Only use SCM detection if --default-branch wasn't provided
589-
if scm is not None and not config.default_branch:
590-
config.default_branch = scm.config.is_default_branch
591-
592610
# Override files if only-facts-file mode is active
593611
if facts_file_to_submit:
594612
specified_files = [facts_file_to_submit]
@@ -702,20 +720,7 @@ def main_code(config: Optional[CliConfig] = None):
702720
f"number={pr_number}, url={pr_context.url or 'unavailable'}"
703721
)
704722

705-
# Determine if this should be treated as default branch
706-
# 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:
712-
is_default_branch = True
713-
elif scm is not None and hasattr(scm.config, 'is_default_branch') and scm.config.is_default_branch:
714-
is_default_branch = True
715-
elif is_repo and git_repo.is_default_branch:
716-
is_default_branch = True
717-
else:
718-
is_default_branch = False
723+
is_default_branch = resolve_default_branch(config, scm, git_repo if is_repo else None)
719724

720725
params = FullScanParams(
721726
org_slug=org_slug,

0 commit comments

Comments
 (0)