Skip to content

Commit 2b912ed

Browse files
committed
Sync the release stack and skip head updates for missing commits
2 parents 29b1612 + 7f4db69 commit 2b912ed

11 files changed

Lines changed: 367 additions & 57 deletions

‎CHANGELOG.md‎

Lines changed: 48 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,27 +4,60 @@
44

55
### Added
66

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`.
7+
- Use `--no-default-branch` to prevent a scan from changing the repository's
8+
default branch or updating a branch head. It is mutually exclusive with
9+
`--default-branch`.
1010

1111
### Changed
1212

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

1917
### Fixed
2018

21-
- Automatic default-branch detection honors an explicitly scanned ref. When
22-
`--branch` or `--commit-sha` names a different ref than the CI environment,
23-
the scan is marked as the default branch only if that branch is the default
24-
branch and that commit is on it. This applies to git detection and to the
25-
`DEFAULT_BRANCH` variable with `--scm github`. With `--commit-sha`, the commit
26-
message and committer fallback come from that commit when the checkout has it;
27-
CI actor values still take precedence for the committer.
19+
- Automatic default-branch detection checks explicit scan refs against the
20+
default branch. An explicit commit must be available in the checkout for
21+
automatic promotion. When available, the selected commit supplies the commit
22+
message and the Git fallback for the committer. CI actor settings retain
23+
precedence.
24+
25+
## 2.15.10
26+
27+
### Added
28+
29+
- Set `SOCKET_COANA_MIRROR_URL` to download the reachability engine through a
30+
mirror of `storage.googleapis.com/socket-coana-cli`.
31+
32+
### Changed: update the Docker image's PyPy to 8.1.1
33+
34+
- The amd64 Docker image now ships PyPy `8.1.1` (Python 3.12), up from PyPy
35+
`8.0.1`.
36+
37+
### Changed: bump pinned Coana CLI to 15.15.12
38+
39+
- Bumped the pinned reachability engine (the Coana CLI) from `15.15.11` to
40+
`15.15.12`. See the
41+
[reachability analysis changelog](https://docs.socket.dev/docs/reachability-analysis-changelog)
42+
for engine changes.
43+
44+
## 2.15.9
45+
46+
### Changed: bump pinned Coana CLI to 15.15.11
47+
48+
- Bumped the pinned reachability engine (the Coana CLI) from `15.15.10` to
49+
`15.15.11`. See the
50+
[reachability analysis changelog](https://docs.socket.dev/docs/reachability-analysis-changelog)
51+
for engine changes.
52+
53+
## 2.15.8
54+
55+
### Changed: bump pinned Coana CLI to 15.15.10
56+
57+
- Bumped the pinned reachability engine (the Coana CLI) from `15.15.9` to
58+
`15.15.10`. See the
59+
[reachability analysis changelog](https://docs.socket.dev/docs/reachability-analysis-changelog)
60+
for engine changes.
2861

2962
## 2.15.7
3063

‎Dockerfile‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,8 +89,8 @@ RUN if [ "$DOTNET_VERSION" = "6" ]; then \
8989
# This is a custom build of PyPy3.12 for Alpine on x86-64.
9090
ARG TARGETARCH # Passed by Docker buildx
9191
RUN if [ "$TARGETARCH" = "amd64" ]; then \
92-
PYPY_URL="https://github.com/BarrensZeppelin/alpine-pypy/releases/download/alp3.24.2-pypy3.12-8.0.1/pypy3.12-v8.0.1-linux64-alpine3.24.tar.gz" && \
93-
PYPY_SHA256="b6d5dd429c6394f1710a52e3e20d5c9198547caff9528547c457d3f2ed37db09" && \
92+
PYPY_URL="https://github.com/BarrensZeppelin/alpine-pypy/releases/download/alp3.24.4-pypy3.12-8.1.1/pypy3.12-v8.1.1-linux64-alpine3.24.tar.gz" && \
93+
PYPY_SHA256="c6c630c7a37a97977014cdd6252a6331fb2cfccddffe15a0a5590480f4741c2c" && \
9494
curl -L -o /tmp/pypy.tar.gz "$PYPY_URL" && \
9595
echo "$PYPY_SHA256 /tmp/pypy.tar.gz" | sha256sum -c - && \
9696
mkdir -p /opt/pypy && \

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ Prebuilt workflow examples:
212212

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

215-
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).
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).
216216

217217
Minimal pattern:
218218

‎docs/cli-reference.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -354,7 +354,7 @@ docs.socket.dev use `SOCKET_SECURITY_API_KEY`. Either works. If both are set,
354354
| Parameter | Required | Default | Description |
355355
|:---------------------------------|:---------|:--------|:---------------------------------------------------------------------------------------------------------------------------|
356356
| `--reach` | False | False | Enable reachability analysis to identify which vulnerable functions are actually called by your code. Creates a full application reachability scan (`scan_type=socket_tier1`). |
357-
| `--reach-version` | False | 15.15.9 | Version of the Coana CLI to use. Defaults to the pinned version that ships with this CLI release, so the engine only changes when you upgrade the Socket CLI. Pass `latest` to always use the newest published version (opt-in auto-update), or an explicit version (e.g. `1.2.3`) to pin it. |
357+
| `--reach-version` | False | 15.15.12 | Version of the Coana CLI to use. Defaults to the pinned version that ships with this CLI release, so the engine only changes when you upgrade the Socket CLI. Pass `latest` to always use the newest published version (opt-in auto-update), or an explicit version (e.g. `1.2.3`) to pin it. |
358358
| `--reach-analysis-timeout` | False | 10m | Timeout for each reachability analysis run, e.g. `90s`, `10m` or `1h`. Omitted by default, so coana applies its own default (`10m`). Alias: `--reach-timeout` |
359359
| `--reach-analysis-memory-limit` | False | 8GB | Memory limit for each reachability analysis run, e.g. `512MB` or `8GB`. Omitted by default, so coana applies its own default (`8GB`). Alias: `--reach-memory-limit` |
360360
| `--reach-concurrency` | False | 1 | Control parallel analysis execution (must be >= 1). Omitted by default, so coana applies its own default. |
@@ -726,7 +726,7 @@ Without either flag, the CLI marks the scan when automatic detection finds the d
726726
727727
#### Scanning a different ref than the CI run
728728
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.
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.
730730
731731
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.
732732

@@ -753,6 +753,7 @@ The organization Alerts page shows each repository's branch head scans. A full s
753753

754754
- A pull request or merge request scan of a non-default branch doesn't ask, even when no PR number is available.
755755
- 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.
756+
- If a Git checkout lacks the commit named by `--commit-sha`, the scan only requests a head update when `--default-branch` explicitly marks it.
756757
- `--no-default-branch` never asks. Use it for a scan of a tracked branch that shouldn't update that branch's head.
757758
758759
`--pending-head` is deprecated and has no effect: it is still accepted so existing pipelines keep working, but it logs a warning.

‎socketsecurity/core/git_interface.py‎

Lines changed: 32 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -512,33 +512,40 @@ def _is_commit_and_branch_default(self) -> bool:
512512
return False
513513

514514
def apply_explicit_ref(self, branch: str | None, commit_sha: str | None) -> None:
515-
"""
516-
Record a --branch or --commit-sha that names a different ref than the CI
517-
variables describe (a workflow_run job that checks out a release tag, for
518-
example). When the checkout has the named commit, it supplies the commit
519-
message, author and committer. Changed-file detection is left as is.
520-
"""
515+
"""Record explicit scan refs and use the selected commit's local metadata."""
521516
self._explicit_branch = branch if branch and branch != self.branch else None
522517
self._explicit_commit_sha = None
523518
self._explicit_commit_found = False
524-
# Compare with the commit CI names, even when the clone lacks it and
525-
# self.commit fell back to HEAD.
526-
ci_commit = (self._ci_sha or self.commit.hexsha).lower()
527-
if commit_sha and not ci_commit.startswith(commit_sha.lower()):
528-
self._explicit_commit_sha = commit_sha
529-
try:
530-
commit = self.repo.commit(
531-
self.repo.git.rev_parse("--verify", f"{commit_sha}^{{commit}}")
532-
)
533-
except Exception as error:
534-
log.debug(f"--commit-sha {commit_sha} is not in the local checkout: {error}")
535-
return
536-
self._explicit_commit_found = True
537-
self.commit = commit
538-
self.author = commit.author
539-
self.commit_sha = commit.binsha
540-
self.commit_message = commit.message
541-
self.committer = commit.committer
519+
if not commit_sha:
520+
return
521+
522+
requested_sha = commit_sha.lower()
523+
selected_sha = self.commit.hexsha
524+
ci_sha = (self._ci_sha or selected_sha).lower()
525+
# Git can fall back to HEAD when the commit named by CI is unavailable.
526+
if ci_sha.startswith(requested_sha) and selected_sha.startswith(requested_sha):
527+
return
528+
529+
self._explicit_commit_sha = commit_sha
530+
try:
531+
commit = self.repo.commit(
532+
self.repo.git.rev_parse("--verify", f"{commit_sha}^{{commit}}")
533+
)
534+
except Exception as error:
535+
log.debug(f"--commit-sha {commit_sha} is not in the local checkout: {error}")
536+
return
537+
538+
self._explicit_commit_found = True
539+
self.commit = commit
540+
self.author = commit.author
541+
self.commit_sha = commit.binsha
542+
self.commit_message = commit.message
543+
self.committer = commit.committer
544+
545+
@property
546+
def explicit_commit_is_missing(self) -> bool:
547+
"""Whether the requested commit could not be resolved in the checkout."""
548+
return bool(self._explicit_commit_sha and not self._explicit_commit_found)
542549

543550
def explicit_ref_allows_default_branch(self) -> bool:
544551
"""
@@ -547,7 +554,7 @@ def explicit_ref_allows_default_branch(self) -> bool:
547554
in the checkout and on the default branch.
548555
"""
549556
commit_sha = self._explicit_commit_sha
550-
if commit_sha and not self._explicit_commit_found:
557+
if self.explicit_commit_is_missing:
551558
log.info(
552559
f"--commit-sha {commit_sha} is not in the local checkout, so the scan "
553560
"is not treated as the default branch. Pass --default-branch to mark it."

‎socketsecurity/core/tools/reachability.py‎

Lines changed: 62 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,10 @@
1111
import tempfile
1212
from dataclasses import dataclass
1313
from typing import Any, Dict, Final, List, Mapping, Optional
14+
from urllib.parse import unquote, urlsplit
1415

1516
import requests
17+
from urllib3.util import parse_url
1618

1719
from socketsecurity import USER_AGENT, __version__
1820
from socketsecurity.core.cli_client import CliClient
@@ -22,13 +24,15 @@
2224
# Pinned Coana CLI version. Bumped deliberately per Python CLI release so the
2325
# reachability engine version only changes through a standard pip upgrade (advance notice).
2426
# Pass --reach-version latest to opt into the newest published version instead.
25-
DEFAULT_COANA_CLI_VERSION: Final = "15.15.9"
27+
DEFAULT_COANA_CLI_VERSION: Final = "15.15.12"
2628

2729
# Vendored from coana-package-manager, where it is generated; the only code that may read or
2830
# write the cache Coana shares with the Socket CLIs. See "Launching Coana" in that repo's
2931
# packages/cli/docs/gcs-releases.md.
3032
_COANA_CACHE_SCRIPT: Final = pathlib.Path(__file__).with_name("coana-cache.mjs")
3133
_COANA_COMPONENT: Final = "cli"
34+
# SOCKET_COANA_MIRROR_URL replaces this prefix of the signed URLs.
35+
_COANA_BUCKET_URL: Final = "https://storage.googleapis.com/socket-coana-cli/"
3236
_NOT_CACHED_EXIT_CODE: Final = 4
3337

3438
_EXACT_VERSION: Final = re.compile(r"\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?")
@@ -75,6 +79,54 @@ def parse(cls, value: object) -> Optional["_CoanaArtifacts"]:
7579
return cls(version=version, cli=_CoanaComponent(sha256=sha256, size=size, url=url))
7680

7781

82+
@dataclass(frozen=True)
83+
class _CoanaMirror:
84+
"""A mirror of Coana's bucket, which SOCKET_COANA_MIRROR_URL names.
85+
86+
"Downloading through a mirror" in coana-package-manager's packages/cli/docs/gcs-releases.md
87+
specifies the rule.
88+
"""
89+
90+
# Ends in "/".
91+
base_url: str
92+
93+
@classmethod
94+
def parse(cls, value: Optional[str]) -> Optional["_CoanaMirror"]:
95+
"""The mirror ``value`` names, or None when it is unset or empty."""
96+
if not value:
97+
return None
98+
try:
99+
parts = urlsplit(value)
100+
# Raises ValueError for an invalid port.
101+
parts.port
102+
except ValueError:
103+
parts = None
104+
# urlsplit drops a bare "?" or "#".
105+
if (
106+
parts is None
107+
or parts.scheme not in ("http", "https")
108+
or not parts.hostname
109+
or "?" in value
110+
or "#" in value
111+
):
112+
# The value may carry credentials.
113+
raise Exception("SOCKET_COANA_MIRROR_URL must be an http or https URL without a query or fragment.")
114+
return cls(value if value.endswith("/") else f"{value}/")
115+
116+
def download_url(self, signed_url: str) -> str:
117+
"""Where to download ``signed_url`` from. The query, which holds the signature, is kept."""
118+
rest = signed_url.removeprefix(_COANA_BUCKET_URL)
119+
# A dot segment could climb out of the bucket, or out of the mirror's base URL.
120+
if rest == signed_url or any(
121+
unquote(segment) in (".", "..") for segment in rest.partition("?")[0].split("/")
122+
):
123+
raise Exception(
124+
f"Socket provided the Coana CLI at {signed_url.partition('?')[0]}, "
125+
f"outside {_COANA_BUCKET_URL}, which SOCKET_COANA_MIRROR_URL mirrors."
126+
)
127+
return self.base_url + rest
128+
129+
78130
class _DownloadRefused(Exception):
79131
"""The download host refused a signed URL with a 4xx, e.g. because it expired."""
80132

@@ -356,18 +408,20 @@ def request_artifacts(spec: str) -> _CoanaArtifacts:
356408
return artifacts
357409

358410
def download(component: _CoanaComponent, dest: pathlib.Path) -> None:
411+
url = component.url if mirror is None else mirror.download_url(component.url)
412+
host = parse_url(url).netloc
359413
with requests.get(
360-
component.url,
414+
url,
361415
headers={"User-Agent": USER_AGENT},
362416
stream=True,
363417
timeout=_DOWNLOAD_TIMEOUT,
364418
verify=not self.client.config.allow_unverified_ssl,
365419
) as response:
366420
if 400 <= response.status_code < 500:
367-
raise _DownloadRefused(
368-
f"The download host refused the Coana CLI URL with status {response.status_code}"
369-
)
370-
response.raise_for_status()
421+
raise _DownloadRefused(f"{host} refused the Coana CLI URL with status {response.status_code}")
422+
# The URL holds the signature, and a mirror's URL may carry credentials.
423+
if not response.ok:
424+
raise Exception(f"{host} responded with status {response.status_code} to the Coana CLI download")
371425
digest = hashlib.sha256()
372426
received = 0
373427
with dest.open("wb") as f:
@@ -397,6 +451,8 @@ def regular_files_only(member: tarfile.TarInfo, path: str) -> Optional[tarfile.T
397451
if artifacts.version != version_spec and (cached := lookup(artifacts.version)):
398452
return cached
399453

454+
# Parsed only once a download is certain, so a warm cache never trips on a stale value.
455+
mirror = _CoanaMirror.parse(env.get("SOCKET_COANA_MIRROR_URL"))
400456
log.info(f"Downloading the Coana CLI {artifacts.version}...")
401457
with tempfile.TemporaryDirectory(prefix="socket-coana-cli-") as tmp:
402458
tarball = pathlib.Path(tmp, "cli.tar.gz")

‎socketsecurity/socketcli.py‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,9 @@ def resolve_default_branch(config: CliConfig, scm, git_repo: Optional[Git]) -> b
264264
return detected and git_repo.explicit_ref_allows_default_branch()
265265

266266

267-
def request_branch_head(config: CliConfig, is_default_branch: bool, pull_request_run: bool) -> bool:
267+
def request_branch_head(
268+
config: CliConfig, is_default_branch: bool, pull_request_run: bool, git_repo: Optional[Git]
269+
) -> bool:
268270
"""
269271
Whether the scan asks the API to make it its branch's head (set_as_pending_head).
270272
@@ -274,7 +276,9 @@ def request_branch_head(config: CliConfig, is_default_branch: bool, pull_request
274276
"""
275277
if config.no_default_branch:
276278
return False
277-
return is_default_branch or not pull_request_run
279+
if is_default_branch:
280+
return True
281+
return not pull_request_run and not (git_repo is not None and git_repo.explicit_commit_is_missing)
278282

279283

280284
def build_socket_sdk(config: CliConfig) -> socketdev:
@@ -751,7 +755,9 @@ def main_code(config: Optional[CliConfig] = None):
751755
pull_request=pr_number,
752756
committers=config.committers,
753757
make_default_branch=is_default_branch,
754-
set_as_pending_head=request_branch_head(config, is_default_branch, pull_request_run),
758+
set_as_pending_head=request_branch_head(
759+
config, is_default_branch, pull_request_run, git_repo
760+
),
755761
tmp=False,
756762
scan_type='socket_tier1' if config.reach else 'socket',
757763
workspace=config.workspace or None,

‎tests/core/test_default_branch_flags.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,19 @@ def test_scm_detection_honors_an_explicit_commit_when_the_ci_commit_is_not_clone
104104
assert _flags(_scan_params(cli_runtime)) == (False, True)
105105

106106

107+
def test_scm_detection_requires_explicit_ci_commit_in_checkout(
108+
cli_runtime, github_dispatch_on_develop, monkeypatch # noqa: F811
109+
):
110+
missing_sha = "f" * 40
111+
monkeypatch.setenv("GITHUB_SHA", missing_sha)
112+
113+
assert github_dispatch_on_develop(["--commit-sha", missing_sha]) == 0
114+
115+
params = _scan_params(cli_runtime)
116+
assert params.commit_hash == missing_sha
117+
assert _flags(params) == (False, False)
118+
119+
107120
def test_scm_detection_still_marks_the_default_branch_run(
108121
cli_runtime, github_dispatch_on_develop # noqa: F811
109122
):

0 commit comments

Comments
 (0)