@rightkit/ci 0.2.45 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +90 -3
- package/artifacts.mjs +290 -0
- package/artifacts.test.mjs +168 -0
- package/checkout.test.mjs +1 -0
- package/cli/right-git.mjs +4 -0
- package/guard-coverage.test.mjs +1 -0
- package/manifest.mjs +545 -30
- package/manifest.schema.json +138 -6
- package/manifest.test.mjs +48 -0
- package/orkflows.test.mjs +0 -0
- package/package.json +2 -2
- package/render.test.mjs +362 -27
- package/supersede.mjs +127 -0
- package/supersede.test.mjs +84 -0
- package/swift-check.test.mjs +95 -0
- package/sync.mjs +4 -1
- package/templates/ci.yml +4 -4
- package/templates/profiles/rust-hybrid/ci.yml +4 -4
- package/templates/profiles/rust-hybrid/release-candidate.yml +2 -1
- package/templates/profiles/rust-hybrid/sign-existing.yml +36 -0
- package/templates/swift-check.yml +85 -0
- package/workflows.mjs +638 -0
- package/workflows.test.mjs +213 -0
package/README.md
CHANGED
|
@@ -12,11 +12,12 @@ Public-repository-only GitHub Actions workflow layer for Right Suite products. T
|
|
|
12
12
|
## Commands
|
|
13
13
|
|
|
14
14
|
- `right-git install <repo> --lanes ci,...` writes `.rightgit.json` and renders workflows.
|
|
15
|
-
- Lanes: `ci`, `qualification`, `package-smoke`, `release-candidate`, `publish-npm`, `publish-package-managers`, `regenerate`. The `regenerate` lane is manual-only: it runs `regenerate.script`, checks the result, and opens a pull request from a `right-git/regenerate-<run>` branch; it never writes to the default branch.
|
|
15
|
+
- Lanes: `ci`, `qualification`, `package-smoke`, `release-candidate`, `publish-npm`, `publish-package-managers`, `regenerate`, `swift-check`. The `regenerate` lane is manual-only: it runs `regenerate.script`, checks the result, and opens a pull request from a `right-git/regenerate-<run>` branch; it never writes to the default branch.
|
|
16
16
|
- `right-git sync` re-renders installed workflows from the manifest.
|
|
17
17
|
- `right-git drift --all` checks installed workflows against templates and re-checks visibility. When the manifest declares the `regenerate` lane, drift also warns (never fails) if the repository's "Allow GitHub Actions to create and approve pull requests" setting is off. It reads `gh api repos/{owner}/{repo}/actions/permissions/workflow` and prints a note instead when gh is unavailable.
|
|
18
18
|
- `right-git adopt` maps an existing repository's workflows onto lanes for review. With `--out <dir>` it writes the candidate templates to that directory.
|
|
19
19
|
- `right-git uninstall` removes every managed file.
|
|
20
|
+
- `right-git artifacts fetch --run <id> --out <dir> [--name <glob>] [--repo owner/repo] [--expect-sha256 <hex> [--file <path>]] [--receipt <file>] [--json]` downloads the artifacts of one workflow run through `gh`, merges them into one tree and writes a JSON receipt (see Fetch CI artifacts).
|
|
20
21
|
|
|
21
22
|
`install` and `sync` refuse private, internal and unconfirmed-visibility repositories. There is no override flag.
|
|
22
23
|
|
|
@@ -95,21 +96,44 @@ Both keys are opt-in; unset, the rendered `ci.yml` is byte-identical.
|
|
|
95
96
|
- `windows: "unsigned"` needs `windowsGlob` and a `windows-*` runner in the ci gate; matched files upload as `dev-windows-<sha>`.
|
|
96
97
|
- The `dev-mac-sign` job uses the `release` environment, so that environment's protection rules (required reviewers, branch policy) apply. The job only exists for pushes to the default branch.
|
|
97
98
|
- Install a mac dev build with `right-release install-app --dev --zip <file>` (Developer ID-signed, not notarized).
|
|
99
|
+
- `devArtifact.macSignManifest` (with `macPayloadMetadata`) replaces `codesign --deep` on the `.app` with `right-release sign-dev-artifact`: each file in the repository-relative sign manifest (`{ "schema": 1, "entries": [{ "file": "Legion.app/Contents/MacOS/legion", "identifier": "com.example.legion" }] }`, paths relative to the extracted archive, nested code before its bundle) is signed with its fixed identifier, the archive's payload metadata (`macPayloadMetadata`, relative to the archive root) is verified before and refreshed after signing, and `sign-evidence.json` is uploaded beside the zip. The job then also checks out the repo and installs dependencies, so `@rightkit/release` 0.2.172 or later must be a dependency. Requires `mac: "sign"`; not combinable with `macEntitlements` (put per-file entitlements in the manifest) or `mac: "notarize"`. Unset keeps the `--deep` lane.
|
|
98
100
|
- `devArtifact.parallel: true` moves each platform's build into its own job, `dev-artifact-mac` or `dev-artifact-windows`. Each runs beside the QA gate job instead of after it, needs only the private-repo guard, and compiles the dev app with `devArtifact.buildScript` (a package script name; required with `parallel`, rejected without it) before staging it. Parallel jobs run on their own platform runners, so they do not need `ciAllOs`. `mac: "sign"` still waits for the gate: `dev-mac-sign` needs `ci` and `dev-artifact-mac`. The trade-off: unsigned uploads no longer wait for the gate, so a failing gate can still leave `dev-windows-<sha>` or `dev-mac-unsigned-<sha>` behind. Unset or `false` keeps the staging inside the gate job.
|
|
99
101
|
- The `~/Library/Developer/Xcode/DerivedData` cache helps only builds that use Xcode's default derived data location. A gate that passes its own `-derivedDataPath` writes outside that directory and gets nothing from the cache; use the default location, or cache the custom path in the gate.
|
|
100
102
|
|
|
103
|
+
## Sign an existing artifact (rust-hybrid, `sign-existing` lane)
|
|
104
|
+
|
|
105
|
+
For a public repository whose signing must run on protected CI, but whose artifact was already built and qualified by an earlier run. The lane never rebuilds, never uses `--release` and never notarizes.
|
|
106
|
+
|
|
107
|
+
```json
|
|
108
|
+
{
|
|
109
|
+
"lanes": ["ci", "sign-existing"],
|
|
110
|
+
"signExisting": {
|
|
111
|
+
"macSignManifest": "build/dev-sign.json",
|
|
112
|
+
"macPayloadMetadata": "payload.json",
|
|
113
|
+
"environment": "release"
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
- `macSignManifest` (repository-relative) and `macPayloadMetadata` (relative to the extracted artifact, and outside every signed bundle: `right-release sign-dev-artifact` refuses metadata inside a signed `.app`, because refreshing it after signing would break that signature) are the same as for `devArtifact.macSignManifest`; `environment` is optional and defaults to the signing environment (`release`). `matrix.os` needs a macOS runner; the first one is used.
|
|
119
|
+
- `signExisting.macPayloadMetadataSource` (optional, repository-relative, for example `dist/dev-macos/payload.json`) makes the unsigned dev packaging step put the payload metadata inside the inner zip. The step stages the `.app` (wrapper layout kept, copied with `ditto`) and that file together and zips them, so the file sits at the inner-zip root under the file name `macPayloadMetadata`, which must then be a bare name such as `payload.json`; the step fails if the file is missing. This applies to every macOS unsigned packaging step (`devArtifact.mac` `sign`, `notarize` or `unsigned`, in the gate job or the parallel `dev-artifact-mac` job). Unset, the step is the single `ditto -c -k --keepParent` line and the render is byte-identical. The app generates the file itself; Legion writes it with `fileEvidence` from `@rightkit/release/macos-file-evidence.mjs`, so its hashes use the same file and bundle-tree digests that `sign-dev-artifact` verifies.
|
|
120
|
+
- Invoke it from the default branch: `gh workflow run sign-existing.yml -f run_id=39001031529 -f artifact=12089612527 -f source_sha=59f451ae`. `artifact` is a numeric artifact id or an artifact name (all digits means id). `source_sha` is 7 to 40 lowercase hex characters and must be a prefix of the run's full head sha.
|
|
121
|
+
- The job refuses, before it downloads the artifact or reads a secret, unless the GitHub API shows that the run belongs to this repository, was built from it (not a fork), completed successfully and has a head sha starting with `source_sha`; that exactly one unexpired artifact of that run matches and records the same run, head sha and repository; and that the source commit is an ancestor of the signing revision (the default-branch commit that runs the job, which also supplies the signing code and sign manifest).
|
|
122
|
+
- The artifact must hold one zip (extracted with `ditto`) or a plain file tree. The job signs it with `right-release sign-dev-artifact`, then uploads `signed-<artifact name>-<sha>` containing the signed zip (same layout), `sign-evidence.json` and `source-verification.json`. It uses the same three Developer ID secrets and temporary keychain as `dev-mac-sign`, with `contents: read` and `actions: read` only. Needs `@rightkit/release` 0.2.172 or later as a dependency. Unset, nothing changes.
|
|
123
|
+
|
|
101
124
|
## Cache keys and concurrency (rust-hybrid)
|
|
102
125
|
|
|
103
126
|
Both keys are opt-in; unset, the rendered workflows are byte-identical.
|
|
104
127
|
|
|
105
128
|
- `rustCache.keySuffix` (1 to 64 characters: letters, digits, `.`, `_`, `-`; starts with a letter or digit) renders `key: <lane>-<suffix>` into every Swatinem/rust-cache step: `ci`, `regenerate`, `release-candidate`. Each lane therefore keeps its own cache entry. The dev-artifact jobs use `<lane>-dev-artifact-<platform>-<suffix>`. Swatinem/rust-cache does not re-save a cache on an exact key hit (third-party behavior, not verified in this repository). To rotate the cache, change the suffix, which gives it a new key.
|
|
106
|
-
- `concurrency
|
|
129
|
+
- `concurrency` (requires lane `ci`; both profiles). The rule is one CI run in progress per repository. By default (`mainPushes: "cancel"`) the ci workflow renders a `supersede` job, the only job with `actions: write`, which runs `supersede.mjs`: a newer push to the default branch cancels an older run of the workflow that never started, has a failed job, or is younger than `graceFraction` (default 0.7) of the median duration of the last `medianWindow` (default 10) successful runs. An older run past that point is left to finish, and the new run's `ci` job waits for it through a job-level group with `cancel-in-progress: false`. PR runs still cancel superseded runs.
|
|
130
|
+
- `concurrency.mainPushes: "queue"` is the opt-out: default-branch pushes each run to completion, no `supersede` job is rendered, and a non-empty single-line `concurrency.reason` is required (the manifest is invalid without one). The reason is rendered as a YAML comment above the `concurrency` block. `graceFraction` and `medianWindow` are not allowed with `queue`. The publish workflow never cancels.
|
|
107
131
|
|
|
108
132
|
```json
|
|
109
133
|
{
|
|
110
134
|
"profile": "rust-hybrid",
|
|
111
135
|
"rustCache": { "workspaces": ["engine"], "keySuffix": "2026-10" },
|
|
112
|
-
"concurrency": { "mainPushes": "queue" },
|
|
136
|
+
"concurrency": { "mainPushes": "queue", "reason": "deploys must see every main commit built in turn" },
|
|
113
137
|
"devArtifact": {
|
|
114
138
|
"mac": "unsigned",
|
|
115
139
|
"windows": "unsigned",
|
|
@@ -121,6 +145,10 @@ Both keys are opt-in; unset, the rendered workflows are byte-identical.
|
|
|
121
145
|
}
|
|
122
146
|
```
|
|
123
147
|
|
|
148
|
+
## Dev qualification (rust-hybrid release-candidate)
|
|
149
|
+
|
|
150
|
+
`candidate.devQualification: { "buildScript": "...", "journeyScript": "..." }` adds a `dev-qualification` job beside the QA-free candidate (bogusyogi/rightkit#107). `@rightkit/release` refuses `qa-native`, `qa-control`, `dev-native`, `dev-inspect` and `test-mode` in any release tier, so in-app journeys cannot run against the sealed candidate. The job needs `admission`, uses the candidate's target matrix, checks out the same `source_revision`, runs `buildScript` (the dev build, QA surface on) and then `journeyScript`, and uploads its evidence as `<prefix>-<run>-<attempt>-devqual-<platform>-<arch>-<version>-<revision><suffix>` plus a `dev-qualification` stage summary. When set, `windows-sign` and `macos-sign` need it, so a failure blocks signing. Installed qualification of the signed candidate is unchanged. Unset, the workflow is byte-identical. Validation refuses a candidate build or check script whose name mentions a QA surface and a `devQualification.buildScript` equal to `candidate.buildScript`; it cannot see cargo features inside a script.
|
|
151
|
+
|
|
124
152
|
## Private Swift packages (ci, qualification, release-candidate, regenerate lanes)
|
|
125
153
|
|
|
126
154
|
Set `swift.privatePackages` to let a public repository's workflows fetch a private Swift package, for example `example-org/private-swift-package`:
|
|
@@ -155,6 +183,38 @@ Never rendered: `package-smoke` (a clean-room tarball check), `publish-npm` and
|
|
|
155
183
|
|
|
156
184
|
Release policy. `@rightkit/release` enforces the `right-git-ci-only` policy over the rendered workflows (`validateHostedWorkflows` in `release.mjs`). It refuses a managed workflow that references any secret outside an allowlist. The allowlist admits the `swift.privatePackages` secret only on its `RIGHT_GIT_PRIVATE_TOKEN_<n>: ${{ secrets.<NAME> }}` env line, inside the "Configure private Swift package access" or "Remove private Swift package access" step, of these jobs: `ci.yml` jobs `ci` (either profile), `dev-artifact-mac` (rust-hybrid with `devArtifact.parallel` and a `devArtifact.mac` leg) and `test` (node profile); `qualification.yml` job `qualification`; `release-candidate.yml` job `candidate`; and `regenerate.yml` job `regenerate` (`SWIFT_PRIVATE_JOBS`, `release.mjs:86-91`). Each reference also needs its lane listed in `.rightgit.json`, `devArtifact.dispatch` not true, and no `pull_request_target` or `workflow_run` trigger. `workflow_dispatch` is allowed only in `release-candidate.yml` and `regenerate.yml` (`swiftPrivateSecretRefusal`, `release.mjs`).
|
|
157
185
|
|
|
186
|
+
## Named workflows: custom, swift-host and dispatch-matrix
|
|
187
|
+
|
|
188
|
+
The `workflows` block renders named workflow files beside the lane files (`right-git sync`, `drift` and `uninstall` treat them like lane files; the file starts with the managed marker). Each entry has a `kind`. Every kind renders: top-level `permissions: contents: read`, a `private-repo-guard` job that every job needs, actions pinned to commit SHAs, `persist-credentials: false` on every checkout, the shared ownership scan (skipped on Linux runners, which ownership approval does not support) after the pinned package-manager install, and no `secrets` reference. Steps may not mention `secrets` or interpolate untrusted event data (`github.head_ref`, `github.event.pull_request.*` and similar); `workflow_dispatch` inputs reach scripts as `RIGHT_GIT_INPUT_<NAME>` environment variables. The node and package-manager setup, install and ownership steps come from the manifest's `matrix.node[0]` and `packageManager`, so a sparse checkout must keep `package.json`, the lockfile and whatever the install needs (cone mode keeps root files).
|
|
189
|
+
|
|
190
|
+
Common fields: `file` (default `<name>.yml`; never a built-in lane filename), `on` (`push` and `pull_request`: `true` or `{ branches, paths }`; `workflow_dispatch: true`), `concurrency` (`{ group, cancelInProgress }`, rendered as `<group>-${{ github.ref }}`), `checkout` (`{ sparse, longPaths }`, replaces the global `checkout` for this workflow), `timeoutMinutes` (default 60).
|
|
191
|
+
|
|
192
|
+
**`custom`** (Orthic-Labs/rightkit#465): `runsOn` (one label or several, which become a matrix), `toolchain` (`rust`: `stable`, `beta`, `nightly` or an exact version, rendered as the pinned `dtolnay/rust-toolchain` `toolchain:` input; `swift`: see below), `steps` (`{ name?, shell: bash|pwsh, workingDirectory?, run }`) and `artifact` (`{ name, path, retentionDays 1-90 (default 14), ifNoFilesFound error|warn|ignore (default error), when success|always }`). Artifact names accept the tokens `{sha}`, `{run_id}`, `{run_attempt}`, `{os}` and `{matrix.<key>}`; with several runners the name must carry `{os}`.
|
|
193
|
+
|
|
194
|
+
```json
|
|
195
|
+
{ "workflows": { "render-windows": {
|
|
196
|
+
"kind": "custom", "file": "render-windows.yml", "runsOn": "windows-2025",
|
|
197
|
+
"on": { "push": { "branches": ["main"], "paths": ["render/**"] }, "workflow_dispatch": true },
|
|
198
|
+
"concurrency": { "group": "render-windows", "cancelInProgress": false },
|
|
199
|
+
"checkout": { "sparse": ["render"], "longPaths": true },
|
|
200
|
+
"toolchain": { "rust": "1.91.0" },
|
|
201
|
+
"steps": [{ "name": "Unit tests", "shell": "pwsh", "workingDirectory": "render", "run": "cargo test --release" }],
|
|
202
|
+
"artifact": { "name": "swiftright-render-{sha}", "path": "render/target/release/render.dll", "retentionDays": 30 }
|
|
203
|
+
} } }
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
**`swift-host`** (Orthic-Labs/rightkit#437): `os` (for example `["windows-2025", "macos-15"]`, rendered as a matrix), `packages` (one `swift test` step per package directory), optional `swiftArgs` (plain options such as `--parallel`), `toolchain.swift` (required when `os` has a Windows runner) and an optional `artifact`. `on` defaults to push on the default branch plus `pull_request`.
|
|
207
|
+
|
|
208
|
+
**`dispatch-matrix`** (Orthic-Labs/rightkit#437): `on.workflow_dispatch: true`, `inputs` (`{ description, type string|boolean|choice, default, required, options }`), `plan` (`{ shell, run, runsOn?, workingDirectory? }`; the script writes `matrix=<JSON>` to `$GITHUB_OUTPUT`), `jobs` (up to 6 per-item jobs `{ id, runsOn, toolchain?, steps, artifact? }`, each run once per matrix entry, artifact names carrying `{matrix.<key>}`) and an optional `collect` job (`{ runsOn?, download: { pattern, path }, steps }`, which runs after the item jobs and only when the guard passed).
|
|
209
|
+
|
|
210
|
+
**`swift-toolchain` step** (Orthic-Labs/rightkit#436): `toolchain.swift = { version, sha256 }` renders, on Windows runners only, `<pm> exec right-release toolchain swift --version <v> --sha256 <pin> --github-env`. The installer's sha256 is verified before it runs, and `--github-env` exports what the installer changed to `GITHUB_ENV` and `GITHUB_PATH` for the later steps. The repository must depend on `@rightkit/release` (the same dependency the ownership scan needs). The step builder is exported as `swiftToolchainStep` from `workflows.mjs`.
|
|
211
|
+
|
|
212
|
+
`@rightkit/release`'s `right-git-ci-only` policy accepts only `<lane>.yml` files for the declared lanes, so a repository that declares `workflows` fails its release check until that policy also accepts the files named by `workflows` (needs an update in the release package).
|
|
213
|
+
|
|
214
|
+
## Fetch CI artifacts
|
|
215
|
+
|
|
216
|
+
`right-git artifacts fetch --run <id> --out <dir>` lists the run's artifacts (`gh api`), keeps those matching `--name` (a glob with `*` and `?`; default all), downloads each by exact name into a staging directory next to `<dir>`, and merges them into `<dir>`. Two artifacts that disagree about a file's bytes fail the fetch. `--repo owner/repo` selects the repository (default: the current checkout's). `--expect-sha256 <hex>` is verified before anything reaches `<dir>`: with `--file <relative path>` it pins that one file (the renderer DLL, for example); without it, the tree digest (sha256 over the sorted lines `<sha256> <path>`). A mismatch, an expired or unsafe-named artifact, a symbolic link or a failed download exits 1 and leaves `<dir>` untouched. `--receipt <file>` writes the JSON receipt (`schema right-git.artifacts-receipt/1`: run, repo, name pattern, per-artifact files with sizes and sha256, `fileCount`, `treeSha256`, `pin`, `verified`); `--json` prints it.
|
|
217
|
+
|
|
158
218
|
## Entry points
|
|
159
219
|
|
|
160
220
|
No importable API. The package has no `main` and no `exports` map. The supported surface is the `right-git` bin.
|
|
@@ -176,3 +236,30 @@ pnpm exec right-git drift --all
|
|
|
176
236
|
- The optional `publish-package-managers` lane needs two long-lived tokens in GitHub Actions secrets. Their names and scope are in the package templates, and they are not zero-exposure. Read `docs/rules/github-access.md` in the workspace before enabling it.
|
|
177
237
|
- Manifest fields are charset-checked before they reach workflow YAML.
|
|
178
238
|
- `swift.privatePackages` renders a secret reference into the workflows listed in its section. The `right-git-ci-only` policy in `@rightkit/release` refuses any reference outside the jobs listed under Release policy above.
|
|
239
|
+
|
|
240
|
+
## Native iOS XCTest (`swift-check`)
|
|
241
|
+
|
|
242
|
+
Use `lanes: ["swift-check"]` with default `node` profile for standalone Swift validation. Existing `ci` stays optional for this profile. Configure native tools & paths in `.rightgit.json`:
|
|
243
|
+
|
|
244
|
+
```json
|
|
245
|
+
{
|
|
246
|
+
"swift": {
|
|
247
|
+
"check": {
|
|
248
|
+
"runner": "macos-15",
|
|
249
|
+
"xcodeVersion": "16.4",
|
|
250
|
+
"projectDirectory": "ios",
|
|
251
|
+
"spec": "project.yml",
|
|
252
|
+
"project": "Widgets.xcodeproj",
|
|
253
|
+
"scheme": "Widgets",
|
|
254
|
+
"xcodegenVersion": "2.44.1"
|
|
255
|
+
},
|
|
256
|
+
"privatePackages": [{ "host": "github.com", "secret": "SWIFT_READ_TOKEN" }]
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
Versions above illustrate configuration; choose exact versions provisioned on selected hosted runner. Xcode & XcodeGen must already match; missing tools or version drift fail before generation. This lane installs no native tools. `projectDirectory` is repository-relative; spec & project paths are relative to that directory. Scheme names permit letters, digits, `.`, `_` & `-`.
|
|
262
|
+
|
|
263
|
+
Lane checks out without persisted GitHub credentials, installs pinned package-manager dependencies, runs shared ownership scan, verifies native tools, configures shared private-package access, generates project, discovers available iPhone simulator, then runs Debug XCTest with `-scmProvider system` & `CODE_SIGNING_ALLOWED=NO`. Repository must directly depend on published `@rightkit/release` for ownership scan. Credentials remain step-scoped & cleanup always runs before `.xcresult` upload. Fork pull requests fail closed when declared private-package secret is unavailable. Owner provisions a read-only credential limited to required private repositories.
|
|
264
|
+
|
|
265
|
+
Only push to configured default branch & `pull_request` trigger this lane. Workflow requests `contents: read`, pins actions to full commit SHAs & includes public-repository refusal guard. `swift.privatePackages` is optional for public-only dependencies. Omit `swift.check` & lane to preserve existing workflow bytes.
|
package/artifacts.mjs
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
// `right-git artifacts fetch`: download the artifacts of one workflow run through `gh`, merge them into one
|
|
2
|
+
// output tree, verify a sha256 pin, and write a JSON receipt (Orthic-Labs/rightkit#439).
|
|
3
|
+
//
|
|
4
|
+
// right-git artifacts fetch --run <id> --out <dir> [--name <glob>] [--repo owner/repo]
|
|
5
|
+
// [--expect-sha256 <hex> [--file <relative path>]] [--receipt <file>]
|
|
6
|
+
//
|
|
7
|
+
// Artifacts are listed first (gh api), filtered by the name glob, then each one is downloaded by its immutable
|
|
8
|
+
// numeric artifact id (gh api .../artifacts/<id>/zip, never by the mutable name) into a staging directory next
|
|
9
|
+
// to <dir>. Nothing reaches <dir> until every artifact downloaded, no two artifacts disagree about a file, the
|
|
10
|
+
// pin matched, and the receipt path does not collide with a fetched file. Files are then placed through
|
|
11
|
+
// no-follow destination checks (a symbolic link in any destination component refuses the fetch). A mismatch
|
|
12
|
+
// removes the staging directory and leaves <dir> as it was.
|
|
13
|
+
//
|
|
14
|
+
// The pin: with --file it is the sha256 of that one file in the merged tree (the renderer DLL, say); without it,
|
|
15
|
+
// the tree digest: sha256 over the lines "<sha256> <relative path>\n" of every file, sorted by path.
|
|
16
|
+
|
|
17
|
+
import fs from "node:fs";
|
|
18
|
+
import path from "node:path";
|
|
19
|
+
import crypto from "node:crypto";
|
|
20
|
+
import { execFile as execFileCb } from "node:child_process";
|
|
21
|
+
import { promisify } from "node:util";
|
|
22
|
+
|
|
23
|
+
const execFileAsync = promisify(execFileCb);
|
|
24
|
+
const RUN_ID_RE = /^[0-9]{1,20}$/;
|
|
25
|
+
const NAME_GLOB_RE = /^[A-Za-z0-9._*?-]{1,120}$/;
|
|
26
|
+
const REPO_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]{1,100}$/;
|
|
27
|
+
const SHA256_RE = /^[0-9a-f]{64}$/;
|
|
28
|
+
const ARTIFACT_NAME_RE = /^[A-Za-z0-9._-]{1,120}$/;
|
|
29
|
+
export const RECEIPT_SCHEMA = "right-git.artifacts-receipt/1";
|
|
30
|
+
|
|
31
|
+
function fail(code, message) {
|
|
32
|
+
const error = new Error(message);
|
|
33
|
+
error.code = code;
|
|
34
|
+
return error;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Glob (`*`, `?`) to an anchored RegExp. */
|
|
38
|
+
export function globToRegExp(glob) {
|
|
39
|
+
const source = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
|
|
40
|
+
return new RegExp(`^${source}$`);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Parse and validate argv for `artifacts fetch`. Throws a coded Error on bad input. */
|
|
44
|
+
export function parseFetchArgs(argv) {
|
|
45
|
+
const opts = {};
|
|
46
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
47
|
+
const arg = argv[i];
|
|
48
|
+
const value = () => {
|
|
49
|
+
if (i + 1 >= argv.length || argv[i + 1].startsWith("--")) throw fail("ARTIFACTS_USAGE", `${arg} needs a value`);
|
|
50
|
+
i += 1;
|
|
51
|
+
return argv[i];
|
|
52
|
+
};
|
|
53
|
+
if (arg === "--run") opts.run = value();
|
|
54
|
+
else if (arg === "--out") opts.out = value();
|
|
55
|
+
else if (arg === "--name") opts.name = value();
|
|
56
|
+
else if (arg === "--repo") opts.repo = value();
|
|
57
|
+
else if (arg === "--expect-sha256") opts.expectSha256 = value().toLowerCase();
|
|
58
|
+
else if (arg === "--file") opts.file = value();
|
|
59
|
+
else if (arg === "--receipt") opts.receipt = value();
|
|
60
|
+
else if (arg === "--json") opts.json = true;
|
|
61
|
+
else throw fail("ARTIFACTS_USAGE", `unknown option: ${arg}`);
|
|
62
|
+
}
|
|
63
|
+
if (!opts.run || !RUN_ID_RE.test(opts.run)) throw fail("ARTIFACTS_USAGE", "--run <numeric run id> is required");
|
|
64
|
+
if (!opts.out) throw fail("ARTIFACTS_USAGE", "--out <dir> is required");
|
|
65
|
+
if (opts.name !== undefined && !NAME_GLOB_RE.test(opts.name)) throw fail("ARTIFACTS_USAGE", "--name must be a glob of letters, digits, '.', '_', '-', '*', '?'");
|
|
66
|
+
if (opts.repo !== undefined && !REPO_RE.test(opts.repo)) throw fail("ARTIFACTS_USAGE", "--repo must be owner/repo");
|
|
67
|
+
if (opts.expectSha256 !== undefined && !SHA256_RE.test(opts.expectSha256)) throw fail("ARTIFACTS_USAGE", "--expect-sha256 must be 64 hex characters");
|
|
68
|
+
if (opts.file !== undefined) {
|
|
69
|
+
if (opts.expectSha256 === undefined) throw fail("ARTIFACTS_USAGE", "--file needs --expect-sha256");
|
|
70
|
+
if (path.isAbsolute(opts.file) || opts.file.split(/[\\/]/).includes("..")) throw fail("ARTIFACTS_USAGE", "--file must be a relative path inside the output tree");
|
|
71
|
+
}
|
|
72
|
+
return opts;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Refuse when `target` or any existing component between `root` (exclusive) and it is a symbolic link. */
|
|
76
|
+
function assertNoSymlinkPath(root, target) {
|
|
77
|
+
const rel = path.relative(root, target);
|
|
78
|
+
let current = root;
|
|
79
|
+
for (const part of rel.split(path.sep).filter(Boolean)) {
|
|
80
|
+
current = path.join(current, part);
|
|
81
|
+
let stat;
|
|
82
|
+
try {
|
|
83
|
+
stat = fs.lstatSync(current);
|
|
84
|
+
} catch (error) {
|
|
85
|
+
if (error.code === "ENOENT") return;
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
if (stat.isSymbolicLink()) throw fail("ARTIFACTS_DEST_SYMLINK", `refusing to write through a symbolic link: ${path.relative(root, current) || current}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function sha256File(file) {
|
|
93
|
+
const hash = crypto.createHash("sha256");
|
|
94
|
+
hash.update(fs.readFileSync(file));
|
|
95
|
+
return hash.digest("hex");
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function listFiles(root) {
|
|
99
|
+
const out = [];
|
|
100
|
+
const walk = (dir) => {
|
|
101
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
102
|
+
const full = path.join(dir, entry.name);
|
|
103
|
+
if (entry.isSymbolicLink()) throw fail("ARTIFACTS_SYMLINK", `artifact contains a symbolic link: ${path.relative(root, full)}`);
|
|
104
|
+
if (entry.isDirectory()) walk(full);
|
|
105
|
+
else if (entry.isFile()) out.push(full);
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
walk(root);
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Digest of a file list [{path, sha256}]: sha256 over sorted "<sha256> <path>\n" lines. */
|
|
113
|
+
export function treeDigest(files) {
|
|
114
|
+
const lines = [...files].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)).map((file) => `${file.sha256} ${file.path}\n`);
|
|
115
|
+
return crypto.createHash("sha256").update(lines.join("")).digest("hex");
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Fetch, merge, verify. `deps.execFile(cmd, args, opts)` defaults to child_process.execFile (promisified).
|
|
120
|
+
* Returns the receipt; throws a coded Error on any failure (staging removed, output tree untouched).
|
|
121
|
+
*/
|
|
122
|
+
export async function fetchArtifacts(options, deps = {}) {
|
|
123
|
+
const execFile = deps.execFile ?? execFileAsync;
|
|
124
|
+
const out = path.resolve(options.out);
|
|
125
|
+
const repoArg = options.repo ?? "{owner}/{repo}";
|
|
126
|
+
const gh = (args) => execFile("gh", args, { maxBuffer: 64 * 1024 * 1024 });
|
|
127
|
+
|
|
128
|
+
let listed;
|
|
129
|
+
try {
|
|
130
|
+
const { stdout } = await gh(["api", "--paginate", "--slurp", `repos/${repoArg}/actions/runs/${options.run}/artifacts`]);
|
|
131
|
+
const pages = JSON.parse(stdout);
|
|
132
|
+
listed = (Array.isArray(pages) ? pages : [pages]).flatMap((page) => page.artifacts ?? []);
|
|
133
|
+
} catch (error) {
|
|
134
|
+
throw fail("ARTIFACTS_LIST", `gh could not list the artifacts of run ${options.run}: ${String(error.message ?? error).split("\n")[0]}`);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const matcher = options.name === undefined ? null : globToRegExp(options.name);
|
|
138
|
+
const matched = listed.filter((artifact) => typeof artifact.name === "string" && (matcher === null || matcher.test(artifact.name)));
|
|
139
|
+
if (matched.length === 0) throw fail("ARTIFACTS_NONE", `run ${options.run} has no artifact matching ${options.name ?? "*"}`);
|
|
140
|
+
for (const artifact of matched) {
|
|
141
|
+
if (!ARTIFACT_NAME_RE.test(artifact.name)) throw fail("ARTIFACTS_NAME", `refusing artifact with an unsafe name: ${JSON.stringify(artifact.name)}`);
|
|
142
|
+
if (artifact.expired === true) throw fail("ARTIFACTS_EXPIRED", `artifact ${artifact.name} of run ${options.run} has expired`);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
146
|
+
const staging = fs.mkdtempSync(path.join(path.dirname(out), `.${path.basename(out)}.fetch-`));
|
|
147
|
+
try {
|
|
148
|
+
const merged = new Map();
|
|
149
|
+
const perArtifact = [];
|
|
150
|
+
for (const artifact of matched.sort((a, b) => (a.name < b.name ? -1 : 1))) {
|
|
151
|
+
const dir = path.join(staging, "dl", artifact.name);
|
|
152
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
153
|
+
if (!Number.isSafeInteger(artifact.id) || artifact.id <= 0) throw fail("ARTIFACTS_ID", `artifact ${artifact.name} has no numeric id; refusing to download by name`);
|
|
154
|
+
const zip = path.join(staging, `${artifact.id}.zip`);
|
|
155
|
+
try {
|
|
156
|
+
const { stdout } = await execFile("gh", ["api", `repos/${repoArg}/actions/artifacts/${artifact.id}/zip`], { maxBuffer: 1024 * 1024 * 1024, encoding: "buffer" });
|
|
157
|
+
fs.writeFileSync(zip, stdout);
|
|
158
|
+
const [cmd, args] = process.platform === "win32" ? ["tar", ["-xf", zip, "-C", dir]] : ["unzip", ["-q", "-o", zip, "-d", dir]];
|
|
159
|
+
await execFile(cmd, args, { maxBuffer: 64 * 1024 * 1024 });
|
|
160
|
+
} catch (error) {
|
|
161
|
+
throw fail("ARTIFACTS_DOWNLOAD", `could not download artifact ${artifact.name} (id ${artifact.id}): ${String(error.message ?? error).split("\n")[0]}`);
|
|
162
|
+
}
|
|
163
|
+
const zipSha256 = sha256File(zip);
|
|
164
|
+
const files = [];
|
|
165
|
+
for (const file of listFiles(dir)) {
|
|
166
|
+
const rel = path.relative(dir, file).split(path.sep).join("/");
|
|
167
|
+
const digest = sha256File(file);
|
|
168
|
+
const earlier = merged.get(rel);
|
|
169
|
+
if (earlier && earlier.sha256 !== digest) {
|
|
170
|
+
throw fail("ARTIFACTS_CONFLICT", `artifacts ${earlier.artifact} and ${artifact.name} disagree about ${rel}`);
|
|
171
|
+
}
|
|
172
|
+
if (!earlier) merged.set(rel, { sha256: digest, source: file, artifact: artifact.name });
|
|
173
|
+
files.push({ path: rel, sha256: digest, size: fs.statSync(file).size });
|
|
174
|
+
}
|
|
175
|
+
perArtifact.push({ name: artifact.name, id: artifact.id, zipSha256, files });
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const tree = [...merged.entries()].map(([rel, entry]) => ({ path: rel, sha256: entry.sha256 }));
|
|
179
|
+
const treeSha256 = treeDigest(tree);
|
|
180
|
+
let pinned = null;
|
|
181
|
+
if (options.expectSha256 !== undefined) {
|
|
182
|
+
const subject = options.file === undefined ? "tree" : options.file.split(path.sep).join("/");
|
|
183
|
+
const actual = options.file === undefined ? treeSha256 : merged.get(subject)?.sha256;
|
|
184
|
+
if (actual === undefined) throw fail("ARTIFACTS_PIN_FILE", `--file ${subject} is not in the fetched artifacts`);
|
|
185
|
+
if (actual !== options.expectSha256) {
|
|
186
|
+
throw fail("ARTIFACTS_PIN_MISMATCH", `sha256 pin mismatch for ${options.file ?? "the artifact tree"}: expected ${options.expectSha256}, got ${actual}`);
|
|
187
|
+
}
|
|
188
|
+
pinned = { subject: options.file ?? "tree", expected: options.expectSha256, actual };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const receiptPath = options.receipt ? path.resolve(options.receipt) : null;
|
|
192
|
+
if (receiptPath) {
|
|
193
|
+
const key = (value) => path.resolve(value).toLowerCase();
|
|
194
|
+
if (key(receiptPath) === key(out)) throw fail("ARTIFACTS_RECEIPT_COLLISION", "--receipt must not be the output directory");
|
|
195
|
+
if (key(receiptPath).startsWith(`${key(out)}${path.sep}`)) {
|
|
196
|
+
for (const rel of merged.keys()) {
|
|
197
|
+
const target = key(path.join(out, ...rel.split("/")));
|
|
198
|
+
if (target === key(receiptPath) || target.startsWith(`${key(receiptPath)}${path.sep}`)) {
|
|
199
|
+
throw fail("ARTIFACTS_RECEIPT_COLLISION", `--receipt ${options.receipt} collides with fetched file ${rel}; choose a path outside the artifacts`);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
try {
|
|
204
|
+
if (fs.lstatSync(receiptPath).isSymbolicLink()) throw fail("ARTIFACTS_DEST_SYMLINK", `refusing to write the receipt through a symbolic link: ${options.receipt}`);
|
|
205
|
+
} catch (error) {
|
|
206
|
+
if (error.code !== "ENOENT") throw error;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
let outStat = null;
|
|
211
|
+
try {
|
|
212
|
+
outStat = fs.lstatSync(out);
|
|
213
|
+
} catch (error) {
|
|
214
|
+
if (error.code !== "ENOENT") throw error;
|
|
215
|
+
}
|
|
216
|
+
if (outStat?.isSymbolicLink()) throw fail("ARTIFACTS_DEST_SYMLINK", `refusing to write through a symbolic link: ${out}`);
|
|
217
|
+
// Stage the verified tree fresh, re-verify it, refuse symlinked destinations, then rename each file into place.
|
|
218
|
+
const verifiedTree = path.join(staging, "tree");
|
|
219
|
+
for (const [rel, entry] of merged) {
|
|
220
|
+
const staged = path.join(verifiedTree, ...rel.split("/"));
|
|
221
|
+
fs.mkdirSync(path.dirname(staged), { recursive: true });
|
|
222
|
+
fs.copyFileSync(entry.source, staged, fs.constants.COPYFILE_EXCL);
|
|
223
|
+
if (sha256File(staged) !== entry.sha256) throw fail("ARTIFACTS_CHANGED", `${rel} changed while staging`);
|
|
224
|
+
}
|
|
225
|
+
for (const rel of merged.keys()) assertNoSymlinkPath(out, path.join(out, ...rel.split("/")));
|
|
226
|
+
fs.mkdirSync(out, { recursive: true });
|
|
227
|
+
let counter = 0;
|
|
228
|
+
for (const [rel, entry] of merged) {
|
|
229
|
+
const target = path.join(out, ...rel.split("/"));
|
|
230
|
+
assertNoSymlinkPath(out, path.dirname(target));
|
|
231
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
232
|
+
assertNoSymlinkPath(out, path.dirname(target));
|
|
233
|
+
counter += 1;
|
|
234
|
+
const temp = path.join(path.dirname(target), `.${path.basename(target)}.${process.pid}.${counter}.tmp`);
|
|
235
|
+
fs.copyFileSync(path.join(verifiedTree, ...rel.split("/")), temp, fs.constants.COPYFILE_EXCL);
|
|
236
|
+
try {
|
|
237
|
+
if (sha256File(temp) !== entry.sha256) throw fail("ARTIFACTS_CHANGED", `${rel} changed while publishing`);
|
|
238
|
+
assertNoSymlinkPath(out, target);
|
|
239
|
+
fs.renameSync(temp, target);
|
|
240
|
+
} catch (error) {
|
|
241
|
+
fs.rmSync(temp, { force: true });
|
|
242
|
+
throw error;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const receipt = {
|
|
247
|
+
schema: RECEIPT_SCHEMA,
|
|
248
|
+
run: options.run,
|
|
249
|
+
repo: options.repo ?? null,
|
|
250
|
+
name: options.name ?? null,
|
|
251
|
+
out,
|
|
252
|
+
artifacts: perArtifact,
|
|
253
|
+
fileCount: merged.size,
|
|
254
|
+
treeSha256,
|
|
255
|
+
pin: pinned,
|
|
256
|
+
verified: pinned !== null,
|
|
257
|
+
};
|
|
258
|
+
if (receiptPath) {
|
|
259
|
+
fs.mkdirSync(path.dirname(receiptPath), { recursive: true });
|
|
260
|
+
fs.writeFileSync(receiptPath, `${JSON.stringify(receipt, null, 2)}\n`, "utf8");
|
|
261
|
+
}
|
|
262
|
+
return receipt;
|
|
263
|
+
} finally {
|
|
264
|
+
fs.rmSync(staging, { recursive: true, force: true });
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** CLI entry: argv after `artifacts`. Returns the process exit code. */
|
|
269
|
+
export async function artifactsCommand(argv, deps = {}, io = { log: console.log, error: console.error }) {
|
|
270
|
+
const [sub, ...rest] = argv;
|
|
271
|
+
if (sub !== "fetch") {
|
|
272
|
+
io.error("right-git artifacts fetch --run <id> --out <dir> [--name <glob>] [--repo owner/repo] [--expect-sha256 <hex> [--file <path>]] [--receipt <file>] [--json]");
|
|
273
|
+
return 2;
|
|
274
|
+
}
|
|
275
|
+
let options;
|
|
276
|
+
try {
|
|
277
|
+
options = parseFetchArgs(rest);
|
|
278
|
+
} catch (error) {
|
|
279
|
+
io.error(`right-git artifacts: ${error.message}`);
|
|
280
|
+
return 2;
|
|
281
|
+
}
|
|
282
|
+
try {
|
|
283
|
+
const receipt = await fetchArtifacts(options, deps);
|
|
284
|
+
io.log(options.json ? JSON.stringify(receipt, null, 2) : `right-git artifacts: fetched ${receipt.artifacts.length} artifact(s), ${receipt.fileCount} file(s) into ${receipt.out} (tree sha256 ${receipt.treeSha256}${receipt.verified ? ", pin verified" : ""})`);
|
|
285
|
+
return 0;
|
|
286
|
+
} catch (error) {
|
|
287
|
+
io.error(`right-git artifacts: ${error.code ?? "ERROR"}: ${error.message}`);
|
|
288
|
+
return 1;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import crypto from "node:crypto";
|
|
7
|
+
import { fetchArtifacts, parseFetchArgs, treeDigest, globToRegExp, artifactsCommand, RECEIPT_SCHEMA } from "./artifacts.mjs";
|
|
8
|
+
|
|
9
|
+
const sha = (text) => crypto.createHash("sha256").update(text).digest("hex");
|
|
10
|
+
|
|
11
|
+
function fakeGh(runs) {
|
|
12
|
+
const calls = [];
|
|
13
|
+
const execFile = async (cmd, args) => {
|
|
14
|
+
calls.push([cmd, ...args]);
|
|
15
|
+
if (cmd === "gh") {
|
|
16
|
+
if (args[0] === "api" && !/\/zip$/.test(args[1])) return { stdout: JSON.stringify([{ artifacts: runs.artifacts }]) };
|
|
17
|
+
assert.equal(args[0], "api");
|
|
18
|
+
const id = Number(/artifacts\/(\d+)\/zip$/.exec(args[1])[1]);
|
|
19
|
+
const artifact = (runs.replacement?.[id] ?? runs.artifacts.find((entry) => entry.id === id));
|
|
20
|
+
const name = artifact.name;
|
|
21
|
+
if (runs.fail?.includes(name)) throw new Error("boom\nsecond line");
|
|
22
|
+
return { stdout: Buffer.from(JSON.stringify(runs.files[name] ?? {})) };
|
|
23
|
+
}
|
|
24
|
+
const zip = args.find((arg) => arg.endsWith(".zip") || args.includes("-xf") && arg === args[args.indexOf("-xf") + 1]);
|
|
25
|
+
const dir = args[args.indexOf("-d") + 1] ?? args[args.indexOf("-C") + 1];
|
|
26
|
+
for (const [rel, text] of Object.entries(JSON.parse(fs.readFileSync(zip, "utf8")))) {
|
|
27
|
+
fs.mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true });
|
|
28
|
+
fs.writeFileSync(path.join(dir, rel), text);
|
|
29
|
+
}
|
|
30
|
+
return { stdout: "" };
|
|
31
|
+
};
|
|
32
|
+
return { execFile, calls };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "right-git-artifacts-"));
|
|
36
|
+
const RUN = {
|
|
37
|
+
artifacts: [{ id: 1, name: "swiftright-render-abc" }, { id: 2, name: "results-mac" }, { id: 3, name: "results-win" }],
|
|
38
|
+
files: {
|
|
39
|
+
"swiftright-render-abc": { "render.dll": "dll-bytes" },
|
|
40
|
+
"results-mac": { "results-mac.jsonl": "mac\n", "shared.txt": "same" },
|
|
41
|
+
"results-win": { "results-win.jsonl": "win\n", "shared.txt": "same", "sub/a.txt": "a" },
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
test("parseFetchArgs requires a run id and an output dir and rejects unsafe values", () => {
|
|
46
|
+
assert.deepEqual(parseFetchArgs(["--run", "12", "--out", "o", "--name", "results-*", "--expect-sha256", "A".repeat(64), "--file", "render.dll"]), { run: "12", out: "o", name: "results-*", expectSha256: "a".repeat(64), file: "render.dll" });
|
|
47
|
+
for (const argv of [[], ["--run", "x", "--out", "o"], ["--run", "1"], ["--run", "1", "--out", "o", "--name", "a b"], ["--run", "1", "--out", "o", "--expect-sha256", "abc"], ["--run", "1", "--out", "o", "--file", "x"], ["--run", "1", "--out", "o", "--expect-sha256", "a".repeat(64), "--file", "../x"], ["--run", "1", "--out", "o", "--repo", "bad"], ["--run", "1", "--out", "o", "--wat"]]) {
|
|
48
|
+
assert.throws(() => parseFetchArgs(argv), (error) => error.code === "ARTIFACTS_USAGE", JSON.stringify(argv));
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
test("globToRegExp supports * and ? and anchors the match", () => {
|
|
53
|
+
assert.ok(globToRegExp("results-*").test("results-mac"));
|
|
54
|
+
assert.ok(!globToRegExp("results-*").test("xresults-mac"));
|
|
55
|
+
assert.ok(globToRegExp("a?c.txt").test("abc.txt"));
|
|
56
|
+
assert.ok(!globToRegExp("a?c.txt").test("abcxtxt"));
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test("fetch merges per-job artifacts into one tree and writes a receipt with the tree digest", async () => {
|
|
60
|
+
const out = path.join(tmp(), "run");
|
|
61
|
+
const receiptPath = path.join(tmp(), "receipt.json");
|
|
62
|
+
const { execFile, calls } = fakeGh(RUN);
|
|
63
|
+
const receipt = await fetchArtifacts({ run: "99", out, name: "results-*", repo: "Orthic-Labs/swiftright", receipt: receiptPath }, { execFile });
|
|
64
|
+
assert.equal(receipt.schema, RECEIPT_SCHEMA);
|
|
65
|
+
assert.deepEqual(receipt.artifacts.map((artifact) => artifact.name), ["results-mac", "results-win"]);
|
|
66
|
+
assert.equal(receipt.fileCount, 4);
|
|
67
|
+
assert.equal(fs.readFileSync(path.join(out, "sub", "a.txt"), "utf8"), "a");
|
|
68
|
+
assert.equal(fs.readFileSync(path.join(out, "shared.txt"), "utf8"), "same");
|
|
69
|
+
const expected = treeDigest([{ path: "shared.txt", sha256: sha("same") }, { path: "results-mac.jsonl", sha256: sha("mac\n") }, { path: "results-win.jsonl", sha256: sha("win\n") }, { path: "sub/a.txt", sha256: sha("a") }]);
|
|
70
|
+
assert.equal(receipt.treeSha256, expected);
|
|
71
|
+
assert.equal(JSON.parse(fs.readFileSync(receiptPath, "utf8")).treeSha256, expected);
|
|
72
|
+
assert.equal(receipt.verified, false);
|
|
73
|
+
assert.ok(calls.some((call) => call[0] === "gh" && call[2] === "repos/Orthic-Labs/swiftright/actions/artifacts/2/zip"));
|
|
74
|
+
assert.ok(calls.every((call) => !call.includes("--name")), "downloads go by artifact id, never by name");
|
|
75
|
+
assert.deepEqual(receipt.artifacts.map((artifact) => artifact.id), [2, 3]);
|
|
76
|
+
assert.ok(receipt.artifacts.every((artifact) => /^[0-9a-f]{64}$/.test(artifact.zipSha256)));
|
|
77
|
+
assert.deepEqual(fs.readdirSync(path.dirname(out)).filter((entry) => entry.includes(".fetch-")), []);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test("a per-file pin passes when it matches and the receipt records it", async () => {
|
|
81
|
+
const out = path.join(tmp(), "pair");
|
|
82
|
+
const { execFile } = fakeGh(RUN);
|
|
83
|
+
const receipt = await fetchArtifacts({ run: "99", out, name: "swiftright-render-*", expectSha256: sha("dll-bytes"), file: "render.dll" }, { execFile });
|
|
84
|
+
assert.equal(receipt.verified, true);
|
|
85
|
+
assert.deepEqual(receipt.pin, { subject: "render.dll", expected: sha("dll-bytes"), actual: sha("dll-bytes") });
|
|
86
|
+
assert.equal(fs.readFileSync(path.join(out, "render.dll"), "utf8"), "dll-bytes");
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test("a pin mismatch fails, leaves the output untouched and removes staging", async () => {
|
|
90
|
+
const root = tmp();
|
|
91
|
+
const out = path.join(root, "pair");
|
|
92
|
+
const { execFile } = fakeGh(RUN);
|
|
93
|
+
await assert.rejects(fetchArtifacts({ run: "99", out, name: "swiftright-render-*", expectSha256: "0".repeat(64), file: "render.dll" }, { execFile }), (error) => error.code === "ARTIFACTS_PIN_MISMATCH");
|
|
94
|
+
assert.equal(fs.existsSync(out), false);
|
|
95
|
+
assert.deepEqual(fs.readdirSync(root), []);
|
|
96
|
+
await assert.rejects(fetchArtifacts({ run: "99", out, name: "swiftright-render-*", expectSha256: "0".repeat(64), file: "missing.dll" }, { execFile }), (error) => error.code === "ARTIFACTS_PIN_FILE");
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test("the tree pin verifies the whole merged tree", async () => {
|
|
100
|
+
const out = path.join(tmp(), "tree");
|
|
101
|
+
const { execFile } = fakeGh(RUN);
|
|
102
|
+
const digest = treeDigest([{ path: "render.dll", sha256: sha("dll-bytes") }]);
|
|
103
|
+
const receipt = await fetchArtifacts({ run: "99", out, name: "swiftright-render-*", expectSha256: digest }, { execFile });
|
|
104
|
+
assert.deepEqual(receipt.pin, { subject: "tree", expected: digest, actual: digest });
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
test("conflicting files across artifacts, no match, expired, failed download and unsafe names are refused", async () => {
|
|
108
|
+
const conflict = { artifacts: RUN.artifacts, files: { ...RUN.files, "results-win": { ...RUN.files["results-win"], "shared.txt": "different" } } };
|
|
109
|
+
await assert.rejects(fetchArtifacts({ run: "1", out: path.join(tmp(), "o"), name: "results-*" }, fakeGh(conflict)), (error) => error.code === "ARTIFACTS_CONFLICT");
|
|
110
|
+
await assert.rejects(fetchArtifacts({ run: "1", out: path.join(tmp(), "o"), name: "nothing-*" }, fakeGh(RUN)), (error) => error.code === "ARTIFACTS_NONE");
|
|
111
|
+
await assert.rejects(fetchArtifacts({ run: "1", out: path.join(tmp(), "o") }, fakeGh({ ...RUN, artifacts: [{ id: 1, name: "old", expired: true }] })), (error) => error.code === "ARTIFACTS_EXPIRED");
|
|
112
|
+
await assert.rejects(fetchArtifacts({ run: "1", out: path.join(tmp(), "o"), name: "results-mac" }, fakeGh({ ...RUN, fail: ["results-mac"] })), (error) => error.code === "ARTIFACTS_DOWNLOAD" && !/second line/.test(error.message));
|
|
113
|
+
await assert.rejects(fetchArtifacts({ run: "1", out: path.join(tmp(), "o") }, fakeGh({ ...RUN, artifacts: [{ id: 1, name: "../evil" }] })), (error) => error.code === "ARTIFACTS_NAME");
|
|
114
|
+
const listing = { execFile: async () => { throw new Error("no auth"); } };
|
|
115
|
+
await assert.rejects(fetchArtifacts({ run: "1", out: path.join(tmp(), "o") }, listing), (error) => error.code === "ARTIFACTS_LIST");
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
test("artifactsCommand prints a summary or JSON and returns exit codes", async () => {
|
|
119
|
+
const lines = [];
|
|
120
|
+
const io = { log: (line) => lines.push(line), error: (line) => lines.push(`E ${line}`) };
|
|
121
|
+
const out = path.join(tmp(), "cmd");
|
|
122
|
+
assert.equal(await artifactsCommand(["fetch", "--run", "5", "--out", out, "--name", "swiftright-render-*", "--json"], fakeGh(RUN), io), 0);
|
|
123
|
+
assert.equal(JSON.parse(lines[0]).run, "5");
|
|
124
|
+
assert.equal(await artifactsCommand(["fetch", "--run", "5"], fakeGh(RUN), io), 2);
|
|
125
|
+
assert.equal(await artifactsCommand(["bogus"], fakeGh(RUN), io), 2);
|
|
126
|
+
assert.equal(await artifactsCommand(["fetch", "--run", "5", "--out", path.join(tmp(), "x"), "--name", "none-*"], fakeGh(RUN), io), 1);
|
|
127
|
+
assert.match(lines.at(-1), /ARTIFACTS_NONE/);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
test("a destination symlink (directory or file) is refused and nothing outside the output root is written", async () => {
|
|
131
|
+
const root = tmp();
|
|
132
|
+
const outside = path.join(root, "outside");
|
|
133
|
+
fs.mkdirSync(outside);
|
|
134
|
+
const out = path.join(root, "out");
|
|
135
|
+
fs.mkdirSync(out);
|
|
136
|
+
fs.symlinkSync(outside, path.join(out, "sub"));
|
|
137
|
+
const { execFile } = fakeGh(RUN);
|
|
138
|
+
await assert.rejects(fetchArtifacts({ run: "9", out, name: "results-win" }, { execFile }), (error) => error.code === "ARTIFACTS_DEST_SYMLINK");
|
|
139
|
+
assert.deepEqual(fs.readdirSync(outside), []);
|
|
140
|
+
fs.rmSync(path.join(out, "sub"));
|
|
141
|
+
const victim = path.join(root, "victim.txt");
|
|
142
|
+
fs.writeFileSync(victim, "keep");
|
|
143
|
+
fs.symlinkSync(victim, path.join(out, "results-win.jsonl"));
|
|
144
|
+
await assert.rejects(fetchArtifacts({ run: "9", out, name: "results-win" }, { execFile }), (error) => error.code === "ARTIFACTS_DEST_SYMLINK");
|
|
145
|
+
assert.equal(fs.readFileSync(victim, "utf8"), "keep");
|
|
146
|
+
const linkedOut = path.join(root, "linked");
|
|
147
|
+
fs.symlinkSync(outside, linkedOut);
|
|
148
|
+
await assert.rejects(fetchArtifacts({ run: "9", out: linkedOut, name: "results-win" }, { execFile }), (error) => error.code === "ARTIFACTS_DEST_SYMLINK");
|
|
149
|
+
assert.deepEqual(fs.readdirSync(outside), []);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
test("downloads use the listed artifact id: a same-name replacement cannot change what the receipt names", async () => {
|
|
153
|
+
const out = path.join(tmp(), "ids");
|
|
154
|
+
const gh = fakeGh({ ...RUN, replacement: {}, });
|
|
155
|
+
const receipt = await fetchArtifacts({ run: "9", out, name: "swiftright-render-*" }, gh);
|
|
156
|
+
assert.deepEqual(receipt.artifacts.map((artifact) => artifact.id), [1]);
|
|
157
|
+
await assert.rejects(fetchArtifacts({ run: "9", out: path.join(tmp(), "n"), name: "results-mac" }, fakeGh({ ...RUN, artifacts: [{ name: "results-mac" }] })), (error) => error.code === "ARTIFACTS_ID");
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
test("a receipt path that collides with a fetched file is refused before anything is written", async () => {
|
|
161
|
+
const root = tmp();
|
|
162
|
+
const out = path.join(root, "out");
|
|
163
|
+
const { execFile } = fakeGh(RUN);
|
|
164
|
+
await assert.rejects(fetchArtifacts({ run: "9", out, name: "swiftright-render-*", expectSha256: sha("dll-bytes"), file: "render.dll", receipt: path.join(out, "render.dll") }, { execFile }), (error) => error.code === "ARTIFACTS_RECEIPT_COLLISION");
|
|
165
|
+
assert.equal(fs.existsSync(out), false);
|
|
166
|
+
const receipt = await fetchArtifacts({ run: "9", out, name: "swiftright-render-*", receipt: path.join(out, "receipt.json") }, { execFile });
|
|
167
|
+
assert.equal(receipt.fileCount, 1);
|
|
168
|
+
});
|
package/checkout.test.mjs
CHANGED
|
@@ -11,6 +11,7 @@ const BASE = {
|
|
|
11
11
|
schemaVersion: 1,
|
|
12
12
|
compile: "github-actions-only",
|
|
13
13
|
lanes: [...KNOWN_LANES],
|
|
14
|
+
swift: { check: { runner: "macos-15", xcodeVersion: "16.4", projectDirectory: "ios", spec: "project.yml", project: "Widgets.xcodeproj", scheme: "Widgets", xcodegenVersion: "2.44.1" } },
|
|
14
15
|
matrix: { os: ["ubuntu-latest", "macos-latest", "windows-latest"], node: ["22.13", "24"] },
|
|
15
16
|
packageManager: "pnpm@11.24.0",
|
|
16
17
|
publish: {
|