Skip to content

Commit 8cae773

Browse files
committed
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.
1 parent b139733 commit 8cae773

9 files changed

Lines changed: 251 additions & 77 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,19 @@
44

55
### Added
66

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.
7+
- `--no-default-branch` prevents the scan from changing the repository's default
8+
branch or updating a branch head, whatever git or the CI environment detects.
9+
It is mutually exclusive with `--default-branch`.
910

1011
### Fixed
1112

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.
13+
- Automatic default-branch detection honors an explicitly scanned ref. When
14+
`--branch` or `--commit-sha` names a different ref than the CI environment,
15+
the scan is marked as the default branch only if that branch is the default
16+
branch and that commit is on it. This applies to git detection and to the
17+
`DEFAULT_BRANCH` variable with `--scm github`. With `--commit-sha`, the commit
18+
message and committer fallback come from that commit when the checkout has it;
19+
CI actor values still take precedence for the committer.
1920

2021
## 2.15.7
2122

‎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: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -324,7 +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` |
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) |
328328
| `--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). |
329329
330330
#### Output Configuration
@@ -720,14 +720,32 @@ The CLI now automatically detects repository information from your git environme
720720
> 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`.
721721
### Default Branch Detection
722722

723-
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.
724724
725-
1. **Explicit `--no-default-branch` or `--default-branch` flag**: Takes highest priority when specified
726-
2. **CI environment detection**: Uses CI platform variables (GitHub Actions, GitLab CI, and Bitbucket Pipelines)
727-
3. **Git repository analysis**: Compares current branch with repository's default branch
728-
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.
729726
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.
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. These flags never turn detection on.
730+
731+
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.
732+
733+
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.
734+
735+
Example: a GitHub Actions job that runs on `develop`, the default branch, after a release and scans the release tag on `main`:
736+
737+
```yaml
738+
- uses: actions/checkout@v4
739+
with:
740+
ref: v1.2.0
741+
fetch-depth: 0
742+
- name: Scan the release tag
743+
run: socketcli --target-path . --branch main --commit-sha "$(git rev-parse HEAD)"
744+
env:
745+
SOCKET_SECURITY_API_TOKEN: ${{ secrets.SOCKET_SECURITY_API_TOKEN }}
746+
```
747+
748+
`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`.
731749

732750
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.
733751

‎socketsecurity/config.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -806,8 +806,9 @@ def create_argument_parser() -> argparse.ArgumentParser:
806806
"--no-default-branch",
807807
dest="no_default_branch",
808808
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."
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."
811812
)
812813
# Deprecated no-op, still accepted so existing pipelines don't fail to parse.
813814
config_group.add_argument(

‎socketsecurity/core/git_interface.py‎

Lines changed: 46 additions & 27 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
@@ -509,41 +512,57 @@ def _is_commit_and_branch_default(self) -> bool:
509512

510513
def apply_explicit_ref(self, branch: str | None, commit_sha: str | None) -> None:
511514
"""
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.
515+
Record a --branch or --commit-sha that names a different ref than the CI
516+
variables describe (a workflow_run job that checks out a release tag, for
517+
example). When the checkout has the named commit, it supplies the commit
518+
message, author and committer. Changed-file detection is left as is.
520519
"""
520+
self._explicit_branch = branch if branch and branch != self.branch else None
521+
self._explicit_commit_sha = None
522+
self._explicit_commit_found = False
521523
if commit_sha and not self.commit.hexsha.startswith(commit_sha.lower()):
524+
self._explicit_commit_sha = commit_sha
522525
try:
523526
commit = self.repo.commit(
524527
self.repo.git.rev_parse("--verify", f"{commit_sha}^{{commit}}")
525528
)
526529
except Exception as error:
527530
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
531+
return
532+
self._explicit_commit_found = True
533+
self.commit = commit
534+
self.author = commit.author
535+
self.commit_sha = commit.binsha
536+
self.commit_message = commit.message
537+
self.committer = commit.committer
538+
539+
def explicit_ref_allows_default_branch(self) -> bool:
540+
"""
541+
Whether the ref recorded by apply_explicit_ref can be the default branch:
542+
the named branch must be the default branch and the named commit must be
543+
in the checkout and on the default branch.
544+
"""
545+
commit_sha = self._explicit_commit_sha
546+
if commit_sha and not self._explicit_commit_found:
547+
log.info(
548+
f"--commit-sha {commit_sha} is not in the local checkout, so the scan "
549+
"is not treated as the default branch. Pass --default-branch to mark it."
550+
)
551+
return False
552+
if commit_sha and not self.is_commit_on_default_branch():
553+
log.info(
554+
f"--commit-sha {commit_sha} is not on the default branch, so the scan "
555+
"is not treated as the default branch"
556+
)
557+
return False
558+
branch = self._explicit_branch
559+
if branch and branch != self.get_default_branch_name():
560+
log.info(
561+
f"--branch {branch} is not the default branch "
562+
f"{self.get_default_branch_name()}, so the scan is not treated as the default branch"
563+
)
564+
return False
565+
return True
547566

548567
@property
549568
def commit_str(self) -> str:

‎socketsecurity/socketcli.py‎

Lines changed: 21 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,26 @@ def apply_git_context(config: CliConfig) -> Tuple[bool, Optional[Git]]:
243243
return True, git_repo
244244

245245

246+
def resolve_default_branch(config: CliConfig, scm, git_repo: Optional[Git]) -> bool:
247+
"""
248+
Whether the scan should become the repository's default branch and head scan.
249+
250+
--no-default-branch and --default-branch decide on their own. Otherwise the
251+
scan qualifies when the SCM adapter or git detects the default branch, and a
252+
--branch or --commit-sha that names a different ref than CI must also be the
253+
default branch.
254+
"""
255+
if config.no_default_branch:
256+
return False
257+
if config.default_branch:
258+
return True
259+
detected = bool(scm is not None and getattr(scm.config, "is_default_branch", False))
260+
if git_repo is None:
261+
return detected
262+
detected = detected or bool(git_repo.is_default_branch)
263+
return detected and git_repo.explicit_ref_allows_default_branch()
264+
265+
246266
def build_socket_sdk(config: CliConfig) -> socketdev:
247267
cli_user_agent_string = f"{USER_AGENT_NAME}/{config.version}"
248268
return socketdev(
@@ -585,11 +605,6 @@ def main_code(config: Optional[CliConfig] = None):
585605
os.environ,
586606
remote_url=getattr(git_repo, "remote_url", None) if is_repo else None,
587607
)
588-
# Don't override config.default_branch if it was explicitly set via --default-branch flag
589-
# Only use SCM detection if --default-branch wasn't provided
590-
if scm is not None and not config.default_branch:
591-
config.default_branch = scm.config.is_default_branch
592-
593608
# Override files if only-facts-file mode is active
594609
if facts_file_to_submit:
595610
specified_files = [facts_file_to_submit]
@@ -703,23 +718,7 @@ def main_code(config: Optional[CliConfig] = None):
703718
f"number={pr_number}, url={pr_context.url or 'unavailable'}"
704719
)
705720

706-
# Determine if this should be treated as default branch
707-
# Priority order:
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:
716-
is_default_branch = True
717-
elif scm is not None and hasattr(scm.config, 'is_default_branch') and scm.config.is_default_branch:
718-
is_default_branch = True
719-
elif is_repo and git_repo.is_default_branch:
720-
is_default_branch = True
721-
else:
722-
is_default_branch = False
721+
is_default_branch = resolve_default_branch(config, scm, git_repo if is_repo else None)
723722

724723
params = FullScanParams(
725724
org_slug=org_slug,

0 commit comments

Comments
 (0)