Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

release-desktop: pin trusted-signing-cli by digest instead of trusting a cache (#8417)

Daniel Haneeb958dd1b3a
diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml
index aa33d911bc6..1d950d60289 100644
--- a/.github/workflows/release-desktop.yml
+++ b/.github/workflows/release-desktop.yml
@@ -853,59 +853,88 @@ jobs:
rm -f certificate.p12
# ── Windows: install Azure Trusted Signing CLI ──
- # `cargo install` builds this from source: 241s and 248s on the last two
- # cache-miss runs. It was only ever fast when the ~550 MB rust-cache
- # happened to restore `~/.cargo/bin` too, and that entry is the first
- # thing evicted under repo cache pressure, which is why Windows swung
- # between 8.8 min and 20.9 min. A dedicated single-binary cache keeps the
- # compile off the critical path independently of the big Rust cache.
- - name: Restore trusted-signing-cli
- id: cache_trusted_signing_cli
- if: matrix.platform == 'windows-latest'
- uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
- with:
- path: ~/.cargo/bin/trusted-signing-cli.exe
- # The version is in the key, so a bump invalidates the cache instead
- # of silently reusing the old binary.
- key: trusted-signing-cli-0.10.0-${{ runner.os }}-${{ runner.arch }}
-
+ # This binary runs in the steps holding the Azure Trusted Signing and
+ # Tauri signing secrets, so where it comes from is a signing-key question,
+ # not a build-speed one. Caching the `cargo install` build (241s and 248s
+ # on the last two runs) made the cache the source of truth: a hit skipped
+ # the install, and the restored executable went on PATH gated only by a
+ # `--version` probe, which any binary can print.
+ #
+ # Upstream publishes the same tool prebuilt, so pin it instead. The URL is
+ # reproducibility, the SHA-256 is the integrity gate: a release asset can
+ # be replaced after upload, and a replaced one now fails the release
+ # rather than signing with an unknown binary. Same shape as the AppImage
+ # toolchain below, and faster than the cache it replaces. Bump the URL and
+ # the digest together when moving off 0.10.0.
- name: Install trusted-signing-cli
- if: matrix.platform == 'windows-latest' && steps.cache_trusted_signing_cli.outputs.cache-hit != 'true'
- run: |
- cargo install trusted-signing-cli --version 0.10.0 --locked
-
- # Unconditional: on a cache hit the install step above is skipped, and the
- # cargo bin dir still has to reach PATH or signing fails.
- - name: Add cargo bin to PATH
if: matrix.platform == 'windows-latest'
+ # Explicit, like every other Windows step here. The retry parameters
+ # below are PowerShell 6+ only, so under 5.1 the download fails with "A
+ # parameter cannot be found that matches parameter name
+ # 'MaximumRetryCount'". Naming the shell keeps that deliberate.
+ shell: pwsh
+ env:
+ TRUSTED_SIGNING_CLI_URL: "https://github.com/Levminer/artifact-signing-cli/releases/download/0.10.0/trusted-signing-cli.exe"
+ TRUSTED_SIGNING_CLI_SHA256: "8c9d750ca582891a7433925dcf302d5d3761fbed757b46c4bf5b417562dccb0e"
run: |
- echo "$env:USERPROFILE\.cargo\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
+ $ErrorActionPreference = "Stop"
+ $dir = Join-Path $env:RUNNER_TEMP "trusted-signing-cli"
+ New-Item -ItemType Directory -Force -Path $dir | Out-Null
+ $dest = Join-Path $dir "trusted-signing-cli.exe"
+
+ Invoke-WebRequest -Uri $env:TRUSTED_SIGNING_CLI_URL -OutFile $dest -MaximumRetryCount 3 -RetryIntervalSec 5
+
+ $actual = (Get-FileHash -Path $dest -Algorithm SHA256).Hash.ToLower()
+ $expected = $env:TRUSTED_SIGNING_CLI_SHA256.ToLower()
+ if ($actual -ne $expected) {
+ # Delete it first: a later step resolving this name off PATH must
+ # not find the rejected download still sitting there.
+ Remove-Item -Force $dest
+ Write-Output "::error::trusted-signing-cli digest mismatch, refusing to sign with an unverified binary. Expected $expected, got $actual. Re-pin TRUSTED_SIGNING_CLI_SHA256 deliberately if upstream republished the asset."
+ exit 1
+ }
+ Write-Output "verified trusted-signing-cli sha256=$actual"
+
+ # $GITHUB_PATH prepends, which is what this needs: swatinem/rust-cache
+ # restores ~/.cargo/bin, already on PATH, and a stale entry there can
+ # carry its own unverified copy of this binary. The verified one has
+ # to win the name lookup.
+ $dir | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
# ── Windows: verify signing CLI is accessible ──
# Fails closed. This used to print a message and exit 0 on both branches,
# so a missing or broken binary reported success and the failure only
# surfaced later, inside the Tauri bundling step, as a signing error with
- # no obvious cause. It matters more now that the binary comes from a
- # cache: a truncated or corrupt cache entry restores, skips the install
- # above, and would otherwise sail through this check.
+ # no obvious cause.
- name: Verify trusted-signing-cli
if: matrix.platform == 'windows-latest'
+ shell: pwsh
run: |
$ErrorActionPreference = "Stop"
Write-Output "PATH: $env:PATH"
$cli = Get-Command trusted-signing-cli -ErrorAction SilentlyContinue
if (-not $cli) {
- Write-Output "::error::trusted-signing-cli is not on PATH. If the cache restored a bad entry, bump the key in 'Restore trusted-signing-cli' to force a rebuild."
+ Write-Output "::error::trusted-signing-cli is not on PATH. Check the 'Install trusted-signing-cli' step above."
exit 1
}
Write-Output "resolved: $($cli.Source)"
+ # The signing script invokes this by bare name, so whatever PATH
+ # resolves is what signs. Only the digest-verified copy installed
+ # above may do that; anything else on PATH under the same name (a
+ # leftover in ~/.cargo/bin, say) is unverified by definition.
+ $verified = [IO.Path]::GetFullPath((Join-Path (Join-Path $env:RUNNER_TEMP "trusted-signing-cli") "trusted-signing-cli.exe"))
+ if ([IO.Path]::GetFullPath($cli.Source) -ne $verified) {
+ Write-Output "::error::trusted-signing-cli resolved to $($cli.Source), not the verified $verified. Refusing to sign with a binary that was never digest checked."
+ exit 1
+ }
+
# Two different failure modes, and neither one covers the other:
- # * the binary cannot be started at all (a truncated cache entry
- # gives "Exec format error"). That raises a terminating error
- # under $ErrorActionPreference = "Stop", so it has to be caught
- # or the step dies here, before the recovery message below.
+ # * the binary cannot be started at all (a truncated download gives
+ # "Exec format error"). That raises a terminating error under
+ # $ErrorActionPreference = "Stop", so it has to be caught or the
+ # step dies here, before the message below.
# * the binary starts and exits non-zero. That does NOT raise, so
# $LASTEXITCODE has to be read explicitly.
try {
@@ -917,11 +946,11 @@ jobs:
# it, and put the recovery ahead of the detail so it survives even if
# the annotation is clipped for length.
$detail = ($_.Exception.Message -replace '\s+', ' ').Trim()
- Write-Output "::error::trusted-signing-cli could not be started. If the cache restored a bad entry, bump the key in 'Restore trusted-signing-cli' to force a rebuild. Underlying error: $detail"
+ Write-Output "::error::trusted-signing-cli could not be started. Re-run to fetch it again; if it persists the pinned asset is bad. Underlying error: $detail"
exit 1
}
if ($LASTEXITCODE -ne 0) {
- Write-Output "::error::trusted-signing-cli is on PATH but exited $LASTEXITCODE. If the cache restored a bad entry, bump the key in 'Restore trusted-signing-cli' to force a rebuild."
+ Write-Output "::error::trusted-signing-cli is on PATH but exited $LASTEXITCODE."
exit 1
}
diff --git a/tests/security/test_release_desktop_signing.py b/tests/security/test_release_desktop_signing.py
index 64510dd50bb..adf0263a3b4 100644
--- a/tests/security/test_release_desktop_signing.py
+++ b/tests/security/test_release_desktop_signing.py
@@ -1,13 +1,17 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""The Windows signing toolchain check has to fail closed.
+"""The Windows signing toolchain has to be verified, and has to fail closed.
-An unsigned or half-signed installer is the failure this workflow exists to
-prevent, so the step that proves `trusted-signing-cli` works must not be able to
-report success when it does not. The check previously ended both of its branches
-in `|| Write-Output "..."`, which exits 0, so a missing or broken binary passed
-and only surfaced later inside the Tauri bundling step.
+`trusted-signing-cli` runs with the Azure Trusted Signing and Tauri signing
+secrets in the environment, so two things must hold: the binary is the one we
+pinned, and a check that cannot prove that cannot report success.
+
+Both have regressed before. The install step once restored the executable from
+an actions/cache and skipped the build on a hit, leaving a spoofable
+`--version` as the only gate. The verify step once ended both branches in
+`|| Write-Output "..."`, which exits 0, so a broken binary passed and surfaced
+later inside Tauri bundling.
"""
from pathlib import Path
@@ -19,34 +23,82 @@ REPO_ROOT = Path(__file__).resolve().parents[2]
WORKFLOW = REPO_ROOT / ".github" / "workflows" / "release-desktop.yml"
-def _verify_step():
+def _build_steps():
workflow = yaml.safe_load(WORKFLOW.read_text(encoding = "utf-8"))
- return next(
- step
- for step in workflow["jobs"]["build"]["steps"]
- if step.get("name") == "Verify trusted-signing-cli"
+ return workflow["jobs"]["build"]["steps"]
+
+
+def _step(name: str):
+ return next(step for step in _build_steps() if step.get("name") == name)
+
+
+def _verify_step():
+ return _step("Verify trusted-signing-cli")
+
+
+def test_the_signing_cli_is_pinned_by_url_and_digest():
+ step = _step("Install trusted-signing-cli")
+ assert (
+ "/releases/download/0.10.0/trusted-signing-cli.exe"
+ in step["env"]["TRUSTED_SIGNING_CLI_URL"]
)
+ assert len(step["env"]["TRUSTED_SIGNING_CLI_SHA256"]) == 64
+
+
+def test_both_steps_name_the_shell_they_need():
+ # -MaximumRetryCount / -RetryIntervalSec are PowerShell 6+ only. Inheriting
+ # the interpreter from a runner default is not where a release download
+ # should get it, and every other Windows step here says pwsh outright.
+ for name in ("Install trusted-signing-cli", "Verify trusted-signing-cli"):
+ assert _step(name)["shell"] == "pwsh", name
+
+
+def test_a_digest_mismatch_stops_the_release_before_anything_is_signed():
+ run = _step("Install trusted-signing-cli")["run"]
+ assert "Get-FileHash" in run
+ assert "if ($actual -ne $expected)" in run
+ assert "exit 1" in run
+ # A rejected download left on disk is still reachable by name from PATH.
+ assert "Remove-Item -Force $dest" in run
+
+
+def test_no_step_restores_the_signing_cli_from_a_cache():
+ # A cache is not an integrity mechanism: restore plus skip-on-hit is what
+ # would let a poisoned entry sign releases.
+ for step in _build_steps():
+ uses = step.get("uses", "")
+ if not uses.startswith("actions/cache"):
+ continue
+ assert "trusted-signing-cli" not in yaml.safe_dump(step)
+
+
+def test_the_verified_binary_is_the_one_that_signs():
+ # The signing script calls the tool by bare name, and rust-cache restores
+ # ~/.cargo/bin, which can hold an unverified copy of the same name. PATH has
+ # to resolve to the digest-checked file.
+ run = _verify_step()["run"]
+ assert "$verified" in run
+ assert "[IO.Path]::GetFullPath($cli.Source) -ne $verified" in run
def test_the_check_exits_non_zero_on_every_failure_path():
run = _verify_step()["run"]
- # Not on PATH, cannot be started, and started but exited non-zero.
- assert run.count("exit 1") == 3
+ # Not on PATH, resolved to an unverified copy, cannot be started, and
+ # started but exited non-zero.
+ assert run.count("exit 1") == 4
def test_a_binary_that_cannot_start_is_caught():
- # A truncated cache entry gives "Exec format error", which is a terminating
- # PowerShell error, not a native exit code. Without the catch the step dies
- # on that line and never prints the cache-bump recovery.
+ # A truncated download raises a terminating PowerShell error, not a native
+ # exit code, so without the catch the step dies before explaining why.
run = _verify_step()["run"]
assert "try {" in run
assert "catch {" in run
def test_the_launch_error_is_flattened_to_one_line():
- # A PowerShell error spans message, offending line and caret. An annotation
- # is truncated at the first newline, so an unflattened message would drop
- # the recovery guidance that follows it.
+ # A PowerShell error spans message, offending line and caret; an annotation
+ # stops at the first newline, dropping the guidance that follows.
run = _verify_step()["run"]
assert "-replace '\\s+', ' '" in run
@@ -57,18 +109,17 @@ def test_failures_are_not_swallowed_by_a_fallback_message():
def test_the_native_exit_code_is_inspected():
- # $ErrorActionPreference does not trap a native binary exiting non-zero,
- # so $LASTEXITCODE has to be read explicitly for the check to mean anything.
+ # $ErrorActionPreference does not trap a native non-zero exit, so
+ # $LASTEXITCODE has to be read explicitly.
run = _verify_step()["run"]
assert "$LASTEXITCODE" in run
-def test_the_operator_is_told_how_to_recover_from_a_bad_cache():
- # The binary is restored from a cache keyed on its version, so a corrupt
- # entry survives until the key changes. Failing closed without saying that
- # would turn a rare cache fault into an unexplained release outage.
+def test_every_failure_says_what_it_was():
+ # Failing closed without saying why turns a rare fetch fault into an
+ # unexplained outage, and the four causes need different fixes.
run = _verify_step()["run"]
- assert run.count("bump the key") == 3
+ assert run.count("::error::") == 4
def test_the_check_still_only_runs_on_windows():
diff --git a/tests/security/test_release_desktop_signing_simulation.py b/tests/security/test_release_desktop_signing_simulation.py
new file mode 100644
index 00000000000..529a0ae09f8
--- /dev/null
+++ b/tests/security/test_release_desktop_signing_simulation.py
@@ -0,0 +1,499 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The Windows signing binary is executed with the release signing secrets.
+
+test_release_desktop_signing.py asserts on the workflow text; this file runs the
+two step bodies, so a change that reads fine but stops failing closed is caught.
+The bodies are extracted, never retyped, then wrapped and invoked the way the
+runner does (ScriptHandlerHelpers.cs prepends `$ErrorActionPreference = 'stop'`
+and appends the $LASTEXITCODE propagation, then runs `pwsh -command ". '<f>'"`).
+That wrapper is what makes `exit 1` mean "the release stops" here too.
+
+A local HTTP server stands in for the release asset, so tampered, truncated and
+unreachable downloads are deterministic and offline.
+
+Needs pwsh. Checks that need a bare name to resolve to a `.exe` need Windows
+PATHEXT; UNSLOTH_NETWORK_TESTS=1 also pulls the real pinned asset.
+"""
+
+import functools
+import hashlib
+import http.server
+import os
+import pathlib
+import shutil
+import subprocess
+import sys
+import threading
+
+import pytest
+import yaml
+
+
+# Only PATHEXT maps a bare name onto the `.exe` the verify step insists on, so
+# checks needing a *passing* resolution are skipped off Windows rather than
+# faked. The rejecting direction is platform neutral and runs everywhere.
+needs_pathext = pytest.mark.skipif(
+ sys.platform != "win32",
+ reason = "needs Windows PATHEXT resolution to map a bare name onto the .exe",
+)
+
+# Opt in, so an offline or rate limited run does not fail on what the digest
+# already pins.
+needs_network = pytest.mark.skipif(
+ not os.environ.get("UNSLOTH_NETWORK_TESTS"),
+ reason = "set UNSLOTH_NETWORK_TESTS=1 to fetch the pinned release asset",
+)
+
+pytestmark = pytest.mark.skipif(
+ shutil.which("pwsh") is None,
+ reason = "pwsh is required to execute the Windows step bodies",
+)
+
+
+REPO = pathlib.Path(__file__).resolve().parents[2]
+WORKFLOW = REPO / ".github" / "workflows" / "release-desktop.yml"
+
+RUNNER_PREPEND = "$ErrorActionPreference = 'stop'"
+RUNNER_APPEND = r"if ((Test-Path -LiteralPath variable:\LASTEXITCODE)) { exit $LASTEXITCODE }"
+
+WINDOWS_GUARD = "matrix.platform == 'windows-latest'"
+
+
+# ── the PR under test ────────────────────────────────────────────────────────
+
+
[email protected]_cache(maxsize = 1)
+def workflow():
+ return yaml.safe_load(WORKFLOW.read_text(encoding = "utf-8"))
+
+
+def step(name):
+ return next(s for s in workflow()["jobs"]["build"]["steps"] if s.get("name") == name)
+
+
[email protected]_cache(maxsize = 1)
+def pinned():
+ env = step("Install trusted-signing-cli")["env"]
+ return env["TRUSTED_SIGNING_CLI_URL"], env["TRUSTED_SIGNING_CLI_SHA256"]
+
+
+def write_step_script(directory, name, filename):
+ body = step(name)["run"]
+ path = pathlib.Path(directory) / filename
+ path.write_text(f"{RUNNER_PREPEND}\n{body}\n{RUNNER_APPEND}\n", encoding = "utf-8")
+ return path
+
+
+def run_step(script, env):
+ """Invoke a step script the way the runner does and return (code, output)."""
+ full = {**os.environ, **env}
+ result = subprocess.run(
+ ["pwsh", "-NoProfile", "-Command", f". '{script}'"],
+ capture_output = True,
+ text = True,
+ env = full,
+ timeout = 300,
+ )
+ return result.returncode, result.stdout + result.stderr
+
+
+# ── a local stand-in for the GitHub release asset ────────────────────────────
+
+
+class _Handler(http.server.BaseHTTPRequestHandler):
+ payload = b""
+ truncate = False
+ status = 200
+
+ def do_GET(self):
+ if self.status != 200:
+ self.send_error(self.status)
+ return
+ body = self.payload[: len(self.payload) // 2] if self.truncate else self.payload
+ self.send_response(200)
+ self.send_header("Content-Type", "application/octet-stream")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *args):
+ pass
+
+
[email protected](scope = "session")
+def asset_server():
+ handler = _Handler
+ handler.payload = b"MZ" + b"\x00" * 4094 + b"pretend trusted-signing-cli"
+ server = http.server.HTTPServer(("127.0.0.1", 0), handler)
+ thread = threading.Thread(target = server.serve_forever, daemon = True)
+ thread.start()
+ yield f"http://127.0.0.1:{server.server_port}/trusted-signing-cli.exe", handler
+ server.shutdown()
+
+
+def sandbox(tmp_path):
+ install = write_step_script(tmp_path, "Install trusted-signing-cli", "install.ps1")
+ verify = write_step_script(tmp_path, "Verify trusted-signing-cli", "verify.ps1")
+ runner_temp = tmp_path / "runner_temp"
+ runner_temp.mkdir()
+ github_path = tmp_path / "github_path"
+ github_path.write_text("", encoding = "utf-8")
+ return {
+ "install": install,
+ "verify": verify,
+ "runner_temp": runner_temp,
+ "github_path": github_path,
+ "env": {
+ "RUNNER_TEMP": str(runner_temp),
+ "GITHUB_PATH": str(github_path),
+ },
+ }
+
+
+def good_digest(handler):
+ return hashlib.sha256(handler.payload).hexdigest()
+
+
+def install_env(sandbox, url, digest):
+ return {
+ **sandbox["env"],
+ "TRUSTED_SIGNING_CLI_URL": url,
+ "TRUSTED_SIGNING_CLI_SHA256": digest,
+ }
+
+
+def installed_binary(sandbox):
+ return sandbox["runner_temp"] / "trusted-signing-cli" / "trusted-signing-cli.exe"
+
+
+# ── static contracts on the PR ───────────────────────────────────────────────
+
+
+def test_pin_is_a_full_sha256_and_a_versioned_url():
+ url, digest = pinned()
+ assert len(digest) == 64 and all(c in "0123456789abcdef" for c in digest)
+ assert url.startswith("https://")
+ assert "/releases/download/0.10.0/" in url
+
+
+def test_no_cache_step_restores_the_signing_binary():
+ for s in workflow()["jobs"]["build"]["steps"]:
+ if str(s.get("uses", "")).startswith("actions/cache"):
+ assert "trusted-signing-cli" not in yaml.safe_dump(s), s.get("name")
+
+
+def test_the_removed_steps_are_gone():
+ names = [s.get("name") for s in workflow()["jobs"]["build"]["steps"]]
+ assert "Restore trusted-signing-cli" not in names
+ assert "Add cargo bin to PATH" not in names
+
+
+def test_every_signing_cli_step_stays_windows_only():
+ for s in workflow()["jobs"]["build"]["steps"]:
+ if "trusted-signing-cli" in yaml.safe_dump(s):
+ assert s.get("if") == WINDOWS_GUARD, s.get("name")
+
+
+def test_other_platform_integrity_paths_are_untouched():
+ names = [s.get("name") for s in workflow()["jobs"]["build"]["steps"]]
+ assert "Pin thin AppImage toolchain" in names
+ assert "Import Apple certificate" in names
+
+
+def test_the_install_step_never_interpolates_workflow_expressions():
+ # `${{ }}` in a run body is a shell-injection surface; the pinned values go
+ # through `env:`.
+ body = step("Install trusted-signing-cli")["run"]
+ assert "${{" not in body
+
+
+# ── the happy path ───────────────────────────────────────────────────────────
+
+
+def test_a_matching_digest_installs_and_publishes_the_path(sandbox, asset_server):
+ url, handler = asset_server
+ code, out = run_step(sandbox["install"], install_env(sandbox, url, good_digest(handler)))
+
+ assert code == 0, out
+ assert installed_binary(sandbox).is_file()
+ assert installed_binary(sandbox).read_bytes() == handler.payload
+ assert sandbox["github_path"].read_text().strip().endswith("trusted-signing-cli")
+ assert "verified trusted-signing-cli sha256=" in out
+
+
+def test_the_digest_check_is_case_insensitive(sandbox, asset_server):
+ url, handler = asset_server
+ code, out = run_step(
+ sandbox["install"],
+ install_env(sandbox, url, good_digest(handler).upper()),
+ )
+ assert code == 0, out
+
+
+def test_installing_twice_is_idempotent(sandbox, asset_server):
+ url, handler = asset_server
+ env = install_env(sandbox, url, good_digest(handler))
+ first = run_step(sandbox["install"], env)
+ second = run_step(sandbox["install"], env)
+
+ assert first[0] == 0, first[1]
+ assert second[0] == 0, second[1]
+ assert sandbox["github_path"].read_text().count("trusted-signing-cli") == 2
+
+
+def test_a_path_containing_spaces_still_works(tmp_path, asset_server):
+ url, handler = asset_server
+ spaced = tmp_path / "Program Files" / "runner temp"
+ spaced.mkdir(parents = True)
+ install = write_step_script(tmp_path, "Install trusted-signing-cli", "install.ps1")
+ github_path = tmp_path / "github_path"
+ github_path.write_text("", encoding = "utf-8")
+
+ code, out = run_step(
+ install,
+ {
+ "RUNNER_TEMP": str(spaced),
+ "GITHUB_PATH": str(github_path),
+ "TRUSTED_SIGNING_CLI_URL": url,
+ "TRUSTED_SIGNING_CLI_SHA256": good_digest(handler),
+ },
+ )
+
+ assert code == 0, out
+ assert (spaced / "trusted-signing-cli" / "trusted-signing-cli.exe").is_file()
+
+
+# ── every way it must fail closed ────────────────────────────────────────────
+
+
+def test_a_tampered_asset_fails_the_release(sandbox, asset_server):
+ url, _ = asset_server
+ code, out = run_step(sandbox["install"], install_env(sandbox, url, "0" * 64))
+
+ assert code != 0
+ assert "digest mismatch" in out
+ assert not installed_binary(sandbox).exists(), "a rejected binary was left on disk"
+ assert sandbox["github_path"].read_text().strip() == "", "PATH was published anyway"
+
+
+def test_a_truncated_download_fails_the_release(sandbox, asset_server):
+ url, handler = asset_server
+ handler.truncate = True
+ try:
+ code, out = run_step(sandbox["install"], install_env(sandbox, url, good_digest(handler)))
+ finally:
+ handler.truncate = False
+
+ assert code != 0
+ assert "digest mismatch" in out
+ assert not installed_binary(sandbox).exists()
+
+
+def test_an_unreachable_asset_fails_the_release(sandbox, asset_server):
+ url, handler = asset_server
+ handler.status = 404
+ try:
+ code, out = run_step(sandbox["install"], install_env(sandbox, url, good_digest(handler)))
+ finally:
+ handler.status = 200
+
+ assert code != 0
+ assert sandbox["github_path"].read_text().strip() == ""
+
+
+def test_a_dead_host_fails_the_release(sandbox):
+ code, out = run_step(
+ sandbox["install"],
+ install_env(sandbox, "http://127.0.0.1:9/nope.exe", "0" * 64),
+ )
+ assert code != 0
+ assert sandbox["github_path"].read_text().strip() == ""
+
+
+def test_an_empty_digest_pin_cannot_pass(sandbox, asset_server):
+ # A cleared or mistyped pin must not degrade into "accept anything".
+ url, _ = asset_server
+ code, out = run_step(sandbox["install"], install_env(sandbox, url, ""))
+ assert code != 0
+ assert not installed_binary(sandbox).exists()
+
+
+# ── the verify step ──────────────────────────────────────────────────────────
+
+
+def _fake_on_path(directory, name, script):
+ directory.mkdir(parents = True, exist_ok = True)
+ target = directory / name
+ target.write_text(script, encoding = "utf-8")
+ target.chmod(0o755)
+ return target
+
+
+def _real_exe_on_path(directory, source):
+ """Put a genuinely runnable executable at the verified name.
+
+ A shebang script cannot stand in: PATHEXT resolves a bare name only to a real
+ `.exe`, which is also what the verify step compares against. The branch under
+ test decides which real binary is borrowed.
+ """
+ directory.mkdir(parents = True, exist_ok = True)
+ target = directory / "trusted-signing-cli.exe"
+ shutil.copy2(source, target)
+ return target
+
+
+def _path_with(*directories):
+ return os.pathsep.join([*(str(d) for d in directories), os.environ["PATH"]])
+
+
+def test_verify_rejects_a_binary_that_was_never_digest_checked(sandbox, tmp_path):
+ # The rust-cache scenario: an identically named copy earlier on PATH that no
+ # digest gate saw. It spoofs the version string, which is what the old
+ # `--version` probe accepted.
+ decoy_dir = tmp_path / "cargo_bin"
+ _fake_on_path(
+ decoy_dir, "trusted-signing-cli", '#!/bin/sh\necho "trusted-signing-cli 0.10.0"\n'
+ )
+
+ code, out = run_step(
+ sandbox["verify"],
+ {
+ **sandbox["env"],
+ "PATH": _path_with(decoy_dir),
+ },
+ )
+
+ assert code != 0
+ assert "not the verified" in out
+
+
+def test_verify_fails_when_nothing_is_on_path(sandbox):
+ code, out = run_step(sandbox["verify"], sandbox["env"])
+ assert code != 0
+ assert "not on PATH" in out
+
+
+@needs_pathext
+def test_verify_fails_when_the_binary_cannot_start(sandbox):
+ # A truncated download: right name and place, not a loadable image. It must
+ # sit at the verified path, or the identity check rejects it first and the
+ # catch block is never reached.
+ directory = sandbox["runner_temp"] / "trusted-signing-cli"
+ directory.mkdir(parents = True)
+ (directory / "trusted-signing-cli.exe").write_bytes(b"\x00\x01not an executable")
+
+ code, out = run_step(sandbox["verify"], {**sandbox["env"], "PATH": _path_with(directory)})
+
+ assert code != 0
+ assert "could not be started" in out, out
+
+
+@needs_pathext
+def test_verify_fails_when_the_binary_exits_non_zero(sandbox):
+ # Starts fine, exits non-zero: where.exe given an option it does not take.
+ directory = sandbox["runner_temp"] / "trusted-signing-cli"
+ _real_exe_on_path(directory, pathlib.Path(os.environ["SystemRoot"], "System32", "where.exe"))
+
+ code, out = run_step(sandbox["verify"], {**sandbox["env"], "PATH": _path_with(directory)})
+
+ assert code != 0
+ assert "is on PATH but exited" in out, out
+
+
+@needs_pathext
+def test_verify_accepts_the_binary_it_installed(sandbox):
+ # The running interpreter answers --version and exits 0, which is all the
+ # verify step asks of the tool.
+ directory = sandbox["runner_temp"] / "trusted-signing-cli"
+ verified = _real_exe_on_path(directory, sys.executable)
+
+ code, out = run_step(sandbox["verify"], {**sandbox["env"], "PATH": _path_with(directory)})
+
+ assert code == 0, out
+ assert str(verified) in out, out
+
+
+def test_an_unverified_copy_ahead_on_path_is_rejected(sandbox, tmp_path):
+ # Rejecting direction of the ordering proof: a copy resolving ahead of the
+ # verified one must not be accepted. Prepending is what prevents it.
+ verified_dir = sandbox["runner_temp"] / "trusted-signing-cli"
+ _fake_on_path(
+ verified_dir, "trusted-signing-cli.exe", '#!/bin/sh\necho "trusted-signing-cli 0.10.0"\n'
+ )
+ decoy_dir = tmp_path / "cargo_bin"
+ _fake_on_path(
+ decoy_dir, "trusted-signing-cli", '#!/bin/sh\necho "trusted-signing-cli 0.10.0"\n'
+ )
+
+ code, out = run_step(
+ sandbox["verify"],
+ {
+ **sandbox["env"],
+ "PATH": _path_with(decoy_dir, verified_dir),
+ },
+ )
+
+ assert code != 0, "an unverified copy ahead on PATH was accepted"
+ assert "not the verified" in out
+
+
+def test_the_install_step_publishes_its_directory_for_path_prepending(sandbox, asset_server):
+ # $GITHUB_PATH prepends, so publishing the install dir is what puts the
+ # verified copy ahead of ~/.cargo/bin.
+ url, handler = asset_server
+ assert run_step(sandbox["install"], install_env(sandbox, url, good_digest(handler)))[0] == 0
+ published = sandbox["github_path"].read_text().strip()
+ assert published == str(sandbox["runner_temp"] / "trusted-signing-cli")
+
+
+# ── the real pinned asset, fetched over the network ──────────────────────────
+
+
+@needs_network
+def test_the_real_pinned_asset_matches_its_digest(sandbox):
+ url, digest = pinned()
+ code, out = run_step(sandbox["install"], install_env(sandbox, url, digest))
+
+ assert code == 0, out
+ downloaded = installed_binary(sandbox)
+ assert hashlib.sha256(downloaded.read_bytes()).hexdigest() == digest
+ assert downloaded.read_bytes()[:2] == b"MZ", "not a Windows executable"
+
+
+@needs_network
+def test_the_real_asset_is_a_64_bit_windows_console_binary(sandbox):
+ url, digest = pinned()
+ assert run_step(sandbox["install"], install_env(sandbox, url, digest))[0] == 0
+ data = installed_binary(sandbox).read_bytes()
+ offset = int.from_bytes(data[0x3C:0x40], "little")
+ assert data[offset : offset + 4] == b"PE\x00\x00"
+ assert int.from_bytes(data[offset + 4 : offset + 6], "little") == 0x8664, "not x86-64"
+
+
+@needs_network
+def test_the_real_asset_declares_the_arguments_the_signing_script_passes(sandbox):
+ # sign-with-trusted-signing.ps1 passes -e and -d; account and certificate
+ # profile come from the environment the release job sets.
+ url, digest = pinned()
+ assert run_step(sandbox["install"], install_env(sandbox, url, digest))[0] == 0
+ blob = installed_binary(sandbox).read_bytes()
+ for token in (
+ b"endpoint",
+ b"description",
+ b"AZURE_TRUSTED_SIGNING_ACCOUNT_NAME",
+ b"AZURE_CERTIFICATE_PROFILE_NAME",
+ b"AZURE_CLIENT_SECRET",
+ b"0.10.0",
+ ):
+ assert token in blob, token
+
+
+def test_the_signing_script_still_calls_the_tool_by_bare_name():
+ # Only reads a file in the tree. This is the contract that makes the PATH
+ # resolution above matter, so it runs in the default job.
+ script = REPO / "studio" / "src-tauri" / "windows" / "sign-with-trusted-signing.ps1"
+ text = script.read_text(encoding = "utf-8")
+ assert "& trusted-signing-cli @trustedSigningArgs" in text