Skip to content

Commit b66d0b1

Browse files
committed
Merge branch 'main' into lelia/version-check-pypi-retry
2 parents fa869b4 + 3b3ec62 commit b66d0b1

21 files changed

Lines changed: 1011 additions & 48 deletions

‎CHANGELOG.md‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,37 @@
11
# Changelog
22

3-
## 2.15.11
3+
## 2.16.1
44

55
### Changed: retry the PyPI lookup in the version check
66

77
- The `check_version` CI job now retries the PyPI request on connection
88
errors, timeouts, HTTP 429 and HTTP 5xx, and says when a failure is PyPI's
99
rather than the PR's version. No change to the CLI itself.
1010

11+
## 2.16.0
12+
13+
### Added
14+
15+
- Use `--no-default-branch` to prevent a scan from changing the repository's
16+
default branch or updating a branch head. It is mutually exclusive with
17+
`--default-branch`.
18+
19+
### Changed
20+
21+
- Full scans of tracked branches can update branch heads, so findings from
22+
those branches can appear on the organization Alerts page after upgrade.
23+
Use `--no-default-branch` to opt a scan out.
24+
- PR and MR security comments link available GHSA and CVE IDs to their public
25+
advisory pages.
26+
27+
### Fixed
28+
29+
- Automatic default-branch detection checks explicit scan refs against the
30+
default branch, including qualified branch refs such as `refs/heads/main`.
31+
An explicit commit must be available in the checkout for automatic promotion.
32+
The selected commit supplies the commit message and Git committer fallback
33+
when available. CI actor settings retain precedence.
34+
1135
## 2.15.10
1236

1337
### Added

‎README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,10 @@ 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+
215+
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).
216+
213217
Minimal pattern:
214218

215219
```yaml

‎docs/cli-reference.md‎

Lines changed: 39 additions & 7 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,14 +720,45 @@ 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.
728726
729-
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.
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`.
751+
752+
#### Branch heads
753+
754+
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.
755+
756+
- A pull request or merge request scan of a non-default branch doesn't ask, even when no PR number is available.
757+
- 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.
758+
- If a Git checkout lacks the commit named by `--commit-sha`, the scan only requests a head update when `--default-branch` explicitly marks it.
759+
- `--no-default-branch` never asks. Use it for a scan of a tracked branch that shouldn't update that branch's head.
760+
761+
`--pending-head` is deprecated and has no effect: it is still accepted so existing pipelines keep working, but it logs a warning.
730762
731763
## Who can ignore an alert
732764

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

‎socketsecurity/config.py‎

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

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

509512
# argparse only enforces the mutually exclusive group for real CLI args;
510513
# this also catches both values arriving via a --config file.
511514
if args.base_scan_id and args.base_commit_sha:
512515
_usage_error("--base-scan-id and --base-commit-sha are mutually exclusive")
516+
if args.default_branch and args.no_default_branch:
517+
_usage_error("--default-branch and --no-default-branch are mutually exclusive")
513518

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

786791
# Branch and Scan Configuration
787792
config_group = parser.add_argument_group('Branch and Scan Configuration')
788-
config_group.add_argument(
793+
default_branch_group = config_group.add_mutually_exclusive_group()
794+
default_branch_group.add_argument(
789795
"--default-branch",
790796
dest="default_branch",
791797
action="store_true",
792798
help="Make this branch the default branch"
793799
)
794-
config_group.add_argument(
800+
default_branch_group.add_argument(
795801
"--default_branch",
796802
dest="default_branch",
797803
action="store_true",
798804
help=argparse.SUPPRESS
799805
)
806+
default_branch_group.add_argument(
807+
"--no-default-branch",
808+
dest="no_default_branch",
809+
action="store_true",
810+
help="Prevent the scan from changing the repository's default branch or updating a "
811+
"branch head, whatever git or the CI environment detects. Mutually exclusive "
812+
"with --default-branch."
813+
)
800814
# Deprecated no-op, still accepted so existing pipelines don't fail to parse.
801815
config_group.add_argument(
802816
"--pending-head",

‎socketsecurity/core/classes.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,27 @@ def advisory_id(self) -> str:
382382
return value.strip().upper()
383383
return ""
384384

385+
def advisory_ids(self) -> List[str]:
386+
"""Return distinct advisory IDs for display, using the API spelling and GHSA first."""
387+
props = getattr(self, "props", None) or {}
388+
ids: List[str] = []
389+
seen = set()
390+
for prop_name in ADVISORY_ID_PROPS:
391+
values = props.get(prop_name)
392+
if isinstance(values, str):
393+
values = [values]
394+
elif not isinstance(values, (list, tuple)):
395+
continue
396+
for value in values:
397+
if not isinstance(value, str) or not value.strip():
398+
continue
399+
value = value.strip()
400+
if value.upper() in seen:
401+
continue
402+
seen.add(value.upper())
403+
ids.append(value)
404+
return ids
405+
385406
def consolidation_key(self) -> Tuple[str, str, str, str]:
386407
"""Identity used to collapse repeat sightings of one finding into one alert.
387408

‎socketsecurity/core/git_interface.py‎

Lines changed: 90 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,92 @@ 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+
@property
568+
def explicit_commit_is_missing(self) -> bool:
569+
"""Whether the requested commit could not be resolved in the checkout."""
570+
return bool(self._explicit_commit_sha and not self._explicit_commit_found)
571+
572+
def explicit_ref_allows_default_branch(self) -> bool:
573+
"""
574+
Whether the ref recorded by apply_explicit_ref can be the default branch:
575+
the named branch must be the default branch and the named commit must be
576+
in the checkout and on the default branch.
577+
"""
578+
commit_sha = self._explicit_commit_sha
579+
if self.explicit_commit_is_missing:
580+
log.info(
581+
f"--commit-sha {commit_sha} is not in the local checkout, so the scan "
582+
"is not treated as the default branch. Pass --default-branch to mark it."
583+
)
584+
return False
585+
if commit_sha and not self.is_commit_on_default_branch():
586+
log.info(
587+
f"--commit-sha {commit_sha} is not on the default branch, so the scan "
588+
"is not treated as the default branch"
589+
)
590+
return False
591+
branch = self._explicit_branch
592+
if branch and branch != self.get_default_branch_name():
593+
log.info(
594+
f"--branch {branch} is not the default branch "
595+
f"{self.get_default_branch_name()}, so the scan is not treated as the default branch"
596+
)
597+
return False
598+
return True
599+
510600
@property
511601
def commit_str(self) -> str:
512602
"""Return commit SHA as a string"""

0 commit comments

Comments
 (0)