Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
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
24 changes: 24 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,29 @@
# Changelog

## 2.16.0

### Added

- Use `--no-default-branch` to prevent a scan from changing the repository's
default branch or updating a branch head. It is mutually exclusive with
`--default-branch`.

### Changed

- Full scans of tracked branches can update branch heads, so findings from
those branches can appear on the organization Alerts page after upgrade.
Use `--no-default-branch` to opt a scan out.
- PR and MR security comments link available GHSA and CVE IDs to their public
advisory pages.

### Fixed

- Automatic default-branch detection checks explicit scan refs against the
default branch. An explicit commit must be available in the checkout for
automatic promotion. When available, the selected commit supplies the commit
message and the Git fallback for the committer. CI actor settings retain
precedence.

## 2.15.10

### Added
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 tracked branches can update branch heads and show their findings 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
44 changes: 37 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,43 @@ 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. 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.

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.
- If a Git checkout lacks the commit named by `--commit-sha`, the scan only requests a head update when `--default-branch` explicitly marks it.
- `--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.10"
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.10'
__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
21 changes: 21 additions & 0 deletions socketsecurity/core/classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,27 @@ def advisory_id(self) -> str:
return value.strip().upper()
return ""

def advisory_ids(self) -> List[str]:
"""Return distinct advisory IDs for display, using the API spelling and GHSA first."""
props = getattr(self, "props", None) or {}
ids: List[str] = []
seen = set()
for prop_name in ADVISORY_ID_PROPS:
values = props.get(prop_name)
if isinstance(values, str):
values = [values]
elif not isinstance(values, (list, tuple)):
continue
for value in values:
if not isinstance(value, str) or not value.strip():
continue
value = value.strip()
if value.upper() in seen:
continue
seen.add(value.upper())
ids.append(value)
return ids

def consolidation_key(self) -> Tuple[str, str, str, str]:
"""Identity used to collapse repeat sightings of one finding into one alert.

Expand Down
68 changes: 68 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,70 @@ 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 explicit scan refs and use the selected commit's local metadata."""
self._explicit_branch = branch if branch and branch != self.branch else None
self._explicit_commit_sha = None
self._explicit_commit_found = False
if not commit_sha:
return

requested_sha = commit_sha.lower()
selected_sha = self.commit.hexsha
ci_sha = (self._ci_sha or selected_sha).lower()
# Git can fall back to HEAD when the commit named by CI is unavailable.
if ci_sha.startswith(requested_sha) and selected_sha.startswith(requested_sha):
return

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

@property
def explicit_commit_is_missing(self) -> bool:
"""Whether the requested commit could not be resolved in the checkout."""
return bool(self._explicit_commit_sha and not self._explicit_commit_found)

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 self.explicit_commit_is_missing:
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
Loading