Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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
26 changes: 26 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,31 @@
# 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`.

### Changed

- Full scans of branches that match an organization's tracked branch patterns
can update those branch heads, so findings from those branches can appear on
the organization Alerts page after upgrade. Untracked branches are not
eligible, pull request and merge request scans of a non-default branch don't
request it, and `--no-default-branch` opts a scan out.

### 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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,10 @@ 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`.

Full scans of branches that match your organization's tracked branch patterns update those branch heads, so their findings appear on the Alerts page. See [Branch heads](https://github.com/SocketDev/socket-python-cli/blob/main/docs/cli-reference.md#branch-heads).

Minimal pattern:

```yaml
Expand Down
43 changes: 36 additions & 7 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,14 +720,42 @@ 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.

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

#### Branch heads

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.

- A pull request or merge request scan of a non-default branch doesn't ask, even when no PR number is available.
- 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.
- `--no-default-branch` never asks. Use it for a scan of a tracked branch that shouldn't update that branch's head.

`--pending-head` is deprecated and has no effect: it is still accepted so existing pipelines keep working, but it logs a warning.

## Who can ignore an alert

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__}'
22 changes: 18 additions & 4 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 @@ -502,14 +504,17 @@ def _from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig':

if args.pending_head:
logging.warning(
"--pending-head is deprecated and has no effect. A scan becomes the head scan "
"when it runs on the default branch; use --default-branch to mark it as such."
"--pending-head is deprecated and has no effect. Full scans ask to become their "
"branch's head, which the API grants on the default branch and on tracked "
"branches (Settings > Alerts > Scans). Use --no-default-branch to opt out."
)

# argparse only enforces the mutually exclusive group for real CLI args;
# 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 +790,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
19 changes: 19 additions & 0 deletions socketsecurity/core/pull_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,25 @@ def parse_pull_request_number(value) -> int:
return parsed if parsed > 0 else 0


def is_pull_request_environment(env: Mapping[str, str]) -> bool:
"""Whether the CI environment describes a pull or merge request run.

This holds even when no PR number is available, for example with an
explicit ``--pr-number 0``.
"""
if env.get("GITHUB_EVENT_NAME", "").lower() in ("pull_request", "pull_request_target"):
return True
if env.get("GITHUB_REF", "").startswith("refs/pull/"):
return True
if env.get("CI_MERGE_REQUEST_IID") or env.get("CI_PIPELINE_SOURCE", "").lower() == "merge_request_event":
return True
if env.get("BITBUCKET_PR_ID") or parse_pull_request_number(env.get("BUILDKITE_PULL_REQUEST")):
return True
return env.get("BUILD_REASON", "").lower() == "pullrequest" or bool(
env.get("SYSTEM_PULLREQUEST_PULLREQUESTID")
)


def _http_url(value: Optional[str]) -> Optional[str]:
"""Return ``value`` if it is an http(s) URL with a host, else ``None``.

Expand Down
Loading