diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d5d0f3a13b0..88262ebf9bb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -116,9 +116,11 @@ jobs: run: python3 scripts/release_dispatch_guard_tests.py - name: Preview data wait tests - # preview-server.yml signs the preview manifest only after this script - # sees its data URLs served; the tests drive the script against a local - # HTTP server and check the publish job waits on every manifest data URL. + # The manifest is signed only after this script sees its data URLs + # served, so the tests drive it against a local HTTP server. They also + # run the publish step's own shell over a stubbed checkout, holding + # packaging/desktop-platforms.txt to the binaries that step uploads: a + # listed triple it does not publish leaves that desktop with no preview. run: python3 scripts/preview_data_wait_tests.py - name: Action pin checker unit tests @@ -158,23 +160,23 @@ jobs: # while only the .deb side was current. run: python3 scripts/check_media_plugin_packaging.py - - name: Desktop platform mapping checker unit tests + - name: Desktop platform matrix checker unit tests # Exercises the checker against throwaway trees only; it does not read # this repository's own files. The direction that matters is refusal: an - # unreadable matrix reads as an empty published set, and the empty set is - # a subset of any mapping, so a checker that understood nothing would - # report a clean pass. - run: python3 scripts/check_shell_platform_mapping_tests.py - - - name: Desktop platform mapping coverage - # Two directions across three files. Every platform shell-release.yml's - # build-shell matrix publishes must be a native_engine.rs ServerPlatform - # variant, or that desktop ships unable to fetch an engine; and every - # triple that enum resolves must reach release.yml signed, with both the - # binary and its signature attached, or the desktop's download 404s on - # whichever half is missing. The Rust-side test pins the pairs it expects - # and cannot see either set grow past them. - run: python3 scripts/check_shell_platform_mapping.py + # unreadable list must raise, not read as an empty list. + run: python3 scripts/check_desktop_platform_matrix_tests.py + + - name: Desktop platform matrix coverage + # packaging/desktop-platforms.txt is the published desktop platform set. + # A platform shell-release.yml's build-shell matrix builds with no row + # there ships a desktop whose ServerPlatform resolves no triple, so it can + # never fetch an engine; preview-server.yml's build and release.yml's + # build-server triples are held to the same file by equality, so a triple + # published for no listed desktop is an error, not a harmless extra. The + # enum half is native_engine.rs's own test, which runs at tag time in + # shell-release.yml's shell-preflight — tauri-check is disabled here, so + # no PR-time job compiles it. + run: python3 scripts/check_desktop_platform_matrix.py - name: Resolution-frame boundary guard # Full-tree guard: legacy resolution keys are reader/fixture-only, and diff --git a/.github/workflows/preview-server.yml b/.github/workflows/preview-server.yml index dc8327e5135..d966a398cb7 100644 --- a/.github/workflows/preview-server.yml +++ b/.github/workflows/preview-server.yml @@ -272,6 +272,13 @@ jobs: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 if: steps.publication-gate.outputs.already_published != 'true' with: + # This job publishes `commit`, so it reads the scripts and the + # platform contract from it rather than from the workflow ref. + # Known split: the YAML around them still comes from the workflow ref, + # so a deploy one commit behind pairs an older contract with a newer + # binaries list. The sign step's diff refuses that pair, publishing + # nothing rather than a partial set, and the next deploy heals it. + ref: ${{ inputs.commit }} persist-credentials: false - name: Wait for the data files the manifest names @@ -351,6 +358,20 @@ jobs: # triple, which is the key the manifest publishes it under. platform_of() { basename "$(dirname "$1")"; } + # Every desktop that asks for a preview has a row in the contract, so a + # listed triple with no binary above publishes no URL for it and that + # desktop silently never sees a preview. Held here, before the first + # upload: a mismatch publishes nothing rather than half a manifest. + listed_triples=$(awk '{sub(/#.*/, ""); if (NF) print $3}' packaging/desktop-platforms.txt | sort -u) + published_triples=$(for binary in "${binaries[@]}"; do platform_of "$binary"; done | sort) + printf 'desktop-platforms.txt triples: %s\nthis job publishes: %s\n' \ + "${listed_triples//$'\n'/ }" "${published_triples//$'\n'/ }" + if [ -z "$listed_triples" ] \ + || ! diff <(printf '%s\n' "$listed_triples") <(printf '%s\n' "$published_triples"); then + echo "::error::packaging/desktop-platforms.txt (<) is not the set of platforms this job publishes (>); a listed triple with no binary here gets no preview URL, and one published without a row goes to no desktop." + exit 1 + fi + declare -A sha256_of for binary in "${binaries[@]}"; do name=$(basename "$binary") diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b44155ccda3..61f7adfa5af 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1243,6 +1243,41 @@ jobs: echo "EOF" } >> "$GITHUB_OUTPUT" + - name: Verify the release assets are the ones desktops download + env: + RELEASE_FILES: ${{ steps.release-assets.outputs.files }} + run: | + set -euo pipefail + # fail_on_unmatched_files only ever sees the list above, so it cannot + # know a platform is missing from it: add a build target, forget this + # file, and every desktop on it 404s with all gates green. Immutable + # releases take no late upload, so this has to fail before the create. + status=0 + # No nullglob: an absent or empty artifacts/ iterates this literally, failing the grep. + for binary in artifacts/phase-server-slim-*/*; do + case "$binary" in *.minisig) continue ;; esac + for asset in "$binary" "$binary.minisig"; do + printf '%s\n' "$RELEASE_FILES" | grep -qxF "$asset" || + { echo "::error::built $asset is missing from the release asset list"; status=1; } + done + done + # Both sides above are publisher-side spellings: rename a pair in the + # build and in the list, they still agree, and the desktop's download + # 404s. native_engine.rs asks for phase-server-slim-, and for + # that name plus .minisig, with .exe on windows; the contract's os and + # triple columns are where CI already holds that naming. + canonical=$(awk '{sub(/#.*/, ""); if (NF) print "phase-server-slim-" $3 ($1 == "windows" ? ".exe" : "")}' packaging/desktop-platforms.txt) + [ -n "$canonical" ] || { echo "::error::packaging/desktop-platforms.txt named no desktop platform"; exit 1; } + printf 'desktop download names: %s\n' "${canonical//$'\n'/ }" + published=$(printf '%s\n' "$RELEASE_FILES" | sed 's|.*/||') + while read -r binary; do + for asset in "$binary" "$binary.minisig"; do + printf '%s\n' "$published" | grep -qxF "$asset" || + { echo "::error::no release asset is published as $asset, which the desktop shell downloads by that exact name"; status=1; } + done + done <<<"$canonical" + exit $status + - name: Create release uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2.6.2 with: diff --git a/client/src-tauri/src/native_engine.rs b/client/src-tauri/src/native_engine.rs index b8fa44eca6b..12b6ecff628 100644 --- a/client/src-tauri/src/native_engine.rs +++ b/client/src-tauri/src/native_engine.rs @@ -2166,9 +2166,8 @@ impl ServerPlatform { ]; /// The pair as `std::env::consts::{OS, ARCH}` spells it, which is also how - /// the `build-shell` matrix spells its `os` and `arch`. - /// `scripts/check_shell_platform_mapping.py` reads these arms to hold that - /// matrix to this enum. + /// `packaging/desktop-platforms.txt` and the `build-shell` matrix spell + /// their `os` and `arch`. fn os_arch(self) -> (&'static str, &'static str) { match self { Self::MacosAarch64 => ("macos", "aarch64"), @@ -3464,14 +3463,25 @@ mod tests { #[test] fn server_target_triple_maps_every_published_desktop_platform() { - for (os, arch, triple) in [ - ("macos", "aarch64", "aarch64-apple-darwin"), - ("windows", "x86_64", "x86_64-pc-windows-msvc"), - ("linux", "x86_64", "x86_64-unknown-linux-musl"), - ("linux", "aarch64", "aarch64-unknown-linux-musl"), - ] { + let mut listed = HashSet::new(); + for line in include_str!("../../../packaging/desktop-platforms.txt").lines() { + let content = line.split_once('#').map_or(line, |(before, _)| before); + let fields: Vec<&str> = content.split_whitespace().collect(); + if fields.is_empty() { + continue; + } + let [os, arch, triple] = fields[..] else { + panic!("expected `os arch triple`, got {line:?}") + }; assert_eq!(server_target_triple(os, arch), Some(triple), "{os}-{arch}"); + listed.insert((os, arch)); } + // The set, not its size: a duplicated row would otherwise stand in for + // a variant no row covers. + assert_eq!( + listed, + HashSet::from(ServerPlatform::ALL.map(ServerPlatform::os_arch)) + ); for (os, arch) in [ ("macos", "x86_64"), ("windows", "aarch64"), diff --git a/packaging/desktop-platforms.txt b/packaging/desktop-platforms.txt new file mode 100644 index 00000000000..4953c544256 --- /dev/null +++ b/packaging/desktop-platforms.txt @@ -0,0 +1,11 @@ +# Desktop platforms the shell release publishes: os arch triple. +# os/arch are spelled as std::env::consts::{OS, ARCH} spells them, which is also +# how shell-release.yml's build-shell matrix spells them. Held to that matrix by +# scripts/check_desktop_platform_matrix.py, and to native_engine.rs's +# ServerPlatform (whose triple each desktop downloads) by that module's own test. +# That script holds the triple column to preview-server.yml and release.yml too. +# preview-server.yml's publish job holds its own upload list to it at run time. +macos aarch64 aarch64-apple-darwin +windows x86_64 x86_64-pc-windows-msvc +linux x86_64 x86_64-unknown-linux-musl +linux aarch64 aarch64-unknown-linux-musl diff --git a/scripts/check_desktop_platform_matrix.py b/scripts/check_desktop_platform_matrix.py new file mode 100755 index 00000000000..367e6ff7d9d --- /dev/null +++ b/scripts/check_desktop_platform_matrix.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +"""Hold the desktop build matrices to packaging/desktop-platforms.txt. + +A platform shell-release.yml's build-shell matrix builds with no row there ships +a desktop whose ServerPlatform resolves no target triple, so it can never fetch +an engine; a triple preview-server.yml builds with no row there provisions a +preview no desktop asks for; a listed triple release.yml's build-server never +builds is a download URL that 404s. native_engine.rs's test cannot see any half. +""" + +import os +import sys +from pathlib import Path + +import yaml + +ROOT = Path(os.environ.get("DESKTOP_PLATFORM_ROOT") or Path(__file__).resolve().parent.parent) +PLATFORMS = ROOT / "packaging" / "desktop-platforms.txt" +MATRIX = ROOT / ".github" / "workflows" / "shell-release.yml" +PREVIEW = ROOT / ".github" / "workflows" / "preview-server.yml" +RELEASE = ROOT / ".github" / "workflows" / "release.yml" +TRIPLE_SOURCES = [ + (PREVIEW, "build", "no desktop would ever ask for that preview", ""), + (RELEASE, "build-server", "no desktop downloads it", "; the desktop's download URL 404s"), +] + + +def listed(): + # read_text raises by design: an empty list fails a populated matrix anyway, but blames it. + rows = [line.split("#")[0].split() for line in PLATFORMS.read_text().splitlines()] + rows = [row for row in rows if row] + if malformed := [row for row in rows if len(row) != 3]: + sys.exit(f"::error::desktop-platforms.txt rows are not `os arch triple`: {malformed}") + return {tuple(row) for row in rows} + + +def include(path, job): + # A matrix runs the product of its free axes too, so reading include alone + # would report those builds as not happening. + matrix = yaml.safe_load(path.read_text())["jobs"][job]["strategy"]["matrix"] + if free := sorted(set(matrix) - {"include", "exclude"}): + sys.exit(f"::error::{path.name} {job} matrix has free axes {free}, whose product builds " + "platforms this checker cannot see") + return matrix["include"] + + +def built(): + return {(entry["os"], entry["arch"]) for entry in include(MATRIX, "build-shell")} + + +def main(): + rows = listed() + want, have = {row[:2] for row in rows}, built() + print(f"desktop-platforms.txt: {sorted(want)}") + print(f"build-shell matrix: {sorted(have)}") + for pair in sorted(have - want): + print(f"::error::build-shell builds {pair}, which desktop-platforms.txt does not " + "list; that desktop would ship unable to fetch an engine", file=sys.stderr) + for pair in sorted(want - have): + print(f"::error::desktop-platforms.txt lists {pair}, which build-shell does not build", + file=sys.stderr) + triples, agree = {row[2] for row in rows}, want == have + print(f"desktop-platforms.txt triples: {sorted(triples)}") + for path, job, unlisted, missing in TRIPLE_SOURCES: + builds = {entry["triple"] for entry in include(path, job)} + print(f"{path.stem} {job} matrix:".ljust(30), sorted(builds)) + agree &= builds == triples + for triple in sorted(builds - triples): + print(f"::error::{path.stem} {job} has a row for {triple}, which " + f"desktop-platforms.txt does not list; {unlisted}", file=sys.stderr) + for triple in sorted(triples - builds): + print(f"::error::desktop-platforms.txt lists {triple}, which {path.stem} {job} " + f"does not build{missing}", file=sys.stderr) + return 0 if agree else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/check_desktop_platform_matrix_tests.py b/scripts/check_desktop_platform_matrix_tests.py new file mode 100755 index 00000000000..aed0e80673b --- /dev/null +++ b/scripts/check_desktop_platform_matrix_tests.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 +"""Legs for check_desktop_platform_matrix.py: agreement, a grown matrix, a +dropped platform, a missing list, a free matrix axis, a grown preview matrix, a +platform nothing releases, a malformed row. The direction that matters is +refusal: an unreadable list must raise, not read as an empty list. +""" + +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +CHECKER = Path(__file__).resolve().parent / "check_desktop_platform_matrix.py" +MATRIX = """\ +jobs: + build-shell: + strategy: + matrix: + include: + - {os: linux, arch: x86_64, runner: ubuntu-latest} + - {os: macos, arch: aarch64, runner: macos-latest} +""" +PREVIEW = """\ +jobs: + build: + strategy: + matrix: + include: + - {triple: x86_64-unknown-linux-musl} + - {triple: aarch64-apple-darwin} +""" +RELEASE = """\ +jobs: + build-server: + strategy: + matrix: + include: + - {triple: x86_64-unknown-linux-musl} + - {triple: aarch64-apple-darwin} +""" +LISTING = "# fields: os arch triple\nlinux x86_64 x86_64-unknown-linux-musl\nmacos aarch64 aarch64-apple-darwin\n" + + +def run(matrix, listing, preview=PREVIEW, release=RELEASE): + root = Path(tempfile.mkdtemp()) + (root / ".github" / "workflows").mkdir(parents=True) + (root / ".github" / "workflows" / "shell-release.yml").write_text(matrix) + (root / ".github" / "workflows" / "preview-server.yml").write_text(preview) + (root / ".github" / "workflows" / "release.yml").write_text(release) + if listing is not None: + (root / "packaging").mkdir() + (root / "packaging" / "desktop-platforms.txt").write_text(listing) + return subprocess.run( + [sys.executable, str(CHECKER)], capture_output=True, text=True, + env={**os.environ, "DESKTOP_PLATFORM_ROOT": str(root)}, + ) + + +agree = run(MATRIX, LISTING) +assert agree.returncode == 0, agree.stderr +assert "('linux', 'x86_64')" in agree.stdout, agree.stdout +assert "('macos', 'aarch64')" in agree.stdout, agree.stdout + +grown = run(MATRIX + " - {os: windows, arch: x86_64, runner: windows-latest}\n", LISTING) +assert grown.returncode != 0, grown.stdout +assert "('windows', 'x86_64')" in grown.stderr, grown.stderr + +dropped = run(MATRIX, LISTING + "freebsd x86_64 nope\n") +assert dropped.returncode != 0, dropped.stdout +assert "('freebsd', 'x86_64')" in dropped.stderr, dropped.stderr + +absent = run(MATRIX, None) +assert absent.returncode != 0, absent.stdout +assert "desktop-platforms.txt" in absent.stderr, absent.stderr +assert "('linux', 'x86_64')" not in absent.stdout, absent.stdout + +free = run(MATRIX + " arch: [riscv64]\n", LISTING) +assert free.returncode != 0, free.stdout +assert "free axes ['arch']" in free.stderr, free.stderr + +previewed = run(MATRIX, LISTING, PREVIEW + " - {triple: riscv64-unknown-linux-musl}\n") +assert previewed.returncode != 0, previewed.stdout +assert "riscv64-unknown-linux-musl" in previewed.stderr, previewed.stderr + +# The reviewer's reproduction: a platform every other matrix gained, which the +# release never builds, so its desktop resolves a download URL that 404s. +unreleased = run( + MATRIX + " - {os: linux, arch: riscv64, runner: ubuntu-latest}\n", + LISTING + "linux riscv64 riscv64-unknown-linux-musl\n", + PREVIEW + " - {triple: riscv64-unknown-linux-musl}\n", +) +assert unreleased.returncode != 0, unreleased.stdout +assert "release build-server does not build" in unreleased.stderr, unreleased.stderr +assert "riscv64-unknown-linux-musl" in unreleased.stderr, unreleased.stderr + +malformed = run(MATRIX, "linux x86_64\n") +assert malformed.returncode != 0, malformed.stdout +assert "['linux', 'x86_64']" in malformed.stderr, malformed.stderr + +print("ok: agreement, grown matrix, dropped platform, missing list, free axis, " + "grown preview matrix, unreleased platform, malformed row") diff --git a/scripts/check_shell_platform_mapping.py b/scripts/check_shell_platform_mapping.py deleted file mode 100755 index 565dd32e196..00000000000 --- a/scripts/check_shell_platform_mapping.py +++ /dev/null @@ -1,1001 +0,0 @@ -#!/usr/bin/env python3 -"""Every desktop platform the shell release publishes must have an engine mapping. - -`shell-release.yml`'s `build-shell` matrix is the set of desktop platforms a tag -publishes. `native_engine.rs`'s `ServerPlatform` is how each of those desktops -resolves which engine binary to fetch. A platform published without a variant -ships a desktop that cannot acquire an engine at all. - -`native_engine.rs`'s own unit test pins the pairs it expects, which is what makes -it discriminating against the mapping being deleted or broken. What it cannot see -is the matrix growing past them: nothing there refers to the workflow. This gate -is that tie, and it runs on every pull request rather than at tag time. - -Nothing here soft-fails to an empty set: every way of failing to read a file -raises, because an empty matrix is a subset of any mapping and a gate that -understood nothing would otherwise print a pass. The mapping is read three times -over -- `ALL`, `os_arch`, `target_triple` -- and the three must name the same -variants. `ALL` is the only thing `from_os_arch` iterates, so a variant absent -from it resolves for no platform at runtime while both matches stay exhaustive -and every population still reads as expected. Each arm block's `Self::` -receivers are compared as a set against the arms read out of it as well, because -an arm rustfmt broke across lines still carries its receiver and would otherwise -be dropped in silence. Two arms naming one platform, or resolving one triple, -refuse for the same reason: a variant nothing can reach. - -Every comparison here is between sets of fully-qualified names rather than their -sizes, because a size holds while its members are substituted underneath it: two -variants collapsing onto one platform, a variant absent from `ALL`, a binary -attached under a name no desktop derives. A set equality has the opposite blind -spot -- an extra member completes it instead of breaking it -- so each block is -also held against something a name this gate invented cannot satisfy. For the -arm blocks that is the receiver-against-arm comparison. For `ALL`, whose entries -carry no arms, it is the `[Self; N]` length rustc checks against those entries, -read out of the same match as the entries themselves so that no other occurrence -of that shape can supply it. - -Non-code text is removed once, where the source is read, so nothing downstream -has raw text in scope to read by mistake. It is removed against each language's -own grammar rather than the spelling some defect happened to use: Rust's two -comment forms, nested to any depth, and neither of them opening inside a string -literal of either kind. The release side takes two -cuts, because that step's shell carries prose comments and its asset list is -data inside a quoted heredoc, where a `#` is neither a comment nor a path the -release attaches. The list is read out of that heredoc alone, and every line of -it must match an `artifacts//` path whole -- a pattern that matched -only a line's tail read either kind of commented name as an attached one. - -The other direction is the same defect pointed the other way. Every variant -resolves the asset name a desktop on that platform downloads -- its triple plus -the `.exe` a `windows` variant's `executable_suffix` appends -- and `release.yml` -is what publishes those assets. A name resolved but never published is a desktop -requesting a URL that 404s. That side is read twice too, from the signing loop -and from the attached asset list, because each proves what the other cannot: the -loop's `test -s` fails the release when the binary was never built, and the asset -list is what the release actually carries. Two readings that disagree describe no -published set, so they refuse rather than pick one. Their agreement is compared -on triples, which is all the loop names; the suffix axis is held against the -mapping instead, where getting it wrong is a silent 404 rather than a release -that fails its own `test -s`. - -The published set is allowed to be a superset. It quantifies over the release's -slim servers, not over desktop platforms, so a triple published for a consumer -that is not a desktop strands nothing and is not counted. - -The mapping is read by regex over `ServerPlatform`'s own blocks, each anchored on -its name, so renaming a method or reshaping its arms breaks this gate loudly -rather than silently. The expected populations are checked last and carry their -own exit code: a readable set that moved is neither a coverage gap nor a failure -to read, and checking it first would let a grown matrix hide the very desktop -that cannot fetch an engine. -""" - -from __future__ import annotations - -import os -import re -import sys -from pathlib import Path - -try: - import yaml -except ModuleNotFoundError: - # Exit 2, not 1: `main` reserves 1 for "a published platform has no mapping", - # 2 for "I could not read this", and 3 for "a population I read perfectly has - # moved". A missing parser is the second kind, and collapsing them would make - # the refusal unreadable from the exit code. - print("REFUSED: check_shell_platform_mapping: PyYAML is required and was " - "not found; refusing to check with a weaker method", file=sys.stderr) - sys.exit(2) - -ROOT = Path(os.environ.get("SHELL_PLATFORM_MAPPING_ROOT") - or Path(__file__).resolve().parent.parent).resolve() - -MAPPING_SOURCE = "client/src-tauri/src/native_engine.rs" -SHELL_RELEASE = ".github/workflows/shell-release.yml" -BUILD_JOB = "build-shell" -RELEASE_WORKFLOW = ".github/workflows/release.yml" -RELEASE_JOB = "release" -SIGN_STEP = "sign-release-artifacts" -ASSET_STEP = "release-assets" - -#: The preview channel provisions its own servers, and `native_engine.rs` reaches -#: them by a different route than a release: `ResolvedArtifact` for a Preview key -#: looks the host's `target_triple()` up in the signed manifest's `binaries` map, -#: so a triple absent from that map is a desktop that resolves nothing. Nothing -#: above reads this workflow, and the two populations it declares are spelled four -#: separate times inside it -- the build matrix, the four artifact downloads, the -#: shell array that signs and uploads, and the jq object that writes the manifest. -#: Any one of them can be edited alone, which is exactly the drift this gate -#: exists to refuse; the release half is held to the same standard two files over. -#: The publish job's steps carry no `id`, so its signing step is named rather than -#: identified. Adding an `id` would be an edit to a publishing workflow made to -#: suit its own observer, and `.github/workflows/**` is a hard stop besides. -PREVIEW_WORKFLOW = ".github/workflows/preview-server.yml" -PREVIEW_BUILD_JOB = "build" -PREVIEW_PUBLISH_JOB = "publish" -PREVIEW_SIGN_STEP = "Sign binaries, publish manifest, and garbage-collect old pairs" -PREVIEW_ARTIFACT_PREFIX = "preview-server-" - -#: `ALL` is the variant list `from_os_arch` iterates, and the two methods are the -#: arms it resolves them through. Each is anchored on its own name and bounded by -#: the closing brace at its indentation, so none of the three can be read as -#: another's contents -- the module also holds a free `target_triple()` function, -#: whose body carries no arms at all and so would read as an empty mapping rather -#: than as a wrong one. -#: `ALL`'s declared length is captured here rather than by a second pattern, so -#: the figure and the entries it is held against come out of one match. Read -#: separately it was satisfiable by any `[Self; N]` elsewhere in the file, which -#: is the whole forgery this cross-check exists to refuse. -MAPPING_ALL_BLOCK = re.compile( - r"const ALL:\s*\[Self;\s*(\d+)\]\s*=\s*\[(.*?)\n \];", re.S) -MAPPING_BLOCK = re.compile(r"fn os_arch\b[^{]*\{(.*?)\n \}", re.S) -MAPPING_TRIPLE_BLOCK = re.compile( - r"fn target_triple\(self\)[^{]*\{(.*?)\n \}", re.S) - -#: Every arm is read through its `Self::` receiver, which is what joins the three -#: blocks into one record per variant. The receivers are also compared as a set -#: against the arms read beside them: an arm rustfmt broke across lines still -#: carries its receiver but matches neither value pattern below, so a receiver -#: with no arm is how a dropped arm announces itself, by name. -MAPPING_RECEIVER = re.compile(r"Self::(\w+)") -MAPPING_ENTRY = re.compile( - r'Self::(\w+)\s*=>\s*\(\s*"([^"]+)"\s*,\s*"([^"]+)"\s*\)') -MAPPING_TRIPLE_ARM = re.compile(r'Self::(\w+)\s*=>\s*"([^"]+)"') - -SLIM_PREFIX = "phase-server-slim-" - -#: The release job's two spellings of its published set: the `for triple in ...` -#: loop it signs, and the `phase-server-slim-*` paths it attaches. The asset -#: pattern spans the whole line, `artifacts//` included, so the directory -#: half of each path -- which repeats the asset name -- is not counted a second -#: time and no line that merely *ends* in something asset-shaped can contribute a -#: name. End-anchoring alone read the tail of any line at all, which a set this -#: gate only ever grows cannot object to: a `#`-prefixed path names an asset the -#: release does not attach, and the desktop whose URL 404s stops being reported. -#: The capture takes the whole filename, `.exe` included, because that suffix is -#: part of the URL a desktop derives; the lazy name plus the trailing group is -#: what tells a binary line from its signature. -SIGN_LOOP = re.compile(r"for triple in((?:\s*\\\s*[\w.-]+)+)\s*;\s*do") -SIGN_TRIPLE = re.compile(r"[\w.-]+") -ASSET_LINE = re.compile( - rf"^\s*artifacts/[\w.-]+/({SLIM_PREFIX}[\w.-]+?)(\.minisig)?$", re.M) -#: The attached list is the heredoc body, not the whole step, which is the other -#: half of the same cut: the pattern above decides what a line must look like, -#: and this decides where a line has to be to count at all. That step's shell -#: carries prose comments and conditional `echo`s around this list, and none of -#: it attaches an asset. Both halves are needed because adding a name is what the -#: subset check cannot object to -- `attached` is allowed to be a superset -- so a -#: name read from anywhere else reads as published and the desktop whose URL is -#: missing stops being reported. Nothing downstream can separate the two: a -#: commented path names the very asset whose absence was the finding, so the -#: population is narrowed at the read rather than compared afterwards. -ASSET_HEREDOC = re.compile(r"cat <<'EOF'\n(.*?)\n\s*EOF\b", re.S) - -#: The preview publish step's two spellings, each narrowed to its own block before -#: any line is read, for the reason the heredoc above is: both sets are compared -#: by subset, so a name picked up from surrounding prose reads as provisioned and -#: silences the very desktop whose absence was the finding. The manifest keys are -#: taken from inside `binaries: {` alone -- the same step's jq also writes a -#: `data:` array of `{name, sha256, url}` objects, and a pattern matching any -#: quoted key followed by a brace would read those as platforms too. -PREVIEW_BINARIES_ARRAY = re.compile(r"binaries=\(\n(.*?)\n\s*\)", re.S) -PREVIEW_ARRAY_LINE = re.compile( - r"^\s*artifacts/[\w.-]+/phase-server-([\w.-]+?)(\.exe)?$", re.M) -#: Anchored on the `data:` key that follows it, because every entry *inside* the -#: object also ends in `},` -- stopping at the first one would read a single -#: platform's interior as the whole map and stranding the other three would look -#: like a finding rather than like a pattern that stopped early. -PREVIEW_MANIFEST_BLOCK = re.compile( - r"binaries:\s*\{\n(.*?)\n\s*\},\s*\n\s*data:", re.S) -PREVIEW_MANIFEST_KEY = re.compile(r'^\s*"([\w.-]+)":\s*\{\s*$', re.M) -#: A signature beside every binary: the desktop derives `sig_url` as well as -#: `url`, so a key carrying only one of them resolves an artifact it cannot -#: verify. Matched per key rather than counted, so the report names which. -#: The whole right-hand side, not its first literal: each URL is a concatenation -#: (`"...preview-server/" + $fingerprint + "/phase-server-"`), so the -#: binary's name is in the second string. A pattern stopping at the first would -#: never see the name it exists to hold the key against. -PREVIEW_MANIFEST_URL = re.compile(r"^\s*(url|sig_url):\s*(.+)$", re.M) -#: The upload path, read from the step that writes it. Every object goes to -#: `$prefix/$name`, so this assignment -- not a spelling of it kept here -- is -#: what fixes the path a manifest entry has to name. A gate holding its own copy -#: of the path passes whenever the manifest agrees with that copy, including when -#: both disagree with the upload the step performs. -PREVIEW_PREFIX_ASSIGN = re.compile(r'^\s*prefix="([^"\n]*)"\s*$', re.M) -#: jq's own binding of a shell variable to the name its program uses. The prefix -#: is shell (`$FINGERPRINT`) and the manifest URL is jq (`$fingerprint`); this -#: flag is the only thing that says the two are one value, so the pairing is read -#: from it rather than inferred from the two spellings looking alike. -PREVIEW_JQ_ARG = re.compile(r'--arg\s+(\w+)\s+"\$(\w+)"') -#: The one comparand this gate cannot derive: the step uploads into the R2 bucket -#: `phase-rs-data`, and the bucket's public hostname is Cloudflare configuration -#: that this repository does not contain. Everything after it -- prefix, -#: fingerprint variable, file name -- is read from the step itself. -PREVIEW_DATA_HOST = "https://data.phase-rs.dev/" -#: A jq concatenation split into the pieces whose identity matters. String -#: contents are captured whole, so whitespace *inside* a literal stays -#: significant -- R2 holds nothing under `preview- server/` -- while whitespace -#: *between* tokens is dropped, so reformatting the expression stays free. A -#: character matching nothing else becomes an `other` token, so a reshaped -#: expression cannot quietly tokenise into the expected sequence. -PREVIEW_JQ_TOKEN = re.compile(r'"((?:[^"\\]|\\.)*)"|\$(\w+)|([()+])|(\S)') - - -def _jq_tokens(expression: str) -> list[tuple[str, str]]: - """A jq expression as typed tokens, less one optional trailing comma. - - The manifest writes `url: (...),` ahead of `sig_url:`, so the first of the - pair carries a separator the second does not. - """ - tokens: list[tuple[str, str]] = [] - for literal, variable, operator, other in PREVIEW_JQ_TOKEN.findall( - expression.strip().removesuffix(",")): - if variable: - tokens.append(("var", variable)) - elif operator: - tokens.append(("op", operator)) - elif other: - tokens.append(("other", other)) - else: - tokens.append(("str", literal)) - return tokens - -#: The desktop platforms a tag publishes and the mapping entries that serve them. -#: Both are expectations, not observations: a change to either is the event this -#: gate reports, so it fails and names which side moved. There is deliberately no -#: expected count for the published slim servers -- that population may exceed the -#: desktop set without stranding a desktop. -PUBLISHED_PLATFORM_COUNT = 4 -MAPPED_PLATFORM_COUNT = 4 - - -class Refusal(Exception): - """A file could not be read the way this gate needs to read it. - - The single authority for every degraded read. No extractor soft-fails by - returning an empty set, because an empty set passes the subset check. - """ - - -def _mapping_text() -> str: - """`native_engine.rs`'s source, or a refusal if it is not there to read.""" - path = ROOT / MAPPING_SOURCE - if not path.is_file(): - raise Refusal(f"{MAPPING_SOURCE} does not exist; the platform mapping " - "is missing, so no published platform can be checked " - "against it") - return _strip_rust_comments(path.read_text(encoding="utf-8")) - - -#: A raw string's opener, matched whole rather than found by looking at what -#: precedes an `r`. `br#"` and `cr#"` are raw strings whose `r` is preceded by an -#: identifier character, so a guard reading that character alone declines to -#: recognise them: it is the prefixed form of the very token it is guarding. The -#: file this gate reads carries six `br#"` literals today. -RAW_OPEN = re.compile(r'[bc]?r(#*)"') -#: A char literal, against the Reference's production rather than against the -#: forms this scanner happened to remember: an ordinary character, an escape, a -#: `\xNN` byte escape, or a `\u{...}` unicode escape. The two multi-character -#: escapes are why the bare `\\.` spelling was wrong -- it consumes exactly two -#: characters and then demands the closing quote, so `'\u{41}'` matched nothing, -#: its trailing quote was left loose, and that quote paired with the next one two -#: characters along and swallowed a real `"`. -#: -#: The unicode escape's bound is on hex digits, not on characters between the -#: braces: `'\u{1_F_6_0_0}'` compiles, and counting its underscores against the -#: budget refused source rustc accepts. Overlong stays refused -- seven digits is -#: not a char literal, and this gate does not read what the compiler rejects. -CHAR_LIT = re.compile( - r"b?'(?:\\u\{_*(?:[0-9a-fA-F]_*){1,6}\}|\\x[0-9a-fA-F]{2}|\\.|[^'\\\n])'") -#: A lifetime or loop label: the only other token that opens with a quote and the -#: reason an unrecognised quote cannot simply be assumed to be a literal. It has -#: no closing quote, so it is consumed as itself. -LIFETIME = re.compile(r"'[A-Za-z_][A-Za-z0-9_]*") - - -def _raw_close(text: str, opener: re.Match[str]) -> int: - """End of the raw string whose opener this match covers. - - Inside one, `\\` escapes nothing and `//` is data, so a scanner reading it as - an ordinary literal leaves literal state open at the first `"` the body - carries and applies every comment rule after that point to code. An - unterminated opener runs to end of input, which preserves the remainder - rather than dropping it; it does not compile, so no tree reaches it. - """ - hashes = opener.group(1) - end = text.find('"' + hashes, opener.end()) - return len(text) if end < 0 else end + 1 + len(hashes) - - -def _strip_rust_comments(text: str) -> str: - """`text` with every Rust comment removed, before any pattern reads it. - - Against the comment grammar whole rather than one of its spellings: `//` - runs to end of line, `/* */` nests to any depth, and neither opens a comment - inside a string literal, so `"http://x"` keeps its arm. Newlines survive, so - the one-arm-per-line shape the callers read is unchanged. - - Nesting is why this scans rather than substitutes: `/\\*.*?\\*/` closes the - outer comment at the inner `*/` and leaves the remainder of it standing as - code. A line-oriented rule cannot serve either, which is where this parts - company with `source_census::code` -- a block comment spans lines, and - whether the quotes left of a `//` on one line are balanced is a different - question from whether that `//` stands inside a literal. Literal state is - tracked instead, so this needs no claim about which blocks carry literals; - `ALL`'s entries carry none. - - A name written inside a string literal is not a comment and is still read. - It refuses rather than passing -- as a receiver written twice in an arm - block, or against `ALL`'s declared length -- because the patterns below are - not literal-aware either: an escaped quote ends a captured value early, so a - corrupted triple reports on the published-asset axis instead of refusing. - - Every opener in Rust's literal grammar, because this reads whole source - files and an enumeration of them is falsified by the member it omits. Each - omission has the same consequence: a quote that opens no literal is read as - one, literal state is left open, and every comment rule after that point is - applied to code. The members are the plain, byte and C-string quotes, the - raw forms with any hash count, and the char literals -- and each is matched - whole, at its own start, rather than recognised by the character before it, - which is a test the prefixed forms fail by construction. - - That enumeration has been wrong five times, so it is no longer trusted to be - complete: a quote matching no opener refuses rather than being read as code. - The bound is the point. A member omitted from here now costs a named refusal - a contributor can act on, instead of a file silently mis-stripped -- which is - the only failure this gate cannot detect in itself. - """ - out: list[str] = [] - i, n, depth = 0, len(text), 0 - while i < n: - pair = text[i:i + 2] - if depth: - if pair == "/*": - depth += 1 - i += 2 - elif pair == "*/": - depth -= 1 - i += 2 - else: - if text[i] == "\n": - out.append("\n") - i += 1 - elif pair == "/*": - depth += 1 - i += 2 - elif pair == "//": - end = text.find("\n", i) - if end < 0: - break - i = end - elif ((i == 0 or not (text[i - 1].isalnum() or text[i - 1] == "_")) - and (opener := RAW_OPEN.match(text, i)) is not None): - close = _raw_close(text, opener) - out.append(text[i:close]) - i = close - elif (lit := CHAR_LIT.match(text, i)) is not None: - out.append(lit.group()) - i = lit.end() - elif (life := LIFETIME.match(text, i)) is not None: - out.append(life.group()) - i = life.end() - elif text[i] == "'": - raise Refusal( - f"{MAPPING_SOURCE} carries a quote at offset {i} that opens no " - f"token this gate knows ({text[i:i + 12]!r}): it is neither a " - "char literal nor a lifetime. Reading it as code would leave " - "literal state open and apply every comment rule after it to " - "code, so this refuses instead of guessing") - elif text[i] == '"': - out.append('"') - i += 1 - while i < n: - if text[i] == "\\": - out.append(text[i:i + 2]) - i += 2 - continue - out.append(text[i]) - i += 1 - if text[i - 1] == '"': - break - else: - out.append(text[i]) - i += 1 - return "".join(out) - - -def _mapping_block(text: str, pattern: re.Pattern[str], what: str) -> str: - """One block's code, out of a source every comment was already removed from. - - The single place both arm blocks are read through. Comments are gone before - this runs, at the read: stripping per block instead left the `//` that opens - one outside the captured group, so a comment carrying a declaration's shape - moved the block boundary and its contents were read as code. - """ - match = pattern.search(text) - if match is None: - raise Refusal(f"{MAPPING_SOURCE} has no readable `ServerPlatform::{what}`; " - "it was renamed or reformatted, and the mapping cannot be " - "read") - return match.group(1) - - -def _all_entries(text: str) -> tuple[int, list[str]]: - """`ALL`'s declared length and its entry names, out of one match. - - Two matches let the length come from somewhere the entries did not, and any - `[Self; N]` in the file would then serve: that is how this cross-check was - satisfiable by a sentence of prose. - """ - match = MAPPING_ALL_BLOCK.search(text) - if match is None: - raise Refusal(f"{MAPPING_SOURCE} has no readable `ServerPlatform::ALL`; " - "it was renamed or reformatted, and the mapping cannot be " - "read") - return int(match.group(1)), MAPPING_RECEIVER.findall(match.group(2)) - - -def _refuse_phantom_all_entry(declared: int, listed: list[str]) -> None: - """Refuse when `ALL` reads as more or fewer entries than rustc counts. - - `ALL` is compared to the two arm blocks by name, and a name this gate - invented is what that comparison cannot object to: a phantom entry makes - `set(listed)` complete rather than short, so the comparison passes and the - variant genuinely missing from `ALL` goes unreported -- the way this block - failed open, where the arm blocks' receiver-against-arm comparison already - refused. `[Self; N]` is checked by rustc against the entries themselves, so - it holds against a name no entry produced. - """ - if len(listed) != declared: - raise Refusal( - f"{MAPPING_SOURCE}: ServerPlatform::ALL is declared `[Self; " - f"{declared}]` but this gate read {len(listed)} entry name(s) in it: " - f"{listed}. rustc counts the entries itself, so a name here it does " - "not count came out of something that is not an entry -- text no " - "comment removal took out, or a name inside a string literal. More " - "names than rustc counts is the direction that would otherwise pass: " - "an extra one completes the by-name comparison instead of breaking " - "it, hiding a variant absent from ALL") - - -def _arms(block: str, pattern: re.Pattern[str], - what: str) -> dict[str, tuple[str, ...]]: - """One block's arms, keyed by the `Self::` receiver each is written against. - - Named, not counted: the receivers present and the arms parsed are compared as - sets, so a dropped arm is reported by name. A count of either would hold while - one arm was substituted for another. - """ - arms = {match[0]: match[1:] for match in pattern.findall(block)} - receivers = MAPPING_RECEIVER.findall(block) - unread = sorted(set(receivers) - set(arms)) - repeated = sorted({name for name in receivers if receivers.count(name) > 1}) - if unread or repeated: - raise Refusal( - f"{MAPPING_SOURCE}: ServerPlatform::{what} has arms this gate could " - f"not read. Receivers with no arm it could parse: {unread}. Receivers " - f"written more than once: {repeated}. An arm rustfmt broke across " - "lines still carries its receiver, so it is named here rather than " - "dropped in silence; write it on one line, or teach this gate the " - "shape it now takes") - return arms - - -def _refuse_shared(owners: dict[str, object], what: str, why: str) -> None: - """Refuse when two variants resolve to one value, naming the variants. - - The collision itself is the finding, so it is reported as the value and the - variants claiming it. A population size cannot see this: two variants - collapsing onto one value is exactly the substitution a count admits. - """ - shared = { - value: names - for value in set(owners.values()) - if len(names := sorted(n for n, v in owners.items() if v == value)) > 1 - } - if shared: - raise Refusal(f"{MAPPING_SOURCE}: ServerPlatform::{what} resolves " - f"{sorted(shared.items(), key=repr)} -- those variants " - f"{why}") - - -def mapped_platforms() -> dict[str, tuple[str, str, str]]: - """Each `ServerPlatform` variant as `(os, arch, triple)`. The desktop's authority.""" - text = _mapping_text() - declared, listed = _all_entries(text) - _refuse_phantom_all_entry(declared, listed) - pairs = _arms(_mapping_block(text, MAPPING_BLOCK, "os_arch"), - MAPPING_ENTRY, "os_arch") - triples = _arms(_mapping_block(text, MAPPING_TRIPLE_BLOCK, "target_triple"), - MAPPING_TRIPLE_ARM, "target_triple") - - if not set(listed) == set(pairs) == set(triples): - raise Refusal( - f"{MAPPING_SOURCE}: ServerPlatform::ALL lists {sorted(set(listed))} " - f"while os_arch covers {sorted(pairs)} and target_triple covers " - f"{sorted(triples)}. ALL is the only source from_os_arch iterates, so " - "a variant missing from it resolves for no platform at runtime while " - "both matches still compile. Add the variant to ALL; its declared " - "length is not what this gate reads") - - mapped = {name: (*pairs[name], *triples[name]) for name in pairs} - - _refuse_shared({name: (os_name, arch) - for name, (os_name, arch, _) in mapped.items()}, - "os_arch", - "claim the same (os, arch), so one of their triples is " - "unreachable and the published set would read as covered by a " - "mapping that cannot serve it") - # Both axes, because neither collision implies the other. Two variants can - # share a bare triple while deriving different names -- exactly one of them - # `windows` appends `.exe` to only its own -- and two distinct triples can - # collapse onto one derived name when they differ only by that suffix. A - # check keyed on either alone reads the other's collision as clean. - # The derived name first, because it is the narrower report: when both axes - # collide, the single URL is what a desktop actually requests. - _refuse_shared({name: slim_asset(os_name, triple) - for name, (os_name, _, triple) in mapped.items()}, - "target_triple's derived asset name", - "derive one asset name, so both desktops request a single URL " - "and the name the second should have asked for is never " - "checked against the release at all") - _refuse_shared({name: triple - for name, (_, _, triple) in mapped.items()}, - "target_triple", - "resolve the same engine triple, so both desktops are served " - "one binary built for one of their platforms and the other " - "runs an engine compiled for a machine it is not. Differing " - "derived names do not separate them: when exactly one of the " - "variants is `windows`, its own `.exe` makes the two names " - "differ and the asset-name check above sees no collision") - return mapped - - -def slim_asset(os_name: str, triple: str) -> str: - """The release asset a desktop on this platform derives and downloads. - - `native_engine.rs` builds the name from its triple plus `executable_suffix`, - which is `.exe` under `cfg(target_os = "windows")` -- the same `windows` this - variant's `os_arch` reports as `std::env::consts::OS`. - """ - return f"{SLIM_PREFIX}{triple}{'.exe' if os_name == 'windows' else ''}" - - -def asset_triple(asset: str) -> str: - """The triple an attached asset name carries, suffix removed.""" - return asset.removeprefix(SLIM_PREFIX).removesuffix(".exe") - - -def published_platforms() -> set[tuple[str, str]]: - """The `(os, arch)` pairs `build-shell` publishes a desktop for.""" - path = ROOT / SHELL_RELEASE - if not path.is_file(): - raise Refusal(f"{SHELL_RELEASE} does not exist; the published platform " - "set cannot be read") - try: - workflow = yaml.safe_load(path.read_text(encoding="utf-8")) - except yaml.YAMLError as exc: - raise Refusal(f"{SHELL_RELEASE} is not parseable YAML: {exc}") from exc - - jobs = (workflow or {}).get("jobs") or {} - job = jobs.get(BUILD_JOB) - if not isinstance(job, dict): - raise Refusal(f"{SHELL_RELEASE}: job '{BUILD_JOB}' is absent; the job " - "that publishes desktop packages was renamed, and this " - "gate no longer knows which platforms ship") - - # The published set is anchored on one job id, so a second job publishing - # desktops is a population this gate never walks. The axis refusal below is - # scoped to this job alone and does not reach siblings, so a sibling's matrix - # is read here in every shape that can produce a platform: a job runs the - # product of its axes with each `include` entry merged in, so `os` on an axis - # and `arch` on an entry ship a platform neither spells by itself. Reading - # only one shape reads a subset of what publishes. - def _publishes_desktops(name: str, other: object) -> bool: - strategy = other.get("strategy") if isinstance(other, dict) else None - if not isinstance(strategy, dict) or "matrix" not in strategy: - return False - matrix = strategy["matrix"] - if not isinstance(matrix, dict): - raise Refusal(f"{SHELL_RELEASE}: job '{name}' declares a " - f"strategy.matrix this gate cannot read ({matrix!r}), " - "so whether it publishes desktops is unknown. A job " - "that might is not one to pass over") - axes = set(matrix) - {"include", "exclude"} - # The same unreadability one level down, and the level a filter would - # swallow: a string iterates characters and a mapping iterates keys, so - # `[e for e in include if isinstance(e, dict)]` turns either into an empty - # list, and an empty list publishes nothing. That is the empty set passing - # a subset check, which is what this gate refuses everywhere else -- - # including on this same key when it belongs to the job being read. - include = matrix.get("include") - if include is not None and not (isinstance(include, list) - and all(isinstance(e, dict) for e in include)): - raise Refusal(f"{SHELL_RELEASE}: job '{name}' declares a " - f"strategy.matrix.include this gate cannot read " - f"({include!r}), so whether it publishes desktops is " - "unknown. A job that might is not one to pass over") - entries = include or [] - return {"os", "arch"} <= axes or any( - {"os", "arch"} <= (axes | e.keys()) for e in entries) - - others = sorted(name for name, other in jobs.items() - if name != BUILD_JOB and _publishes_desktops(name, other)) - if others: - raise Refusal(f"{SHELL_RELEASE}: {others} also declare matrix entries " - f"carrying both `os` and `arch`, so they publish desktops " - f"too, but this gate reads only '{BUILD_JOB}'. Every " - "platform they ship is one no ServerPlatform variant was " - "checked against") - - matrix = (job.get("strategy") or {}).get("matrix", {}) - # A matrix runs its product axes as well as its `include` entries, so reading - # `include` alone reads a subset of what publishes and the platforms an axis - # contributes strand silently. This gate identifies a platform by an (os, - # arch) pair on one entry, which a product has no single entry for, so an - # axis is a shape it cannot read rather than one it reads partially. - if isinstance(matrix, dict) and (axes := sorted(set(matrix) - - {"include", "exclude"})): - raise Refusal(f"{SHELL_RELEASE}: {BUILD_JOB} declares matrix axes " - f"{axes} beside `include`; every combination of those runs " - "and publishes a desktop too, so the published platform " - "set is larger than the `include` list this gate reads") - include = matrix.get("include") if isinstance(matrix, dict) else None - if not isinstance(include, list): - raise Refusal(f"{SHELL_RELEASE}: {BUILD_JOB} declares no " - "strategy.matrix.include list; the published platform set " - "cannot be read from this shape") - - platforms: set[tuple[str, str]] = set() - for entry in include: - if not isinstance(entry, dict) or not {"os", "arch"} <= entry.keys(): - raise Refusal(f"{SHELL_RELEASE}: {BUILD_JOB} matrix has an entry " - f"without both `os` and `arch`: {entry!r}. This gate " - "identifies a platform by that pair") - platforms.add((str(entry["os"]), str(entry["arch"]))) - return platforms - - -def _workflow_job(workflow: str, job_id: str, reads: str) -> dict[str, object]: - """One job of one workflow: the only place a workflow file is opened.""" - path = ROOT / workflow - if not path.is_file(): - raise Refusal(f"{workflow} does not exist; {reads} cannot be read") - try: - parsed = yaml.safe_load(path.read_text(encoding="utf-8")) - except yaml.YAMLError as exc: - raise Refusal(f"{workflow} is not parseable YAML: {exc}") from exc - - job = ((parsed or {}).get("jobs") or {}).get(job_id) - if not isinstance(job, dict): - raise Refusal(f"{workflow}: job '{job_id}' is absent or unreadable; the " - f"job that {reads} depends on was renamed or reshaped, and " - "a job this gate cannot find declares nothing rather than " - "declaring an empty set") - return job - - -def _step_bodies(workflow: str, job_id: str, reads: str) -> dict[str, str]: - """Each step's shell body, reachable by `id` and by `name`. - - Both, because the two workflows this gate reads identify their steps - differently: the release job gives its steps ids, while the preview publish - job names them and gives ids to neither. A duplicate key refuses rather than - resolving to one of the two bodies -- picking either would read one step's - shell as another's, and the set that came back would be a real set read off - the wrong step, which no downstream subset check can tell from the right one. - """ - steps = _workflow_job(workflow, job_id, reads).get("steps") - if not isinstance(steps, list): - raise Refusal(f"{workflow}: job '{job_id}' declares no steps list; the " - f"job that {reads} depends on was reshaped, and this gate " - "no longer knows which triples ship") - bodies: dict[str, str] = {} - for step in steps: - if not isinstance(step, dict): - continue - run = str(step.get("run") or "") - for key in (step.get("id"), step.get("name")): - if not isinstance(key, str): - continue - if key in bodies and bodies[key] != run: - raise Refusal(f"{workflow}: job '{job_id}' has two steps " - f"answering to '{key}', so {reads} would be read " - "off whichever this gate happened to keep") - bodies[key] = run - return bodies - - -def _step_body(bodies: dict[str, str], step: str, workflow: str, job_id: str, - reads: str) -> str: - body = bodies.get(step) - if body is None: - raise Refusal(f"{workflow}: {job_id} has no step '{step}', so {reads} " - "cannot be read") - return body - - -def published_assets() -> set[str]: - """Every `phase-server-slim-*` name the release attaches, signatures included. - - A desktop derives two URLs from its platform, the binary and the signature - beside it, so each is its own fully-qualified identity here rather than one - identity carrying a flag. Whichever of them a release fails to attach is then - the name that comes back missing, instead of a pair that drops out of a count. - """ - bodies = _step_bodies(RELEASE_WORKFLOW, RELEASE_JOB, - "the set of published slim server assets") - - loop = SIGN_LOOP.search( - _step_body(bodies, SIGN_STEP, RELEASE_WORKFLOW, RELEASE_JOB, - "the triples the release signs")) - if loop is None: - raise Refusal(f"{RELEASE_WORKFLOW}: {SIGN_STEP} has no readable `for " - "triple in ...` loop; the signed set was reshaped, and a " - "set this gate cannot read is not an empty one") - signed = set(SIGN_TRIPLE.findall(loop.group(1))) - listing = ASSET_HEREDOC.search( - _step_body(bodies, ASSET_STEP, RELEASE_WORKFLOW, RELEASE_JOB, - "the assets the release attaches")) - if listing is None: - raise Refusal(f"{RELEASE_WORKFLOW}: {ASSET_STEP} has no readable `cat " - "<<'EOF'` asset list; the attached set was reshaped, and a " - "set this gate cannot read is not an empty one") - lines = ASSET_LINE.findall(listing.group(1)) - attached = {f"{asset}{signature}" for asset, signature in lines} - - # Compared on triples, because a triple is all the loop names: it appends the - # suffix itself, from its own test of which triple is Windows. That test being - # wrong is self-announcing -- a Windows triple it failed to special-case fails - # `test -s` and takes the release down with it -- whereas a wrong name in the - # asset list publishes cleanly and 404s a desktop, which is why the suffix - # axis is held against the mapping rather than against this loop. - binaries = {asset_triple(asset) for asset, signature in lines if not signature} - if signed != binaries: - raise Refusal( - f"{RELEASE_WORKFLOW}: {RELEASE_JOB} signs {sorted(signed)} and " - f"attaches binaries for {sorted(binaries)}. Signed, never attached: " - f"{sorted(signed - binaries)}. Attached, never signed: " - f"{sorted(binaries - signed)}. A binary built and signed but never " - "attached, or attached without ever being built, is published in " - "neither sense this gate can report") - return attached - - -def preview_platforms() -> dict[str, set[str]]: - """Every triple preview provisioning declares, one set per place it says so. - - `native_engine.rs` resolves a Preview key by looking the running host's - `target_triple()` up in the signed manifest's `binaries` map, so each of these - is a place a platform can be dropped while the release half stays green. - - They are kept apart rather than unioned, because a union is satisfied by any - one spelling and the drift is precisely that they disagree: a triple built and - signed but never written into the manifest leaves a desktop resolving nothing, - and a union would still contain it. Held as subsets for the same reason the - release assets are -- an extra triple strands no desktop, a missing one does. - """ - build = _workflow_job(PREVIEW_WORKFLOW, PREVIEW_BUILD_JOB, - "the preview server binaries built per platform") - matrix = (build.get("strategy") or {}).get("matrix") - if not isinstance(matrix, dict): - raise Refusal(f"{PREVIEW_WORKFLOW}: job '{PREVIEW_BUILD_JOB}' declares a " - f"strategy.matrix this gate cannot read ({matrix!r}); the " - "set of platforms preview builds cannot be read") - if axes := sorted(set(matrix) - {"include", "exclude"}): - raise Refusal(f"{PREVIEW_WORKFLOW}: {PREVIEW_BUILD_JOB} declares matrix " - f"axes {axes} beside `include`; every combination of those " - "builds a preview server too, so the built set is larger " - "than the `include` list this gate reads") - include = matrix.get("include") - if not isinstance(include, list): - raise Refusal(f"{PREVIEW_WORKFLOW}: {PREVIEW_BUILD_JOB} declares no " - "strategy.matrix.include list; the built platform set " - "cannot be read from this shape") - built: set[str] = set() - for entry in include: - if not isinstance(entry, dict) or not isinstance(entry.get("triple"), str): - raise Refusal(f"{PREVIEW_WORKFLOW}: {PREVIEW_BUILD_JOB} matrix has an " - f"entry with no readable `triple`: {entry!r}. That " - "field is the whole identity of a preview binary") - built.add(entry["triple"]) - - publish = _workflow_job(PREVIEW_WORKFLOW, PREVIEW_PUBLISH_JOB, - "the preview binaries downloaded, signed and published") - steps = publish.get("steps") - if not isinstance(steps, list): - raise Refusal(f"{PREVIEW_WORKFLOW}: job '{PREVIEW_PUBLISH_JOB}' declares " - "no steps list; the job that signs and publishes preview " - "servers was reshaped") - downloaded: set[str] = set() - for step in steps: - with_ = step.get("with") if isinstance(step, dict) else None - name = with_.get("name") if isinstance(with_, dict) else None - if not isinstance(name, str) or not name.startswith(PREVIEW_ARTIFACT_PREFIX): - continue - # The build job uploads under this same prefix as `${{ matrix.triple }}`, - # which names every platform at once and so identifies none of them. Read - # as a literal it would contribute one nonsense triple that no mapping - # holds, turning a superset check into a permanent failure. - if "${{" in name: - continue - downloaded.add(name.removeprefix(PREVIEW_ARTIFACT_PREFIX)) - - bodies = _step_bodies(PREVIEW_WORKFLOW, PREVIEW_PUBLISH_JOB, - "the preview binaries signed and written to the manifest") - body = _step_body(bodies, PREVIEW_SIGN_STEP, PREVIEW_WORKFLOW, - PREVIEW_PUBLISH_JOB, - "the signed binaries and the manifest naming them") - array = PREVIEW_BINARIES_ARRAY.search(body) - if array is None: - raise Refusal(f"{PREVIEW_WORKFLOW}: {PREVIEW_SIGN_STEP} has no readable " - "`binaries=( ... )` array; the signed set was reshaped, and " - "a set this gate cannot read is not an empty one") - # The array is the single authority for artifact file names: the step uploads - # `basename "$binary"` taken from it, so the name in the manifest's URL has to - # be exactly this one -- `.exe` included, which only windows carries. - artifacts = {triple: f"phase-server-{triple}{exe}" - for triple, exe in PREVIEW_ARRAY_LINE.findall(array.group(1))} - signed = set(artifacts) - block = PREVIEW_MANIFEST_BLOCK.search(body) - if block is None: - raise Refusal(f"{PREVIEW_WORKFLOW}: {PREVIEW_SIGN_STEP} has no readable " - "`binaries: {` object in the manifest it writes; the keys a " - "desktop resolves against cannot be read") - manifest_keys = PREVIEW_MANIFEST_KEY.findall(block.group(1)) - duplicate_keys = sorted({key for key in manifest_keys - if manifest_keys.count(key) > 1}) - if duplicate_keys: - raise Refusal(f"{PREVIEW_WORKFLOW}: {PREVIEW_SIGN_STEP} writes duplicate " - f"manifest binary key(s) {duplicate_keys}; jq keeps the " - "later value, so every emitted URL pair must have one " - "unambiguous key") - keys = set(manifest_keys) - - assignments = PREVIEW_PREFIX_ASSIGN.findall(body) - if len(assignments) != 1: - raise Refusal(f"{PREVIEW_WORKFLOW}: {PREVIEW_SIGN_STEP} has no readable " - f'`prefix="..."` assignment (found {len(assignments)}); the ' - "path every preview object is uploaded to must be " - "unambiguous, and a path this gate supplies itself would " - "check the manifest against nothing") - prefix = assignments[0] - shell = re.search(r"\$(\w+)", prefix) - if shell is None: - raise Refusal(f"{PREVIEW_WORKFLOW}: {PREVIEW_SIGN_STEP} uploads to " - f"'{prefix}', which carries no variable; every fingerprint " - "would publish over one path, so the manifest could not " - "name a per-fingerprint object at all") - bound = [jq for jq, sh in PREVIEW_JQ_ARG.findall(body) - if sh == shell.group(1)] - if len(bound) != 1: - raise Refusal(f"{PREVIEW_WORKFLOW}: {PREVIEW_SIGN_STEP} binds " - f"${shell.group(1)} to {len(bound)} jq argument(s) " - f"{sorted(bound)}; exactly one is what lets the manifest's " - "variable be checked against the uploaded path") - head, tail = prefix[:shell.start()], prefix[shell.end():] - - def expected(name: str) -> list[tuple[str, str]]: - """The one URL that names the object this step uploads for `name`.""" - return [("op", "("), ("str", f"{PREVIEW_DATA_HOST}{head}"), - ("op", "+"), ("var", bound[0]), ("op", "+"), - ("str", f"{tail}/{name}"), ("op", ")")] - - # A desktop fetches `url` and `sig_url` verbatim, so an entry has to name the - # object the step uploaded. Compared as tokens against a URL derived from that - # step's own prefix, fingerprint binding and array-authorised name, because - # every weaker rule leaves something free: a substring admits - # `phase-server--old`, a terminal segment admits a moved prefix, and a - # comparison against a path spelled here admits a prefix that moves in the - # workflow alone. Per key, so the report names which key rather than a count. - paired: set[str] = set() - for key in keys: - entry = re.search(rf'"{re.escape(key)}":\s*\{{(.*?)\n\s*\}}', - block.group(1), re.S) - if entry is None or key not in artifacts: - continue - urls = dict(PREVIEW_MANIFEST_URL.findall(entry.group(1))) - name = artifacts[key] - if (_jq_tokens(urls.get("url", "")) == expected(name) - and _jq_tokens(urls.get("sig_url", "")) - == expected(f"{name}.minisig")): - paired.add(key) - - return {"builds": built, "downloads": downloaded, "signs": signed, - "names in its manifest": keys, - "gives a signed URL pair in its manifest": paired} - - -def main() -> int: - try: - mapped = mapped_platforms() - published = published_platforms() - attached = published_assets() - provisioned = preview_platforms() - except Refusal as exc: - print(f"REFUSED: {exc}", file=sys.stderr) - return 2 - - pairs = {(os_name, arch) for os_name, arch, _ in mapped.values()} - binaries = {slim_asset(os_name, triple) - for os_name, _, triple in mapped.values()} - # Both URLs, because a desktop derives both and either one 404s on its own. - resolved = {name for binary in binaries - for name in (binary, f"{binary}.minisig")} - status = 0 - - unmapped = sorted(published - pairs) - if unmapped: - print(f"{SHELL_RELEASE}'s {BUILD_JOB} publishes {len(unmapped)} " - f"platform(s) that {MAPPING_SOURCE} cannot map to an engine " - "target:", file=sys.stderr) - for os_name, arch in unmapped: - print(f" {os_name}-{arch}", file=sys.stderr) - print("A desktop published for a platform with no ServerPlatform " - "variant cannot download an engine. Add the variant, or stop " - "publishing the platform.", file=sys.stderr) - status = 1 - - unpublished = sorted(resolved - attached) - if unpublished: - print(f"{MAPPING_SOURCE}'s ServerPlatform resolves {len(unpublished)} " - f"asset URL(s) that {RELEASE_WORKFLOW}'s {RELEASE_JOB} job " - "does not publish:", file=sys.stderr) - for asset in unpublished: - print(f" {asset}", file=sys.stderr) - print("A desktop resolving one of these asks the release for an asset " - "that is not there and its download 404s. Publish that exact " - "name, or stop resolving it.", file=sys.stderr) - status = 1 - - triples = {triple for _, _, triple in mapped.values()} - for what, declared in sorted(provisioned.items()): - stranded = sorted(triples - declared) - if not stranded: - continue - print(f"{MAPPING_SOURCE}'s ServerPlatform resolves {len(stranded)} " - f"triple(s) that {PREVIEW_WORKFLOW} never {what}:", file=sys.stderr) - for triple in stranded: - print(f" {triple}", file=sys.stderr) - print("A desktop on that platform looks its triple up in the signed " - "preview manifest and finds no binary, so Try Preview fails there " - "while every release check stays green. Provision that triple, or " - "stop resolving it.", file=sys.stderr) - status = 1 - - moved: list[str] = [] - if len(pairs) != MAPPED_PLATFORM_COUNT: - moved.append(f"{MAPPING_SOURCE}: ServerPlatform::os_arch reads as " - f"{len(pairs)} platform(s), expected " - f"{MAPPED_PLATFORM_COUNT}: {sorted(pairs)}") - if len(published) != PUBLISHED_PLATFORM_COUNT: - moved.append(f"{SHELL_RELEASE}: {BUILD_JOB} publishes {len(published)} " - f"platform(s), expected {PUBLISHED_PLATFORM_COUNT}: " - f"{sorted(published)}") - if moved: - print("MOVED: a population this gate holds an expectation about has " - "changed. Every check above is by name and ran clean, so this is " - "the expectation to re-confirm, not a hole:", file=sys.stderr) - for line in moved: - print(f" {line}", file=sys.stderr) - status = status or 3 - - if status: - return status - - print(f"shell platform mapping OK: {len(published)} published platform(s) " - f"({', '.join(f'{o}-{a}' for o, a in sorted(published))}) all mapped " - f"by ServerPlatform ({len(mapped)} variant(s))") - print(f"engine target triples OK: {len(binaries)} resolved asset(s) " - f"({', '.join(sorted(binaries))}), each with its signature, all " - f"published by {RELEASE_WORKFLOW}'s {RELEASE_JOB} job " - f"({len(attached)} slim asset URL(s))") - print(f"preview provisioning OK: {len(triples)} engine triple(s) " - f"({', '.join(sorted(triples))}) each built, downloaded, signed, named " - f"in {PREVIEW_WORKFLOW}'s manifest, and given a signed URL pair there") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/scripts/check_shell_platform_mapping_tests.py b/scripts/check_shell_platform_mapping_tests.py deleted file mode 100644 index 7142475e20b..00000000000 --- a/scripts/check_shell_platform_mapping_tests.py +++ /dev/null @@ -1,1407 +0,0 @@ -#!/usr/bin/env python3 -"""Tests for check_shell_platform_mapping.py. - -The gate compares populations it reads out of four files, and every way of -failing to read one yields an empty set -- which is a subset of any mapping. So -what matters is not that the gate passes a correct tree but that it refuses an -unreadable one instead of printing a pass over nothing. Each case builds a -throwaway tree holding all four files and points the real script at it through -SHELL_PLATFORM_MAPPING_ROOT. - -Every fixture materialises all four files even when the case under test concerns -only one of them. A partial tree would make the gate refuse for a reason the test -did not intend, and a refusal that arrives for the wrong reason proves nothing -about the property being tested. -""" - -from __future__ import annotations - -import os -import shutil -import subprocess -import sys -import tempfile -import unittest -from pathlib import Path - -SCRIPT = Path(__file__).resolve().parent / "check_shell_platform_mapping.py" -MAPPING_REL = "client/src-tauri/src/native_engine.rs" -WORKFLOW_REL = ".github/workflows/shell-release.yml" -RELEASE_REL = ".github/workflows/release.yml" -PREVIEW_REL = ".github/workflows/preview-server.yml" -REAL_MAPPING = Path(__file__).resolve().parent.parent / MAPPING_REL -REAL_WORKFLOW = Path(__file__).resolve().parent.parent / WORKFLOW_REL -REAL_RELEASE = Path(__file__).resolve().parent.parent / RELEASE_REL -REAL_PREVIEW = Path(__file__).resolve().parent.parent / PREVIEW_REL -#: The publish job's steps carry no ids, so the gate finds this one by name. -PREVIEW_SIGN_STEP = "Sign binaries, publish manifest, and garbage-collect old pairs" - -#: The four published platforms and their triples, as all three files carry them. -DEFAULT_PLATFORMS = ( - ("macos", "aarch64", "aarch64-apple-darwin"), - ("windows", "x86_64", "x86_64-pc-windows-msvc"), - ("linux", "x86_64", "x86_64-unknown-linux-musl"), - ("linux", "aarch64", "aarch64-unknown-linux-musl"), -) -DEFAULT_TRIPLES = tuple(triple for _, _, triple in DEFAULT_PLATFORMS) -# Named in a fixture and nowhere in the real tree, so a checker that read this -# checkout instead of the fixture could not produce them. -SENTINEL_ARCH = "fixture-sentinel-arch" -SENTINEL_TRIPLE = "fixture-sentinel-triple" - -Platforms = tuple[tuple[str, str, str], ...] - - -def with_arch(platforms: Platforms, index: int, arch: str) -> Platforms: - """One platform's arch replaced, keeping the population size.""" - out = list(platforms) - os_name, _, triple = out[index] - out[index] = (os_name, arch, triple) - return tuple(out) - - -def with_triple(platforms: Platforms, index: int, triple: str) -> Platforms: - """One platform's triple replaced, keeping the population size.""" - out = list(platforms) - os_name, arch, _ = out[index] - out[index] = (os_name, arch, triple) - return tuple(out) - - -def mapping_source(platforms: Platforms = DEFAULT_PLATFORMS, *, - method: str = "os_arch", - triple_method: str = "target_triple", - listed: int | None = None, - wrap: int | None = None, - comment: int | None = None) -> str: - """A stand-in for the real module's `ServerPlatform`. - - Variants are indexed rather than named after their platform, so a duplicate - `(os, arch)` or a duplicate triple is expressible at all. Both methods are - read populations, and each is also the other's overrun guard: a block regex - that ran past one reads the other's string literals as its own entries. - - `listed` truncates `ALL` while leaving both matches exhaustive, which is the - shape a variant added without extending `ALL` takes: it compiles, and - `from_os_arch` reaches it for no `(os, arch)`. `wrap` renders one arm the way - rustfmt breaks one too long for a line, in both matches. `comment` names one - arm's variant in a legal comment, both above the arm and trailing on it, in - both matches: the two shapes such a note takes, neither of which is an arm. - """ - variants = [f"Platform{i}" for i in range(len(platforms))] - in_all = variants if listed is None else variants[:listed] - all_arms = "\n".join(f" Self::{v}," for v in in_all) - pairs = "\n".join( - f' Self::{v} => (\n "{os_name}",\n' - f' "{arch}",\n ),' - if i == wrap else - f' Self::{v} => ("{os_name}", "{arch}"),' - for i, (v, (os_name, arch, _)) in enumerate(zip(variants, platforms))) - triples = "\n".join( - f' Self::{v} => {{\n "{triple}"\n }}' - if i == wrap else - f' Self::{v} => "{triple}",' - for i, (v, (_, _, triple)) in enumerate(zip(variants, platforms))) - declared = "\n".join(f" {v}," for v in variants) - body = (f"""//! Fixture stand-in for the real native engine module. - -#[derive(Clone, Copy, Debug)] -enum ServerPlatform {{ -{declared} -}} - -impl ServerPlatform {{ - const ALL: [Self; {len(in_all)}] = [ -{all_arms} - ]; - - fn {method}(self) -> (&'static str, &'static str) {{ - match self {{ -{pairs} - }} - }} - - fn {triple_method}(self) -> &'static str {{ - match self {{ -{triples} - }} - }} -}} -""") - if comment is not None: - arm = f" Self::{variants[comment]} =>" - note = f"// Self::{variants[comment]} is the desktop this arm serves." - body = "\n".join( - f" {note}\n{line} {note}" if line.startswith(arm) else line - for line in body.splitlines()) + "\n" - return body - - -def annotate(body: str, line: str, note: str) -> str: - """`note` spliced onto the one `line`, refusing if it is not there to annotate. - - A comment case that silently annotated nothing would pass over an - unmarked tree, so the line it names has to be present exactly once. - """ - if body.count(line) != 1: - raise AssertionError( - f"fixture carries {body.count(line)} copies of {line!r}; a comment " - "case that annotates nothing, or two places, measures neither") - return body.replace(line, note.replace("@", line)) - - -#: The lines the comment cases annotate, as `mapping_source` writes them. -ALL_ENTRY = " Self::Platform2," -OS_ARCH_ARM = ' Self::Platform0 => ("macos", "aarch64"),' - - -def workflow_source(platforms: Platforms = DEFAULT_PLATFORMS, *, - job: str = "build-shell", os_key: str = "os") -> str: - include = "\n".join( - f" - {os_key}: {os_name}\n" - f" arch: {arch}\n" - f" runner: ubuntu-latest" - for os_name, arch, _ in platforms) - return f"""name: Shell release -on: - push: - tags: ['shell-v*'] -jobs: - {job}: - runs-on: ubuntu-latest - strategy: - matrix: - include: -{include} - steps: - - run: echo build -""" - - -def slim_asset_lines(triple: str, omit: str = "", exe: str = ".exe") -> str: - """The binary and signature paths the release attaches for one triple. - - `omit` drops one half, which is how a triple published at only one of the - two URLs a desktop derives from it is expressed. `exe` is the suffix a - Windows triple's asset carries; emptying it attaches a complete pair under a - name no Windows desktop asks for. - """ - name = f"phase-server-slim-{triple}" - ext = exe if "windows" in triple else "" - halves = {"binary": f" artifacts/{name}/{name}{ext}", - "signature": f" artifacts/{name}/{name}{ext}.minisig"} - return "\n".join(line for half, line in halves.items() if half != omit) - - -def release_source(triples: tuple[str, ...] = DEFAULT_TRIPLES, *, - attached: tuple[str, ...] | None = None, - omit: dict[str, str] | None = None, - sign_step: str = "sign-release-artifacts", - asset_step: str = "release-assets", - loop_var: str = "triple", - exe: str = ".exe") -> str: - """A stand-in for the release job's slim-server signing and asset steps. - - `attached` defaults to `triples`, so the two readings agree unless a case - sets them apart. `omit` maps a triple to the half of its asset pair the - release leaves behind. - """ - signed = " \\\n ".join(triples) - files = "\n".join(slim_asset_lines(t, (omit or {}).get(t, ""), exe) - for t in (triples if attached is None else attached)) - return f"""name: Release -on: - push: - tags: ['v*'] -jobs: - release: - runs-on: ubuntu-latest - steps: - - name: Sign slim server artifacts - id: {sign_step} - run: | - for {loop_var} in \\ - {signed}; do - binary="artifacts/phase-server-slim-${loop_var}/phase-server-slim-${loop_var}" - test -s "$binary" - sign "$binary" - done - - - name: Build release asset list - id: {asset_step} - run: | - cat <<'EOF' -{files} - EOF -""" - - -#: Built by substitution rather than as an f-string: the jq object this mirrors is -#: dense with braces, and doubling every one of them to satisfy a format string is -#: a defect waiting to be written into the fixture the tests trust. -PREVIEW_TEMPLATE = """name: Preview server -on: - workflow_dispatch: -jobs: - __BUILD_JOB__: - runs-on: ubuntu-latest - strategy: - matrix: - include: -__INCLUDE__ - steps: - - name: Upload preview server binary - uses: actions/upload-artifact@v4 - with: - name: preview-server-${{ matrix.triple }} - path: phase-server - __PUBLISH_JOB__: - runs-on: ubuntu-latest - steps: -__DOWNLOADS__ - - name: __SIGN_STEP__ - run: | - binaries=( -__ARRAY__ - ) - prefix="desktop/preview-server/$FINGERPRINT" - for binary in "${binaries[@]}"; do - name=$(basename "$binary") - npx wrangler r2 object put "phase-rs-data/$prefix/$name" --file "$binary" --remote - npx wrangler r2 object put "phase-rs-data/$prefix/$name.minisig" --file "$binary.minisig" --remote - done - jq -n \ - --arg fingerprint "$FINGERPRINT" \ - '{ - fingerprints: ( - { - ($fingerprint): { - binaries: { -__ENTRIES__ - }, - data: [ - { - name: "card-data.json" - } - ] - } - } - ) - }' -""" - - -def preview_source(platforms: Platforms = DEFAULT_PLATFORMS, *, - build_job: str = "build", - publish_job: str = "publish", - sign_step: str = PREVIEW_SIGN_STEP, - drop_build: str = "", - drop_download: str = "", - drop_sign: str = "", - drop_key: str = "", - drop_sig: str = "") -> str: - """The preview channel's four spellings of the platforms it provisions. - - Each `drop_*` removes one triple from one spelling, which is how a platform - built but never signed -- or signed but never named in the manifest -- is - expressed. The upload step is templated off `matrix.triple` exactly as the - real workflow spells it, so a reader that counted artifact names literally - would contribute a triple no mapping holds. - """ - triples = [triple for _, _, triple in platforms] - url = ('("https://data.phase-rs.dev/desktop/preview-server/" ' - '+ $fingerprint + "/{name}{suffix}")') - include = "\n".join( - f" - os: {os_name}\n" - f" triple: {triple}\n" - f" runner: ubuntu-latest" - for os_name, _, triple in platforms if triple != drop_build) - downloads = "\n".join( - f" - name: Download {triple}\n" - f" uses: actions/download-artifact@v4\n" - f" with:\n" - f" name: preview-server-{triple}\n" - f" path: artifacts/{triple}" - for triple in triples if triple != drop_download) - def artifact(triple: str) -> str: - # The step uploads `basename "$binary"` from the array, so the array and - # the manifest URLs name the same file -- `.exe` on windows included. - return f"phase-server-{triple}{'.exe' if 'windows' in triple else ''}" - - array = "\n".join( - f" artifacts/{triple}/{artifact(triple)}" - for triple in triples if triple != drop_sign) - entries = ",\n".join( - f' "{triple}": {{\n' - f" url: {url.format(name=artifact(triple), suffix='')}" - + ("" if triple == drop_sig else - ",\n sig_url: " - + url.format(name=artifact(triple), suffix=".minisig")) - + "\n }" - for triple in triples if triple != drop_key) - return (PREVIEW_TEMPLATE - .replace("__BUILD_JOB__", build_job) - .replace("__PUBLISH_JOB__", publish_job) - .replace("__SIGN_STEP__", sign_step) - .replace("__INCLUDE__", include) - .replace("__DOWNLOADS__", downloads) - .replace("__ARRAY__", array) - .replace("__ENTRIES__", entries)) - - -class MappingTree: - """A throwaway tree holding every file the gate reads.""" - - def __init__(self, root: Path) -> None: - self.root = root - self.write_mapping() - self.write_workflow() - self.write_release() - self.write_preview() - - def _write(self, rel: str, body: str) -> None: - path = self.root / rel - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(body, encoding="utf-8") - - def write_mapping(self, platforms: Platforms = DEFAULT_PLATFORMS, - **kwargs: str | int | None) -> None: - self._write(MAPPING_REL, mapping_source(platforms, **kwargs)) - - def write_workflow(self, platforms: Platforms = DEFAULT_PLATFORMS, - **kwargs: str) -> None: - self._write(WORKFLOW_REL, workflow_source(platforms, **kwargs)) - - def write_release(self, triples: tuple[str, ...] = DEFAULT_TRIPLES, *, - attached: tuple[str, ...] | None = None, - omit: dict[str, str] | None = None, - **kwargs: str) -> None: - self._write(RELEASE_REL, release_source(triples, attached=attached, - omit=omit, **kwargs)) - - def write_preview(self, platforms: Platforms = DEFAULT_PLATFORMS, - **kwargs: str) -> None: - self._write(PREVIEW_REL, preview_source(platforms, **kwargs)) - - def write_preview_text(self, body: str) -> None: - """A preview body the case built itself.""" - self._write(PREVIEW_REL, body) - - def write_workflow_text(self, body: str) -> None: - """A workflow body the case built itself, for matrix shapes no keyword spells.""" - self._write(WORKFLOW_REL, body) - - def write_mapping_text(self, body: str) -> None: - """A mapping body the case built itself, for shapes no keyword spells.""" - self._write(MAPPING_REL, body) - - def write_release_text(self, body: str) -> None: - """A release body the case built itself.""" - self._write(RELEASE_REL, body) - - def delete(self, rel: str) -> None: - (self.root / rel).unlink() - - def run(self) -> subprocess.CompletedProcess: - return subprocess.run( - [sys.executable, str(SCRIPT)], - env={**os.environ, "SHELL_PLATFORM_MAPPING_ROOT": str(self.root)}, - capture_output=True, text=True, - ) - - -class ShellPlatformMappingTests(unittest.TestCase): - def tree(self) -> MappingTree: - d = tempfile.mkdtemp() - self.addCleanup(shutil.rmtree, d, ignore_errors=True) - return MappingTree(Path(d)) - - def test_a_complete_tree_passes(self) -> None: - # Without this a gate that refuses everything would look identical to a - # gate that works. - t = self.tree() - r = t.run() - self.assertEqual(r.returncode, 0, r.stderr) - self.assertIn("shell platform mapping OK", r.stdout) - self.assertIn("engine target triples OK", r.stdout) - for triple in DEFAULT_TRIPLES: - self.assertIn(triple, r.stdout) - - def test_an_unmapped_published_platform_fails(self) -> None: - # Four platforms on each side, so neither count assertion fires and only - # the subset check can catch it. - t = self.tree() - t.write_workflow(with_arch(DEFAULT_PLATFORMS, 3, SENTINEL_ARCH)) - r = t.run() - self.assertEqual(r.returncode, 1, r.stdout) - self.assertIn(SENTINEL_ARCH, r.stderr) - self.assertIn("cannot map to an engine target", r.stderr) - - def test_a_new_published_platform_names_the_gap_and_the_moved_count(self) -> None: - # The matrix grew past a readable mapping, so the new platform is both an - # unmapped desktop and evidence that this gate's expected population - # moved. The population having moved must not cost the run the name of - # the desktop that cannot fetch an engine. - t = self.tree() - t.write_workflow( - DEFAULT_PLATFORMS + (("freebsd", "x86_64", "x86_64-unknown-freebsd"),)) - r = t.run() - self.assertEqual(r.returncode, 1, r.stdout) - self.assertIn("freebsd-x86_64", r.stderr) - self.assertIn("cannot map to an engine target", r.stderr) - self.assertIn("publishes 5 platform(s)", r.stderr) - - def test_a_renamed_matrix_key_refuses(self) -> None: - # The vacuous-green direction: a matrix this gate cannot read is an empty - # published set, and the empty set is a subset of any mapping, so a - # tolerant reader would announce a clean pass over nothing. - t = self.tree() - t.write_workflow(os_key="platform") - r = t.run() - self.assertEqual(r.returncode, 2, r.stdout) - self.assertIn("without both `os` and `arch`", r.stderr) - self.assertNotIn("mapping OK", r.stdout) - - def test_an_unreadable_mapping_refuses(self) -> None: - # Both ways the authority goes unread. An absent mapping and a renamed - # accessor are the same empty set, and it maps no published platform. - # Each leg names its own reason, because "REFUSED" alone is also what an - # interpreter with no YAML parser prints for every one of them. - for label, prepare, reason in ( - ("absent file", lambda t: t.delete(MAPPING_REL), - "the platform mapping is missing"), - ("renamed method", lambda t: t.write_mapping(method="platform_pair"), - "ServerPlatform::os_arch"), - ("renamed triple method", - lambda t: t.write_mapping(triple_method="server_triple"), - "ServerPlatform::target_triple"), - ): - with self.subTest(mapping=label): - t = self.tree() - prepare(t) - r = t.run() - self.assertEqual(r.returncode, 2, r.stdout) - self.assertIn(reason, r.stderr) - self.assertNotIn("mapping OK", r.stdout) - - def test_a_duplicate_os_arch_entry_refuses(self) -> None: - # Five arms, two claiming linux-aarch64, so the fifth variant's triple is - # unreachable while the distinct platforms still number the expected four. - # The finding is which variants collided, so both are named. - t = self.tree() - t.write_mapping(DEFAULT_PLATFORMS + (("linux", "aarch64", "wrong-triple"),)) - r = t.run() - self.assertEqual(r.returncode, 2, r.stdout) - self.assertIn("('linux', 'aarch64')", r.stderr) - self.assertIn("'Platform3', 'Platform4'", r.stderr) - self.assertNotIn("mapping OK", r.stdout) - - def test_a_fifth_distinct_mapping_arm_names_its_unpublished_asset(self) -> None: - # Five arms naming five platforms is a readable mapping whose population - # moved, and the fifth resolves an asset the release does not carry. Both - # are reported: the moved count explains why, the asset is what 404s. - t = self.tree() - t.write_mapping( - DEFAULT_PLATFORMS + (("freebsd", "x86_64", "x86_64-unknown-freebsd"),)) - r = t.run() - self.assertEqual(r.returncode, 1, r.stdout) - self.assertIn("phase-server-slim-x86_64-unknown-freebsd", r.stderr) - self.assertIn("reads as 5 platform(s)", r.stderr) - self.assertNotIn("mapping OK", r.stdout) - - def test_a_shrunken_platform_set_reports_a_moved_population(self) -> None: - # Every population read perfectly and no desktop is stranded, so this is - # neither a coverage gap nor a failure to read. It is the expected set - # moving, which the exit code has to distinguish from both. - t = self.tree() - t.write_mapping(DEFAULT_PLATFORMS[:3]) - t.write_workflow(DEFAULT_PLATFORMS[:3]) - t.write_release(DEFAULT_TRIPLES[:3]) - r = t.run() - self.assertEqual(r.returncode, 3, r.stdout) - self.assertIn("reads as 3 platform(s)", r.stderr) - self.assertIn("publishes 3 platform(s)", r.stderr) - self.assertNotIn("REFUSED", r.stderr) - self.assertNotIn("mapping OK", r.stdout) - - def test_a_variant_absent_from_all_refuses(self) -> None: - # ALL is the only thing from_os_arch iterates, so a variant left out of - # it resolves for no (os, arch) at runtime while both matches stay - # exhaustive and every population still counts four. - t = self.tree() - t.write_mapping(listed=3) - r = t.run() - self.assertEqual(r.returncode, 2, r.stdout) - self.assertIn("ServerPlatform::ALL", r.stderr) - self.assertIn("Platform3", r.stderr) - # A refusal that tells the reader to adjust a number teaches them to - # switch it off. The repair is the variant, so that is what it asks for. - self.assertIn("Add the variant to ALL", r.stderr) - self.assertNotIn("count", r.stderr) - self.assertNotIn("mapping OK", r.stdout) - - def test_a_wrapped_match_arm_refuses(self) -> None: - # rustfmt breaks an arm too long for one line, and an arm pattern written - # for the single-line shape reads straight past it. Every arm carries its - # `Self::` receiver whatever its shape, so counting those is what notices. - t = self.tree() - t.write_mapping(wrap=3) - r = t.run() - self.assertEqual(r.returncode, 2, r.stdout) - self.assertIn("no arm it could parse: ['Platform3']", r.stderr) - self.assertNotIn("mapping OK", r.stdout) - - def test_a_comment_naming_a_variant_is_not_an_arm(self) -> None: - # The companion of the case above, pointed the other way. A legal note - # naming the variant it documents is not a second arm, but scanning raw - # block text counted every mention as a receiver and refused with - # "written more than once" -- diagnosed as an arm rustfmt broke across - # lines, a wrapping the reader would hunt and never find. - body = mapping_source(comment=0) - self.assertEqual( - body.count("// Self::Platform0"), 4, - "the fixture must carry the note in both matches, above each arm " - "and trailing on it, or this test passes over an unannotated tree") - t = self.tree() - t.write_mapping(comment=0) - r = t.run() - self.assertEqual(r.returncode, 0, r.stderr) - self.assertIn("shell platform mapping OK", r.stdout) - - def test_a_block_comment_naming_a_variant_is_not_an_arm(self) -> None: - # The case above in Rust's other comment form, which a rule written for - # `//` leaves untouched. Every shape it takes is covered, because an - # enumeration of comment syntaxes admits the one it omits: trailing on - # an arm, spanning lines with the variant in its interior, and nested -- - # the last of which `/\\*.*?\\*/` closes at the inner `*/`, leaving the - # remainder of one comment standing as code. - for label, note in ( - ("trailing", "@ /* Self::Platform3 ships from the other arm */"), - ("multi-line interior", " /* This arm serves\n" - " Self::Platform3's neighbour. */\n@"), - ("nested", "@ /* outer /* inner */ Self::Platform3 */"), - ): - with self.subTest(comment=label): - body = annotate(mapping_source(), OS_ARCH_ARM, note) - self.assertIn("Self::Platform3", body, - "the comment must name a variant, or this case " - "passes over an unannotated tree") - t = self.tree() - t.write_mapping_text(body) - r = t.run() - self.assertEqual(r.returncode, 0, r.stderr) - self.assertIn("shell platform mapping OK", r.stdout) - - def test_a_comment_hiding_a_variant_absent_from_all_refuses(self) -> None: - # Why `ALL` cannot be read raw, in the direction that failed open. The - # variant really is missing from `ALL`, so it resolves for no platform at - # runtime, while a legal note names it. Counting that note as an entry - # makes the three-way comparison *complete* rather than short, so the - # gate prints a pass over the one defect it reads `ALL` at all to catch. - for label, note in ( - ("block", "@ /* Self::Platform3 temporarily not shipped */"), - ("line", "@ // Self::Platform3 temporarily not shipped"), - ): - with self.subTest(comment=label): - t = self.tree() - t.write_mapping_text( - annotate(mapping_source(listed=3), ALL_ENTRY, note)) - r = t.run() - self.assertEqual(r.returncode, 2, r.stdout) - self.assertIn("ServerPlatform::ALL", r.stderr) - self.assertIn("Platform3", r.stderr) - self.assertIn("Add the variant to ALL", r.stderr) - self.assertNotIn("mapping OK", r.stdout) - - def test_a_name_all_cannot_count_refuses_against_its_declared_length(self) -> None: - # The cross-check for the one block held only by name, and the member no - # comment rule can reach: a `Self::` inside a string literal is not a - # comment, so it survives every removal there is. It names the variant - # genuinely absent from `ALL`, which makes the by-name comparison agree. - # Only rustc's own element count objects, because it is the one figure - # here not read out of the text being checked. - t = self.tree() - t.write_mapping_text(annotate(mapping_source(listed=3), ALL_ENTRY, - '@ "Self::Platform3",')) - r = t.run() - self.assertEqual(r.returncode, 2, r.stdout) - self.assertIn("declared `[Self; 3]`", r.stderr) - self.assertIn("read 4 entry name(s)", r.stderr) - self.assertNotIn("mapping OK", r.stdout) - - def test_a_commented_out_arm_refuses(self) -> None: - # Removing comments before reading must not let a commented-out arm read - # as cleanly absent. The variant is still listed in `ALL` and is still a - # platform no arm resolves, which is a desktop that fetches no engine. - t = self.tree() - t.write_mapping_text(annotate(mapping_source(), OS_ARCH_ARM, - " // " + OS_ARCH_ARM.lstrip())) - r = t.run() - self.assertEqual(r.returncode, 2, r.stdout) - self.assertIn("ServerPlatform::ALL", r.stderr) - self.assertIn("Platform0", r.stderr) - self.assertNotIn("mapping OK", r.stdout) - - def test_a_double_slash_inside_a_string_literal_keeps_its_arm(self) -> None: - # The bound on comment removal: `//` inside a literal is data. Stripping - # from it truncates the arm's value, and the arm then reads as one this - # gate could not parse -- a refusal naming a wrapping that is not there. - platforms = with_arch(DEFAULT_PLATFORMS, 2, "x86//64") - t = self.tree() - t.write_mapping(platforms) - t.write_workflow(platforms) - r = t.run() - self.assertEqual(r.returncode, 0, r.stderr) - self.assertIn("linux-x86//64", r.stdout) - - def test_a_commented_asset_path_is_not_a_published_asset(self) -> None: - # The same fail-open shape on the release side. `attached` is allowed to - # be a superset, so no later comparison can object to a name added to - # it, and a commented path names exactly the URL whose absence would - # otherwise be reported. Both placements count: outside the heredoc, - # where the shell reads `#` as a comment, and inside it, where `#` is - # literal text and the line is not an attached path either way. - triple = DEFAULT_TRIPLES[3] - asset = f"phase-server-slim-{triple}" - comment = f" # artifacts/{asset}/{asset}.minisig" - body = release_source(omit={triple: "signature"}) - for label, anchor in (("outside the heredoc", " cat <<'EOF'"), - ("inside the heredoc", " EOF")): - with self.subTest(placement=label): - self.assertEqual(body.count(anchor), 1, - "the placement must be unambiguous, or this " - "case injects somewhere it did not intend") - t = self.tree() - t.write_release_text(body.replace(anchor, f"{comment}\n{anchor}")) - r = t.run() - self.assertEqual(r.returncode, 1, r.stdout) - self.assertIn(f"{asset}.minisig", r.stderr) - self.assertIn("does not publish", r.stderr) - - def test_a_windows_asset_without_its_exe_suffix_fails(self) -> None: - # A desktop derives its asset name from its triple plus the suffix its - # own platform implies, so a Windows desktop asks for `...-msvc.exe`. A - # release attaching a complete, signed pair under the bare triple - # publishes nothing at either URL that desktop requests. - t = self.tree() - t.write_release(exe="") - r = t.run() - self.assertEqual(r.returncode, 1, r.stdout) - self.assertIn("phase-server-slim-x86_64-pc-windows-msvc.exe", r.stderr) - self.assertIn("does not publish", r.stderr) - - def test_a_mapped_triple_the_release_does_not_publish_fails(self) -> None: - # Four triples on each side, so neither count assertion fires and only - # the subset check can catch it. A desktop on this platform resolves an - # asset name the release never carries and its download 404s. - t = self.tree() - t.write_mapping(with_triple(DEFAULT_PLATFORMS, 3, SENTINEL_TRIPLE)) - r = t.run() - self.assertEqual(r.returncode, 1, r.stdout) - self.assertIn(SENTINEL_TRIPLE, r.stderr) - self.assertIn("does not publish", r.stderr) - - def test_a_published_triple_the_mapping_does_not_name_passes(self) -> None: - # The release's slim-server set is not the desktop platform set. A triple - # published for a consumer that is not a desktop is a superset no variant - # resolves, and a superset cannot 404 anything a desktop asks for. - t = self.tree() - t.write_release(DEFAULT_TRIPLES + ("x86_64-unknown-freebsd",)) - r = t.run() - self.assertEqual(r.returncode, 0, r.stderr) - self.assertIn("engine target triples OK", r.stdout) - - def test_a_signed_triple_the_release_never_attaches_refuses(self) -> None: - # The signing loop and the asset list are two readings of one published - # set. A triple signed but never attached is a built, verified binary at - # a URL that 404s, and a reader trusting the loop alone passes it. - t = self.tree() - t.write_release(attached=DEFAULT_TRIPLES[:3]) - r = t.run() - self.assertEqual(r.returncode, 2, r.stdout) - self.assertIn("signs", r.stderr) - self.assertIn(DEFAULT_TRIPLES[3], r.stderr) - self.assertNotIn("mapping OK", r.stdout) - - def test_each_half_of_a_derived_pair_is_its_own_identity(self) -> None: - # A desktop derives two URLs from its platform, the binary and the - # signature beside it, and whichever is missing 404s on its own. Each is - # therefore its own name here: the unbuilt binary disagrees with the - # signing loop, while the unattached signature is simply a URL nobody - # published. Both are dropped in turn because an enumeration is falsified - # by the member it omits. - triple = DEFAULT_TRIPLES[3] - for half, code, reason in ( - ("binary", 2, f"Signed, never attached: ['{triple}']"), - ("signature", 1, f"phase-server-slim-{triple}.minisig"), - ): - with self.subTest(missing=half): - t = self.tree() - t.write_release(omit={triple: half}) - r = t.run() - self.assertEqual(r.returncode, code, r.stdout) - self.assertIn(reason, r.stderr) - self.assertNotIn("mapping OK", r.stdout) - - def test_a_duplicate_target_triple_arm_refuses(self) -> None: - # Four arms resolving three triples, so one platform's desktop downloads - # another platform's binary. The two variants sharing the triple are the - # finding; the size of the distinct set is not. - t = self.tree() - t.write_mapping(with_triple(DEFAULT_PLATFORMS, 2, DEFAULT_TRIPLES[3])) - r = t.run() - self.assertEqual(r.returncode, 2, r.stdout) - self.assertIn(f"'phase-server-slim-{DEFAULT_TRIPLES[3]}'", r.stderr) - self.assertIn("'Platform2', 'Platform3'", r.stderr) - self.assertNotIn("mapping OK", r.stdout) - - def test_two_triples_that_derive_one_asset_name_refuse(self) -> None: - # The other end of the same class. The suffix is part of the name a - # desktop requests, so two variants whose triples differ only by the - # suffix one of their platforms appends derive a single URL: the Windows - # desktop and the linux-x86_64 desktop ask for the same file and one of - # them gets a binary built for the other OS. Compared as bare triples - # these are two distinct values and the tree reads as clean. - t = self.tree() - t.write_mapping( - with_triple(DEFAULT_PLATFORMS, 2, f"{DEFAULT_TRIPLES[1]}.exe")) - r = t.run() - self.assertEqual(r.returncode, 2, r.stdout) - self.assertIn(f"'phase-server-slim-{DEFAULT_TRIPLES[1]}.exe'", r.stderr) - self.assertIn("'Platform1', 'Platform2'", r.stderr) - self.assertNotIn("mapping OK", r.stdout) - - def test_two_variants_sharing_one_bare_triple_refuse_when_one_is_windows(self) -> None: - # The middle of that class, and the member a derived-name key alone - # admits. The windows variant is given the linux-x86_64 variant's - # triple, so the two derive `...-musl.exe` and `...-musl` and no asset - # name collides at all. The release attaches both of those names, so the - # unpublished-asset check has nothing to report and only a key on the - # bare triple can object -- while both desktops resolve one engine build - # and one of them is not the platform it was compiled for. - t = self.tree() - shared = DEFAULT_TRIPLES[2] - t.write_mapping(with_triple(DEFAULT_PLATFORMS, 1, shared)) - t.write_release(attached=DEFAULT_TRIPLES + (f"{shared}.exe",)) - r = t.run() - self.assertEqual(r.returncode, 2, r.stdout) - self.assertIn(f"'{shared}'", r.stderr) - self.assertIn("'Platform1', 'Platform2'", r.stderr) - # Which axis collided, not merely that something did: this is the bare - # triple's refusal, and the derived-name one would be the wrong report. - self.assertIn("resolve the same engine triple", r.stderr) - self.assertNotIn("does not publish", r.stderr) - self.assertNotIn("mapping OK", r.stdout) - - def test_an_unreadable_release_workflow_refuses(self) -> None: - # The vacuous-green direction on the published-asset side: a set this - # gate cannot read is empty, and an empty published set makes every - # mapped triple unpublished or none of them, depending on which way a - # tolerant reader took the difference. Neither answer was measured. - for label, prepare, reason in ( - ("absent file", lambda t: t.delete(RELEASE_REL), - "slim server assets cannot be read"), - ("renamed signing step", - lambda t: t.write_release(sign_step="sign-artifacts"), - "has no step 'sign-release-artifacts'"), - ("renamed asset step", - lambda t: t.write_release(asset_step="assets"), - "has no step 'release-assets'"), - ("reshaped loop", lambda t: t.write_release(loop_var="target"), - "`for triple in ...` loop"), - ): - with self.subTest(release=label): - t = self.tree() - prepare(t) - r = t.run() - self.assertEqual(r.returncode, 2, r.stdout) - self.assertIn(reason, r.stderr) - self.assertNotIn("mapping OK", r.stdout) - - def test_a_complete_preview_tree_reports_its_provisioning(self) -> None: - # The positive control for the line every preview case below asserts the - # absence of. Without it a gate that never printed that line at all would - # satisfy all of them, and the whole preview block would be vacuous. - t = self.tree() - r = t.run() - self.assertEqual(r.returncode, 0, r.stderr) - self.assertIn("preview provisioning OK", r.stdout) - for _, _, triple in DEFAULT_PLATFORMS: - self.assertIn(triple, r.stdout) - - def test_a_triple_dropped_from_any_preview_site_strands_a_desktop(self) -> None: - # preview-server.yml spells its platform set four times and the desktop - # reads only the manifest, so a triple built and signed but never written - # there resolves nothing at runtime while every release check stays green. - # Each spelling is dropped in turn: an enumeration is falsified by the - # member it omits, and one site standing in for the others would be that - # omission. `drop_sig` keeps the key and removes half its URL pair, which - # is the platform resolvable to an artifact that cannot be verified. - stranded = DEFAULT_TRIPLES[3] - for knob, names in ( - ("drop_build", "builds"), - ("drop_download", "downloads"), - ("drop_sign", "signs"), - ("drop_key", "names in its manifest"), - ("drop_sig", "gives a signed URL pair in its manifest"), - ): - with self.subTest(site=knob): - t = self.tree() - t.write_preview(**{knob: stranded}) - r = t.run() - self.assertEqual(r.returncode, 1, r.stdout) - self.assertIn(stranded, r.stderr) - self.assertIn(names, r.stderr) - self.assertNotIn("preview provisioning OK", r.stdout) - - def test_a_url_that_is_not_the_exact_artifact_strands_a_desktop(self) -> None: - # The desktop fetches both URLs verbatim, so an entry naming anything but - # the uploaded object strands it. Every case keeps the terminal file name - # intact, so only comparing the whole URL can refuse them: the first three - # append to or alter that name, and the last two leave it untouched while - # moving the upload prefix and swapping the fingerprint for a variable the - # step never binds. Each `old` carries the name, so exactly one platform's - # `url` line is rewritten and the report can still name it. - stranded = DEFAULT_TRIPLES[3] - name = (f"phase-server-{stranded}" - f"{'.exe' if 'windows' in stranded else ''}") - for label, old, new in ( - ("appended binary name", f'/{name}"', f'/{name}-old"'), - ("appended signature", f'/{name}.minisig"', f'/{name}.minisig.bak"'), - ("altered signature suffix", f'/{name}.minisig"', f'/{name}.sig"'), - ("mutated upload prefix", - f'preview-server/" + $fingerprint + "/{name}"', - f'preview-server-old/" + $fingerprint + "/{name}"'), - ("mutated fingerprint authority", - f'+ $fingerprint + "/{name}"', - f'+ $commit + "/{name}"'), - ): - with self.subTest(case=label): - body = preview_source() - self.assertIn(old, body) - t = self.tree() - t.write_preview_text(body.replace(old, new)) - r = t.run() - self.assertEqual(r.returncode, 1, r.stdout) - self.assertIn(stranded, r.stderr) - self.assertIn("gives a signed URL pair in its manifest", r.stderr) - self.assertNotIn("preview provisioning OK", r.stdout) - - def test_reformatted_url_whitespace_still_names_the_exact_artifact(self) -> None: - # Equality over the whole URL is one keystroke from refusing what it should - # admit, so the normalisation that keeps formatting free needs its own - # control: respacing the jq concatenation names the same object and must - # still pass. Without this the normalisation is unobservable, because the - # template and the workflow happen to share their spacing. - body = preview_source() - respaced = body.replace('" + $fingerprint + "', '" + $fingerprint + "') - self.assertNotEqual(respaced, body) - t = self.tree() - t.write_preview_text(respaced) - r = t.run() - self.assertEqual(r.returncode, 0, r.stderr) - self.assertIn("preview provisioning OK", r.stdout) - - def test_moving_the_upload_authority_alone_strands_every_desktop(self) -> None: - # The manifest is untouched in both cases: only the step's own upload path - # moves. A gate comparing the manifest against a path spelled in the gate - # would stay green here, because neither side of that comparison changed -- - # which is why the path is read from this assignment instead. Moving it - # strands every platform (exit 1); pointing it at an unbound variable is a - # shape the gate cannot read at all (exit 2), and the two are kept apart so - # a refusal can never be mistaken for a finding. - for label, old, new, code in ( - ("upload prefix path", - 'prefix="desktop/preview-server/$FINGERPRINT"', - 'prefix="desktop/preview-server-v2/$FINGERPRINT"', 1), - ("upload fingerprint variable", - 'prefix="desktop/preview-server/$FINGERPRINT"', - 'prefix="desktop/preview-server/$COMMIT"', 2), - ): - with self.subTest(case=label): - body = preview_source() - self.assertIn(old, body) - t = self.tree() - t.write_preview_text(body.replace(old, new)) - r = t.run() - self.assertEqual(r.returncode, code, r.stdout + r.stderr) - self.assertNotIn("preview provisioning OK", r.stdout) - - def test_a_second_upload_prefix_assignment_refuses(self) -> None: - # Shell assignment is sequential: the later value controls every upload, - # so accepting the first assignment checks a path the step does not use. - # A different second value ensures this case reaches the ambiguity guard - # rather than merely duplicating harmless text. - original = 'prefix="desktop/preview-server/$FINGERPRINT"' - body = preview_source() - self.assertEqual(body.count(original), 1) - t = self.tree() - t.write_preview_text(body.replace( - original, - f'{original}\n prefix="desktop/preview-server-old/$FINGERPRINT"', - )) - r = t.run() - self.assertEqual(r.returncode, 2, r.stdout + r.stderr) - self.assertIn('`prefix="..."` assignment (found 2)', r.stderr) - self.assertNotIn("preview provisioning OK", r.stdout) - - def test_a_duplicate_manifest_key_with_a_later_bad_url_refuses(self) -> None: - # jq keeps the later value for a duplicate object key. A checker that - # reduces keys to a set and reads the first matching block sees the valid - # entry instead, so this inserts a later key whose URL or signature is - # bad while preserving the original complete entry. - triple = DEFAULT_TRIPLES[3] - name = f"phase-server-{triple}" - closing = " },\n data: [" - for field, suffix in (("url", "-old"), ("sig_url", ".bak")): - with self.subTest(field=field): - url_suffix = suffix if field == "url" else "" - bad_url = ( - f'("https://data.phase-rs.dev/desktop/preview-server/" ' - f'+ $fingerprint + "/{name}{url_suffix}")' - ) - duplicate = ( - f' "{triple}": {{\n' - f' url: {bad_url},\n' - f' sig_url: ' - f'("https://data.phase-rs.dev/desktop/preview-server/" ' - f'+ $fingerprint + "/{name}.minisig")\n' - " },\n" - ) - if field == "sig_url": - duplicate = duplicate.replace( - f'/{name}.minisig")', f'/{name}.minisig{suffix}")') - body = preview_source() - self.assertEqual(body.count(closing), 1) - t = self.tree() - t.write_preview_text(body.replace("}\n" + closing, "},\n" + duplicate + closing)) - r = t.run() - self.assertEqual(r.returncode, 2, r.stdout + r.stderr) - self.assertIn("duplicate manifest binary key", r.stderr) - self.assertIn(triple, r.stderr) - self.assertNotIn("preview provisioning OK", r.stdout) - - def test_whitespace_inside_a_url_literal_is_not_free(self) -> None: - # Normalising the expression must not reach inside its strings. R2 holds no - # object under `preview- server/`, so a space there names a missing file - # while leaving the token sequence and the terminal name intact -- the - # member a whitespace-blind normalisation admits. - body = preview_source() - old = '"https://data.phase-rs.dev/desktop/preview-server/"' - new = '"https://data.phase-rs.dev/desktop/preview- server/"' - self.assertIn(old, body) - t = self.tree() - t.write_preview_text(body.replace(old, new)) - r = t.run() - self.assertEqual(r.returncode, 1, r.stdout) - self.assertIn("gives a signed URL pair in its manifest", r.stderr) - self.assertNotIn("preview provisioning OK", r.stdout) - - def test_a_manifest_data_entry_shaped_like_a_platform_is_not_one(self) -> None: - # The step's jq also writes a `data:` array beside `binaries`, and a - # pattern taking any quoted key followed by a brace would harvest those as - # platforms. The triple missing from `binaries` would then come back - # covered by a name that provisions no binary at all -- the admitted - # member this population is narrowed at the read to keep out. - missing = DEFAULT_TRIPLES[3] - body = preview_source(drop_key=missing).replace( - 'name: "card-data.json"', - f'"{missing}": {{\n ' - 'name: "card-data.json"') - self.assertIn(f'"{missing}"', body) - t = self.tree() - t.write_preview_text(body) - r = t.run() - self.assertEqual(r.returncode, 1, r.stdout) - self.assertIn(missing, r.stderr) - self.assertIn("names in its manifest", r.stderr) - - def test_an_unreadable_preview_workflow_refuses(self) -> None: - # The vacuous-green direction on the preview side: a set this gate cannot - # read comes back empty, and an empty provisioned set makes every mapped - # triple stranded or none of them, depending which way a tolerant reader - # took the difference. Neither answer was measured, so each shape refuses. - for label, prepare, reason in ( - ("absent file", lambda t: t.delete(PREVIEW_REL), - "preview server binaries built per platform cannot be read"), - ("renamed build job", - lambda t: t.write_preview(build_job="compile"), - "job 'build' is absent"), - ("renamed publish job", - lambda t: t.write_preview(publish_job="ship"), - "job 'publish' is absent"), - ("renamed signing step", - lambda t: t.write_preview(sign_step="Sign and publish"), - f"has no step '{PREVIEW_SIGN_STEP}'"), - ("matrix product axis", - lambda t: t.write_preview_text(preview_source().replace( - " matrix:\n include:", - " matrix:\n arch: [x86_64]\n include:")), - "declares matrix axes"), - ("reshaped binaries array", - lambda t: t.write_preview_text( - preview_source().replace("binaries=(", "bins=(")), - "`binaries=( ... )` array"), - ("reshaped manifest object", - lambda t: t.write_preview_text( - preview_source().replace("binaries: {", "bins: {")), - "`binaries: {` object"), - ("two steps answering to one name", - lambda t: t.write_preview_text( - preview_source() - + f" - name: {PREVIEW_SIGN_STEP}\n" - + " run: echo not the signing step\n"), - "has two steps answering to"), - ): - with self.subTest(preview=label): - t = self.tree() - prepare(t) - r = t.run() - self.assertEqual(r.returncode, 2, r.stdout) - self.assertIn(reason, r.stderr) - self.assertNotIn("preview provisioning OK", r.stdout) - - def test_a_raw_string_before_the_impl_does_not_desync_comment_removal(self) -> None: - # Comment removal reads whole source files, so it passes through every - # literal on the way to the blocks. A raw string read as an ordinary one - # ends at the first quote it carries, leaving literal state open, and the - # `//` inside it then opens a comment that swallows real code after it. - # The raw string carries an odd number of interior quotes, which is what - # desynchronises a reader that takes `r#"` for an ordinary literal: it - # closes at that quote and reopens at the next one in the file, so the - # comments below fall inside what it believes is a literal and survive - # removal. They then read as receivers written twice. An even number - # re-synchronises by accident and would measure nothing, and an interior - # quote followed by `#` would close the raw string itself. - anchor = "impl ServerPlatform {" - body = mapping_source(comment=0) - self.assertEqual(body.count(anchor), 1, - "the raw string must be spliced above the one impl, or " - "this case measures a tree it did not build") - self.assertIn("// Self::Platform0", body, - "a comment must fall after the raw string, or the desync " - "has nothing to swallow and the case cannot discriminate") - raw = 'const NOTE: &str = r#"paths contain a " character"#;\n' - t = self.tree() - t.write_mapping_text(body.replace(anchor, f"{raw}\n{anchor}")) - r = t.run() - self.assertEqual(r.returncode, 0, r.stderr) - self.assertIn("shell platform mapping OK", r.stdout) - - def test_a_matrix_product_axis_beside_include_refuses(self) -> None: - # `include` is not the whole published set: a product axis publishes its - # combinations as well, and this gate reads a platform off one entry's - # (os, arch) pair, which a product has no entry for. Reading `include` - # and ignoring the rest passes a tree publishing a desktop it never saw, - # and the count guard cannot object because `include` still numbers four. - anchor = " matrix:\n include:\n" - body = workflow_source() - self.assertEqual(body.count(anchor), 1, - "the axis must be spliced beside the one include, or " - "this case measures a shape it did not build") - t = self.tree() - t.write_workflow_text(body.replace( - anchor, " matrix:\n os: [freebsd]\n" - " arch: [x86_64]\n include:\n")) - r = t.run() - self.assertEqual(r.returncode, 2, r.stdout) - self.assertIn("declares matrix axes", r.stderr) - self.assertIn("'arch'", r.stderr) - self.assertNotIn("mapping OK", r.stdout) - - def test_an_asset_path_in_another_heredoc_is_not_a_published_asset(self) -> None: - # The other half of the release-side cut: the pattern decides what a line - # must look like, this decides where it has to be. A perfectly - # asset-shaped path inside a different heredoc is not in the list the - # release attaches, and counting it hides the signature genuinely - # missing from that list -- `attached` being a superset means no later - # comparison can object to the addition. - triple = DEFAULT_TRIPLES[3] - asset = f"phase-server-slim-{triple}" - anchor = " cat <<'EOF'" - body = release_source(omit={triple: "signature"}) - self.assertEqual(body.count(anchor), 1, - "the decoy must precede the one real heredoc, or this " - "case measures a step it did not build") - decoy = (" cat <<'SKIP' > /dev/null\n" - f" artifacts/{asset}/{asset}.minisig\n" - " SKIP\n") - t = self.tree() - t.write_release_text(body.replace(anchor, decoy + anchor)) - r = t.run() - self.assertEqual(r.returncode, 1, r.stdout) - self.assertIn(f"{asset}.minisig", r.stderr) - self.assertIn("does not publish", r.stderr) - - def test_every_raw_string_prefix_is_recognised(self) -> None: - # The prefixed forms are the members an enumeration written for `r` - # omits, and they are the ones a guard reading the character before the - # `r` must decline: `b` and `c` are identifier characters. Only a hashed - # form can carry an interior quote -- `r"a " b"` closes at that quote and - # is not one literal at all -- so the desyncing body belongs to those, - # and the hash-less forms stand for recognition alone. An odd interior - # quote is what leaves literal state open when the opener goes - # unrecognised; the comments below then survive removal and read as - # receivers written twice. - anchor = "impl ServerPlatform {" - for prefix in ("r", "br", "cr"): - for hashes in ("", "#"): - with self.subTest(prefix=f"{prefix}{hashes}"): - body = mapping_source(comment=0) - self.assertEqual(body.count(anchor), 1) - inner = ('paths contain a " character' if hashes - else "paths look like this") - raw = (f'const NOTE: &str = ' - f'{prefix}{hashes}"{inner}"{hashes};\n') - t = self.tree() - t.write_mapping_text(body.replace(anchor, f"{raw}\n{anchor}")) - r = t.run() - self.assertEqual(r.returncode, 0, r.stderr) - self.assertIn("shell platform mapping OK", r.stdout) - - def test_a_literal_carrying_the_declaration_shape_does_not_supply_the_count(self) -> None: - # Why `ALL`'s count comes out of the same match as its entries. A string - # literal is not a comment, so it survives removal and any second pattern - # searching the file finds it first -- which is how a sentence of prose - # once supplied the figure the entries are held against. The real - # declaration says three and the entries read four, so this refuses iff - # the count came from the declaration rather than from the literal. - body = annotate(mapping_source(listed=3), ALL_ENTRY, '@ "Self::Platform3",') - anchor = "impl ServerPlatform {" - self.assertEqual(body.count(anchor), 1) - t = self.tree() - t.write_mapping_text(body.replace( - anchor, 'const HELP: &str = "const ALL: [Self; 4]";\n\n' + anchor)) - r = t.run() - self.assertEqual(r.returncode, 2, r.stdout) - self.assertIn("declared `[Self; 3]`", r.stderr) - self.assertIn("read 4 entry name(s)", r.stderr) - self.assertNotIn("mapping OK", r.stdout) - - def test_a_second_job_publishing_desktops_refuses(self) -> None: - # The published set is anchored on one job id, so a sibling job shipping - # desktops is a population this gate never walks: its platforms have no - # ServerPlatform variant checked against them, and the expected count - # cannot object because it counts only the job that was read. - t = self.tree() - t.write_workflow_text(workflow_source() + """ build-shell-bsd: - runs-on: ubuntu-latest - strategy: - matrix: - include: - - os: freebsd - arch: x86_64 - runner: ubuntu-latest - steps: - - run: echo build -""") - r = t.run() - self.assertEqual(r.returncode, 2, r.stdout) - self.assertIn("build-shell-bsd", r.stderr) - self.assertIn("publish desktops", r.stderr) - self.assertNotIn("mapping OK", r.stdout) - - def test_a_char_literal_holding_a_quote_does_not_hide_a_defect(self) -> None: - # The last opener in Rust's literal grammar, and the only omission that - # needs no look-behind to happen. `'"'` carries a quote that opens no - # literal; read as code it leaves literal state open, the comment below - # it survives removal, and the commented-out arm this tree is built - # around stops being reported. The benign forms are controls: a char - # literal with no quote, and a lifetime, must change nothing. - defect = annotate(mapping_source(), OS_ARCH_ARM, - " // " + OS_ARCH_ARM.lstrip()) - anchor = "impl ServerPlatform {" - self.assertEqual(defect.count(anchor), 1) - for label, decl, code in ( - ("char literal holding a quote", "const Q: char = '\"';", 2), - ("byte char holding a quote", "const Q: u8 = b'\"';", 2), - ("escaped quote char", "const Q: char = '\\'';", 2), - ("escaped quote byte char", "const Q: u8 = b'\\'';", 2), - # The multi-character escapes. A two-character escape rule consumes - # `\u` and then demands the closing quote, so these matched nothing - # and left a loose quote to pair with the next one along. The absent - # space after each comma is load-bearing: it is what leaves the two - # quotes two characters apart. - ("unicode escape beside a quote char", - "const Q: (char, char) = ('\\u{41}','\"');", 2), - ("hex escape beside a quote char", - "const Q: (char, char) = ('\\x41','\"');", 2), - # Underscores are legal inside a unicode escape and do not count - # against its digit budget. A scanner that refused this would fail on - # compiling source, so the assertion below that the refusal names - # `Platform0` is what separates the two exit-2 paths. - ("underscored unicode escape beside a quote char", - "const Q: (char, char) = ('\\u{1_F_6_0_0}','\"');", 2), - ("char literal without a quote", "const Q: u8 = b'!';", 2), - ("a lifetime, not a literal", "struct S<'a>(&'a str);", 2), - ): - with self.subTest(form=label): - t = self.tree() - t.write_mapping_text(defect.replace(anchor, f"{decl}\n\n{anchor}")) - r = t.run() - self.assertEqual(r.returncode, code, r.stdout) - self.assertIn("Platform0", r.stderr) - self.assertNotIn("mapping OK", r.stdout) - - def test_a_second_job_publishing_desktops_by_product_axes_refuses(self) -> None: - # A platform is an (os, arch) pair whichever shape a matrix spells it in, - # and the axis refusal elsewhere is scoped to the job this gate reads, so - # it never reaches a sibling. Reading only `include` entries on siblings - # reads a subset of what publishes. The unrelated-axes case is the - # control: a sibling matrixed on something that is not a platform must - # not fire, or the refusal would be a tripwire on every workflow. - for label, matrix, code in ( - ("product axes", " os: [freebsd]\n arch: [x86_64]", 2), - # A job runs the product of its axes with each `include` entry merged - # in, so this ships freebsd/x86_64 though neither half spells it. - ("an axis and an include entry", - " os: [freebsd]\n include:\n - arch: x86_64", 2), - # The control that pins the conjunction rather than either half: a - # gate refusing on `os` alone would fire on every cross-platform job. - ("an os axis alone", " os: [ubuntu-latest, macos-latest]", 0), - ("unrelated axes", " rust: [stable, beta]", 0), - ): - with self.subTest(sibling=label): - t = self.tree() - t.write_workflow_text(workflow_source() + f""" build-shell-bsd: - runs-on: ubuntu-latest - strategy: - matrix: -{matrix} - steps: - - run: echo build -""") - r = t.run() - self.assertEqual(r.returncode, code, r.stdout) - if code: - # The reason, not just the refusal: this file raises in - # twenty-odd places and every one of them exits 2. - self.assertIn("build-shell-bsd", r.stderr) - self.assertIn("publish desktops", r.stderr) - - def test_a_quote_opening_no_known_token_refuses(self) -> None: - # The bound on the literal-opener enumeration, which five readers have - # now each found one more member of. An unrecognised quote refuses rather - # than being read as code, so the next omission costs a named refusal - # instead of a file stripped with literal state left open. The two - # controls are what the refusal must never fire on. - anchor = "impl ServerPlatform {" - body = mapping_source(comment=0) - self.assertEqual(body.count(anchor), 1) - for label, decl, code in ( - ("a quote opening no token", "const Q: char = '\\u{41;", 2), - # rustc compiles the first and rejects the second as an overlong - # escape, so the bound this pins is on hex digits rather than on - # characters between the braces. - ("an underscored unicode escape", - "const Q: char = '\\u{1_F_6_0_0}';", 0), - ("an overlong unicode escape", "const Q: char = '\\u{1234567}';", 2), - ("a char literal", "const Q: char = 'x';", 0), - ("a lifetime", "struct S<'a>(&'a str);", 0), - ): - with self.subTest(form=label): - t = self.tree() - t.write_mapping_text(body.replace(anchor, f"{decl}\n\n{anchor}")) - r = t.run() - self.assertEqual(r.returncode, code, r.stdout) - if code: - self.assertIn("opens no token", r.stderr) - - def test_a_sibling_matrix_this_gate_cannot_read_refuses(self) -> None: - # A matrix built at run time is a job whose platforms are unknown at read - # time. Passing over it reads a subset of what publishes, and this gate - # soft-fails nowhere else. The three shapes are the same unreadability at - # two depths -- the matrix, and the `include` inside it. The second depth - # is the one a dict filter swallows: a string iterates characters and a - # mapping iterates keys, so either becomes an empty list that publishes - # nothing, which is the empty set passing a subset check. - for label, strategy in ( - ("the matrix is an expression", - " matrix: ${{ fromJSON(needs.setup.outputs.matrix) }}"), - ("include is an expression", - " matrix:\n os: [freebsd]\n" - " include: ${{ fromJSON(needs.setup.outputs.entries) }}"), - ("include is a mapping, not a list", - " matrix:\n os: [freebsd]\n" - " include:\n arch: x86_64"), - ): - with self.subTest(sibling=label): - t = self.tree() - t.write_workflow_text(workflow_source() + f""" build-shell-bsd: - runs-on: ubuntu-latest - strategy: -{strategy} - steps: - - run: echo build -""") - r = t.run() - self.assertEqual(r.returncode, 2, r.stdout) - self.assertIn("build-shell-bsd", r.stderr) - self.assertIn("cannot read", r.stderr) - - def test_an_escaped_quote_inside_a_literal_keeps_its_arm(self) -> None: - # The bound on the ordinary-literal reader. An escaped quote does not - # close the literal, so a reader that stopped there would leave state - # open across the rest of the block and swallow the comments after it. - anchor = "impl ServerPlatform {" - body = mapping_source(comment=0) - self.assertEqual(body.count(anchor), 1) - t = self.tree() - t.write_mapping_text(body.replace( - anchor, 'const NOTE: &str = "a \\" quote";\n\n' + anchor)) - r = t.run() - self.assertEqual(r.returncode, 0, r.stderr) - self.assertIn("shell platform mapping OK", r.stdout) - - def test_a_receiver_written_twice_in_one_block_refuses(self) -> None: - # The other half of the receiver-against-arm comparison. Two arms naming - # one variant is a variant whose second arm is unreachable, and the - # dictionary keyed on receivers cannot see it -- the second simply - # replaces the first. Counting the receivers is what notices. - t = self.tree() - t.write_mapping_text(annotate(mapping_source(), OS_ARCH_ARM, - "@\n" + OS_ARCH_ARM)) - r = t.run() - self.assertEqual(r.returncode, 2, r.stdout) - self.assertIn("written more than once: ['Platform0']", r.stderr) - self.assertNotIn("mapping OK", r.stdout) - - def test_a_renamed_publishing_job_refuses(self) -> None: - # The vacuous-green direction on the workflow side, and the leg the - # mapping and release sides both already have: a job this gate cannot - # find is an empty published set, and the empty set is a subset of any - # mapping, so a tolerant reader announces a clean pass over nothing. - # The reason is asserted, not just the refusal: a renamed job is also a - # sibling job publishing desktops, and that refusal names `build-shell` - # too, so a case reading only the job name passes whichever check fired. - t = self.tree() - t.write_workflow(job="build-desktop") - r = t.run() - self.assertEqual(r.returncode, 2, r.stdout) - self.assertIn("is absent", r.stderr) - self.assertNotIn("mapping OK", r.stdout) - - def test_the_harness_reads_the_fixture_not_the_real_tree(self) -> None: - # If SHELL_PLATFORM_MAPPING_ROOT were ignored, every case above would be - # measuring this checkout and the passing ones would be vacuous. - for real in (REAL_MAPPING, REAL_WORKFLOW, REAL_RELEASE, REAL_PREVIEW): - body = real.read_text(encoding="utf-8") - for sentinel in (SENTINEL_ARCH, SENTINEL_TRIPLE): - self.assertNotIn(sentinel, body, - "the sentinel must not exist in the real tree, " - "or this test proves nothing") - t = self.tree() - t.write_workflow(with_arch(DEFAULT_PLATFORMS, 2, SENTINEL_ARCH)) - r = t.run() - self.assertEqual(r.returncode, 1, r.stdout) - self.assertIn(SENTINEL_ARCH, r.stderr) - - t = self.tree() - t.write_mapping(with_triple(DEFAULT_PLATFORMS, 2, SENTINEL_TRIPLE)) - r = t.run() - self.assertEqual(r.returncode, 1, r.stdout) - self.assertIn(SENTINEL_TRIPLE, r.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/scripts/preview_data_wait_tests.py b/scripts/preview_data_wait_tests.py index e4aff7bfbfb..9e0dff9e8be 100755 --- a/scripts/preview_data_wait_tests.py +++ b/scripts/preview_data_wait_tests.py @@ -12,12 +12,16 @@ against a local HTTP server that answers HEAD the way the data endpoint does. The wiring tests decode the workflows with `yaml.safe_load`, the way GitHub reads them, and assert over the decoded structure -- not over workflow text. +The publish step's own `run` is one such decoded value, which `publish` below +runs against a stubbed checkout, so the platform check inside it is measured +rather than read. """ from __future__ import annotations import functools import http.server +import os import re import subprocess import tempfile @@ -50,6 +54,34 @@ "phase-rs-data/staging/$CARD_DATA_FILENAME", "phase-rs-data/staging/$DRAFT_POOLS_FILENAME", ) +CONTRACT = ROOT / "packaging/desktop-platforms.txt" +# Every command the publish step shells out to, as one stub dispatching on the +# name it was invoked by: minisign writes a signature, npx records the upload +# and fills a bucket, curl answers out of it. None of this is under test -- it +# is the least that lets the shipped step run somewhere it cannot publish. +COMMAND_STUB = """#!/usr/bin/env python3 +import os, shutil, sys +from pathlib import Path + +me, argv, bucket = Path(sys.argv[0]).name, sys.argv[1:], Path(os.environ["BUCKET"]) +if me == "minisign": + Path(argv[argv.index("-x") + 1]).write_text("untrusted signature\\n") +elif me == "npx": # npx wrangler r2 object [--file ] + with open(os.environ["UPLOAD_LOG"], "a") as log: + log.write(f"{argv[3]} {argv[4]}\\n") + if argv[3] == "put": + (bucket / argv[4]).parent.mkdir(parents=True, exist_ok=True) + shutil.copy(argv[argv.index("--file") + 1], bucket / argv[4]) +elif me == "curl" and "-w" in argv: # the manifest this run would supersede + print("404", end="") +elif me == "curl" and "--get" in argv: # the object listing retention walks + print('{"success":true,"result":[],"result_info":{"is_truncated":false}}') +elif me == "curl": # a just-published object, read back for verification + published = bucket / "phase-rs-data" / argv[-1].split(".dev/")[1] + if not published.is_file(): + sys.exit(22) + shutil.copy(published, argv[argv.index("-o") + 1]) +""" class _QuietHandler(http.server.SimpleHTTPRequestHandler): @@ -216,6 +248,18 @@ def wait_and_sign(self) -> tuple[list[dict], int, int]: self.assertEqual(len(signs), 1, "publish must sign manifest data URLs in exactly one step") return steps, waits[0], signs[0] + def test_publish_checks_out_the_commit_it_publishes(self) -> None: + # The scripts and the platform contract this job reads have to come from + # the commit whose binaries it signs, not from whichever ref is running + # the workflow. `commit` is a required input, so there is no fallback. + checkouts = [ + step.get("with") or {} + for step in self.preview["jobs"]["publish"]["steps"] + if "actions/checkout@" in str(step.get("uses", "")) + ] + self.assertEqual(len(checkouts), 1, "publish must check out exactly once") + self.assertEqual(checkouts[0].get("ref"), "${{ inputs.commit }}") + def test_the_wait_step_carries_nothing_but_its_run(self) -> None: steps, wait_index, _ = self.wait_and_sign() wait = steps[wait_index] @@ -278,6 +322,78 @@ def test_the_gate_publishes_no_deadline_for_the_wait_to_inherit(self) -> None: for run in _run_strings(self.preview): self.assertNotRegex(run, r"data_deadline_epoch") + def publish(self, contract: str) -> tuple[subprocess.CompletedProcess, list[str]]: + """Runs the shipped publish step over a checkout holding `contract`, and + returns it with every upload the step managed to make.""" + runs = [run for run in _run_strings(self.preview) if "binaries=(" in run] + self.assertEqual(len(runs), 1, "one step must list the binaries to publish") + with tempfile.TemporaryDirectory() as tmp: + work, stubs, log = Path(tmp, "work"), Path(tmp, "bin"), Path(tmp, "uploads") + (work / "packaging").mkdir(parents=True) + (work / CONTRACT.relative_to(ROOT)).write_text(contract, encoding="utf-8") + stubs.mkdir() + for command in ("sudo", "apt-get", "minisign", "npx", "curl"): + # sudo and apt-get fall off the end of the stub and exit 0. + (stubs / command).write_text(COMMAND_STUB, encoding="utf-8") + (stubs / command).chmod(0o755) + for entry in self.preview["jobs"]["build"]["strategy"]["matrix"]["include"]: + artifact = work / "artifacts" / entry["triple"] + artifact.mkdir(parents=True) + binary = f"phase-server-{entry['triple']}{entry['extension']}" + (artifact / binary).write_text(entry["triple"], encoding="utf-8") + env = {name: name.lower() for name in self.preview["jobs"]["publish"]["env"]} + result = subprocess.run( + ["bash", "-c", runs[0]], + cwd=work, + env={**env, "PATH": f"{stubs}:{os.environ['PATH']}", "TMPDIR": tmp, + "BUCKET": str(Path(tmp, "bucket")), "UPLOAD_LOG": str(log)}, + capture_output=True, + text=True, + timeout=300, + ) + # Read inside the sandbox: an upload log collected after cleanup is + # empty whether the step published or not. + uploads = log.read_text(encoding="utf-8").splitlines() if log.exists() else [] + return result, uploads + + def printed_set(self, stdout: str, label: str) -> list[str]: + lines = [line for line in stdout.splitlines() if line.startswith(label)] + self.assertEqual(len(lines), 1, f"the publish step must print {label!r} once") + return sorted(lines[0].split(":", 1)[1].split()) + + def test_publish_holds_the_contract_against_what_it_uploads(self) -> None: + # Both sets are printed, so a pass here cannot be a check that never ran. + result, uploads = self.publish(CONTRACT.read_text(encoding="utf-8")) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + built = sorted( + entry["triple"] + for entry in self.preview["jobs"]["build"]["strategy"]["matrix"]["include"] + ) + self.assertEqual(self.printed_set(result.stdout, "desktop-platforms.txt"), built) + self.assertEqual(self.printed_set(result.stdout, "this job publishes"), built) + self.assertIn("put phase-rs-data/desktop/preview-server.json", uploads) + + def test_a_listed_triple_publish_does_not_carry_stops_before_publication(self) -> None: + # A triple this job builds and the contract lists, absent from the step's + # own `binaries`, would leave that desktop with no preview URL at all. + # Publication is the only authority that can see both, so it must refuse. + unpublished = "linux riscv64 riscv64gc-unknown-linux-musl\n" + result, uploads = self.publish(CONTRACT.read_text(encoding="utf-8") + unpublished) + self.assertNotEqual(result.returncode, 0, result.stdout) + self.assertIn("riscv64gc-unknown-linux-musl", result.stdout) + self.assertIn("::error::packaging/desktop-platforms.txt", result.stdout) + self.assertEqual(uploads, [], "a mismatch must publish nothing at all") + + def test_a_published_triple_with_no_contract_row_stops_before_publication(self) -> None: + # The other direction the same error promises: a binary this job uploads + # that the contract does not list is a preview no desktop ever asks for. + dropped = "aarch64-apple-darwin" + rows = CONTRACT.read_text(encoding="utf-8").splitlines(True) + result, uploads = self.publish("".join(r for r in rows if dropped not in r)) + self.assertNotEqual(result.returncode, 0, result.stdout) + self.assertIn(f"> {dropped}", result.stdout) + self.assertEqual(uploads, [], "a mismatch must publish nothing at all") + def test_the_deploy_caller_needs_the_job_that_uploads_the_data(self) -> None: def needs(job: str) -> set[str]: value = self.deploy["jobs"][job].get("needs") diff --git a/scripts/release_dispatch_guard_tests.py b/scripts/release_dispatch_guard_tests.py index 23859372936..d4cec924c3d 100755 --- a/scripts/release_dispatch_guard_tests.py +++ b/scripts/release_dispatch_guard_tests.py @@ -1,24 +1,32 @@ #!/usr/bin/env python3 -"""Tests for the release recovery-dispatch guard. +"""Tests for release.yml's publication guards. -The guard decides whether a `workflow_dispatch` run of release.yml may publish -the tag it asks for, so it gets a discriminating test rather than a smoke test. +The recovery-dispatch guard decides whether a `workflow_dispatch` run may +publish the tag it asks for, and the asset-name check decides whether what the +release publishes is what a desktop downloads. Both get discriminating tests +rather than smoke tests. -The shell under test is `scripts/require-tag-ref-dispatch.sh` itself -- the same -file the workflow step runs. Nothing here re-types the guard, and nothing here -executes text pulled out of a YAML file. +The dispatch guard's shell is `scripts/require-tag-ref-dispatch.sh` itself -- +the same file the workflow step runs. The asset-name check has no script of its +own, so its tests decode the step's `run` with `yaml.safe_load`, the way GitHub +reads it, and execute that over a stub checkout. Nothing here re-types either. """ from __future__ import annotations +import os import re import subprocess +import tempfile import unittest from pathlib import Path +import yaml + ROOT = Path(__file__).resolve().parent.parent GUARD = ROOT / "scripts/require-tag-ref-dispatch.sh" WORKFLOW = ROOT / ".github/workflows/release.yml" +CONTRACT = ROOT / "packaging/desktop-platforms.txt" def dispatch(**env: str) -> subprocess.CompletedProcess: @@ -81,5 +89,70 @@ def test_the_workflow_runs_this_guard_on_the_dispatch_path(self) -> None: self.assertRegex(body, rf"{var}:\s*\$\{{\{{\s*{expr}\s*\}}\}}") +class DesktopDownloadNameTests(unittest.TestCase): + """The release must publish the filenames the desktop shell downloads. + + The built artifacts and the upload list are both publisher-side spellings: + rename a pair in both and they still agree while the canonical URL 404s. + native_engine.rs fetches `phase-server-slim-`, plus `.exe` on + windows, and that name plus `.minisig`; the contract's os/triple columns + are what CI already holds that mapping to. + """ + + @classmethod + def setUpClass(cls) -> None: + steps = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))["jobs"]["release"]["steps"] + runs = [str(step.get("run", "")) for step in steps] + cls.check = cls._only(runs, "artifacts/phase-server-slim-*/*") + listing = re.search(r"cat <<'EOF'\n(.*?)\n *EOF\n", cls._only(runs, "files< str: + found = [run for run in runs if needle in run] + assert len(found) == 1, f"{len(found)} release steps contain {needle!r}" + return found[0] + + def publish(self, assets: list[str]) -> subprocess.CompletedProcess: + """Runs the shipped check over a checkout whose built artifacts and + upload list are both `assets` -- the agreement it has to see past.""" + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + (work / CONTRACT.relative_to(ROOT).parent).mkdir() + (work / CONTRACT.relative_to(ROOT)).write_bytes(CONTRACT.read_bytes()) + for asset in assets: + (work / asset).parent.mkdir(parents=True, exist_ok=True) + (work / asset).write_text("", encoding="utf-8") + return subprocess.run( + ["bash", "-c", self.check], cwd=work, + env={"PATH": os.environ["PATH"], "RELEASE_FILES": "\n".join(assets)}, + capture_output=True, text=True, timeout=60, + ) + + def test_the_shipped_asset_list_publishes_every_canonical_download(self) -> None: + # The names are printed, so this passing cannot be a check that never ran. + result = self.publish(self.assets) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + printed = re.search(r"desktop download names: (.*)", result.stdout) + self.assertIsNotNone(printed, result.stdout) + rows = [line.split("#")[0].split() for line in CONTRACT.read_text(encoding="utf-8").splitlines()] + self.assertEqual( + sorted(printed.group(1).split()), + sorted(f"phase-server-slim-{triple}{'.exe' if platform == 'windows' else ''}" + for platform, _arch, triple in (row for row in rows if row)), + ) + + def test_a_renamed_pair_the_upload_list_agrees_with_is_rejected(self) -> None: + # What the artifact/list check cannot see: both publisher-side spellings + # agree, and every desktop on that platform asks for a name nobody + # published. The release is immutable, so it has to fail before create. + canonical = "phase-server-slim-aarch64-apple-darwin" + result = self.publish([a.replace(canonical, f"{canonical}-renamed") for a in self.assets]) + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + for missing in (canonical, f"{canonical}.minisig"): + self.assertIn(f"::error::no release asset is published as {missing}, which", result.stdout) + + if __name__ == "__main__": unittest.main()