Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
# Changelog

## 2.16.0

### Added

- `--no-default-branch` prevents the scan from changing the repository's default
branch or updating a branch head, whatever git or the CI environment detects.
It is mutually exclusive with `--default-branch`.

### Fixed

- Automatic default-branch detection honors an explicitly scanned ref. When
`--branch` or `--commit-sha` names a different ref than the CI environment,
the scan is marked as the default branch only if that branch is the default
branch and that commit is on it. This applies to git detection and to the
`DEFAULT_BRANCH` variable with `--scm github`. With `--commit-sha`, the commit
message and committer fallback come from that commit when the checkout has it;
CI actor values still take precedence for the committer.

## 2.15.7

### Changed: bump pinned Coana CLI to 15.15.9
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,8 @@ Prebuilt workflow examples:
- [GitLab CI](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/gitlab-ci.yml)
- [Bitbucket Pipelines](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/bitbucket-pipelines.yml)

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

Minimal pattern:

```yaml
Expand Down
33 changes: 27 additions & 6 deletions docs/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ socketcli [-h] [--api-token API_TOKEN] [--repo REPO] [--workspace WORKSPACE] [--
[--base-scan-id BASE_SCAN_ID | --base-commit-sha BASE_COMMIT_SHA]
[--target-path TARGET_PATH] [--sbom-file SBOM_FILE] [--license-file-name LICENSE_FILE_NAME] [--save-submitted-files-list SAVE_SUBMITTED_FILES_LIST]
[--save-manifest-tar SAVE_MANIFEST_TAR] [--files FILES] [--sub-path SUB_PATH] [--workspace-name WORKSPACE_NAME]
[--excluded-ecosystems EXCLUDED_ECOSYSTEMS] [--exclude-paths EXCLUDE_PATHS] [--include-dirs INCLUDE_DIRS] [--default-branch] [--generate-license] [--enable-debug]
[--excluded-ecosystems EXCLUDED_ECOSYSTEMS] [--exclude-paths EXCLUDE_PATHS] [--include-dirs INCLUDE_DIRS] [--default-branch | --no-default-branch] [--generate-license] [--enable-debug]
[--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>]
[--disable-overview] [--exclude-license-details] [--allow-unverified] [--disable-security-issue]
[--ignore-commit-files] [--disable-blocking] [--disable-ignore] [--enable-diff] [--scm SCM] [--timeout TIMEOUT] [--include-module-folders]
Expand Down Expand Up @@ -324,6 +324,7 @@ docs.socket.dev use `SOCKET_SECURITY_API_KEY`. Either works. If both are set,
| Parameter | Required | Default | Description |
|:-------------------------|:---------|:--------|:------------------------------------------------------------------------------------------------------|
| `--default-branch` | False | *auto* | Make this branch the default branch (auto-detected from git and CI environment when not specified) |
| `--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) |
| `--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). |

#### Output Configuration
Expand Down Expand Up @@ -719,12 +720,32 @@ The CLI now automatically detects repository information from your git environme
> 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`.
### Default Branch Detection

The CLI uses intelligent default branch detection with the following priority:
`--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.

1. **Explicit `--default-branch` flag**: Takes highest priority when specified
2. **CI environment detection**: Uses CI platform variables (GitHub Actions, GitLab CI, and Bitbucket Pipelines)
3. **Git repository analysis**: Compares current branch with repository's default branch
4. **Fallback**: Defaults to `false` if none of the above methods succeed
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.

#### Scanning a different ref than the CI run

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.

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.

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.

Example: a GitHub Actions job that runs on `develop`, the default branch, after a release and scans the release tag on `main`:

```yaml
- uses: actions/checkout@v4
with:
ref: v1.2.0
fetch-depth: 0
- name: Scan the release tag
run: socketcli --target-path . --branch main --commit-sha "$(git rev-parse HEAD)"
env:
SOCKET_SECURITY_API_TOKEN: ${{ secrets.SOCKET_SECURITY_API_TOKEN }}
```

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

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.

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ build-backend = "hatchling.build"

[project]
name = "socketsecurity"
version = "2.15.7"
version = "2.16.0"
requires-python = ">= 3.11"
license = {"file" = "LICENSE"}
dependencies = [
Expand Down
2 changes: 1 addition & 1 deletion socketsecurity/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
__author__ = 'socket.dev'
__version__ = '2.15.7'
__version__ = '2.16.0'
USER_AGENT_NAME = 'socket-python-cli'
USER_AGENT = f'{USER_AGENT_NAME}/{__version__}'
17 changes: 15 additions & 2 deletions socketsecurity/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ class CliConfig:
pr_number_explicit: bool = False
commit_message: Optional[str] = None
default_branch: bool = False
no_default_branch: bool = False
target_path: str = "./"
scm: str = "api"
sbom_file: Optional[str] = None
Expand Down Expand Up @@ -345,6 +346,7 @@ def _from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig':
'pr_number_explicit': pr_number_explicit,
'commit_message': commit_message,
'default_branch': args.default_branch,
'no_default_branch': args.no_default_branch,
'target_path': os.path.expanduser(args.target_path),
'scm': args.scm,
'sbom_file': args.sbom_file,
Expand Down Expand Up @@ -510,6 +512,8 @@ def _from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig':
# this also catches both values arriving via a --config file.
if args.base_scan_id and args.base_commit_sha:
_usage_error("--base-scan-id and --base-commit-sha are mutually exclusive")
if args.default_branch and args.no_default_branch:
_usage_error("--default-branch and --no-default-branch are mutually exclusive")

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

# Branch and Scan Configuration
config_group = parser.add_argument_group('Branch and Scan Configuration')
config_group.add_argument(
default_branch_group = config_group.add_mutually_exclusive_group()
default_branch_group.add_argument(
"--default-branch",
dest="default_branch",
action="store_true",
help="Make this branch the default branch"
)
config_group.add_argument(
default_branch_group.add_argument(
"--default_branch",
dest="default_branch",
action="store_true",
help=argparse.SUPPRESS
)
default_branch_group.add_argument(
"--no-default-branch",
dest="no_default_branch",
action="store_true",
help="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."
)
# Deprecated no-op, still accepted so existing pipelines don't fail to parse.
config_group.add_argument(
"--pending-head",
Expand Down
61 changes: 61 additions & 0 deletions socketsecurity/core/git_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ def __init__(self, path: str, base_commit_sha: str | None = None):
self.base_commit_sha = base_commit_sha
self._fetched_ref_commits = {}
self._default_branch_name: str | None = None
self._explicit_branch: str | None = None
self._explicit_commit_sha: str | None = None
self._explicit_commit_found = False
self.ensure_safe_directory(path)
self.repo = Repo(path)
assert self.repo
Expand All @@ -54,6 +57,7 @@ def __init__(self, path: str, base_commit_sha: str | None = None):
((source, sha) for source, sha in ci_commits if sha),
(None, None),
)
self._ci_sha = ci_sha

if ci_sha:
try:
Expand Down Expand Up @@ -507,6 +511,63 @@ def _is_commit_and_branch_default(self) -> bool:
log.debug(f"Error determining if commit and branch are default: {error}")
return False

def apply_explicit_ref(self, branch: str | None, commit_sha: str | None) -> None:
"""
Record a --branch or --commit-sha that names a different ref than the CI
variables describe (a workflow_run job that checks out a release tag, for
example). When the checkout has the named commit, it supplies the commit
message, author and committer. Changed-file detection is left as is.
"""
self._explicit_branch = branch if branch and branch != self.branch else None
self._explicit_commit_sha = None
self._explicit_commit_found = False
# Compare with the commit CI names, even when the clone lacks it and
# self.commit fell back to HEAD.
ci_commit = (self._ci_sha or self.commit.hexsha).lower()
if commit_sha and not ci_commit.startswith(commit_sha.lower()):
self._explicit_commit_sha = commit_sha
try:
commit = self.repo.commit(
self.repo.git.rev_parse("--verify", f"{commit_sha}^{{commit}}")
)
except Exception as error:
log.debug(f"--commit-sha {commit_sha} is not in the local checkout: {error}")
return
self._explicit_commit_found = True
self.commit = commit
self.author = commit.author
self.commit_sha = commit.binsha
self.commit_message = commit.message
self.committer = commit.committer

def explicit_ref_allows_default_branch(self) -> bool:
"""
Whether the ref recorded by apply_explicit_ref can be the default branch:
the named branch must be the default branch and the named commit must be
in the checkout and on the default branch.
"""
commit_sha = self._explicit_commit_sha
if commit_sha and not self._explicit_commit_found:
log.info(
f"--commit-sha {commit_sha} is not in the local checkout, so the scan "
"is not treated as the default branch. Pass --default-branch to mark it."
)
return False
if commit_sha and not self.is_commit_on_default_branch():
log.info(
f"--commit-sha {commit_sha} is not on the default branch, so the scan "
"is not treated as the default branch"
)
return False
branch = self._explicit_branch
if branch and branch != self.get_default_branch_name():
log.info(
f"--branch {branch} is not the default branch "
f"{self.get_default_branch_name()}, so the scan is not treated as the default branch"
)
return False
return True

@property
def commit_str(self) -> str:
"""Return commit SHA as a string"""
Expand Down
41 changes: 22 additions & 19 deletions socketsecurity/socketcli.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ def apply_git_context(config: CliConfig) -> Tuple[bool, Optional[Git]]:
except NoSuchPathError:
raise Exception(f"Unable to find path {config.target_path}")

git_repo.apply_explicit_ref(config.branch, config.commit_sha)
if not config.repo:
config.repo = git_repo.repo_name
if not config.commit_sha:
Expand All @@ -242,6 +243,26 @@ def apply_git_context(config: CliConfig) -> Tuple[bool, Optional[Git]]:
return True, git_repo


def resolve_default_branch(config: CliConfig, scm, git_repo: Optional[Git]) -> bool:
"""
Whether the scan should become the repository's default branch and head scan.

--no-default-branch and --default-branch decide on their own. Otherwise the
scan qualifies when the SCM adapter or git detects the default branch, and a
--branch or --commit-sha that names a different ref than CI must also be the
default branch.
"""
if config.no_default_branch:
return False
if config.default_branch:
return True
detected = bool(scm is not None and getattr(scm.config, "is_default_branch", False))
if git_repo is None:
return detected
detected = detected or bool(git_repo.is_default_branch)
return detected and git_repo.explicit_ref_allows_default_branch()


def build_socket_sdk(config: CliConfig) -> socketdev:
cli_user_agent_string = f"{USER_AGENT_NAME}/{config.version}"
return socketdev(
Expand Down Expand Up @@ -584,11 +605,6 @@ def main_code(config: Optional[CliConfig] = None):
os.environ,
remote_url=getattr(git_repo, "remote_url", None) if is_repo else None,
)
# Don't override config.default_branch if it was explicitly set via --default-branch flag
# Only use SCM detection if --default-branch wasn't provided
if scm is not None and not config.default_branch:
config.default_branch = scm.config.is_default_branch

# Override files if only-facts-file mode is active
if facts_file_to_submit:
specified_files = [facts_file_to_submit]
Expand Down Expand Up @@ -702,20 +718,7 @@ def main_code(config: Optional[CliConfig] = None):
f"number={pr_number}, url={pr_context.url or 'unavailable'}"
)

# Determine if this should be treated as default branch
# Priority order:
# 1. If --default-branch flag is explicitly set to True, use that
# 2. If SCM detected it's the default branch, use that
# 3. If it's a git repo, use git_repo.is_default_branch
# 4. Otherwise, default to False
if config.default_branch:
is_default_branch = True
elif scm is not None and hasattr(scm.config, 'is_default_branch') and scm.config.is_default_branch:
is_default_branch = True
elif is_repo and git_repo.is_default_branch:
is_default_branch = True
else:
is_default_branch = False
is_default_branch = resolve_default_branch(config, scm, git_repo if is_repo else None)

params = FullScanParams(
org_slug=org_slug,
Expand Down
Loading
Loading