Skip to content

Commit 0678b59

Browse files
ci(desktop): harden preview workflows per GitHub secure-use guidance
Pin every third-party action to a full commit SHA, disable credential persistence on checkouts, pass only the Apple signing secrets to the reusable build instead of inheriting all, and validate the untrusted js-bundle ZIP (allowed roots, regular files only, bounded size) before it reaches the signing runner. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent 210627f commit 0678b59

7 files changed

Lines changed: 271 additions & 38 deletions

File tree

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
"""Stage an untrusted preview ZIP without letting it replace packaging code."""
2+
3+
import shutil
4+
import stat
5+
import sys
6+
import zipfile
7+
from pathlib import Path
8+
9+
ROOTS = ("server/dist", "desktop/dist-electron")
10+
REQUIRED_FILES = {
11+
"server/dist/bin.mjs",
12+
"server/dist/client/index.html",
13+
"desktop/dist-electron/main.cjs",
14+
}
15+
# The current bundle is about 32 MiB compressed. Bound extraction on the
16+
# trusted runner even when the PR replaces the uploader entirely.
17+
MAX_ARCHIVE_BYTES = 512 * 1024 * 1024
18+
MAX_EXPANDED_BYTES = 2 * 1024 * 1024 * 1024
19+
MAX_ENTRIES = 50_000
20+
21+
22+
def stage_bundle(archive: Path, destination: Path):
23+
if archive.stat().st_size > MAX_ARCHIVE_BYTES:
24+
raise ValueError("Preview archive is too large")
25+
with zipfile.ZipFile(archive) as bundle:
26+
entries = bundle.infolist()
27+
if len(entries) > MAX_ENTRIES:
28+
raise ValueError("Preview archive has too many entries")
29+
if sum(entry.file_size for entry in entries) > MAX_EXPANDED_BYTES:
30+
raise ValueError("Expanded preview bundle is too large")
31+
seen = set()
32+
files = set()
33+
for entry in entries:
34+
name = entry.filename.removesuffix("/")
35+
parts = name.split("/")
36+
# Reject ambiguous paths before normalization, including names
37+
# that would alias on the macOS signing runner.
38+
if (
39+
entry.orig_filename != entry.filename
40+
or any(part in ("", ".", "..") for part in parts)
41+
or any(char in name for char in "\\:")
42+
or not name.isascii()
43+
or any(ord(char) < 32 or ord(char) == 127 for char in name)
44+
):
45+
raise ValueError(f"Unsafe preview path: {entry.filename!r}")
46+
allowed = any(name.startswith(root + "/") for root in ROOTS)
47+
if entry.is_dir():
48+
allowed |= any(root == name or root.startswith(name + "/") for root in ROOTS)
49+
if not allowed:
50+
raise ValueError(f"Unexpected preview path: {name!r}")
51+
kind = stat.S_IFMT(entry.external_attr >> 16)
52+
if kind not in (0, stat.S_IFDIR if entry.is_dir() else stat.S_IFREG):
53+
raise ValueError(f"Non-regular preview entry: {name!r}")
54+
if name.casefold() in seen:
55+
raise ValueError(f"Duplicate preview path: {name!r}")
56+
seen.add(name.casefold())
57+
if not entry.is_dir():
58+
files.add(name)
59+
if not REQUIRED_FILES <= files:
60+
raise ValueError("Preview bundle is missing required entry points")
61+
# Validate all names before writing anything. This is a fresh directory
62+
# outside the checkout; neither pre-existing links nor trusted files
63+
# can be followed or overwritten. ZIP permissions are never restored.
64+
destination.mkdir(parents=True, exist_ok=False)
65+
for entry in entries:
66+
target = destination / entry.filename
67+
if entry.is_dir():
68+
target.mkdir(parents=True, exist_ok=True)
69+
else:
70+
target.parent.mkdir(parents=True, exist_ok=True)
71+
with bundle.open(entry) as source, target.open("xb") as output:
72+
shutil.copyfileobj(source, output)
73+
74+
75+
if __name__ == "__main__":
76+
stage_bundle(Path(sys.argv[1]), Path(sys.argv[2]))
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
import importlib.util
2+
import stat
3+
import tempfile
4+
import unittest
5+
import zipfile
6+
from pathlib import Path
7+
from unittest.mock import patch
8+
9+
spec = importlib.util.spec_from_file_location(
10+
"stage_preview_bundle", Path(__file__).with_name("stage-preview-bundle.py")
11+
)
12+
staging = importlib.util.module_from_spec(spec)
13+
spec.loader.exec_module(staging)
14+
15+
16+
class StagePreviewBundleTests(unittest.TestCase):
17+
def setUp(self):
18+
self.temp = tempfile.TemporaryDirectory()
19+
self.addCleanup(self.temp.cleanup)
20+
self.root = Path(self.temp.name)
21+
self.archive = self.root / "bundle.zip"
22+
self.destination = self.root / "staged"
23+
24+
def bundle(self, extra=(), missing=None):
25+
with zipfile.ZipFile(self.archive, "w") as bundle:
26+
for name in sorted(staging.REQUIRED_FILES - {missing}):
27+
bundle.writestr(name, b"bundle data, never executed")
28+
for name, content in extra:
29+
bundle.writestr(name, content)
30+
31+
def stage(self):
32+
staging.stage_bundle(self.archive, self.destination)
33+
34+
def test_preserves_valid_bundle_layout_and_bytes(self):
35+
self.bundle([("server/", b""), ("server/dist/", b""),
36+
("desktop/dist-electron/chunks/helper.cjs", b"chunk")])
37+
self.stage()
38+
for name in staging.REQUIRED_FILES:
39+
self.assertEqual((self.destination / name).read_bytes(), b"bundle data, never executed")
40+
self.assertEqual((self.destination / "desktop/dist-electron/chunks/helper.cjs").read_bytes(), b"chunk")
41+
42+
def test_rejects_builder_overwrite_and_unsafe_paths_before_writing(self):
43+
for name in [
44+
"desktop/node_modules/electron-builder/cli.js",
45+
"desktop/package.json",
46+
"server/dist/../../desktop/package.json",
47+
"../package.json",
48+
"/server/dist/absolute",
49+
"server/dist/./alias",
50+
"server/dist//alias",
51+
"server/dist/back\\slash",
52+
"server/dist/file:stream",
53+
"server/dist/BIN.MJS",
54+
]:
55+
with self.subTest(name=name):
56+
self.bundle([(name, b"untrusted")])
57+
with self.assertRaises(ValueError):
58+
self.stage()
59+
self.assertFalse(self.destination.exists())
60+
61+
def test_rejects_links_and_special_files(self):
62+
for mode in [stat.S_IFLNK, stat.S_IFIFO, stat.S_IFCHR]:
63+
with self.subTest(mode=mode):
64+
entry = zipfile.ZipInfo("server/dist/link")
65+
entry.create_system = 3
66+
entry.external_attr = (mode | 0o777) << 16
67+
self.bundle([(entry, b"../../../desktop/node_modules")])
68+
with self.assertRaises(ValueError):
69+
self.stage()
70+
self.assertFalse(self.destination.exists())
71+
72+
def test_requires_entry_points(self):
73+
self.bundle(missing="desktop/dist-electron/main.cjs")
74+
with self.assertRaises(ValueError):
75+
self.stage()
76+
self.assertFalse(self.destination.exists())
77+
78+
def test_bounds_archive_size_expanded_size_and_entry_count(self):
79+
for limit in ["MAX_ARCHIVE_BYTES", "MAX_EXPANDED_BYTES", "MAX_ENTRIES"]:
80+
with self.subTest(limit=limit), patch.object(staging, limit, 1):
81+
self.bundle()
82+
with self.assertRaises(ValueError):
83+
self.stage()
84+
self.assertFalse(self.destination.exists())
85+
86+
def test_refuses_existing_destination(self):
87+
self.bundle()
88+
self.destination.mkdir()
89+
sentinel = self.destination / "trusted"
90+
sentinel.write_text("untouched")
91+
with self.assertRaises(FileExistsError):
92+
self.stage()
93+
self.assertEqual(sentinel.read_text(), "untouched")
94+
95+
96+
if __name__ == "__main__":
97+
unittest.main()

‎.github/workflows/ci.yml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,9 @@ jobs:
103103
sudo sed -i 's|http://|https://|g' /etc/apt/blacksmith-ubuntu-mirrors.txt /etc/apt/sources.list.d/ubuntu.sources
104104
sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config
105105
106+
- name: Test preview artifact validation
107+
run: python3 -B .github/scripts/stage-preview-bundle.test.py
108+
106109
- name: Test nightly release checks
107110
run: node --test .github/scripts/check-nightly-release.test.cjs
108111

‎.github/workflows/desktop-macos-preview-publish.yml‎

Lines changed: 45 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ jobs:
5050
steps:
5151
- id: pr
5252
name: Resolve the pull request behind the build
53-
uses: actions/github-script@v8
53+
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
5454
with:
5555
script: |
5656
const run = context.payload.workflow_run;
@@ -65,8 +65,9 @@ jobs:
6565
run_id: run.id,
6666
per_page: 100,
6767
});
68-
if (!artifacts.some((artifact) => artifact.name === "js-bundle" && !artifact.expired)) {
69-
core.info("The build run produced no js-bundle artifact. Skipping.");
68+
const bundles = artifacts.filter((artifact) => artifact.name === "js-bundle" && !artifact.expired);
69+
if (bundles.length !== 1) {
70+
core.info(`Expected one js-bundle artifact; found ${bundles.length}. Skipping.`);
7071
core.setOutput("eligible", "false");
7172
return;
7273
}
@@ -114,6 +115,7 @@ jobs:
114115
return;
115116
}
116117
118+
core.setOutput("artifact_id", String(bundles[0].id));
117119
core.setOutput("eligible", "true");
118120
core.setOutput("pr_number", String(pull.number));
119121
core.setOutput("head_sha", pull.head.sha);
@@ -124,7 +126,7 @@ jobs:
124126
- id: vouch
125127
name: Check PR author trust
126128
if: steps.pr.outputs.eligible == 'true'
127-
uses: mitchellh/vouch/action/check-user@v1
129+
uses: mitchellh/vouch/action/check-user@d66fa29a64600490892131ad87597c30c91fcac4 # v1
128130
with:
129131
user: ${{ steps.pr.outputs.author }}
130132
allow-fail: true
@@ -199,21 +201,33 @@ jobs:
199201
echo "${output}=${value}" >> "$GITHUB_OUTPUT"
200202
done
201203
202-
# release-desktop.yml downloads `js-bundle` from its own run, so the PR
203-
# build's bundle is re-published under this run. It is copied as data
204-
# and never executed here.
205-
- name: Download PR JS bundle
204+
# Only the default-branch revision that owns this workflow supplies the
205+
# validator. Never check out the PR in a workflow_run job.
206+
- name: Checkout trusted artifact validator
206207
if: steps.gate.outputs.eligible == 'true'
207-
uses: actions/download-artifact@v8
208+
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
208209
with:
209-
name: js-bundle
210-
path: ${{ runner.temp }}/js-bundle
211-
github-token: ${{ secrets.GITHUB_TOKEN }}
212-
run-id: ${{ github.event.workflow_run.id }}
210+
ref: ${{ github.sha }}
211+
persist-credentials: false
212+
sparse-checkout: .github/scripts
213213

214+
# Fetch the archive as bytes. Extracting it over the checkout, even with
215+
# download-artifact, could replace code that runs with signing secrets.
216+
- name: Download and validate PR JS bundle
217+
if: steps.gate.outputs.eligible == 'true'
218+
shell: bash
219+
env:
220+
GH_TOKEN: ${{ github.token }}
221+
ARTIFACT_ID: ${{ steps.pr.outputs.artifact_id }}
222+
run: |
223+
set -euo pipefail
224+
gh api "repos/${GITHUB_REPOSITORY}/actions/artifacts/${ARTIFACT_ID}/zip" > "$RUNNER_TEMP/js-bundle.zip"
225+
python3 .github/scripts/stage-preview-bundle.py "$RUNNER_TEMP/js-bundle.zip" "$RUNNER_TEMP/js-bundle"
226+
227+
# Only validated bundle files cross into the signing job's artifact.
214228
- name: Stage JS bundle for packaging
215229
if: steps.gate.outputs.eligible == 'true'
216-
uses: actions/upload-artifact@v7
230+
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
217231
with:
218232
name: js-bundle
219233
path: ${{ runner.temp }}/js-bundle
@@ -230,10 +244,16 @@ jobs:
230244
group: desktop-macos-preview-${{ needs.resolve.outputs.pr_number }}-build
231245
cancel-in-progress: true
232246
uses: ./.github/workflows/release-desktop.yml
233-
secrets: inherit
247+
secrets:
248+
CSC_LINK: ${{ secrets.CSC_LINK }}
249+
CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
250+
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
251+
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
252+
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
253+
MACOS_PROVISIONING_PROFILE: ${{ secrets.MACOS_PROVISIONING_PROFILE }}
234254
with:
235255
version: ${{ needs.resolve.outputs.version }}
236-
ref: ${{ github.event.repository.default_branch }}
256+
ref: ${{ github.sha }}
237257
release_channel: preview
238258
relay_client_tracing: false
239259
clerk_publishable_key: ${{ needs.resolve.outputs.clerk_publishable_key }}
@@ -270,7 +290,7 @@ jobs:
270290
pull-requests: write
271291
steps:
272292
- name: Download macOS artifacts
273-
uses: actions/download-artifact@v8
293+
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
274294
with:
275295
name: desktop-mac-arm64
276296
path: release
@@ -362,7 +382,7 @@ jobs:
362382
363383
- name: Comment download link
364384
if: steps.upload.outputs.download_url != ''
365-
uses: actions/github-script@v8
385+
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
366386
env:
367387
PR_NUMBER: ${{ needs.resolve.outputs.pr_number }}
368388
DOWNLOAD_URL: ${{ steps.upload.outputs.download_url }}
@@ -406,7 +426,9 @@ jobs:
406426
issue_number: prNumber,
407427
per_page: 100,
408428
});
409-
const existing = comments.find((comment) => comment.body?.includes(marker));
429+
const existing = comments.find(
430+
(comment) => comment.user?.login === "github-actions[bot]" && comment.body?.includes(marker),
431+
);
410432
411433
if (existing) {
412434
await github.rest.issues.updateComment({
@@ -479,7 +501,7 @@ jobs:
479501
480502
- name: Mark the preview comment as removed
481503
if: steps.delete.outputs.removed == 'true'
482-
uses: actions/github-script@v8
504+
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
483505
with:
484506
script: |
485507
const marker = "<!-- desktop-macos-preview -->";
@@ -489,7 +511,9 @@ jobs:
489511
issue_number: context.payload.pull_request.number,
490512
per_page: 100,
491513
});
492-
const existing = comments.find((comment) => comment.body?.includes(marker));
514+
const existing = comments.find(
515+
(comment) => comment.user?.login === "github-actions[bot]" && comment.body?.includes(marker),
516+
);
493517
if (!existing) {
494518
return;
495519
}

‎.github/workflows/desktop-macos-preview.yml‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,16 +31,17 @@ jobs:
3131
timeout-minutes: 30
3232
steps:
3333
- name: Checkout
34-
uses: actions/checkout@v6
34+
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
3535
with:
3636
ref: ${{ github.event.pull_request.head.sha }}
37+
persist-credentials: false
3738
sparse-checkout: |
3839
/*
3940
!/.repos/
4041
sparse-checkout-cone-mode: false
4142

4243
- name: Setup Vite+
43-
uses: voidzero-dev/setup-vp@v1
44+
uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1
4445
with:
4546
node-version-file: package.json
4647
cache: true
@@ -74,7 +75,7 @@ jobs:
7475
# Same layout as release.yml's js-bundle so release-desktop.yml can
7576
# package it unchanged.
7677
- name: Upload JS bundle
77-
uses: actions/upload-artifact@v7
78+
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
7879
with:
7980
name: js-bundle
8081
path: |

0 commit comments

Comments
 (0)