From 032a86719a15737fc976529de9433848d67017d1 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 26 Oct 2026 13:48:10 -0400 Subject: [PATCH] Self-host releases: only CoderHelm's release workflow can ship an update Installs, updates and the Launch Stack now refuse anything that merely looks like a CoderHelm release. - Signature identity is exact: release.yml on refs/tags/, GitHub's OIDC issuer, workflow repository and ref, and a Rekor entry. The installer also reads the certificate itself before cosign runs. No signature, no cosign or gh, or any mismatch: nothing is installed. No skip flag. - No downgrade: updates only go forward; rollbacks only to versions the install ran before (installer and updater). The updater reads releases only from api.github.com for this repo and reports a stale list. - Downloads only from this repo's GitHub release URLs over HTTPS (redirects included); cosign in CodeBuild pinned by SHA-256; VERSION must be a tag. - release.yml: check (signed annotated tag on main), build (read-only, no secrets), publish (release environment with reviewers; signs, verifies, attests; never replaces a release or an S3 template; latest.json only moves forward). The AWS publisher role trusts only that environment. - Every action in every workflow pinned by commit SHA; CI fails otherwise (check_workflows.py), plus actionlint and Dependabot for actions. - scripts/release-protection.sh applies the tag rulesets, main protection, release environment, immutable releases and Actions settings. - docs/self-host/updates-security.md: what is checked and how to verify a release yourself. --- .github/dependabot.yml | 14 + .github/scripts/check_workflows.py | 105 +++++++ .github/scripts/test_check_workflows.py | 71 +++++ .github/workflows/ci.yml | 64 +++-- .github/workflows/deploy.yml | 24 +- .github/workflows/jira-app-release.yml | 6 +- .github/workflows/release.yml | 264 +++++++++++++----- .github/workflows/reviewer-evals.yml | 8 +- docs/self-host/security.md | 2 +- docs/self-host/updates-security.md | 102 +++++++ docs/self-host/updates.md | 10 +- infra/cfn/coderhelm-selfhost-launch.yaml | 25 +- infra/lib/release-verify.ts | 53 ++++ infra/lib/updates-stack.ts | 32 +-- infra/lib/worker-stack.ts | 11 +- infra/test/launch-stack.test.ts | 18 +- infra/test/synth.test.ts | 19 +- installer/lib/cli.mjs | 2 +- installer/lib/commands.mjs | 27 +- installer/lib/release.mjs | 161 ++++++++--- installer/lib/sigstore.mjs | 129 +++++++++ installer/test/fixtures/make-signers.sh | 34 +++ .../fixtures/real-github-actions-bundle.json | 1 + installer/test/fixtures/signers.json | 8 + installer/test/installer.test.mjs | 31 +- installer/test/release-security.test.mjs | 263 +++++++++++++++++ lambda/tests/test_updater.py | 66 +++++ lambda/updater/handler.py | 91 +++++- scripts/release-protection.sh | 140 ++++++++++ selfhost/install.sh | 43 ++- selfhost/launch/bootstrap.mjs | 9 +- selfhost/launch/bootstrap.test.mjs | 10 + 32 files changed, 1619 insertions(+), 224 deletions(-) create mode 100644 .github/dependabot.yml create mode 100644 .github/scripts/check_workflows.py create mode 100644 .github/scripts/test_check_workflows.py create mode 100644 docs/self-host/updates-security.md create mode 100644 infra/lib/release-verify.ts create mode 100644 installer/lib/sigstore.mjs create mode 100644 installer/test/fixtures/make-signers.sh create mode 100644 installer/test/fixtures/real-github-actions-bundle.json create mode 100644 installer/test/fixtures/signers.json create mode 100644 installer/test/release-security.test.mjs create mode 100755 scripts/release-protection.sh diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..add41b74f --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,14 @@ +# Keeps the SHA-pinned GitHub Actions current: each update is a PR that moves +# the commit SHA and its "# vX.Y.Z" comment together, and goes through CI +# and review like any change. +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + groups: + actions: + patterns: ["*"] + commit-message: + prefix: "ci" diff --git a/.github/scripts/check_workflows.py b/.github/scripts/check_workflows.py new file mode 100644 index 000000000..16221d6a1 --- /dev/null +++ b/.github/scripts/check_workflows.py @@ -0,0 +1,105 @@ +"""Supply-chain rules for every GitHub Actions workflow in this repository. + +Fails (exit 1) when a workflow: + +- uses an action by tag or branch instead of a full commit SHA, or without + the version it stands for in a comment (`uses: owner/repo@<40 hex> # v1.2.3`). + Local actions (`./...`) and `docker://image@sha256:...` are fine; +- runs on `pull_request_target` or `workflow_run` (both run with this + repository's secrets on behalf of code or events a stranger controls); +- puts untrusted values (`github.event.*`, `github.head_ref`, `inputs.*`) straight into + a `run:` script, where they become shell code; pass them through `env:`; +- has no top-level or per-job `permissions:` (the token's default can write). + + python3 .github/scripts/check_workflows.py [.github/workflows] +""" + +import pathlib +import re +import sys + +import yaml + +SHA_PIN = re.compile(r"^[^@\s]+@[0-9a-f]{40}$") +DOCKER_PIN = re.compile(r"^docker://[^@\s]+@sha256:[0-9a-f]{64}$") +VERSION_COMMENT = re.compile(r"#\s*\S+") +UNTRUSTED = re.compile(r"\$\{\{[^}]*\b(github\.event\.|github\.head_ref|inputs\.)[^}]*\}\}") +FORBIDDEN_TRIGGERS = {"pull_request_target", "workflow_run"} + + +def _triggers(doc): + # PyYAML reads the key `on` as True. + on = doc.get("on", doc.get(True)) + if isinstance(on, str): + return {on} + if isinstance(on, list): + return set(on) + if isinstance(on, dict): + return set(on) + return set() + + +def check_text(name, text): + """The problems in one workflow file, as 'file:line: message' strings.""" + problems = [] + lines = text.split("\n") + for i, line in enumerate(lines, 1): + m = re.match(r"^\s*(?:-\s+)?uses:\s*([^\s#]+)\s*(#.*)?$", line) + if not m: + continue + ref, comment = m.group(1).strip("'\""), m.group(2) or "" + if ref.startswith("./"): + continue + if ref.startswith("docker://"): + if not DOCKER_PIN.match(ref): + problems.append(f"{name}:{i}: {ref} must be pinned by digest (docker://image@sha256:...)") + continue + if not SHA_PIN.match(ref): + problems.append(f"{name}:{i}: {ref} must be pinned by full commit SHA (owner/repo@<40 hex> # vX.Y.Z)") + elif not VERSION_COMMENT.match(comment): + problems.append(f"{name}:{i}: {ref} needs the version it stands for in a comment (# vX.Y.Z)") + + try: + doc = yaml.safe_load(text) or {} + except yaml.YAMLError as e: + return problems + [f"{name}: not valid YAML: {e}"] + for t in sorted(_triggers(doc) & FORBIDDEN_TRIGGERS): + problems.append(f"{name}: runs on {t}, which hands this repository's secrets to code or events others control") + + jobs = doc.get("jobs") or {} + if "permissions" not in doc: + for job_id, job in jobs.items(): + if isinstance(job, dict) and "permissions" not in job: + problems.append(f"{name}: job {job_id} has no permissions (set them at the top or on the job)") + + for job_id, job in jobs.items(): + for step in (job or {}).get("steps") or []: + run = step.get("run") if isinstance(step, dict) else None + if isinstance(run, str): + for m in UNTRUSTED.finditer(run): + problems.append(f"{name}: job {job_id}: {m.group(0)} is used inside run:; pass it through env: instead") + return problems + + +def check_dir(path): + problems = [] + files = sorted(pathlib.Path(path).glob("*.y*ml")) + for f in files: + problems += check_text(str(f), f.read_text()) + return files, problems + + +def main(argv): + path = argv[1] if len(argv) > 1 else ".github/workflows" + files, problems = check_dir(path) + for p in problems: + print(p) + if problems: + print(f"{len(problems)} problem(s) in {len(files)} workflow(s)") + return 1 + print(f"{len(files)} workflows: every action pinned by SHA, no untrusted triggers or inputs in scripts") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/.github/scripts/test_check_workflows.py b/.github/scripts/test_check_workflows.py new file mode 100644 index 000000000..91e08b3a4 --- /dev/null +++ b/.github/scripts/test_check_workflows.py @@ -0,0 +1,71 @@ +"""Tests for check_workflows.py, and the repository's own workflows against it. + +Run: python3 -m unittest discover -s .github/scripts +""" + +import pathlib +import sys +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).parent)) +import check_workflows as cw # noqa: E402 + +SHA = "11d5960a326750d5838078e36cf38b85af677262" + + +def wf(steps, on="push:\n branches: [main]", top_permissions=True): + perms = "permissions:\n contents: read\n" if top_permissions else "" + body = "\n".join(f" {s}" for s in steps) + return f"name: t\non:\n {on.replace(chr(10), chr(10) + ' ')}\n{perms}jobs:\n a:\n runs-on: ubuntu-latest\n steps:\n{body}\n" + + +class Pins(unittest.TestCase): + def test_sha_with_version_comment_passes(self): + self.assertEqual(cw.check_text("w", wf([f"- uses: actions/checkout@{SHA} # v4.4.0"])), []) + + def test_tags_branches_and_short_shas_fail(self): + for ref in ("actions/checkout@v4", "dtolnay/rust-toolchain@stable", "actions/checkout@11d5960", "actions/checkout@main"): + p = cw.check_text("w", wf([f"- uses: {ref}"])) + self.assertTrue(any("full commit SHA" in x for x in p), ref) + + def test_a_sha_needs_its_version_in_a_comment(self): + p = cw.check_text("w", wf([f"- uses: actions/checkout@{SHA}"])) + self.assertTrue(any("version it stands for" in x for x in p)) + + def test_local_and_digest_pinned_docker_pass(self): + self.assertEqual(cw.check_text("w", wf(["- uses: ./.github/actions/x", "- uses: docker://alpine@sha256:" + "a" * 64])), []) + self.assertTrue(cw.check_text("w", wf(["- uses: docker://alpine:3"]))) + + +class Triggers(unittest.TestCase): + def test_pull_request_target_and_workflow_run_fail(self): + for on in ("pull_request_target:\n branches: [main]", "workflow_run:\n workflows: [CI]"): + p = cw.check_text("w", wf([f"- uses: actions/checkout@{SHA} # v4.4.0"], on=on)) + self.assertTrue(any("hands this repository's secrets" in x for x in p), on) + + +class Scripts(unittest.TestCase): + def test_untrusted_values_in_run_fail(self): + for expr in ("${{ github.event.pull_request.title }}", "${{ github.head_ref }}", "${{ inputs.tag }}", "${{ github.event.inputs.tag || github.ref_name }}"): + p = cw.check_text("w", wf([f'- run: echo "{expr}"'])) + self.assertTrue(any("pass it through env" in x for x in p), expr) + + def test_env_is_fine(self): + steps = ["- env:", " T: ${{ github.event.pull_request.title }}", ' run: echo "$T"'] + self.assertEqual(cw.check_text("w", wf(steps)), []) + + def test_permissions_are_required(self): + p = cw.check_text("w", wf([f"- uses: actions/checkout@{SHA} # v4.4.0"], top_permissions=False)) + self.assertTrue(any("has no permissions" in x for x in p)) + + +class ThisRepository(unittest.TestCase): + def test_every_workflow_here_passes(self): + root = pathlib.Path(__file__).resolve().parents[1] / "workflows" + files, problems = cw.check_dir(root) + self.assertGreater(len(files), 0) + self.assertEqual(problems, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a960cc1d9..1c9968b6e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,10 +8,40 @@ concurrency: group: ci-${{ github.ref }} cancel-in-progress: true +# Pull requests (including from forks) get a read-only token and no secrets. +permissions: + contents: read + env: CARGO_TERM_COLOR: always jobs: + # Every action pinned by commit SHA, no pull_request_target, no untrusted + # values in scripts (.github/scripts/check_workflows.py), and actionlint. + workflows: + name: Workflow security + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + with: + python-version: "3.12" + - name: Pinned actions and safe triggers + run: | + pip install --quiet pyyaml==6.0.2 + python3 .github/scripts/check_workflows.py + - name: actionlint + env: + ACTIONLINT_VERSION: 1.7.12 + ACTIONLINT_SHA256: 8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8 + run: | + curl --proto =https -fsSL -o "$RUNNER_TEMP/al.tgz" "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz" + echo "${ACTIONLINT_SHA256} $RUNNER_TEMP/al.tgz" | sha256sum -c - + tar -xzf "$RUNNER_TEMP/al.tgz" -C "$RUNNER_TEMP" actionlint + "$RUNNER_TEMP/actionlint" -color + rust: name: Rust (workspace) runs-on: ubuntu-latest @@ -19,11 +49,11 @@ jobs: run: working-directory: services steps: - - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable with: components: rustfmt, clippy - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: workspaces: services cache-on-failure: true @@ -37,8 +67,8 @@ jobs: name: Lambda (Python) runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version: "3.12" - run: python3 -m unittest discover -s lambda/tests @@ -50,8 +80,8 @@ jobs: run: working-directory: lambda/mcp-proxy steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: lts/* - run: npm ci @@ -64,14 +94,14 @@ jobs: run: working-directory: coderhelm-jira steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: lts/* # Pure rules only (no Forge runtime); `forge lint` needs a login and # runs in the release workflow (jira-app-release.yml). - run: npm test - - uses: actions/setup-python@v5 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version: "3.12" # The release workflow's permission check (scopes, egress, web triggers). @@ -88,8 +118,8 @@ jobs: run: working-directory: infra steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: lts/* cache: npm @@ -118,8 +148,8 @@ jobs: run: working-directory: installer steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: lts/* - run: npm test @@ -129,13 +159,13 @@ jobs: name: Launch Stack (template and installer) runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: lts/* # The installer the stack runs, and the release's template stamping. - run: node --test selfhost/launch/*.test.mjs - - uses: actions/setup-python@v5 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version: "3.12" - name: cfn-lint the CloudFormation templates diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index deb337ffe..ce1888f47 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -59,17 +59,19 @@ jobs: needs: [gate] if: needs.gate.outputs.changed == 'true' runs-on: ubuntu-latest + permissions: + contents: read steps: - - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable with: targets: aarch64-unknown-linux-musl # Cache ~/.cargo/registry + services/target in one hit for both crates - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: workspaces: services cache-on-failure: true - - uses: mlugg/setup-zig@v2 + - uses: mlugg/setup-zig@d1434d08867e3ee9daa34448df10607b98908d29 # v2.2.1 - name: Install cargo-zigbuild run: pip3 install --retries 3 --timeout 60 cargo-zigbuild # Build both gateway + worker in one invocation — shared deps compiled once @@ -83,11 +85,11 @@ jobs: rm bootstrap cp services/target/aarch64-unknown-linux-musl/release/worker bootstrap zip worker.zip bootstrap - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: gateway path: gateway.zip - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: worker path: worker.zip @@ -101,24 +103,24 @@ jobs: id-token: write contents: read steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: lts/* cache: npm cache-dependency-path: | infra/package-lock.json - - uses: actions/download-artifact@v4 + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: gateway path: artifacts/ - - uses: actions/download-artifact@v4 + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: worker path: artifacts/ - - uses: aws-actions/configure-aws-credentials@v4 + - uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4.3.1 with: role-to-assume: ${{ secrets.AWS_DEPLOY_ROLE_ARN }} aws-region: ${{ env.AWS_REGION }} diff --git a/.github/workflows/jira-app-release.yml b/.github/workflows/jira-app-release.yml index 61028912c..0a3de979c 100644 --- a/.github/workflows/jira-app-release.yml +++ b/.github/workflows/jira-app-release.yml @@ -61,12 +61,12 @@ jobs: exit 1 fi - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: ref: ${{ inputs.ref || github.sha }} fetch-depth: 0 # the permission check reads the last released manifest - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 24 cache: npm @@ -74,7 +74,7 @@ jobs: coderhelm-jira/package-lock.json coderhelm-jira/resources/admin/package-lock.json - - uses: actions/setup-python@v5 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version: "3.12" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f55d15d3b..f81358b39 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -3,38 +3,81 @@ name: Release # A tag vX.Y.Z publishes a self-host release: prebuilt Lambda code (no Rust # toolchain needed to install), the dashboard build, the CDK app's source, # the installer, the install script and the Launch Stack template (also -# published to S3 for the Launch Stack link), with -# SHA256SUMS and build provenance (GitHub artifact attestations: Sigstore, +# published to S3 for the Launch Stack link), with SHA256SUMS, its keyless +# signature and build provenance (GitHub artifact attestations: Sigstore, # no keys to manage). The hosted deployment is not touched by this workflow. +# +# Who can publish (docs/self-host/updates-security.md): +# check the tag is a signed, annotated vX.Y.Z tag on a commit on main. +# build builds everything with a read-only token and no secrets. +# publish signs, attests and publishes. It runs in the "release" +# environment, so a maintainer must approve it: a tag alone +# publishes nothing. Only this job can write the release or +# assume the AWS role (whose trust names the environment). +# +# Every action is pinned by commit SHA (.github/scripts/check_workflows.py +# fails CI otherwise). Installs and updates check the signature names +# exactly this file on refs/tags/. on: push: tags: ["v*.*.*"] + # Re-run for an existing tag: choose the tag in "Use workflow from" + # (the signature names the ref the run is on, so it must be the tag). workflow_dispatch: - inputs: - tag: - description: Existing tag to (re)build the release for - required: true -permissions: - contents: write - id-token: write - attestations: write +permissions: {} + +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false env: CARGO_TERM_COLOR: always jobs: - release: - name: Build and publish + check: + name: Check the tag runs-on: ubuntu-latest + permissions: + contents: read + outputs: + tag: ${{ steps.tag.outputs.tag }} steps: - id: tag - run: echo "tag=${{ github.event.inputs.tag || github.ref_name }}" >> "$GITHUB_OUTPUT" - - uses: actions/checkout@v4 + name: A version tag, nothing else + env: + REF_TYPE: ${{ github.ref_type }} + TAG: ${{ github.ref_name }} + run: | + [ "$REF_TYPE" = tag ] || { echo "::error::Run this on a tag (vX.Y.Z), not a branch"; exit 1; } + [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] || { echo "::error::$TAG is not vX.Y.Z"; exit 1; } + echo "tag=$TAG" >> "$GITHUB_OUTPUT" + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: - ref: ${{ steps.tag.outputs.tag }} + ref: ${{ github.ref }} fetch-depth: 0 - + persist-credentials: false + # The tag must point at reviewed code: a commit on main (which needs a + # PR, signed commits and passing checks). + - name: The tag is on main + env: + TAG: ${{ steps.tag.outputs.tag }} + run: | + git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main + commit=$(git rev-parse "refs/tags/$TAG^{commit}") + git merge-base --is-ancestor "$commit" origin/main || { echo "::error::$TAG ($commit) is not on main"; exit 1; } + # Signed by a maintainer, and GitHub says the signature checks out. + - name: The tag and its commit are signed + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ steps.tag.outputs.tag }} + run: | + ref=$(gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/$TAG" --jq '.object.type + " " + .object.sha') + read -r type sha <<< "$ref" + [ "$type" = tag ] || { echo "::error::$TAG is a lightweight tag: make it with git tag -s $TAG -m $TAG"; exit 1; } + [ "$(gh api "repos/$GITHUB_REPOSITORY/git/tags/$sha" --jq .verification.verified)" = true ] || { echo "::error::$TAG's signature is missing or not verified by GitHub"; exit 1; } + commit=$(gh api "repos/$GITHUB_REPOSITORY/git/tags/$sha" --jq .object.sha) + [ "$(gh api "repos/$GITHUB_REPOSITORY/commits/$commit" --jq .commit.verification.verified)" = true ] || { echo "::error::$TAG's commit is not signed and verified"; exit 1; } # The updater and the installer compare versions: a release must sort # above every earlier one, including the v0.2.x to v0.6.0 tags from # before self-hosting (they have no releases). The first self-host @@ -44,10 +87,9 @@ jobs: env: TAG: ${{ steps.tag.outputs.tag }} run: | + # shellcheck disable=SC2016 # JavaScript, not shell node -e ' const tag = process.env.TAG; - const m = tag.match(/^v(\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z.-]+)?$/); - if (!m) { console.error(`${tag} is not vX.Y.Z`); process.exit(1); } const n = (v) => v.replace(/^v/, "").split(/[.-]/).slice(0, 3).map(Number); const [a, b] = [n(tag), n("v0.6.0")]; const above = a[0] !== b[0] ? a[0] > b[0] : a[1] !== b[1] ? a[1] > b[1] : a[2] > b[2]; @@ -57,18 +99,32 @@ jobs: require("./selfhost/MIGRATIONS.json"); ' - # ── Rust Lambdas ─────────────────────────────────────────────── - - uses: dtolnay/rust-toolchain@stable + build: + name: Build + needs: check + runs-on: ubuntu-latest + # Read-only token, no secrets, no OIDC: this job runs the build scripts. + permissions: + contents: read + env: + TAG: ${{ needs.check.outputs.tag }} + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + ref: ${{ github.ref }} + fetch-depth: 0 + persist-credentials: false + + # ── Rust Lambdas (no build cache: a release builds from scratch) ── + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable with: + toolchain: stable targets: aarch64-unknown-linux-musl - - uses: Swatinem/rust-cache@v2 - with: - workspaces: services - - uses: mlugg/setup-zig@v2 - - run: pip3 install --retries 3 --timeout 60 cargo-zigbuild + - uses: mlugg/setup-zig@d1434d08867e3ee9daa34448df10607b98908d29 # v2.2.1 + - run: pip3 install --retries 3 --timeout 60 cargo-zigbuild==0.24.0 - name: Build gateway and worker working-directory: services - run: cargo zigbuild --workspace --release --target aarch64-unknown-linux-musl + run: cargo zigbuild --locked --workspace --release --target aarch64-unknown-linux-musl - name: Package Lambdas run: | mkdir -p dist @@ -78,7 +134,7 @@ jobs: rm bootstrap done - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: lts/* @@ -91,11 +147,12 @@ jobs: - name: Pick the dashboard commit id: dash run: echo "ref=$(node -p 'require("./selfhost/versions.json").dashboardRef')" >> "$GITHUB_OUTPUT" - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: repository: CoderHelm/coderhelm ref: ${{ steps.dash.outputs.ref }} path: dashboard-src + persist-credentials: false - name: Build the dashboard working-directory: dashboard-src/dashboard # No API URL baked in: a self-hosted deployment serves @@ -111,17 +168,17 @@ jobs: # ── Source, installer, script, template ──────────────────────── - name: Source and installer run: | - TAG="${{ steps.tag.outputs.tag }}" # The source, plus the release stamp each install shows (Settings, then System). SRC="$RUNNER_TEMP/src/coderhelm-platform-${TAG#v}" mkdir -p "$SRC" && git archive --format=tar "$TAG" | tar -x -C "$SRC" - printf '{"version":"%s","commit":"%s","releasedAt":"%s"}\n' "$TAG" "$(git rev-parse "$TAG^{commit}")" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$SRC/selfhost/release.json" + printf '{"version":"%s","commit":"%s","dashboardCommit":"%s","releasedAt":"%s"}\n' "$TAG" "$(git rev-parse "$TAG^{commit}")" "$(git -C dashboard-src rev-parse HEAD)" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$SRC/selfhost/release.json" tar -czf dist/source.tar.gz -C "$RUNNER_TEMP/src" "coderhelm-platform-${TAG#v}" (cd installer && npm version --no-git-tag-version --allow-same-version "${TAG#v}" >/dev/null && npm pack --silent --pack-destination ../dist >/dev/null) mv dist/coderhelm-selfhost-*.tgz dist/coderhelm-selfhost.tgz cp selfhost/install.sh dist/install.sh # The Launch Stack template, pinned to this release, and the # installer its CodeBuild project runs (checked against SHA256SUMS). + # The publish job uploads this same launch-stack.yaml to S3. node selfhost/launch/stamp-template.mjs infra/cfn/coderhelm-selfhost-launch.yaml "$TAG" > dist/launch-stack.yaml cp selfhost/launch/bootstrap.mjs dist/launch-bootstrap.mjs (cd dist && sha256sum gateway.zip worker.zip mcp-proxy.zip dashboard.tar.gz source.tar.gz coderhelm-selfhost.tgz install.sh launch-stack.yaml launch-bootstrap.mjs > SHA256SUMS) @@ -139,13 +196,57 @@ jobs: mkdir -p "$RUNNER_TEMP/dash" && tar -xzf ../dist/dashboard.tar.gz -C "$RUNNER_TEMP/dash" CODERHELM_DASHBOARD_DIR="$RUNNER_TEMP/dash" npx cdk synth --all --quiet -c config=config/selfhost.example.json -o "$RUNNER_TEMP/synth" - # Keyless signature of the checksums: the update build and the - # installer check it was made by this workflow, on a tag. - - uses: sigstore/cosign-installer@v3 + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: release-dist + path: dist/ + if-no-files-found: error + retention-days: 3 + + # Signs, attests and publishes what the build made. Runs only after a + # reviewer approves the "release" environment; runs no code from the + # repository (no checkout). + publish: + name: Sign and publish + needs: [check, build] + runs-on: ubuntu-latest + environment: release + permissions: + contents: write # the GitHub release + id-token: write # keyless signing and the AWS role + attestations: write # build provenance + env: + TAG: ${{ needs.check.outputs.tag }} + PUBLIC_BUCKET: coderhelm-public + steps: + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: release-dist + path: dist + - name: The files are the ones the build listed + run: | + cd dist + sha256sum -c SHA256SUMS + diff <(find . -maxdepth 1 -type f ! -name SHA256SUMS -printf '%f\n' | sort) <(awk '{print $2}' SHA256SUMS | sort) + + # Keyless signature of the checksums: installs and updates check it was + # made by exactly this workflow on this tag, and logged in Rekor. The + # cosign version matches the one the update build verifies with. + - uses: sigstore/cosign-installer@7e8b541eb2e61bf99390e1afd4be13a184e9ebc5 # v3.10.1 + with: + cosign-release: v2.4.1 - name: Sign the checksums run: cosign sign-blob --yes --bundle dist/SHA256SUMS.sigstore.json dist/SHA256SUMS + - name: Verify the signature as an install will + run: | + cosign verify-blob --bundle dist/SHA256SUMS.sigstore.json \ + --certificate-identity "https://github.com/$GITHUB_REPOSITORY/.github/workflows/release.yml@refs/tags/$TAG" \ + --certificate-oidc-issuer https://token.actions.githubusercontent.com \ + --certificate-github-workflow-repository "$GITHUB_REPOSITORY" \ + --certificate-github-workflow-ref "refs/tags/$TAG" \ + dist/SHA256SUMS - - uses: actions/attest-build-provenance@v2 + - uses: actions/attest-build-provenance@e8998f949152b193b063cb0ec769d69d929409be # v2.4.0 with: subject-path: | dist/gateway.zip @@ -154,61 +255,76 @@ jobs: dist/dashboard.tar.gz dist/source.tar.gz dist/coderhelm-selfhost.tgz + dist/install.sh dist/launch-bootstrap.mjs dist/launch-stack.yaml + # A published release's files are never replaced: a re-run only fills in + # a release that has no SHA256SUMS yet (one made by hand, without + # assets), or confirms the files are already these. - name: Publish the release env: GH_TOKEN: ${{ github.token }} run: | - TAG="${{ steps.tag.outputs.tag }}" - NOTES="Self-host release ${TAG}. Install: npx -y github:${GITHUB_REPOSITORY}#${TAG} init, then deploy. Update: npx -y github:${GITHUB_REPOSITORY}#${TAG} update --to ${TAG}. Check an install: npx -y github:${GITHUB_REPOSITORY} doctor. See docs/self-host." - if gh release view "$TAG" >/dev/null 2>&1; then - gh release upload "$TAG" dist/* --clobber + NOTES="Self-host release ${TAG}. Install: npx -y github:${GITHUB_REPOSITORY}#${TAG} init, then deploy. Update: npx -y github:${GITHUB_REPOSITORY}#${TAG} update --to ${TAG}. Check an install: npx -y github:${GITHUB_REPOSITORY} doctor. Verify it yourself: docs/self-host/updates-security.md." + if gh release view "$TAG" -R "$GITHUB_REPOSITORY" >/dev/null 2>&1; then + mkdir -p "$RUNNER_TEMP/old" + if gh release download "$TAG" -R "$GITHUB_REPOSITORY" -p SHA256SUMS -D "$RUNNER_TEMP/old" 2>/dev/null; then + cmp -s "$RUNNER_TEMP/old/SHA256SUMS" dist/SHA256SUMS || { echo "::error::$TAG is already published with other files; a release is never replaced"; exit 1; } + echo "$TAG is already published with these files." + else + gh release upload "$TAG" -R "$GITHUB_REPOSITORY" dist/* + fi else - gh release create "$TAG" dist/* --title "$TAG" --notes "$NOTES" --verify-tag + gh release create "$TAG" -R "$GITHUB_REPOSITORY" dist/* --title "$TAG" --notes "$NOTES" --verify-tag fi - # CloudFormation's Launch Stack links only open templates stored in S3, so - # the release's template also goes to the hosted deployment's public bucket - # (infra/lib/log-analyzer-stack.ts), by version, and latest.json names the - # newest stable one for the install guide (docs.coderhelm.com/self-host/install). - # A separate job: the GitHub release is published even if this one fails, - # and re-running it later is safe. - launch-template: - name: Publish the Launch Stack template - needs: release - runs-on: ubuntu-latest - permissions: - contents: read - id-token: write - env: - PUBLIC_BUCKET: coderhelm-public - steps: - - id: tag - run: echo "tag=${{ github.event.inputs.tag || github.ref_name }}" >> "$GITHUB_OUTPUT" - - uses: actions/checkout@v4 - with: - ref: ${{ steps.tag.outputs.tag }} - - uses: actions/setup-node@v4 - with: - node-version: lts/* - # The role only tag builds of this repository may assume, and only to - # write launch/* in the public bucket (infra/lib/worker-stack.ts, - # ReleasePublisherRole). The hosted deploy creates it. - - uses: aws-actions/configure-aws-credentials@v4 + # CloudFormation's Launch Stack links only open templates stored in S3, + # so the release's template also goes to the hosted deployment's public + # bucket (infra/lib/log-analyzer-stack.ts), by version, and latest.json + # names the newest stable one for the install guide + # (docs.coderhelm.com/self-host/install). It is byte for byte the + # launch-stack.yaml in the signed SHA256SUMS. + # The role trusts only this repository's "release" environment + # (infra/lib/worker-stack.ts, ReleasePublisherRole). + - uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4.3.1 with: role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_ID }}:role/coderhelm-prod-release-publisher role-duration-seconds: 3600 aws-region: us-east-1 - name: Upload the template and latest.json - env: - TAG: ${{ steps.tag.outputs.tag }} run: | - node selfhost/launch/stamp-template.mjs infra/cfn/coderhelm-selfhost-launch.yaml "$TAG" > launch.yaml - aws s3 cp launch.yaml "s3://$PUBLIC_BUCKET/launch/$TAG/coderhelm-launch.yaml" --content-type text/yaml --cache-control "public, max-age=31536000, immutable" - # Pre-releases (v1.2.3-rc.1) are published by version but never become latest. + key="launch/$TAG/coderhelm-launch.yaml" + url="https://$PUBLIC_BUCKET.s3.amazonaws.com/$key" + # Written once: a template already there must be this one. + if curl --proto =https -fsSL -o "$RUNNER_TEMP/existing.yaml" "$url"; then + cmp -s "$RUNNER_TEMP/existing.yaml" dist/launch-stack.yaml || { echo "::error::$key already holds another template"; exit 1; } + else + aws s3api put-object --bucket "$PUBLIC_BUCKET" --key "$key" --body dist/launch-stack.yaml --if-none-match '*' \ + --content-type text/yaml --cache-control "public, max-age=31536000, immutable" >/dev/null + fi + # Pre-releases (v1.2.3-rc.1) are published by version but never become latest, + # and latest.json only ever moves forward. if [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then - node -e 'import("./selfhost/launch/stamp-template.mjs").then(m=>process.stdout.write(JSON.stringify(m.latestDoc(process.argv[1]))))' "$TAG" > latest.json - aws s3 cp latest.json "s3://$PUBLIC_BUCKET/launch/latest.json" --content-type application/json --cache-control "public, max-age=300" + current=$(curl --proto =https -fsSL "https://$PUBLIC_BUCKET.s3.amazonaws.com/launch/latest.json" 2>/dev/null || echo '{}') + # shellcheck disable=SC2016 # JavaScript, not shell + CURRENT="$current" SHA=$(sha256sum dist/launch-stack.yaml | cut -d' ' -f1) node -e ' + const tag = process.env.TAG; + const n = (v) => String(v || "v0.0.0").replace(/^v/, "").split(/[.-]/).slice(0, 3).map(Number); + let cur = {}; + try { cur = JSON.parse(process.env.CURRENT); } catch {} + const [a, b] = [n(tag), n(cur.version)]; + const newer = a[0] !== b[0] ? a[0] > b[0] : a[1] !== b[1] ? a[1] > b[1] : a[2] > b[2]; + if (!newer && cur.version !== tag) { console.error(`latest.json names ${cur.version}, newer than ${tag}: left as it is`); process.exit(0); } + const bucket = process.env.PUBLIC_BUCKET; + require("fs").writeFileSync("latest.json", JSON.stringify({ + version: tag, + templateUrl: `https://${bucket}.s3.amazonaws.com/launch/${tag}/coderhelm-launch.yaml`, + templateSha256: process.env.SHA, + publishedAt: new Date().toISOString(), + })); + ' + if [ -f latest.json ]; then + aws s3 cp latest.json "s3://$PUBLIC_BUCKET/launch/latest.json" --content-type application/json --cache-control "public, max-age=300" + fi fi diff --git a/.github/workflows/reviewer-evals.yml b/.github/workflows/reviewer-evals.yml index 109bbca68..404ee60ed 100644 --- a/.github/workflows/reviewer-evals.yml +++ b/.github/workflows/reviewer-evals.yml @@ -36,12 +36,12 @@ jobs: run: working-directory: services steps: - - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - - uses: Swatinem/rust-cache@v2 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: workspaces: services - - uses: aws-actions/configure-aws-credentials@v4 + - uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4.3.1 with: role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_ID }}:role/coderhelm-prod-reviewer-evals role-session-name: reviewer-evals-${{ github.run_id }} diff --git a/docs/self-host/security.md b/docs/self-host/security.md index 8adfde2f5..23a4ba7dd 100644 --- a/docs/self-host/security.md +++ b/docs/self-host/security.md @@ -41,7 +41,7 @@ order: 11 ## Supply chain -Releases are built by GitHub Actions from a tag, with checksums and build provenance attestations (Sigstore, through GitHub). The installer checks both. You can also deploy from source (`--source`) after reviewing the code. +Releases are built by GitHub Actions from a signed tag on `main`, published only after a maintainer approves, and signed keylessly (Sigstore) with build provenance attestations. The installer, the update build and the Launch Stack check that the signature was made by exactly CoderHelm's release workflow on that release's tag, and refuse anything else, including older releases you never ran. [How updates are kept safe](./updates-security.md) has the details and the commands to check a release yourself. You can also deploy from source (`--source`) after reviewing the code. ## Reporting a problem diff --git a/docs/self-host/updates-security.md b/docs/self-host/updates-security.md new file mode 100644 index 000000000..93f1e95c0 --- /dev/null +++ b/docs/self-host/updates-security.md @@ -0,0 +1,102 @@ +--- +title: How updates are kept safe +description: How CoderHelm proves a release is really CoderHelm's, what installs and updates check, what happens when a check fails, and how to verify a release yourself. +order: 9.5 +--- + +Nothing gets onto your install just because it looks like a CoderHelm release. Every install and update checks a release's signature. The signature must have been made by CoderHelm's own release workflow, on that release's own tag. If any check fails, nothing is installed. + +## Who can publish a release + +A release is a `vX.Y.Z` tag on `CoderHelm/coderhelm-platform`, built by `.github/workflows/release.yml`. + +- **The tag.** It must be an annotated tag, signed by a maintainer, on a commit that is already on `main`. Code reaches `main` only through a reviewed pull request with signed commits and passing checks. Only repository admins can create `v*` tags. Nobody can move or delete one. +- **The build.** It runs with a read-only token, no secrets and no cloud credentials. +- **Publishing.** A separate job signs and publishes the release. It runs in the `release` environment, so a maintainer has to approve it. A pushed tag alone publishes nothing. Only that job can write the GitHub release or upload the Launch Stack template to S3. The AWS role it uses trusts only that environment. +- **No replacing.** A published release's files are never replaced. Releases are immutable on GitHub, and a template already in S3 is never overwritten. +- **Third-party code.** Every GitHub Action is pinned by commit SHA, and CI fails on any action that isn't. No workflow runs on `pull_request_target`. A pull request from outside gets a read-only token and no secrets. + +## What installs and updates check + +The installer, the update build (`coderhelm--update`) and the Launch Stack's installer make the same checks before they use anything from a release: + +1. **The signature.** `SHA256SUMS` has a keyless Sigstore signature, `SHA256SUMS.sigstore.json`. Its certificate must name exactly + `https://github.com/CoderHelm/coderhelm-platform/.github/workflows/release.yml@refs/tags/`. + It must also be issued by `https://token.actions.githubusercontent.com` and be in the Rekor transparency log. Several kinds of signature are refused: + - one from another repository, another workflow or a branch; + - one made for a different tag, so an old release's signature can't stand in for a new one; + - a bundle with no Rekor entry; + - a missing signature. +2. **The files.** Every file must match its line in `SHA256SUMS`. That covers the Lambdas, the dashboard, the source, the installer, `install.sh`, `launch-stack.yaml` and `launch-bootstrap.mjs`. A file changed after signing is refused before anything is unpacked. +3. **Where files come from.** Files come only from `https://github.com/CoderHelm/coderhelm-platform/releases/download//` over HTTPS, including after GitHub's redirects. Any other host, plain HTTP, or a version that isn't `vX.Y.Z` is refused. +4. **No going back.** An update only goes to a newer release than the one running. A rollback only goes to a release this install has run before. An admin starts it from **Settings, then System**, or with `coderhelm-selfhost rollback`. An older signed release that this install never ran can't be pushed onto it. +5. **A fresh release list.** The updater reads the release list only from `api.github.com` for this repository. If the list stops showing the newest version it saw before, **Settings, then System** marks the list as stale. It does the same when the list hasn't been read for over 3 days. A stale copy can hold an install back, but it can never make it go back. + +The installer verifies with `cosign` when it is installed, or else with the GitHub CLI (`gh attestation verify`, checking the same repository, workflow and tag). If neither tool is installed, it stops and asks you to install one. No flag skips the check. To run code that isn't a signed release, deploy from a checkout you reviewed (`--source`). + +## The Launch Stack + +CloudFormation can't check a signature on a template. So the template is published at one fixed CoderHelm address per release: + +```text +https://coderhelm-public.s3.amazonaws.com/launch//coderhelm-launch.yaml +``` + +It is the same file, byte for byte, as `launch-stack.yaml` in that release's signed `SHA256SUMS`. `launch/latest.json` names the newest one and its SHA-256, and it only ever moves forward. The template's installer runs nothing from the release until it has done three things: + +1. installed a cosign pinned by its SHA-256; +2. checked `SHA256SUMS` against its signature, with the exact identity above; +3. checked `coderhelm-selfhost.tgz` and `launch-bootstrap.mjs` against `SHA256SUMS`. + +The installer then checks the rest of the release the same way. You can check the template yourself before you launch it (below). + +## Check a release yourself + +Use [cosign](https://docs.sigstore.dev/cosign/system_config/installation/) 2.x or the [GitHub CLI](https://cli.github.com/). + +```sh +V=v0.7.0 +R=CoderHelm/coderhelm-platform +for f in SHA256SUMS SHA256SUMS.sigstore.json coderhelm-selfhost.tgz launch-stack.yaml; do + curl --proto =https -fsSLO "https://github.com/$R/releases/download/$V/$f" +done + +# 1. The checksums were signed by CoderHelm's release workflow, on this tag. +cosign verify-blob --bundle SHA256SUMS.sigstore.json \ + --certificate-identity "https://github.com/$R/.github/workflows/release.yml@refs/tags/$V" \ + --certificate-oidc-issuer https://token.actions.githubusercontent.com \ + --certificate-github-workflow-repository "$R" \ + --certificate-github-workflow-ref "refs/tags/$V" \ + SHA256SUMS + +# 2. The files match the checksums (on macOS: shasum -a 256 -c). +sha256sum -c --ignore-missing SHA256SUMS + +# Or, with the GitHub CLI: each file was built by that workflow, on that tag. +gh attestation verify coderhelm-selfhost.tgz --repo "$R" \ + --signer-workflow "$R/.github/workflows/release.yml" \ + --source-ref "refs/tags/$V" \ + --cert-oidc-issuer https://token.actions.githubusercontent.com \ + --deny-self-hosted-runners +``` + +To check the Launch Stack template before you launch it, compare it with the signed one: + +```sh +curl --proto =https -fsSL "https://coderhelm-public.s3.amazonaws.com/launch/$V/coderhelm-launch.yaml" | sha256sum +grep ' launch-stack.yaml$' SHA256SUMS +``` + +The two hashes must be the same. + +To check `install.sh` before running it, download it with the files above and add `install.sh` to the `for` line. Run step 2, then `sh install.sh`. The script itself checks the installer's signature before running it. + +## When a check fails + +Nothing is installed or changed: + +- **Update build:** the history in **Settings, then System** shows the update as failed, with the step that stopped it. Admins get an email. Automatic updates skip that release until an admin tries it again by hand. +- **Terminal:** the installer names the check that failed, for example *"The release's signature is not CoderHelm's release workflow for v0.8.0"*, and exits without deploying. +- **Launch Stack:** the install guide shows *"The release files did not match their signed checksums, so nothing was installed."* The stack ends in a failed state, and you can delete it. + +A failure on a release that should be good means something between you and GitHub changed the files. Please report it privately (see [Security model](./security.md#reporting-a-problem)). diff --git a/docs/self-host/updates.md b/docs/self-host/updates.md index 28bed219f..61d7afc57 100644 --- a/docs/self-host/updates.md +++ b/docs/self-host/updates.md @@ -68,7 +68,7 @@ From the terminal, `update` runs a preflight first and stops before anything cha The update runs as a CodeBuild job in your account, `coderhelm--update`: -1. **Checks the release.** It downloads the release's `SHA256SUMS` and checks its signature with cosign: it must be signed, keyless, by `CoderHelm/coderhelm-platform`'s release workflow on a version tag. Every file is then checked against `SHA256SUMS`. A release that fails either check is refused. +1. **Checks the release.** It downloads the release's `SHA256SUMS` and checks its signature with cosign: it must be signed, keyless, by exactly `CoderHelm/coderhelm-platform`'s `release.yml`, on that release's own tag, and be in the Rekor transparency log. Every file is then checked against `SHA256SUMS`. A release that fails either check is refused, and so is an older release than the one you run unless it is a rollback. See [How updates are kept safe](./updates-security.md). 2. **Checks health first.** The stacks, functions, dead-letter queue, keys and URLs. An unhealthy install is not updated. 3. **Reads the migration notes.** Every release between yours and the target is listed. One that needs action stops an automatic update; an admin does what it says, then updates by hand. 4. **Deploys.** It runs the release's CDK app through the CDK roles in your account. @@ -97,7 +97,7 @@ The job's role can only assume the CDK bootstrap roles (which do the deploying), ## Roll back -**Settings, then System, then Roll back** (or `coderhelm-selfhost rollback`) deploys the release before the last successful update. To pick a version: `coderhelm-selfhost rollback --to v0.7.0`. +**Settings, then System, then Roll back** (or `coderhelm-selfhost rollback`) deploys the release before the last successful update. To pick a version: `coderhelm-selfhost rollback --to v0.7.0`. Only a release this install ran before can be picked: an older release it never ran is refused, even though it is signed. Data written by a newer release stays. Releases only add fields to stored items, so an older release keeps reading them. CloudFormation also rolls a stack back by itself if a deploy fails partway. @@ -106,10 +106,10 @@ Data written by a newer release stays. Releases only add fields to stored items, ```sh npx -y github:CoderHelm/coderhelm-platform update # latest release npx -y github:CoderHelm/coderhelm-platform update --to v0.8.0 -npx -y github:CoderHelm/coderhelm-platform update --auto-rollback --require-signature +npx -y github:CoderHelm/coderhelm-platform update --auto-rollback ``` -The terminal update runs the same steps on your machine. It shows `cdk diff` and asks before deploying unless you pass `--yes`. Signatures are checked when `cosign` or the GitHub CLI is installed; `--require-signature` refuses a release that can't be checked. +The terminal update runs the same steps on your machine. It shows `cdk diff` and asks before deploying unless you pass `--yes`. It needs `cosign` or the GitHub CLI (`gh`) to check the signature, and refuses the release without one of them. (`--require-signature` is still accepted; it is always on.) ## Another machine @@ -133,4 +133,4 @@ Each release (a `vX.Y.Z` tag) has, on its GitHub release page: | `install.sh`, `launch-stack.yaml` | The install script and the Launch Stack template | | `SHA256SUMS`, `SHA256SUMS.sigstore.json` | Checksums, and their keyless signature | -Every artifact also has a GitHub build provenance attestation (`gh attestation verify --repo CoderHelm/coderhelm-platform`). +Every artifact also has a GitHub build provenance attestation. To check a release yourself, see [How updates are kept safe](./updates-security.md#check-a-release-yourself). diff --git a/infra/cfn/coderhelm-selfhost-launch.yaml b/infra/cfn/coderhelm-selfhost-launch.yaml index 2768e8a4a..0331cd77f 100644 --- a/infra/cfn/coderhelm-selfhost-launch.yaml +++ b/infra/cfn/coderhelm-selfhost-launch.yaml @@ -224,10 +224,10 @@ Resources: nodejs: 20 commands: - set -euo pipefail - # cosign, checked against its own release's checksums. - - curl -fsSLo /tmp/cosign https://github.com/sigstore/cosign/releases/download/v2.4.1/cosign-linux-amd64 - - curl -fsSLo /tmp/cosign_checksums.txt https://github.com/sigstore/cosign/releases/download/v2.4.1/cosign_checksums.txt - - (cd /tmp && grep ' cosign-linux-amd64$' cosign_checksums.txt | sed 's/cosign-linux-amd64$/cosign/' | sha256sum -c -) + # cosign, pinned by its SHA-256. These lines and the checks below + # match infra/lib/release-verify.ts (infra/test/launch-stack.test.ts). + - curl --proto =https --proto-redir =https --tlsv1.2 -fsSL -o /tmp/cosign https://github.com/sigstore/cosign/releases/download/v2.4.1/cosign-linux-amd64 + - echo "8b24b946dd5809c6bd93de08033bcf6bc0ed7d336b7785787c080f574b89249b /tmp/cosign" | sha256sum -c - - install -m 0755 /tmp/cosign /usr/local/bin/cosign build: commands: @@ -235,16 +235,19 @@ Resources: - REPO=CoderHelm/coderhelm-platform - | if [ "$VERSION" = "latest" ]; then - VERSION=$(curl -fsSL "https://api.github.com/repos/$REPO/releases/latest" | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>console.log(JSON.parse(s).tag_name))') + VERSION=$(curl --proto =https --proto-redir =https --tlsv1.2 -fsSL "https://api.github.com/repos/$REPO/releases/latest" | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{const r=JSON.parse(s);if(r.draft||r.prerelease)process.exit(1);console.log(r.tag_name)})') export VERSION fi + - '[[ "$VERSION" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] || { echo "VERSION=$VERSION is not a release tag"; exit 1; }' - echo "Installing CoderHelm $VERSION" - mkdir -p /tmp/ch && cd /tmp/ch - - B="https://github.com/$REPO/releases/download/$VERSION" - - for f in SHA256SUMS SHA256SUMS.sigstore.json coderhelm-selfhost.tgz launch-bootstrap.mjs; do curl -fsSLo "$f" "$B/$f"; done - # The checksums were signed by this repository's release workflow, on a tag. - - cosign verify-blob --bundle SHA256SUMS.sigstore.json --certificate-identity-regexp '^https://github.com/CoderHelm/coderhelm-platform/.github/workflows/release.yml@refs/tags/v' --certificate-oidc-issuer https://token.actions.githubusercontent.com SHA256SUMS - - grep -E ' (coderhelm-selfhost\.tgz|launch-bootstrap\.mjs)$' SHA256SUMS | sha256sum -c - + - B="https://github.com/CoderHelm/coderhelm-platform/releases/download/$VERSION" + - for f in SHA256SUMS SHA256SUMS.sigstore.json coderhelm-selfhost.tgz launch-bootstrap.mjs; do curl --proto =https --proto-redir =https --tlsv1.2 -fsSL -o "$f" "$B/$f"; done + # Signed by exactly this repository's release.yml, on this tag, logged in Rekor. + - cosign verify-blob --bundle SHA256SUMS.sigstore.json --certificate-identity "https://github.com/CoderHelm/coderhelm-platform/.github/workflows/release.yml@refs/tags/$VERSION" --certificate-oidc-issuer https://token.actions.githubusercontent.com --certificate-github-workflow-repository CoderHelm/coderhelm-platform --certificate-github-workflow-ref "refs/tags/$VERSION" SHA256SUMS + # Both files, each matched by name: grep finding one is not enough. + - grep ' coderhelm-selfhost.tgz$' SHA256SUMS | sha256sum -c - + - grep ' launch-bootstrap.mjs$' SHA256SUMS | sha256sum -c - - node launch-bootstrap.mjs post_build: commands: @@ -257,7 +260,7 @@ Resources: URL=$(node -e 'try{console.log(require("/tmp/coderhelm-final.json").url||"")}catch{console.log("")}') if [ -n "$WAIT_URL" ]; then if [ "$CODEBUILD_BUILD_SUCCEEDING" = "1" ] && [ -n "$URL" ]; then S=SUCCESS; R="CoderHelm is running"; else S=FAILURE; R="The install failed: open the installer log (CloudWatch, /aws/codebuild/${CODEBUILD_BUILD_ID%%:*})"; fi - curl -fsS -X PUT -H 'Content-Type:' --data-binary "{\"Status\":\"$S\",\"Reason\":\"$R\",\"UniqueId\":\"install\",\"Data\":\"$URL\"}" "$WAIT_URL" + curl --proto =https --proto-redir =https --tlsv1.2 -fsS -X PUT -H 'Content-Type:' --data-binary "{\"Status\":\"$S\",\"Reason\":\"$R\",\"UniqueId\":\"install\",\"Data\":\"$URL\"}" "$WAIT_URL" fi StarterRole: diff --git a/infra/lib/release-verify.ts b/infra/lib/release-verify.ts new file mode 100644 index 000000000..33ca489d4 --- /dev/null +++ b/infra/lib/release-verify.ts @@ -0,0 +1,53 @@ +/** + * How a CodeBuild project (the update build, infra/lib/updates-stack.ts, and + * the Launch Stack's installer, infra/cfn/coderhelm-selfhost-launch.yaml) + * checks a CoderHelm release before running anything from it. + * + * - cosign is downloaded from its GitHub release and must match a SHA-256 + * pinned here (not only the checksums file published next to it). + * - $VERSION must be a release tag (vX.Y.Z), so it can't reach a path or a + * command as anything else. + * - Downloads are HTTPS only, redirects included (curl --proto =https). + * - SHA256SUMS must carry a keyless signature whose certificate names + * exactly this repository's release.yml on refs/tags/$VERSION, issued by + * GitHub Actions' OIDC issuer; cosign also requires its Rekor (transparency + * log) entry, since no --insecure-ignore-tlog is passed. + * + * The Launch Stack template is plain YAML, so its buildspec repeats these + * lines; infra/test/launch-stack.test.ts checks they stay identical. + */ + +export const RELEASE_REPO = "CoderHelm/coderhelm-platform"; +export const RELEASE_WORKFLOW = `${RELEASE_REPO}/.github/workflows/release.yml`; +export const SIGNER_ISSUER = "https://token.actions.githubusercontent.com"; + +/** The cosign release the builds install, and its linux-amd64 binary's SHA-256 (cosign_checksums.txt of that release). */ +export const COSIGN_VERSION = "v2.4.1"; +export const COSIGN_LINUX_AMD64_SHA256 = "8b24b946dd5809c6bd93de08033bcf6bc0ed7d336b7785787c080f574b89249b"; + +/** curl that only speaks HTTPS, also after a redirect. */ +export const CURL = "curl --proto =https --proto-redir =https --tlsv1.2 -fsSL"; + +/** Installs the pinned cosign. */ +export function installCosignCommands(): string[] { + return [ + `${CURL} -o /tmp/cosign https://github.com/sigstore/cosign/releases/download/${COSIGN_VERSION}/cosign-linux-amd64`, + `echo "${COSIGN_LINUX_AMD64_SHA256} /tmp/cosign" | sha256sum -c -`, + "install -m 0755 /tmp/cosign /usr/local/bin/cosign", + ]; +} + +/** Refuses a $VERSION that isn't a release tag. */ +export const CHECK_VERSION = `[[ "$VERSION" =~ ^v[0-9]+\\.[0-9]+\\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] || { echo "VERSION=$VERSION is not a release tag"; exit 1; }`; + +/** Where release files come from. */ +export const RELEASE_BASE = `B="https://github.com/${RELEASE_REPO}/releases/download/$VERSION"`; + +/** Checks SHA256SUMS against its signature: exactly release.yml on this tag, GitHub's issuer, in Rekor. */ +export const VERIFY_SUMS = + "cosign verify-blob --bundle SHA256SUMS.sigstore.json" + + ` --certificate-identity "https://github.com/${RELEASE_WORKFLOW}@refs/tags/$VERSION"` + + ` --certificate-oidc-issuer ${SIGNER_ISSUER}` + + ` --certificate-github-workflow-repository ${RELEASE_REPO}` + + ` --certificate-github-workflow-ref "refs/tags/$VERSION"` + + " SHA256SUMS"; diff --git a/infra/lib/updates-stack.ts b/infra/lib/updates-stack.ts index 8b06ae218..2a31c7122 100644 --- a/infra/lib/updates-stack.ts +++ b/infra/lib/updates-stack.ts @@ -32,14 +32,14 @@ import { Construct } from "constructs"; import { ResolvedConfig } from "./config"; import { repoPath } from "./paths"; import { releaseStamp, stampEnvironment } from "./release"; +import { CHECK_VERSION, CURL, installCosignCommands, RELEASE_BASE, RELEASE_REPO, VERIFY_SUMS } from "./release-verify"; /** The functions that read the install's secret once, at start. */ export function secretReaders(prefix: string): string[] { return [`${prefix}-gateway`, `${prefix}-streaming`, `${prefix}-worker`]; } -/** The cosign release the update build installs (checked against its checksums). */ -export const COSIGN_VERSION = "v2.4.1"; +export { COSIGN_VERSION } from "./release-verify"; export interface UpdatesStackProps extends cdk.StackProps { cfg: ResolvedConfig; @@ -49,8 +49,6 @@ export interface UpdatesStackProps extends cdk.StackProps { /** The update build's script (also checked by the tests). */ export function updateBuildSpec(cfg: ResolvedConfig): codebuild.BuildSpec { - const repo = "CoderHelm/coderhelm-platform"; - const identity = `^https://github.com/${repo}/.github/workflows/release.yml@refs/tags/v`; return codebuild.BuildSpec.fromObject({ version: "0.2", env: { shell: "bash" }, @@ -59,25 +57,25 @@ export function updateBuildSpec(cfg: ResolvedConfig): codebuild.BuildSpec { "runtime-versions": { nodejs: 20 }, commands: [ "set -euo pipefail", - // cosign, checked against its release's checksums. - `curl -fsSLo /tmp/cosign https://github.com/sigstore/cosign/releases/download/${COSIGN_VERSION}/cosign-linux-amd64`, - `curl -fsSLo /tmp/cosign_checksums.txt https://github.com/sigstore/cosign/releases/download/${COSIGN_VERSION}/cosign_checksums.txt`, - "(cd /tmp && grep ' cosign-linux-amd64$' cosign_checksums.txt | sed 's/cosign-linux-amd64$/cosign/' | sha256sum -c -)", - "install -m 0755 /tmp/cosign /usr/local/bin/cosign", + // cosign, pinned by its SHA-256 (infra/lib/release-verify.ts). + ...installCosignCommands(), ], }, build: { commands: [ "set -euo pipefail", + CHECK_VERSION, "mkdir -p /tmp/ch && cd /tmp/ch", - `B="https://github.com/${repo}/releases/download/$VERSION"`, - 'curl -fsSLo SHA256SUMS "$B/SHA256SUMS"', - 'curl -fsSLo SHA256SUMS.sigstore.json "$B/SHA256SUMS.sigstore.json"', - // The checksums were signed by the release workflow for this repo. - `cosign verify-blob --bundle SHA256SUMS.sigstore.json --certificate-identity-regexp '${identity}' --certificate-oidc-issuer https://token.actions.githubusercontent.com SHA256SUMS`, - 'curl -fsSLo coderhelm-selfhost.tgz "$B/coderhelm-selfhost.tgz"', + RELEASE_BASE, + `${CURL} -o SHA256SUMS "$B/SHA256SUMS"`, + `${CURL} -o SHA256SUMS.sigstore.json "$B/SHA256SUMS.sigstore.json"`, + // Signed by exactly this repository's release.yml, on this tag, in Rekor. + VERIFY_SUMS, + `${CURL} -o coderhelm-selfhost.tgz "$B/coderhelm-selfhost.tgz"`, "grep ' coderhelm-selfhost.tgz$' SHA256SUMS | sha256sum -c -", - "npm install -g ./coderhelm-selfhost.tgz", + // The installer then checks every other file of the release the same way, + // and refuses an older release unless it is a rollback to one this install ran. + "npm install -g --ignore-scripts ./coderhelm-selfhost.tgz", `coderhelm-selfhost pull --stage ${cfg.stage} --region "$AWS_REGION"${cfg.raw.resourcePrefix ? ` --resource-prefix ${cfg.raw.resourcePrefix}` : ""}`, 'EXTRA=""; if [ "$MODE" = "rollback" ]; then EXTRA="--rollback"; fi', // A domain change (MODE=domain) redeploys the release that runs, @@ -208,7 +206,7 @@ export class UpdatesStack extends cdk.Stack { ADMIN_EMAILS: cfg.admins.join(","), SES_FROM_ADDRESS: cfg.email.from, APP_URL: props.appUrl, - RELEASE_REPO: "CoderHelm/coderhelm-platform", + RELEASE_REPO, // Restarted after the gateway stores new keys (refresh_secrets). REFRESH_FUNCTIONS: secretReaders(prefix).join(","), // Your own domain (docs/self-host/domains.md). diff --git a/infra/lib/worker-stack.ts b/infra/lib/worker-stack.ts index b45bd6932..64143f2d3 100644 --- a/infra/lib/worker-stack.ts +++ b/infra/lib/worker-stack.ts @@ -552,11 +552,16 @@ export class WorkerStack extends cdk.Stack { if (cfg.publicBucketName) { const publisher = new iam.Role(this, "ReleasePublisherRole", { roleName: `${prefix}-release-publisher`, - description: "Release workflow (GitHub Actions, v* tags): publishes the Launch Stack template to the public bucket", + description: "Release workflow (GitHub Actions, release environment): publishes the Launch Stack template to the public bucket", maxSessionDuration: cdk.Duration.hours(1), assumedBy: new iam.WebIdentityPrincipal(githubOidc.openIdConnectProviderArn, { - StringEquals: { "token.actions.githubusercontent.com:aud": "sts.amazonaws.com" }, - StringLike: { "token.actions.githubusercontent.com:sub": `repo:${RELEASE_REPO}:ref:refs/tags/v*` }, + // Only a job in the repository's "release" environment (which + // needs a reviewer's approval, .github/workflows/release.yml): + // with an environment, GitHub's token names it, not the tag. + StringEquals: { + "token.actions.githubusercontent.com:aud": "sts.amazonaws.com", + "token.actions.githubusercontent.com:sub": `repo:${RELEASE_REPO}:environment:release`, + }, }), }); publisher.addToPolicy( diff --git a/infra/test/launch-stack.test.ts b/infra/test/launch-stack.test.ts index 941e33a22..84e8766bc 100644 --- a/infra/test/launch-stack.test.ts +++ b/infra/test/launch-stack.test.ts @@ -10,6 +10,7 @@ import * as cdk from "aws-cdk-lib"; import { Template } from "aws-cdk-lib/assertions"; import { CfnInclude } from "aws-cdk-lib/cloudformation-include"; import { repoPath } from "../lib/paths"; +import { CHECK_VERSION, COSIGN_LINUX_AMD64_SHA256, installCosignCommands, VERIFY_SUMS } from "../lib/release-verify"; const FILE = repoPath("infra", "cfn", "coderhelm-selfhost-launch.yaml"); @@ -67,8 +68,21 @@ test("the build checks the release's signature and checksums before running anyt const sums = spec.lastIndexOf("sha256sum -c -"); const runs = at("node launch-bootstrap.mjs"); assert.ok(verify < sums && sums < runs, "verify, then checksums, then run"); - assert.match(spec, /release\.yml@refs\/tags\/v/, "signed by the release workflow, on a tag"); - assert.match(spec, /coderhelm-selfhost\\\.tgz\|launch-bootstrap\\\.mjs/); + assert.ok(spec.includes(VERIFY_SUMS), "the exact identity: release.yml on refs/tags/$VERSION, GitHub's issuer"); + assert.ok(spec.indexOf(CHECK_VERSION) >= 0 && spec.indexOf(CHECK_VERSION) < verify, "VERSION is a release tag before it is used"); + for (const line of installCosignCommands()) assert.ok(spec.includes(line), `pinned cosign: ${line}`); + assert.ok(spec.includes(COSIGN_LINUX_AMD64_SHA256)); + assert.ok(spec.includes("grep ' coderhelm-selfhost.tgz$' SHA256SUMS | sha256sum -c -")); + assert.ok(spec.includes("grep ' launch-bootstrap.mjs$' SHA256SUMS | sha256sum -c -")); +}); + +test("no loose signature checks: no identity regexp, no skipped transparency log, HTTPS-only downloads", () => { + const spec: string = load().toJSON().Resources.InstallerProject.Properties.Source.BuildSpec; + assert.doesNotMatch(spec, /identity-regexp|insecure-ignore|ignore-tlog|--offline/); + for (const line of spec.split("\n").filter((l) => /\bcurl\b/.test(l))) { + assert.match(line, /curl --proto =https --proto-redir =https --tlsv1\.2/, line); + } + assert.ok(spec.includes('B="https://github.com/CoderHelm/coderhelm-platform/releases/download/$VERSION"')); }); test("the starter may only start the installer and open the progress file", () => { diff --git a/infra/test/synth.test.ts b/infra/test/synth.test.ts index 4c478b926..63a0a020f 100644 --- a/infra/test/synth.test.ts +++ b/infra/test/synth.test.ts @@ -16,6 +16,8 @@ import { Template } from "aws-cdk-lib/assertions"; import { buildApp } from "../lib/app"; import { CoderhelmConfig, loadConfigFile, resolveConfig, ResolvedConfig } from "../lib/config"; import { API_PATHS, STREAM_PATH, runtimeConfigScript } from "../lib/web-stack"; +import { updateBuildSpec } from "../lib/updates-stack"; +import { CHECK_VERSION, COSIGN_LINUX_AMD64_SHA256, VERIFY_SUMS } from "../lib/release-verify"; const INFRA = path.join(__dirname, "..", ".."); @@ -252,6 +254,14 @@ test("updates: on by default for self-host, with a least-privilege build role; o const spec = JSON.stringify(u.findResources("AWS::CodeBuild::Project")); assert.ok(spec.includes("cosign verify-blob")); assert.ok(spec.includes("--require-signature --auto-rollback")); + const commands: string[] = [...Object.values((updateBuildSpec(cfg) as any).spec.phases)].flatMap((p: any) => p.commands); + const verifyAt = commands.indexOf(VERIFY_SUMS); + assert.ok(verifyAt >= 0, "exact identity: release.yml on refs/tags/$VERSION"); + assert.ok(commands.indexOf(CHECK_VERSION) >= 0 && commands.indexOf(CHECK_VERSION) < verifyAt, "VERSION must be a release tag first"); + assert.ok(verifyAt < commands.findIndex((c) => c.startsWith("npm install")), "verified before the installer is installed"); + assert.doesNotMatch(commands.join("\n"), /identity-regexp|insecure-ignore|ignore-tlog/); + assert.ok(commands.some((c) => c.includes(COSIGN_LINUX_AMD64_SHA256)), "cosign pinned by its hash"); + assert.ok(commands.includes("npm install -g --ignore-scripts ./coderhelm-selfhost.tgz")); // The gateway knows the updater and may call it. assert.equal(envOf(t["coderhelm-prod-api"], "coderhelm-prod-gateway").UPDATER_FUNCTION_NAME, "coderhelm-prod-updater"); assert.ok(json(t["coderhelm-prod-api"]).includes("function:coderhelm-prod-updater")); @@ -346,7 +356,7 @@ test("the manifest landing: self-host only, may write only this install's secret }); }); -test("the release publisher: only v* tag builds of the platform repo, only launch/* in the public bucket", () => { +test("the release publisher: only the platform repo's approved release environment, only launch/* in the public bucket", () => { const cfg = loadConfigFile(path.join(INFRA, "config", "hosted.prod.json"), { CDK_DEFAULT_ACCOUNT: "654654210434" }); const t = synth(cfg, zoneContext("654654210434", "us-east-1", "coderhelm.com")); const w = t["coderhelm-prod-worker"]; @@ -356,8 +366,11 @@ test("the release publisher: only v* tag builds of the platform repo, only launc const [st] = role.Properties.AssumeRolePolicyDocument.Statement; assert.equal(st.Action, "sts:AssumeRoleWithWebIdentity"); assert.deepEqual(st.Condition, { - StringEquals: { "token.actions.githubusercontent.com:aud": "sts.amazonaws.com" }, - StringLike: { "token.actions.githubusercontent.com:sub": "repo:CoderHelm/coderhelm-platform:ref:refs/tags/v*" }, + StringEquals: { + "token.actions.githubusercontent.com:aud": "sts.amazonaws.com", + // Only a job in the release environment, which needs a reviewer's approval. + "token.actions.githubusercontent.com:sub": "repo:CoderHelm/coderhelm-platform:environment:release", + }, }); const policies = Object.values(w.findResources("AWS::IAM::Policy")) as any[]; const mine = policies.filter((p) => JSON.stringify(p.Properties.Roles).includes("ReleasePublisherRole")); diff --git a/installer/lib/cli.mjs b/installer/lib/cli.mjs index 45fc34df4..ea0ed59bd 100644 --- a/installer/lib/cli.mjs +++ b/installer/lib/cli.mjs @@ -56,7 +56,7 @@ Options Enterprise Server); secrets come from GITHUB_WEBHOOK_SECRET and GITHUB_CLIENT_SECRET --skip-github-app deploy: don't create the GitHub App now - --require-signature update/deploy: refuse a release whose signature can't be checked + --require-signature (always on: a release whose signature can't be checked is refused) --auto-rollback update: deploy the previous release again if health fails --result-file update: write {status, from, to, reason} to this file --skip-checks init: go on past these failed checks (comma-separated diff --git a/installer/lib/commands.mjs b/installer/lib/commands.mjs index b1ba01fd5..df5d46146 100644 --- a/installer/lib/commands.mjs +++ b/installer/lib/commands.mjs @@ -4,7 +4,7 @@ import fs from "node:fs"; import path from "node:path"; import crypto from "node:crypto"; import { checkPrereqs } from "./prereqs.mjs"; -import { fetchRelease, latestVersion, releasePaths, releasesDir, verifySignature } from "./release.mjs"; +import { checkTag, fetchRelease, latestVersion, releasePaths, releasesDir, TAG_RE } from "./release.mjs"; import { openBrowser } from "./github-app.mjs"; import { ensureSecret, hasGithubApp, mergeSecret, readSecret } from "./secrets.mjs"; import { runManifestFlow, secretKeysFromApp } from "./github-app.mjs"; @@ -84,8 +84,8 @@ export async function resolveSource(ctx, version) { } const tag = version ?? (runner.dryRun ? "v0.0.0-dry-run" : await latestVersion(ctx.fetchImpl)); log(`Release ${tag}`); + // Downloads, then checks the checksums and the signature before unpacking. const paths = await fetchRelease(tag, { runner, fetchImpl: ctx.fetchImpl, log }); - if (!runner.dryRun) await verifySignature(paths, runner, { require: !!flags.requireSignature, log }); return { version: tag, infra: paths.infra, @@ -146,6 +146,7 @@ export async function deploy(ctx) { const publicUrl = known ?? "https://"; const next = { ...state, installId: state.installId ?? crypto.randomUUID(), version: src.version, deployedAt: new Date().toISOString(), ...(known ? { publicUrl: known } : {}) }; if (state.version && state.version !== src.version) next.previousVersion = state.version; + next.versions = ranVersions(next); saveState(flags, next, runner); await saveRemote(ctx, cfg, next); @@ -325,8 +326,8 @@ export function migrationNotes(migrations, from, to) { /** * Moves the install to a release, safely: * 1. health check first (an unhealthy install isn't updated, unless --force); - * 2. the release's checksums and signature (--require-signature refuses - * one that can't be verified); + * 2. the release's checksums and signature (always: a release that can't + * be verified is refused); * 3. the migration notes it crosses (action-needed ones stop it without --yes); * 4. deploy; * 5. health check after; when it fails and --auto-rollback is set, the @@ -352,6 +353,9 @@ export async function update(ctx) { if (state.version && semverCompare(target, state.version) < 0 && !flags.rollback) { throw new Error(`${target} is older than ${state.version}. Use "coderhelm-selfhost rollback" to go back.`); } + // Going back only to a release this install ran before: an older signed + // release with a since-fixed problem can't be pushed onto it. + if (flags.rollback) checkRollbackTarget(state, target); log(`${flags.rollback ? "Rolling back" : "Updating"} ${state.version ?? "(unknown)"} to ${target}`); // Preflight: what would stop the update, each with its fix, before @@ -469,6 +473,21 @@ const HEALTH_FIX = { API: "Check the gateway function's logs in CloudWatch, then deploy again.", }; +/** Every release this install has run (state.versions, plus the current and previous one). */ +export function ranVersions(state) { + const all = [...(state.versions ?? []), state.previousVersion, state.version]; + return [...new Set(all.filter((v) => typeof v === "string" && TAG_RE.test(v)))].sort(semverCompare).slice(-50); +} + +/** A rollback goes only to an older release this install ran before. */ +export function checkRollbackTarget(state, target) { + checkTag(target); + const ran = ranVersions(state).filter((v) => v !== state.version); + if (!ran.includes(target)) { + throw plainError(`${target} is not a release this install ran before (${ran.join(", ") || "none recorded"}), so it can't be rolled back to. Update forward instead.`); + } +} + /** The old name for update. */ export const upgrade = update; diff --git a/installer/lib/release.mjs b/installer/lib/release.mjs index cf971206a..ce26daecf 100644 --- a/installer/lib/release.mjs +++ b/installer/lib/release.mjs @@ -9,14 +9,19 @@ // SHA256SUMS.sigstore.json cosign's keyless signature of SHA256SUMS, // made by this repository's release workflow // -// Every file is checked against SHA256SUMS before use, and SHA256SUMS -// against its signature (cosign) or the files' GitHub build attestations -// (gh) when either tool is installed. `--require-signature` (the update -// build always passes it) refuses a release that can't be verified. +// Nothing from a release is used until it checks out: every file against +// SHA256SUMS, and SHA256SUMS against its signature, which must have been made +// by exactly this repository's release.yml, on the release's own tag, with +// a GitHub Actions certificate logged in Rekor (cosign), or else every file +// against its GitHub build attestation from that same workflow and tag (gh). +// No cosign and no gh, no bundle, or any mismatch: the release is refused. +// There is no switch that skips this; deploy from a checkout (--source) to +// run code that isn't a signed release. import fs from "node:fs"; import path from "node:path"; import os from "node:os"; import { REPO, sha256File } from "./util.mjs"; +import { checkBundleIdentity } from "./sigstore.mjs"; export const ASSETS = ["gateway.zip", "worker.zip", "mcp-proxy.zip", "dashboard.tar.gz", "source.tar.gz"]; @@ -26,6 +31,14 @@ export function releasesDir() { : path.join(os.homedir(), ".coderhelm", "releases"); } +/** A release tag: vX.Y.Z, or vX.Y.Z-pre (also selfhost/launch/stamp-template.mjs). */ +export const TAG_RE = /^v\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/; + +export function checkTag(tag) { + if (typeof tag !== "string" || !TAG_RE.test(tag)) throw new Error(`${JSON.stringify(tag)} is not a CoderHelm release (vX.Y.Z).`); + return tag; +} + /** The latest release tag, from GitHub. */ export async function latestVersion(fetchImpl = fetch) { const r = await fetchImpl(`https://api.github.com/repos/${REPO}/releases/latest`, { @@ -33,7 +46,43 @@ export async function latestVersion(fetchImpl = fetch) { }); if (!r.ok) throw new Error(`Could not look up the latest release (GitHub answered ${r.status}).`); const j = await r.json(); - return j.tag_name; + if (j.draft || j.prerelease) throw new Error("GitHub's latest release is a draft or a pre-release: pass --to vX.Y.Z."); + return checkTag(j.tag_name); +} + +/** + * Where release files may come from: GitHub's release download URL for this + * repository, over HTTPS, and the hosts GitHub redirects those downloads to. + */ +export const DOWNLOAD_HOSTS = ["github.com", "objects.githubusercontent.com", "release-assets.githubusercontent.com"]; + +export function releaseUrl(tag, name) { + return `https://github.com/${REPO}/releases/download/${checkTag(tag)}/${name}`; +} + +/** Throws unless a (possibly redirected) download came from an expected HTTPS host. */ +export function checkDownloadUrl(url) { + let u; + try { + u = new URL(url); + } catch { + throw new Error(`Refusing a download from ${url}: not a URL.`); + } + if (u.protocol !== "https:" || !DOWNLOAD_HOSTS.includes(u.hostname) || u.username || u.password || u.port) { + throw new Error(`Refusing a download from ${u.origin}: releases come only from GitHub over HTTPS.`); + } + if (u.hostname === "github.com" && !u.pathname.startsWith(`/${REPO}/releases/download/`)) { + throw new Error(`Refusing a download from ${u.href}: not a ${REPO} release.`); + } + return u.href; +} + +async function download(fetchImpl, tag, name) { + const url = releaseUrl(tag, name); + const r = await fetchImpl(url, { redirect: "follow" }); + if (!r.ok) throw new Error(`Could not download ${name} for ${tag} (${r.status}). Is ${tag} a CoderHelm release?`); + checkDownloadUrl(r.url || url); + return Buffer.from(await r.arrayBuffer()); } /** Parses SHA256SUMS (" " per line). */ @@ -60,6 +109,7 @@ export function verifySums(dir, sums, names = ASSETS) { * it, and unpacks the source and dashboard. Returns the paths deploy needs. */ export async function fetchRelease(tag, { runner, fetchImpl = fetch, log = console.log }) { + checkTag(tag); const dir = path.join(releasesDir(), tag); const done = path.join(dir, ".ready"); const paths = releasePaths(dir); @@ -67,19 +117,21 @@ export async function fetchRelease(tag, { runner, fetchImpl = fetch, log = conso log(` [dry run] download release ${tag} into ${dir} and check SHA256SUMS`); return paths; } - if (fs.existsSync(done)) return paths; + // A release downloaded before is checked again: its files may have changed since. + if (fs.existsSync(done)) { + verifySums(dir, parseSums(fs.readFileSync(path.join(dir, "SHA256SUMS"), "utf8"))); + await verifySignature(paths, runner, { tag, log }); + return paths; + } + fs.rmSync(dir, { recursive: true, force: true }); fs.mkdirSync(dir, { recursive: true }); - const base = `https://github.com/${REPO}/releases/download/${tag}`; - for (const n of ["SHA256SUMS", ...ASSETS]) { + for (const n of ["SHA256SUMS", SIGNATURE, ...ASSETS]) { log(` downloading ${n}`); - const r = await fetchImpl(`${base}/${n}`, { redirect: "follow" }); - if (!r.ok) throw new Error(`Could not download ${n} for ${tag} (${r.status}). Is ${tag} a CoderHelm release?`); - fs.writeFileSync(path.join(dir, n), Buffer.from(await r.arrayBuffer())); + fs.writeFileSync(path.join(dir, n), await download(fetchImpl, tag, n)); } - // The signature is optional to download; verifySignature decides if it is needed. - const sig = await fetchImpl(`${base}/${SIGNATURE}`, { redirect: "follow" }).catch(() => null); - if (sig?.ok) fs.writeFileSync(path.join(dir, SIGNATURE), Buffer.from(await sig.arrayBuffer())); + // Checked before anything is unpacked or run. verifySums(dir, parseSums(fs.readFileSync(path.join(dir, "SHA256SUMS"), "utf8"))); + await verifySignature(paths, runner, { tag, log }); fs.mkdirSync(paths.source, { recursive: true }); fs.mkdirSync(paths.dashboard, { recursive: true }); await runner.run("tar", ["-xzf", path.join(dir, "source.tar.gz"), "-C", paths.source, "--strip-components=1"]); @@ -101,9 +153,37 @@ export function releasePaths(dir) { } export const SIGNATURE = "SHA256SUMS.sigstore.json"; -/** Who may have signed a release: this repository's release workflow, on a tag. */ -export const SIGNER_IDENTITY = `^https://github.com/${REPO}/.github/workflows/release.yml@refs/tags/v`; export const SIGNER_ISSUER = "https://token.actions.githubusercontent.com"; +export const SIGNER_WORKFLOW = `${REPO}/.github/workflows/release.yml`; + +/** The one certificate identity a release's signature may have: release.yml, run on that release's tag. */ +export function signerIdentity(tag) { + return `https://github.com/${SIGNER_WORKFLOW}@refs/tags/${checkTag(tag)}`; +} + +/** cosign's arguments: the exact identity, issuer, repository and ref (and Rekor, which cosign requires by default). */ +export function cosignArgs(tag, bundle, file) { + return [ + "verify-blob", "--bundle", bundle, + "--certificate-identity", signerIdentity(tag), + "--certificate-oidc-issuer", SIGNER_ISSUER, + "--certificate-github-workflow-repository", REPO, + "--certificate-github-workflow-ref", `refs/tags/${tag}`, + file, + ]; +} + +/** gh's arguments: the attestation must come from release.yml in this repository, on the tag, on GitHub's runners. */ +export function attestationArgs(tag, file) { + return [ + "attestation", "verify", file, + "--repo", REPO, + "--signer-workflow", SIGNER_WORKFLOW, + "--source-ref", `refs/tags/${checkTag(tag)}`, + "--cert-oidc-issuer", SIGNER_ISSUER, + "--deny-self-hosted-runners", + ]; +} const has = async (runner, cmd, args) => { const r = await runner.run(cmd, args, { capture: true, allowFail: true }).catch(() => null); @@ -112,35 +192,40 @@ const has = async (runner, cmd, args) => { /** * Checks that the release was built and signed by this repository's release - * workflow: SHA256SUMS against its cosign signature, or the artifacts' - * GitHub attestations. Returns how it was verified, or null when no tool - * was there; throws on a bad signature, and when `require` is set and it - * couldn't be checked. + * workflow on `tag`: the signature bundle's certificate must name exactly + * that workflow and tag, then SHA256SUMS is checked against it with cosign, + * or every asset against its GitHub attestation with gh. Throws on any + * mismatch, a missing bundle, or when neither tool is installed; returns + * how it was verified. (`require` is accepted for older callers: it is + * always required now.) */ -export async function verifySignature(paths, runner, { require = false, log = console.log } = {}) { +export async function verifySignature(paths, runner, { tag, log = console.log } = {}) { + checkTag(tag); const sigFile = path.join(paths.dir, SIGNATURE); - if (fs.existsSync(sigFile) && (await has(runner, "cosign", ["version"]))) { - const r = await runner.run("cosign", [ - "verify-blob", "--bundle", sigFile, - "--certificate-identity-regexp", SIGNER_IDENTITY, - "--certificate-oidc-issuer", SIGNER_ISSUER, - path.join(paths.dir, "SHA256SUMS"), - ], { capture: true, allowFail: true }); + if (!fs.existsSync(sigFile)) throw new Error(`The release has no signature (${SIGNATURE}): not installing it.`); + try { + checkBundleIdentity(fs.readFileSync(sigFile, "utf8"), { + identity: signerIdentity(tag), + issuer: SIGNER_ISSUER, + repositoryUri: `https://github.com/${REPO}`, + ref: `refs/tags/${tag}`, + }); + } catch (e) { + throw new Error(`The release's signature is not CoderHelm's release workflow for ${tag}: ${e.message}. Not installing it.`); + } + if (await has(runner, "cosign", ["version"])) { + const r = await runner.run("cosign", cosignArgs(tag, sigFile, path.join(paths.dir, "SHA256SUMS")), { capture: true, allowFail: true }); if (r.code !== 0) throw new Error(`The release's signature does not verify: not installing it.${r.stderr ? `\n${r.stderr.trim()}` : ""}`); - log(" signature verified (cosign: signed by this repository's release workflow)"); + log(` signature verified (cosign: ${SIGNER_WORKFLOW} on ${tag}, in the Rekor log)`); return "cosign"; } if (await has(runner, "gh", ["--version"])) { - for (const n of ["gateway.zip", "worker.zip", "source.tar.gz"]) { - const r = await runner.run("gh", ["attestation", "verify", path.join(paths.dir, n), "--repo", REPO], { capture: true, allowFail: true }); - if (r.code !== 0) throw new Error(`${n} has no valid build attestation from ${REPO}: not installing it.`); + for (const n of ASSETS) { + const r = await runner.run("gh", attestationArgs(tag, path.join(paths.dir, n)), { capture: true, allowFail: true }); + if (r.code !== 0) throw new Error(`${n} has no valid build attestation from ${SIGNER_WORKFLOW} on ${tag}: not installing it.`); } - log(" provenance verified (gh: built by this repository's release workflow)"); + log(` provenance verified (gh: built by ${SIGNER_WORKFLOW} on ${tag})`); return "attestation"; } - if (require) { - throw new Error("Can't verify the release's signature (install cosign or the GitHub CLI), and --require-signature is set: not installing it."); - } - log(" (cosign and gh not found: checksums verified, signature not checked)"); - return null; + throw new Error("Can't check the release's signature: install cosign (https://docs.sigstore.dev/cosign/system_config/installation/) or the GitHub CLI (gh), then run this again. Nothing was installed."); } diff --git a/installer/lib/sigstore.mjs b/installer/lib/sigstore.mjs new file mode 100644 index 000000000..056007b79 --- /dev/null +++ b/installer/lib/sigstore.mjs @@ -0,0 +1,129 @@ +// Reads the signing certificate out of a cosign bundle (SHA256SUMS.sigstore.json) +// and checks who it was issued to, before cosign checks the signature itself. +// +// A Sigstore keyless certificate (Fulcio) names the GitHub Actions workflow +// that signed: its subjectAltName is the workflow's URL at the ref it ran on, +// and extensions under 1.3.6.1.4.1.57264.1 carry the OIDC issuer, the +// repository and the ref. Checking these here as well as with cosign's own +// flags means a release signed by another repository, another workflow, a +// branch or another tag is refused with a plain reason, and that a cosign +// left out of the picture (the GitHub CLI path) still never accepts a +// bundle made for something else. +import crypto from "node:crypto"; + +/** Fulcio's certificate extensions (https://github.com/sigstore/fulcio/blob/main/docs/oid-info.md). */ +export const OID = { + issuerV1: "1.3.6.1.4.1.57264.1.1", + issuer: "1.3.6.1.4.1.57264.1.8", + buildSignerUri: "1.3.6.1.4.1.57264.1.9", + sourceRepositoryUri: "1.3.6.1.4.1.57264.1.12", + sourceRepositoryRef: "1.3.6.1.4.1.57264.1.14", +}; + +/** DER bytes of an OBJECT IDENTIFIER's value (without tag and length). */ +export function encodeOid(oid) { + const parts = oid.split(".").map(Number); + const out = [40 * parts[0] + parts[1]]; + for (const n of parts.slice(2)) { + const bytes = [n & 0x7f]; + for (let v = n >>> 7; v > 0; v >>>= 7) bytes.unshift((v & 0x7f) | 0x80); + out.push(...bytes); + } + return Buffer.from(out); +} + +/** Reads a DER length at `i`; returns [length, index after it]. */ +function readLength(buf, i) { + const first = buf[i]; + if (first < 0x80) return [first, i + 1]; + const n = first & 0x7f; + if (n === 0 || n > 4 || i + 1 + n > buf.length) throw new Error("bad DER length"); + let len = 0; + for (let k = 0; k < n; k++) len = len * 256 + buf[i + 1 + k]; + return [len, i + 1 + n]; +} + +/** + * The value of a certificate extension, as text, or null when the + * certificate has none. The extension is `SEQUENCE { OID, [BOOLEAN], OCTET + * STRING }`; Fulcio's newer extensions hold a DER UTF8String inside the + * OCTET STRING, the first one (issuer v1) holds the raw text. + */ +export function extensionValue(der, oid) { + const needle = Buffer.concat([Buffer.from([0x06, encodeOid(oid).length]), encodeOid(oid)]); + const at = der.indexOf(needle); + if (at < 0) return null; + let i = at + needle.length; + if (der[i] === 0x01) { + const [len, next] = readLength(der, i + 1); + i = next + len; + } + if (der[i] !== 0x04) return null; + const [len, start] = readLength(der, i + 1); + const inner = der.subarray(start, start + len); + if (inner[0] === 0x0c) { + const [l2, s2] = readLength(inner, 1); + return inner.subarray(s2, s2 + l2).toString("utf8"); + } + return inner.toString("utf8"); +} + +/** The certificate (DER) and whether a transparency log entry is in a cosign bundle (old or new format). */ +export function readBundle(text) { + let b; + try { + b = JSON.parse(text); + } catch { + throw new Error("the signature bundle is not valid JSON"); + } + let der = null; + // cosign 2.x `sign-blob --bundle`: base64 of the PEM certificate. + if (typeof b?.cert === "string") { + const pem = Buffer.from(b.cert, "base64").toString("utf8"); + der = new crypto.X509Certificate(pem.includes("BEGIN CERTIFICATE") ? pem : Buffer.from(b.cert, "base64")).raw; + } + // Sigstore bundle v0.2/v0.3 (cosign --new-bundle-format, cosign 3). + const vm = b?.verificationMaterial; + const raw = vm?.certificate?.rawBytes ?? vm?.x509CertificateChain?.certificates?.[0]?.rawBytes; + if (!der && typeof raw === "string") der = new crypto.X509Certificate(Buffer.from(raw, "base64")).raw; + if (!der) throw new Error("the signature bundle has no signing certificate"); + const tlog = Boolean(b?.rekorBundle?.SignedEntryTimestamp || b?.rekorBundle?.Payload?.logIndex !== undefined) + || (Array.isArray(vm?.tlogEntries) && vm.tlogEntries.some((e) => e?.logIndex !== undefined && (e?.inclusionPromise || e?.inclusionProof))); + return { der, tlog }; +} + +/** Who the certificate names: its URI subjectAltName and the Fulcio extensions. */ +export function certificateClaims(der) { + const x = new crypto.X509Certificate(der); + const uris = String(x.subjectAltName ?? "") + .split(/,\s*/) + .filter((s) => s.startsWith("URI:")) + .map((s) => s.slice(4)); + return { + identities: uris, + issuer: extensionValue(der, OID.issuer) ?? extensionValue(der, OID.issuerV1), + repository: extensionValue(der, OID.sourceRepositoryUri), + ref: extensionValue(der, OID.sourceRepositoryRef), + buildSigner: extensionValue(der, OID.buildSignerUri), + }; +} + +/** + * Throws unless the bundle's certificate was issued to exactly `identity` + * by `issuer`, for `repositoryUri` at `ref`, and the bundle carries a + * transparency log (Rekor) entry. This is a pre-check: the signature and + * the certificate chain are checked by cosign (or the GitHub CLI). + */ +export function checkBundleIdentity(text, { identity, issuer, repositoryUri, ref }) { + const { der, tlog } = readBundle(text); + const c = certificateClaims(der); + const problems = []; + if (c.identities.length !== 1 || c.identities[0] !== identity) problems.push(`it was signed by ${c.identities.join(", ") || "an unnamed signer"}, not ${identity}`); + if (c.issuer !== issuer) problems.push(`its certificate was issued for ${c.issuer ?? "an unknown issuer"}, not ${issuer}`); + if (c.repository !== null && c.repository !== repositoryUri) problems.push(`it was built from ${c.repository}, not ${repositoryUri}`); + if (c.ref !== null && c.ref !== ref) problems.push(`it was built from ${c.ref}, not ${ref}`); + if (c.buildSigner !== null && c.buildSigner !== identity) problems.push(`its build signer is ${c.buildSigner}, not ${identity}`); + if (!tlog) problems.push("it has no transparency log (Rekor) entry"); + if (problems.length) throw new Error(problems.join("; ")); + return c; +} diff --git a/installer/test/fixtures/make-signers.sh b/installer/test/fixtures/make-signers.sh new file mode 100644 index 000000000..8d7796de6 --- /dev/null +++ b/installer/test/fixtures/make-signers.sh @@ -0,0 +1,34 @@ +#!/bin/sh +# Regenerates signers.json: self-signed stand-ins for Sigstore (Fulcio) +# certificates, each naming a different signer, for the signature tests +# (test/release-security.test.mjs). They carry the same subjectAltName and +# Fulcio extensions as a real GitHub Actions certificate; the signature +# itself is cosign's job and is stubbed in the tests. +# +# sh test/fixtures/make-signers.sh > test/fixtures/signers.json +set -eu +dir=$(mktemp -d) +trap 'rm -rf "$dir"' EXIT +GH=https://github.com +WF=.github/workflows +ISS=https://token.actions.githubusercontent.com +cert() { # name repo workflow-file ref issuer + openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -keyout "$dir/k" -subj "/O=sigstore.dev" -days 3650 \ + -addext "subjectAltName=URI:$GH/$2/$WF/$3@$4" \ + -addext "1.3.6.1.4.1.57264.1.8=ASN1:UTF8String:$5" \ + -addext "1.3.6.1.4.1.57264.1.9=ASN1:UTF8String:$GH/$2/$WF/$3@$4" \ + -addext "1.3.6.1.4.1.57264.1.12=ASN1:UTF8String:$GH/$2" \ + -addext "1.3.6.1.4.1.57264.1.14=ASN1:UTF8String:$4" \ + -out "$dir/$1.pem" 2>/dev/null + printf ' "%s": %s' "$1" "$(node -p 'JSON.stringify(require("fs").readFileSync(process.argv[1], "utf8"))' "$dir/$1.pem")" +} +R=CoderHelm/coderhelm-platform +echo "{" +cert good "$R" release.yml refs/tags/v1.2.3 "$ISS"; echo "," +cert otherRepo evil/coderhelm-platform release.yml refs/tags/v1.2.3 "$ISS"; echo "," +cert otherWorkflow "$R" ci.yml refs/tags/v1.2.3 "$ISS"; echo "," +cert branch "$R" release.yml refs/heads/main "$ISS"; echo "," +cert otherTag "$R" release.yml refs/tags/v1.0.0 "$ISS"; echo "," +cert otherIssuer "$R" release.yml refs/tags/v1.2.3 https://accounts.google.com +echo +echo "}" diff --git a/installer/test/fixtures/real-github-actions-bundle.json b/installer/test/fixtures/real-github-actions-bundle.json new file mode 100644 index 000000000..35b106048 --- /dev/null +++ b/installer/test/fixtures/real-github-actions-bundle.json @@ -0,0 +1 @@ +{"mediaType": "application/vnd.dev.sigstore.bundle.v0.3+json", "verificationMaterial": {"certificate": {"rawBytes": "MIIG6DCCBm6gAwIBAgIUSrkuC2eKH1x/zobSe9gbgGz/muIwCgYIKoZIzj0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kjOPQQDAwNoADBlAjANasBrXsa5ah0u3EKnW9IzgJCp4cM10wLkEjRI4jVUzZ5+OTbd1jr/OHl6+kJxluICMQDdqddGo21mpg0S9zz8aEY2Y+EzXa4Y+cUNkbCGAUu84yzC5x0ATo80FOQISSMUNhs="}, "tlogEntries": [{"logIndex": "3425010592", "logId": {"keyId": "wNI9atQGlz+VWfO6LRygH4QUfY/8W4RFwiT5i5WRgB0="}, "kindVersion": {"kind": "dsse", "version": "0.0.1"}, "integratedTime": "1792786936", "inclusionPromise": {"signedEntryTimestamp": "MEYCIQCvKHD9R/8ux5xdj5zMRVaPspT2y0jiZ8h52JPNUCxxlgIhALjA/TkDRNIl7UKQ6R9+wjxtR6w9QNrvGvg3Fp481dhC"}, "inclusionProof": {"logIndex": "3303106330", "rootHash": "MfFPd1+aVnQVM32VBbSpa3yfvJ6lBe20zlYeYIzKNzA=", "treeSize": "3303106342", "hashes": ["a4Pl7/Xi4DLI6As592MFdR9NwVj4rO4i+n1vZT1IDgw=", "6IXRaDtjSTCVpoH214+YkU85TNCR2QvhkWwWNMdUjnw=", "d/A1rV99VxzxFKX78ZVvMd4sl82kKvjYj1KlZl5ixFw=", "V7pUHmRf51GulQePBOfte8zYrsGuPXhNnunRMCAb8o8=", "lM6DU+hO6fBu4TV3lUMZ0LSHt1YqORBi7RD7suNCl0s=", "tHs09azel82P9BcEMC8wcLDQM7zcwd2gEH9lzBHSpFI=", "ZmTGO3VYfHJdzGRzrVsfQsBgfEvz5oIwDlDElCUAKt4=", "7+VFcQRclag2OHYkrZZ5b68iHjXS/bPn+it/gRaO4fc=", "8R9vhuJoaC36HqcX725eYKCiYRY9VaRX3YoL6k6CZoo=", "cqmZyShw5uxGc8Qsf9p60DHSUR8bp4mkXhctOLm9/zk=", "M6U0IC1cKubSdlJ9QRf7id0VUOPzqu9OuAArso+6o+o=", "ofiRCo8xiqFJs5mRvtn/fXsqyHbriVjd/ohR4QacbGU=", "jPf+rQvxACYExraoNMuPijXWOK16XPyk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9fSwiaW50ZXJuYWxQYXJhbWV0ZXJzIjp7ImdpdGh1YiI6eyJldmVudF9uYW1lIjoid29ya2Zsb3dfZGlzcGF0Y2giLCJyZXBvc2l0b3J5X2lkIjoiMjEyNjEzMDQ5IiwicmVwb3NpdG9yeV9vd25lcl9pZCI6IjU5NzA0NzExIiwicnVubmVyX2Vudmlyb25tZW50IjoiZ2l0aHViLWhvc3RlZCJ9fSwicmVzb2x2ZWREZXBlbmRlbmNpZXMiOlt7InVyaSI6ImdpdCtodHRwczovL2dpdGh1Yi5jb20vY2xpL2NsaUByZWZzL2hlYWRzL3RydW5rIiwiZGlnZXN0Ijp7ImdpdENvbW1pdCI6IjRmMmNmZTkyZTM0OTlmODU4MWJmMzlkYjc3ZTBhMTQzMWZhN2I1NWMifX1dfSwicnVuRGV0YWlscyI6eyJidWlsZGVyIjp7ImlkIjoiaHR0cHM6Ly9naXRodWIuY29tL2NsaS9jbGkvLmdpdGh1Yi93b3JrZmxvd3MvZGVwbG95bWVudC55bWxAcmVmcy9oZWFkcy90cnVuayJ9LCJtZXRhZGF0YSI6eyJpbnZvY2F0aW9uSWQiOiJodHRwczovL2dpdGh1Yi5jb20vY2xpL2NsaS9hY3Rpb25zL3J1bnMvNDAwMTcxNDkwNzUvYXR0ZW1wdHMvMSJ9fX19", "payloadType": "application/vnd.in-toto+json", "signatures": [{"sig": "MEYCIQDk8IbUgPcmYFh/5zKxf6r4cEAMxBrNyjg3v2/2sEXvtwIhAMHl0UZEkAxCvZJP+3OJE66tprnFYpfQ81XYJEXdCp5X"}]}} \ No newline at end of file diff --git a/installer/test/fixtures/signers.json b/installer/test/fixtures/signers.json new file mode 100644 index 000000000..70e933235 --- /dev/null +++ b/installer/test/fixtures/signers.json @@ -0,0 +1,8 @@ +{ + "good": "-----BEGIN CERTIFICATE-----\nMIIC4DCCAoegAwIBAgIUHW+NHQxnv76psAK4AWCvEtzTaQIwCgYIKoZIzj0EAwIw\nFzEVMBMGA1UECgwMc2lnc3Rvc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3MjY0NlowFzEVMBMGA1UECgwMc2lnc3RvcmUuZGV2MFkwEwYHKoZIzj0CAQYI\nKoZIzj0DAQcDQgAEJ64NxkDqmx5IGIi7M3xr8FybRuIv+3/DqthGLNavclGNVhsF\noOALc8Zj7xL0Yfxk0LL88h0HWWPxWxKNv+/xlqOCAZ8wggGbMB0GA1UdDgQWBBSp\nSsKULCcvtn2162BLpTejSWhCozAPBgNVHRMBAf8EBTADAQH/MGkGA1UdEQRiMGCG\nXmh0dHBzOi8vZ2l0aHViLmNvbS9Db2RlckhlbG0vY29kZXJoZWxtLXBsYXRmb3Jt\nLy5naXRodWIvd29ya2Zsb3dzL3JlbGVhc2UueW1sQHJlZnMvdGFncy92MS4yLjMw\nKwYKKwYBBAGDvzABCAQdDBtodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20wbgYK\nKwYBBAGDvzABCQRgDF5odHRwczovL2dpdGh1Yi5jb20vQ29kZXJIZWxtL2NvZGVy\naGVsbS1wbGF0Zm9ybS8uZ2l0aHViL3dvcmtmbG93cy9yZWxlYXNlLnltbEByZWZz\nL3RhZ3MvdjEuMi4zMD8GCisGAQQBg78wAQwEMQwvaHR0cHM6Ly9naXRodWIuY29t\nL0NvZGVySGVsbS9jb2RlcmhlbG0tcGxhdGZvcm0wIAYKKwYBBAGDvzABDgQSDBBy\nZWZzL3RhZ3MvdjEuMi4zMAoGCCqGSM49BAMCA0cAMEQCIAW5FTDfGpaApvfWKByX\nQHStfCRCmPiSNzpGk/6pHo9VAiBTkFKXLeJJPpyCenq3WN99tfRyBP+NfY8RZxNp\n+WJ/gQ==\n-----END CERTIFICATE-----\n" +} diff --git a/installer/test/installer.test.mjs b/installer/test/installer.test.mjs index 05d6ed968..dec68a164 100644 --- a/installer/test/installer.test.mjs +++ b/installer/test/installer.test.mjs @@ -12,7 +12,7 @@ import http from "node:http"; import { main } from "../lib/cli.mjs"; import * as cmd from "../lib/commands.mjs"; import { buildManifest, convertCode, EVENTS, formPage, newAppUrl, PERMISSIONS, runManifestFlow, secretKeysFromApp } from "../lib/github-app.mjs"; -import { parseSums, verifySignature, verifySums } from "../lib/release.mjs"; +import { parseSums, verifySums } from "../lib/release.mjs"; import { initialSecret, hasGithubApp } from "../lib/secrets.mjs"; import { checkPrereqs } from "../lib/prereqs.mjs"; import { redactArg, Runner } from "../lib/runner.mjs"; @@ -327,6 +327,16 @@ test("upgrade refuses to go backwards; rollback needs a recorded version", async assert.match(same.out, /Already on v1.4.0/); }); +test("rollback refuses a release the install never ran (no downgrade to an old signed release)", async () => { + const dir = tmpdir(); + const file = writeConfig(dir); + fs.mkdirSync(path.join(dir, ".coderhelm")); + fs.writeFileSync(path.join(dir, ".coderhelm", "state.json"), JSON.stringify({ version: "v1.4.0", previousVersion: "v1.3.0" })); + const deps = { runner: new FakeRunner(awsAnswers()), log: () => {}, interactive: false, ask: quietAsk(), resolveSource: fakeSource([]) }; + await assert.rejects(() => main(["rollback", "--config", file, "--to", "v1.0.0"], deps), /not a release this install ran before/); + await assert.rejects(() => main(["update", "--config", file, "--to", "v1.0.0", "--rollback"], deps), /not a release this install ran before|older than/); +}); + test("update --dry-run: health check, deploy with live progress, health check; no bootstrap", async () => { const dir = tmpdir(); const file = writeConfig(dir); @@ -401,24 +411,7 @@ test("update: a healthy release succeeds; an unhealthy install isn't touched", a assert.equal(JSON.parse(fs.readFileSync(path.join(sick.dir, "r.json"), "utf8")).status, "failed"); }); -test("signature: a bad signature refuses the release; --require-signature refuses an unverifiable one", async () => { - const dir = tmpdir(); - fs.writeFileSync(path.join(dir, "SHA256SUMS"), "x"); - fs.writeFileSync(path.join(dir, "SHA256SUMS.sigstore.json"), "{}"); - const paths = { dir }; - const bad = new FakeRunner({ "cosign version": "v2.4.1", "cosign verify-blob": { code: 1, stderr: "none of the expected identities matched" } }); - await assert.rejects(() => verifySignature(paths, bad, { log: () => {} }), /signature does not verify/); - const good = new FakeRunner({ "cosign version": "v2.4.1", "cosign verify-blob": "Verified OK" }); - assert.equal(await verifySignature(paths, good, { log: () => {} }), "cosign"); - const verify = good.commands.find((c) => c.args[0] === "verify-blob"); - assert.ok(verify.args.join(" ").includes("release.yml@refs/tags/v"), "only this repository's release workflow may sign"); - const none = new FakeRunner({ "cosign version": { code: 127 }, "gh --version": { code: 127 } }); - await assert.rejects(() => verifySignature(paths, none, { require: true, log: () => {} }), /--require-signature/); - assert.equal(await verifySignature(paths, none, { log: () => {} }), null); - const ghBad = new FakeRunner({ "cosign version": { code: 127 }, "gh --version": "gh 2", "gh attestation verify": { code: 1 } }); - fs.rmSync(path.join(dir, "SHA256SUMS.sigstore.json")); - await assert.rejects(() => verifySignature(paths, ghBad, { log: () => {} }), /no valid build attestation/); -}); +// Signature and download checks: test/release-security.test.mjs. test("auto-update on with a window: saved in the config and sent to the running updater", async () => { const { file } = stateDir("v1.0.0"); diff --git a/installer/test/release-security.test.mjs b/installer/test/release-security.test.mjs new file mode 100644 index 000000000..66d01f616 --- /dev/null +++ b/installer/test/release-security.test.mjs @@ -0,0 +1,263 @@ +// Release verification: nothing that merely looks like a CoderHelm release +// gets installed. Signers come from test/fixtures/signers.json (stand-in +// Fulcio certificates; make-signers.sh regenerates them); cosign and gh are +// stubbed, and each test checks the exact identity they are asked for. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import crypto from "node:crypto"; +import { fileURLToPath } from "node:url"; +import { + ASSETS, attestationArgs, checkDownloadUrl, cosignArgs, fetchRelease, latestVersion, signerIdentity, SIGNATURE, verifySignature, +} from "../lib/release.mjs"; +import { certificateClaims, checkBundleIdentity, encodeOid, readBundle } from "../lib/sigstore.mjs"; +import { checkRollbackTarget, ranVersions } from "../lib/commands.mjs"; +import { FakeRunner } from "./fake.mjs"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const SIGNERS = JSON.parse(fs.readFileSync(path.join(here, "fixtures", "signers.json"), "utf8")); +const TAG = "v1.2.3"; +const IDENTITY = "https://github.com/CoderHelm/coderhelm-platform/.github/workflows/release.yml@refs/tags/v1.2.3"; + +/** A cosign 2.x bundle around a signer's certificate (with or without its Rekor entry). */ +function bundle(signer, { rekor = true } = {}) { + return JSON.stringify({ + base64Signature: "c2ln", + cert: Buffer.from(SIGNERS[signer]).toString("base64"), + ...(rekor ? { rekorBundle: { SignedEntryTimestamp: "c2V0", Payload: { logIndex: 1, integratedTime: 1 } } } : {}), + }); +} + +/** A Sigstore v0.3 bundle (cosign 3, --new-bundle-format). */ +function newBundle(signer, { tlog = true } = {}) { + const der = new crypto.X509Certificate(SIGNERS[signer]).raw.toString("base64"); + return JSON.stringify({ + mediaType: "application/vnd.dev.sigstore.bundle.v0.3+json", + verificationMaterial: { certificate: { rawBytes: der }, tlogEntries: tlog ? [{ logIndex: "1", inclusionProof: { logIndex: "1" } }] : [] }, + }); +} + +function tmpdir() { + return fs.mkdtempSync(path.join(os.tmpdir(), "ch-rel-")); +} + +const sha = (b) => crypto.createHash("sha256").update(b).digest("hex"); + +/** A release on disk: assets, SHA256SUMS over them, and a bundle from `signer`. */ +function releaseDir(signer = "good", { withBundle = true } = {}) { + const dir = tmpdir(); + const lines = []; + for (const n of ASSETS) { + const body = Buffer.from(`contents of ${n}`); + fs.writeFileSync(path.join(dir, n), body); + lines.push(`${sha(body)} ${n}`); + } + fs.writeFileSync(path.join(dir, "SHA256SUMS"), lines.join("\n") + "\n"); + if (withBundle) fs.writeFileSync(path.join(dir, SIGNATURE), bundle(signer)); + return { dir }; +} + +const cosignOk = () => new FakeRunner({ "cosign version": "v2.4.1", "cosign verify-blob": "Verified OK" }); +const quiet = { tag: TAG, log: () => {} }; + +// ── the signer's identity ─────────────────────────────────────────────── + +test("the certificate reader finds the identity and Fulcio's extensions", () => { + assert.deepEqual([...encodeOid("1.3.6.1.4.1.57264.1.8")], [0x2b, 6, 1, 4, 1, 0x83, 0xbf, 0x30, 1, 8]); + const c = certificateClaims(readBundle(bundle("good")).der); + assert.deepEqual(c.identities, [IDENTITY]); + assert.equal(c.issuer, "https://token.actions.githubusercontent.com"); + assert.equal(c.repository, "https://github.com/CoderHelm/coderhelm-platform"); + assert.equal(c.ref, "refs/tags/v1.2.3"); + assert.equal(readBundle(newBundle("good")).tlog, true); +}); + +test("a real GitHub Actions bundle (cli/cli's build provenance, public Sigstore) reads the same way", () => { + // fixtures/real-github-actions-bundle.json: from `gh attestation download` on a GitHub CLI release. + const text = fs.readFileSync(path.join(here, "fixtures", "real-github-actions-bundle.json"), "utf8"); + const { tlog, der } = readBundle(text); + assert.equal(tlog, true); + const c = certificateClaims(der); + assert.deepEqual(c.identities, ["https://github.com/cli/cli/.github/workflows/deployment.yml@refs/heads/trunk"]); + assert.equal(c.issuer, "https://token.actions.githubusercontent.com"); + assert.equal(c.repository, "https://github.com/cli/cli"); + // A genuine Sigstore signature, just not CoderHelm's release workflow on a tag: refused. + assert.throws(() => checkBundleIdentity(text, { + identity: IDENTITY, issuer: "https://token.actions.githubusercontent.com", + repositoryUri: "https://github.com/CoderHelm/coderhelm-platform", ref: "refs/tags/v1.2.3", + }), /signed by https:\/\/github\.com\/cli\/cli.*built from https:\/\/github\.com\/cli\/cli.*refs\/heads\/trunk/); +}); + +test("the identity is exact: this repository's release.yml on the release's own tag", () => { + assert.equal(signerIdentity(TAG), IDENTITY); + assert.throws(() => signerIdentity("v1.2.3/../../x"), /not a CoderHelm release/); + assert.throws(() => signerIdentity("main"), /not a CoderHelm release/); + const args = cosignArgs(TAG, "b.json", "SHA256SUMS"); + assert.equal(args[args.indexOf("--certificate-identity") + 1], IDENTITY); + assert.equal(args[args.indexOf("--certificate-oidc-issuer") + 1], "https://token.actions.githubusercontent.com"); + assert.equal(args[args.indexOf("--certificate-github-workflow-repository") + 1], "CoderHelm/coderhelm-platform"); + assert.equal(args[args.indexOf("--certificate-github-workflow-ref") + 1], "refs/tags/v1.2.3"); + assert.ok(!args.some((a) => /regexp|insecure|ignore-tlog|offline/.test(a)), "no loose match and no skipped transparency log"); + const gh = attestationArgs(TAG, "f"); + for (const f of ["--repo", "--signer-workflow", "--source-ref", "--cert-oidc-issuer", "--deny-self-hosted-runners"]) assert.ok(gh.includes(f), f); + assert.equal(gh[gh.indexOf("--source-ref") + 1], "refs/tags/v1.2.3"); +}); + +for (const [signer, why] of [ + ["otherRepo", /evil\/coderhelm-platform/], + ["otherWorkflow", /ci\.yml/], + ["branch", /refs\/heads\/main/], + ["otherTag", /refs\/tags\/v1\.0\.0/], + ["otherIssuer", /accounts\.google\.com/], +]) { + test(`a valid-looking signature from the wrong signer is refused (${signer})`, async () => { + assert.throws(() => checkBundleIdentity(bundle(signer), { + identity: IDENTITY, issuer: "https://token.actions.githubusercontent.com", + repositoryUri: "https://github.com/CoderHelm/coderhelm-platform", ref: "refs/tags/v1.2.3", + }), why); + // Even when cosign (stubbed) would say yes, the release is refused first. + const runner = cosignOk(); + await assert.rejects(() => verifySignature(releaseDir(signer), runner, quiet), /not CoderHelm's release workflow for v1\.2\.3/); + assert.ok(!runner.commands.some((c) => c.args[0] === "verify-blob"), "cosign is never asked"); + }); +} + +test("a signature without a Rekor transparency log entry is refused", async () => { + const p = releaseDir(); + fs.writeFileSync(path.join(p.dir, SIGNATURE), bundle("good", { rekor: false })); + await assert.rejects(() => verifySignature(p, cosignOk(), quiet), /no transparency log/); + fs.writeFileSync(path.join(p.dir, SIGNATURE), newBundle("good", { tlog: false })); + await assert.rejects(() => verifySignature(p, cosignOk(), quiet), /no transparency log/); +}); + +test("a missing or broken bundle is refused", async () => { + await assert.rejects(() => verifySignature(releaseDir("good", { withBundle: false }), cosignOk(), quiet), /has no signature/); + const p = releaseDir(); + fs.writeFileSync(path.join(p.dir, SIGNATURE), "{}"); + await assert.rejects(() => verifySignature(p, cosignOk(), quiet), /no signing certificate/); + fs.writeFileSync(path.join(p.dir, SIGNATURE), "not json"); + await assert.rejects(() => verifySignature(p, cosignOk(), quiet), /not valid JSON/); +}); + +test("the right signer: cosign checks the signature with the exact identity", async () => { + const runner = cosignOk(); + assert.equal(await verifySignature(releaseDir(), runner, quiet), "cosign"); + const v = runner.commands.find((c) => c.args[0] === "verify-blob"); + assert.equal(v.args[v.args.indexOf("--certificate-identity") + 1], IDENTITY); +}); + +test("tampered SHA256SUMS: cosign says no, the release is refused", async () => { + const p = releaseDir(); + fs.appendFileSync(path.join(p.dir, "SHA256SUMS"), `${"0".repeat(64)} extra.zip\n`); + // cosign checks the signature over the file's bytes; the stub answers as cosign would. + const runner = new FakeRunner({ "cosign version": "v2.4.1", "cosign verify-blob": { code: 1, stderr: "invalid signature when validating ASN.1 encoded signature" } }); + await assert.rejects(() => verifySignature(p, runner, quiet), /signature does not verify/); +}); + +test("no cosign and no gh: refused (no unchecked install, with or without --require-signature)", async () => { + const none = new FakeRunner({ "cosign version": { code: 127 }, "gh --version": { code: 127 } }); + await assert.rejects(() => verifySignature(releaseDir(), none, quiet), /install cosign .* or the GitHub CLI/); + await assert.rejects(() => verifySignature(releaseDir(), none, { ...quiet, require: false }), /Nothing was installed/); +}); + +test("gh only: every asset needs an attestation from release.yml on the tag", async () => { + const ok = new FakeRunner({ "cosign version": { code: 127 }, "gh --version": "gh 2", "gh attestation verify": "ok" }); + assert.equal(await verifySignature(releaseDir(), ok, quiet), "attestation"); + const verified = ok.commands.filter((c) => c.args[0] === "attestation").map((c) => path.basename(c.args[2])); + assert.deepEqual(verified, ASSETS); + const bad = new FakeRunner({ "cosign version": { code: 127 }, "gh --version": "gh 2", "gh attestation verify": { code: 1 } }); + await assert.rejects(() => verifySignature(releaseDir(), bad, quiet), /no valid build attestation from .*release\.yml on v1\.2\.3/); + // gh doesn't make a bad bundle acceptable. + await assert.rejects(() => verifySignature(releaseDir("branch"), ok, quiet), /not CoderHelm's release workflow/); +}); + +// ── downloads ─────────────────────────────────────────────────────────── + +/** A fake GitHub: serves a release's files (optionally redirected elsewhere). */ +function fakeGithub(files, { redirectTo } = {}) { + const asked = []; + const fetchImpl = async (url) => { + asked.push(url); + const name = url.split("/").pop(); + if (!(name in files)) return { ok: false, status: 404 }; + return { ok: true, status: 200, url: redirectTo ? `${redirectTo}/${name}` : url, arrayBuffer: async () => Buffer.from(files[name]) }; + }; + return { fetchImpl, asked }; +} + +function releaseFiles(signer = "good") { + const p = releaseDir(signer); + return Object.fromEntries(["SHA256SUMS", SIGNATURE, ...ASSETS].map((n) => [n, fs.readFileSync(path.join(p.dir, n))])); +} + +test("downloads: only GitHub's release URLs for this repository, over HTTPS", () => { + assert.ok(checkDownloadUrl("https://github.com/CoderHelm/coderhelm-platform/releases/download/v1.2.3/SHA256SUMS")); + assert.ok(checkDownloadUrl("https://release-assets.githubusercontent.com/github-production-release-asset/1/abc?sig=x")); + for (const bad of [ + "http://github.com/CoderHelm/coderhelm-platform/releases/download/v1.2.3/SHA256SUMS", + "https://github.com/evil/coderhelm-platform/releases/download/v1.2.3/SHA256SUMS", + "https://evil.example.com/SHA256SUMS", + "https://github.com.evil.example/x", + "https://user:pw@github.com/CoderHelm/coderhelm-platform/releases/download/v1.2.3/x", + ]) assert.throws(() => checkDownloadUrl(bad), /Refusing a download/, bad); +}); + +test("fetchRelease: a file changed after signing is refused before anything is unpacked", async () => { + process.env.CODERHELM_HOME = tmpdir(); + const files = releaseFiles(); + files["worker.zip"] = Buffer.from("swapped after the release was signed"); + const runner = cosignOk(); + await assert.rejects(() => fetchRelease(TAG, { runner, fetchImpl: fakeGithub(files).fetchImpl, log: () => {} }), /worker\.zip does not match its checksum/); + assert.ok(!runner.commands.some((c) => c.cmd === "tar"), "nothing unpacked"); +}); + +test("fetchRelease: no bundle on the release means no install", async () => { + process.env.CODERHELM_HOME = tmpdir(); + const files = releaseFiles(); + delete files[SIGNATURE]; + await assert.rejects(() => fetchRelease(TAG, { runner: cosignOk(), fetchImpl: fakeGithub(files).fetchImpl, log: () => {} }), /Could not download SHA256SUMS\.sigstore\.json/); +}); + +test("fetchRelease: a redirect off GitHub is refused; a signed release is checked before it is unpacked", async () => { + process.env.CODERHELM_HOME = tmpdir(); + const evil = fakeGithub(releaseFiles(), { redirectTo: "https://mirror.example.com" }); + await assert.rejects(() => fetchRelease(TAG, { runner: cosignOk(), fetchImpl: evil.fetchImpl, log: () => {} }), /Refusing a download from https:\/\/mirror\.example\.com/); + + process.env.CODERHELM_HOME = tmpdir(); + const runner = cosignOk(); + const gh = fakeGithub(releaseFiles()); + await fetchRelease(TAG, { runner, fetchImpl: gh.fetchImpl, log: () => {} }); + assert.ok(gh.asked.every((u) => u.startsWith("https://github.com/CoderHelm/coderhelm-platform/releases/download/v1.2.3/"))); + const order = runner.commands.map((c) => (c.args[0] === "verify-blob" ? "verify" : c.cmd === "tar" ? "tar" : null)).filter(Boolean); + assert.deepEqual(order, ["verify", "tar", "tar"]); + // Run again from the cache: checked again. + await fetchRelease(TAG, { runner, fetchImpl: gh.fetchImpl, log: () => {} }); + assert.equal(runner.commands.filter((c) => c.args[0] === "verify-blob").length, 2); +}); + +test("fetchRelease: a tag that isn't a release tag is refused before any download", async () => { + const gh = fakeGithub({}); + await assert.rejects(() => fetchRelease("../../etc", { runner: cosignOk(), fetchImpl: gh.fetchImpl, log: () => {} }), /not a CoderHelm release/); + assert.equal(gh.asked.length, 0); +}); + +test("latest release: drafts, pre-releases and odd tags are refused", async () => { + const answer = (j) => async () => ({ ok: true, json: async () => j }); + assert.equal(await latestVersion(answer({ tag_name: "v1.2.3" })), "v1.2.3"); + await assert.rejects(() => latestVersion(answer({ tag_name: "v1.2.3", prerelease: true })), /pre-release/); + await assert.rejects(() => latestVersion(answer({ tag_name: "main; rm -rf /" })), /not a CoderHelm release/); +}); + +// ── no downgrade ──────────────────────────────────────────────────────── + +test("rollback: only to a release this install ran before", () => { + const state = { version: "v1.4.0", previousVersion: "v1.3.0", versions: ["v1.1.0", "v1.3.0"] }; + assert.deepEqual(ranVersions(state), ["v1.1.0", "v1.3.0", "v1.4.0"]); + assert.doesNotThrow(() => checkRollbackTarget(state, "v1.3.0")); + assert.doesNotThrow(() => checkRollbackTarget(state, "v1.1.0")); + assert.throws(() => checkRollbackTarget(state, "v1.2.0"), /not a release this install ran before/); + assert.throws(() => checkRollbackTarget(state, "v1.4.0"), /not a release this install ran before/); + assert.throws(() => checkRollbackTarget({ version: "v1.4.0" }, "v1.0.0"), /none recorded/); +}); diff --git a/lambda/tests/test_updater.py b/lambda/tests/test_updater.py index 140651435..122840038 100644 --- a/lambda/tests/test_updater.py +++ b/lambda/tests/test_updater.py @@ -179,6 +179,72 @@ def test_bad_settings_are_refused(self): self.assertIsNone(self.store.get("AUTO_UPDATE")) +class NoDowngrade(unittest.TestCase): + """Only forward, unless an admin rolls back to a version this install ran; a stale list can't hide a release.""" + + def setUp(self): + self.db = FakeDynamo() + self.store = u.Store(self.db, "t") + self.builds = [] + u.start_build = lambda env, version, actor, mode, hid, extra=None: self.builds.append((version, mode)) or "b" + u.notify = lambda subject, text, env=None: 1 + self.env = {"CODERHELM_VERSION": "v1.2.0", "APP_URL": "https://helm.example.org", "UPDATE_PROJECT_NAME": "p"} + self.fetch = lambda _r: [rel("v1.3.0")] + + def test_update_now_never_goes_back_or_sideways(self): + for v in ("v1.1.0", "v1.2.0", "v1.2.0-rc.1"): + with self.assertRaisesRegex(ValueError, "not newer"): + u.handle({"action": "update_now", "version": v}, self.env, self.store, SUNDAY_3AM, self.fetch) + self.assertEqual(self.builds, []) + u.handle({"action": "update_now", "version": "v1.3.0"}, self.env, self.store, SUNDAY_3AM, self.fetch) + self.assertEqual(self.builds, [("v1.3.0", "update")]) + + def test_rollback_only_to_a_version_this_install_ran(self): + # Never ran v1.0.0 (an older signed release): refused. + with self.assertRaisesRegex(ValueError, "not a version this install ran"): + u.handle({"action": "rollback", "version": "v1.0.0"}, self.env, self.store, SUNDAY_3AM, self.fetch) + # The running version is not a rollback target either. + with self.assertRaisesRegex(ValueError, "not a version this install ran"): + u.handle({"action": "rollback", "version": "v1.2.0"}, self.env, self.store, SUNDAY_3AM, self.fetch) + # Run v1.2.0, update to v1.3.0: now v1.2.0 is a version it ran. + e = u.handle({"action": "update_now", "version": "v1.3.0"}, self.env, self.store, SUNDAY_3AM, self.fetch) + u.handle({"action": "finished", "status": "succeeded", "history_id": e["id"]}, self.env, self.store, SUNDAY_3AM, self.fetch) + self.assertEqual(self.store.get("UPDATE_STATE")["ran_versions"], ["v1.2.0", "v1.3.0"]) + on13 = dict(self.env, CODERHELM_VERSION="v1.3.0") + r = u.handle({"action": "rollback", "version": "v1.2.0", "actor": "admin"}, on13, self.store, SUNDAY_3AM + timedelta(hours=1), self.fetch) + self.assertEqual((r["version"], r["mode"]), ("v1.2.0", "rollback")) + with self.assertRaisesRegex(ValueError, "not a version this install ran"): + u.handle({"action": "rollback", "version": "v1.1.0"}, on13, self.store, SUNDAY_3AM + timedelta(hours=1), self.fetch) + + def test_a_stale_release_list_is_not_believed(self): + u.handle({"action": "status"}, self.env, self.store, SUNDAY_3AM, lambda r: [rel("v1.3.0"), rel("v1.2.0")]) + # An hour later the "latest" list no longer has v1.3.0 (a stale mirror or cache). + later = SUNDAY_3AM + timedelta(hours=2) + s = u.handle({"action": "status"}, self.env, self.store, later, lambda r: [rel("v1.2.0"), rel("v1.1.0")]) + self.assertIsNone(s["latest"], "nothing older than the running version is offered") + self.assertTrue(s["releases"]["stale"]) + self.assertIn("v1.3.0", s["releases"]["reason"]) + # A fresh list with v1.3.0 (or newer) is believed again. + s = u.handle({"action": "status"}, self.env, self.store, later + timedelta(hours=2), lambda r: [rel("v1.4.0"), rel("v1.3.0")]) + self.assertEqual(s["latest"]["version"], "v1.4.0") + self.assertFalse(s["releases"]["stale"]) + + def test_an_old_list_is_reported_stale(self): + u.handle({"action": "status"}, self.env, self.store, SUNDAY_3AM, self.fetch) + def down(_r): + raise OSError("GitHub is down") + s = u.handle({"action": "status"}, self.env, self.store, SUNDAY_3AM + timedelta(days=4), down) + self.assertTrue(s["releases"]["stale"]) + + def test_releases_only_from_coderhelms_repository(self): + calls = [] + s = u.handle({"action": "status"}, dict(self.env, RELEASE_REPO="evil/coderhelm-platform"), self.store, SUNDAY_3AM, lambda r: calls.append(r) or [rel("v9.0.0")]) + self.assertEqual(calls, []) + self.assertIsNone(s["latest"]) + with self.assertRaises(ValueError): + u.fetch_releases("evil/coderhelm-platform") + + class FakeLambda: def __init__(self, conflicts=0): self.env = {"f-gateway": {"A": "1"}, "f-worker": {}} diff --git a/lambda/updater/handler.py b/lambda/updater/handler.py index 0c0c0a1ac..7e625d26b 100644 --- a/lambda/updater/handler.py +++ b/lambda/updater/handler.py @@ -10,7 +10,10 @@ release notes, settings, history. - settings saves auto-update settings (validated). - update_now starts the update build for a version (default: the latest). -- rollback starts the build for the version before the last update. + Only a version newer than the one running: going back is a + rollback. +- rollback starts the build for the version before the last update, or an + admin's pick, which must be a version this install ran before. - finished the update build reports its result; history and notices. - refresh_secrets the gateway stored new keys in the install's secret (the GitHub App, from the install guide): restart the services that @@ -27,6 +30,12 @@ The build itself (CodeBuild, infra/lib/updates-stack.ts) runs `coderhelm-selfhost update`: health check, checksum and signature check, deploy, health check, and a rollback when the new version is unhealthy. +The build checks the release itself (signature made by exactly this +repository's release.yml on the version's tag), so the release list read +here only decides what to offer, never what is trusted. It is still checked: +it must come from api.github.com for CoderHelm/coderhelm-platform, and a list +that no longer shows the newest version seen before is reported as stale in +status (a stale copy can't quietly hold an install back). State lives on the settings table under pk SYSTEM. The domain's states and checks are documented in docs/self-host/domains.md. @@ -48,6 +57,10 @@ CHANNELS = ("stable", "preview") MAJORS = ("ask", "auto") CACHE_SECONDS = 3600 +# A release list not refreshed for this long is shown as stale. +STALE_SECONDS = 3 * 24 * 3600 +RELEASE_REPO = "CoderHelm/coderhelm-platform" +RELEASES_URL = f"https://api.github.com/repos/{RELEASE_REPO}/releases?per_page=30" RUNNING_STALE = timedelta(hours=3) PK = "SYSTEM" @@ -260,20 +273,44 @@ def client(name, region=None): return _clients[key] +def check_repo(repo): + """Releases come only from CoderHelm's own repository.""" + if repo != RELEASE_REPO: + raise ValueError(f"releases come only from {RELEASE_REPO}, not {repo}") + return repo + + def fetch_releases(repo): + check_repo(repo) req = urllib.request.Request( - f"https://api.github.com/repos/{repo}/releases?per_page=30", + RELEASES_URL, headers={"accept": "application/vnd.github+json", "user-agent": "coderhelm-updater"}, ) with urllib.request.urlopen(req, timeout=10) as r: + # A redirect anywhere but GitHub's API over HTTPS is refused. + if not r.geturl().startswith("https://api.github.com/"): + raise ValueError(f"the release list came from {r.geturl()}") return json.loads(r.read()) +def newest(releases): + """The highest release version in a list (drafts and odd tags skipped), or None.""" + best = None + for r in releases or []: + tag = r.get("tag_name") or r.get("version") + if r.get("draft") or not parse_version(tag): + continue + if best is None or compare(tag, best) > 0: + best = tag + return best + + def releases_cached(store, repo, now_ts, fetch=fetch_releases): cached = store.get("RELEASES_CACHE", {}) if cached and now_ts - cached.get("fetched_at", 0) < CACHE_SECONDS: return cached.get("releases", []) try: + check_repo(repo) rel = [ {k: r.get(k) for k in ("tag_name", "prerelease", "draft", "body", "published_at", "html_url")} for r in fetch(repo) @@ -281,10 +318,45 @@ def releases_cached(store, repo, now_ts, fetch=fetch_releases): except Exception as e: # GitHub down: keep the old list logger.warning(f"Could not read releases: {e}") return cached.get("releases", []) - store.put("RELEASES_CACHE", {"fetched_at": now_ts, "releases": rel}) + # Freshness: a list without the newest version seen before is either a + # stale copy or a release that was withdrawn. Either way it can only hold + # back an update (nothing below the running version is ever applied), so + # the list is used as it is, and admins see why it looks older. + seen = cached.get("newest_seen") if cached else None + top = newest(rel) + doc = {"fetched_at": now_ts, "releases": rel, "newest_seen": top or seen} + if seen and (top is None or compare(top, seen) < 0): + logger.warning(f"Release list looks stale: newest is {top}, {seen} was seen before") + doc.update(newest_seen=seen, stale_reason=f"GitHub's release list no longer shows {seen} (withdrawn, or a stale copy)") + store.put("RELEASES_CACHE", doc) return rel +def releases_freshness(store, now_ts): + """Whether the release list is current: {fetched_at, stale, reason}.""" + cached = store.get("RELEASES_CACHE", {}) or {} + at = cached.get("fetched_at") + reason = cached.get("stale_reason") + if not reason and (not at or now_ts - at > STALE_SECONDS): + reason = "the release list has not been read from GitHub for over 3 days" + return {"fetched_at": at, "stale": bool(reason), "reason": reason} + + +def ran_versions(store, state, current): + """Every version this install has run: recorded ones, the history, the current one.""" + out = set(v for v in (state.get("ran_versions") or []) if parse_version(v)) + for h in store.history(50): + if h.get("mode") == "domain": + continue + if h.get("from_version") and parse_version(h["from_version"]): + out.add(h["from_version"]) + if h.get("status") == "succeeded" and parse_version(h.get("version")): + out.add(h["version"]) + if parse_version(current): + out.add(current) + return out + + def notify(subject, text, env=None): """Email every install admin, and post to the updates webhook if set.""" env = os.environ if env is None else env @@ -604,6 +676,8 @@ def begin(store, env, now, version, actor, mode, extra=None, note=None): if running(state, now): raise ValueError("an update is already running") current = env.get("CODERHELM_VERSION", "") + if parse_version(current): + state["ran_versions"] = sorted(set(state.get("ran_versions") or []) | {current}) hid = f"UPDATE#{now.strftime('%Y-%m-%dT%H:%M:%SZ')}#{uuid.uuid4().hex[:8]}" entry = {"version": version, "from_version": current, "actor": actor, "mode": mode, "status": "running", "started_at": now.isoformat(), "reason": ""} @@ -637,6 +711,7 @@ def handle(event, env, store, now, fetch=fetch_releases): }, "latest": latest, "update_available": latest is not None, + "releases": releases_freshness(store, now.timestamp()), "settings": settings, "running": running(state, now), # Releases whose last try failed or rolled back: the dashboard's @@ -659,6 +734,9 @@ def handle(event, env, store, now, fetch=fetch_releases): version = latest["version"] if not parse_version(version): raise ValueError("version must look like v1.2.3") + # Forward only: an older (or the same) release is a rollback. + if parse_version(current) and compare(version, current) <= 0: + raise ValueError(f"{version} is not newer than {current}; use Roll back to go to an earlier release") return begin(store, env, now, version, event.get("actor") or "unknown", "update") if action == "rollback": @@ -670,6 +748,11 @@ def handle(event, env, store, now, fetch=fetch_releases): target = done[0]["from_version"] if not parse_version(target): raise ValueError("version must look like v1.2.3") + # Only to a release this install ran: an old signed release with a + # since-fixed problem can't be pushed onto it. + ran = ran_versions(store, state, current) - {current} + if target not in ran: + raise ValueError(f"{target} is not a version this install ran before, so it can't be rolled back to") return begin(store, env, now, target, event.get("actor") or "unknown", "rollback") if action == "finished": @@ -691,6 +774,8 @@ def handle(event, env, store, now, fetch=fetch_releases): failed = set(state.get("failed_versions") or []) failed.add(version) state["failed_versions"] = sorted(failed) + if status == "succeeded" and parse_version(version): + state["ran_versions"] = sorted(set(state.get("ran_versions") or []) | {version}) store.put("UPDATE_STATE", state) words = {"succeeded": "is now on", "failed": "could not update to", "rolled_back": "rolled back after trying"}[status] notify( diff --git a/scripts/release-protection.sh b/scripts/release-protection.sh new file mode 100755 index 000000000..8c32f1c00 --- /dev/null +++ b/scripts/release-protection.sh @@ -0,0 +1,140 @@ +#!/usr/bin/env bash +# Repository and organization settings that make a CoderHelm release +# impossible to fake (docs/self-host/updates-security.md, "Who can publish"). +# The workflows assume them; the code can't turn them on by itself. +# +# Run once, as an organization owner, with the GitHub CLI signed in: +# +# bash scripts/release-protection.sh # apply +# bash scripts/release-protection.sh --check # only show what is set +# +# Safe to run again: each setting is put in place by name. +set -euo pipefail + +REPO="${REPO:-CoderHelm/coderhelm-platform}" +ORG="${REPO%%/*}" +# Who approves a release (GitHub logins, comma-separated). +REVIEWERS="${REVIEWERS:-nambok}" +# The checks main must pass (CI job names, .github/workflows/ci.yml). +CHECKS=("Workflow security" "Rust (workspace)" "Lambda (Python)" "MCP Proxy (Node)" "Jira app (Forge)" "Infra (config, synth)" "Self-host installer" "Launch Stack (template and installer)") + +api() { gh api -H "Accept: application/vnd.github+json" -H "X-GitHub-Api-Version: 2022-11-28" "$@"; } + +if [ "${1:-}" = "--check" ]; then + echo "Rulesets:"; api "repos/$REPO/rulesets" --jq '.[] | " \(.name): \(.target), \(.enforcement)"' + echo "Environments:"; api "repos/$REPO/environments" --jq '.environments[] | " \(.name): \([.protection_rules[].type] | join(", "))"' + echo "Immutable releases:"; api "repos/$REPO/immutable-releases" --jq '" enabled: \(.enabled)"' || true + echo "Actions:"; api "repos/$REPO/actions/permissions" --jq '" allowed: \(.allowed_actions), sha pinning required: \(.sha_pinning_required)"' + echo "Token default:"; api "repos/$REPO/actions/permissions/workflow" --jq '" \(.default_workflow_permissions)"' + echo "Org 2FA required:"; api "orgs/$ORG" --jq '" \(.two_factor_requirement_enabled)"' + exit 0 +fi + +# Creates or replaces a ruleset by name. +ruleset() { + local name="$1" body="$2" id + id=$(api "repos/$REPO/rulesets" --jq ".[] | select(.name == \"$name\") | .id") + if [ -n "$id" ]; then + api -X PUT "repos/$REPO/rulesets/$id" --input - <<<"$body" >/dev/null + else + api -X POST "repos/$REPO/rulesets" --input - <<<"$body" >/dev/null + fi + echo "ruleset: $name" +} + +# 1. Release tags (v*) are never moved or deleted, by anyone. No bypass: +# changing one means turning this ruleset off first, which the audit log shows. +ruleset "release tags: never moved or deleted" '{ + "name": "release tags: never moved or deleted", + "target": "tag", + "enforcement": "active", + "conditions": {"ref_name": {"include": ["refs/tags/v*"], "exclude": []}}, + "rules": [{"type": "update"}, {"type": "deletion"}, {"type": "non_fast_forward"}], + "bypass_actors": [] +}' + +# 2. Only repository and organization admins create release tags, and only +# signed ones. (The release workflow also checks the tag is signed and on main.) +ruleset "release tags: admins create, signed" '{ + "name": "release tags: admins create, signed", + "target": "tag", + "enforcement": "active", + "conditions": {"ref_name": {"include": ["refs/tags/v*"], "exclude": []}}, + "rules": [{"type": "creation"}, {"type": "required_signatures"}], + "bypass_actors": [ + {"actor_type": "OrganizationAdmin", "actor_id": 1, "bypass_mode": "always"}, + {"actor_type": "RepositoryRole", "actor_id": 5, "bypass_mode": "always"} + ] +}' + +# 3. main: changes only through a pull request with passing checks, signed +# commits, no force pushes or deletion. Admins may merge a PR without the +# approval (bypass_mode "pull_request"), never push to main directly. +checks_json=$(printf '%s\n' "${CHECKS[@]}" | jq -R '{context: .}' | jq -s .) +ruleset "main: pull requests, checks, signed" "$(jq -n --argjson checks "$checks_json" '{ + name: "main: pull requests, checks, signed", + target: "branch", + enforcement: "active", + conditions: {ref_name: {include: ["~DEFAULT_BRANCH"], exclude: []}}, + rules: [ + {type: "deletion"}, + {type: "non_fast_forward"}, + {type: "required_signatures"}, + {type: "pull_request", parameters: { + required_approving_review_count: 1, + dismiss_stale_reviews_on_push: true, + require_code_owner_review: false, + require_last_push_approval: true, + required_review_thread_resolution: false + }}, + {type: "required_status_checks", parameters: { + strict_required_status_checks_policy: false, + required_status_checks: $checks + }} + ], + bypass_actors: [ + {actor_type: "OrganizationAdmin", actor_id: 1, bypass_mode: "pull_request"}, + {actor_type: "RepositoryRole", actor_id: 5, bypass_mode: "pull_request"} + ] +}')" + +# 4. The "release" environment: a listed reviewer approves every publish, +# and only v* tags may deploy to it. The publisher role in AWS trusts only +# this environment (infra/lib/worker-stack.ts). +reviewers_json=$(for u in ${REVIEWERS//,/ }; do api "users/$u" --jq '{type: "User", id: .id}'; done | jq -s .) +api -X PUT "repos/$REPO/environments/release" --input - >/dev/null </dev/null +fi +echo "environment: release (reviewers: $REVIEWERS; v* tags only; admins can't skip it)" + +# 5. Published releases can't have their files replaced, or their tag moved. +api -X PUT "repos/$REPO/immutable-releases" >/dev/null && echo "immutable releases: on" + +# 6. Actions: every action must be pinned to a full SHA, the default token is +# read-only, and workflows from outside contributors' PRs wait for approval. +api -X PUT "repos/$REPO/actions/permissions" -F enabled=true -f allowed_actions=all -F sha_pinning_required=true >/dev/null +api -X PUT "repos/$REPO/actions/permissions/workflow" -f default_workflow_permissions=read -F can_approve_pull_request_reviews=false >/dev/null +api -X PUT "repos/$REPO/actions/permissions/fork-pr-contributor-approval" -f approval_policy=all_external_contributors >/dev/null +echo "actions: SHA pinning required, read-only default token, outside PRs need approval" + +# 7. Dependabot: alerts and security fixes (.github/dependabot.yml keeps the +# pinned actions current). +api -X PUT "repos/$REPO/vulnerability-alerts" >/dev/null +api -X PUT "repos/$REPO/automated-security-fixes" >/dev/null +echo "dependabot: alerts and security updates on" + +# 8. Two-factor authentication for everyone in the organization has no API: +# https://github.com/organizations/$ORG/settings/security +# then "Require two-factor authentication for everyone in the organization". +echo +echo "Left to do by hand: require 2FA at https://github.com/organizations/$ORG/settings/security" +echo "Then check: bash scripts/release-protection.sh --check" diff --git a/selfhost/install.sh b/selfhost/install.sh index f2d79c07d..0099d5cd3 100755 --- a/selfhost/install.sh +++ b/selfhost/install.sh @@ -4,12 +4,19 @@ # curl -fsSL https://github.com/CoderHelm/coderhelm-platform/releases/latest/download/install.sh | sh # # Checks for Node.js 20+ and the AWS CLI v2, downloads the installer for the -# latest release (or $CODERHELM_VERSION), verifies its checksum, and runs -# "coderhelm-selfhost init" then "deploy". Nothing is installed globally. +# latest release (or $CODERHELM_VERSION), checks it against the release's +# signed SHA256SUMS, and runs "coderhelm-selfhost init" then "deploy". +# Nothing is installed globally. +# +# The signature must be cosign's keyless signature made by exactly +# CoderHelm/coderhelm-platform's release.yml on the release's own tag +# (cosign), or the installer's GitHub build attestation from that workflow +# and tag (gh). Without cosign or gh, or on any mismatch, nothing runs. set -eu REPO="CoderHelm/coderhelm-platform" VERSION="${CODERHELM_VERSION:-latest}" +ISSUER="https://token.actions.githubusercontent.com" need() { command -v "$1" >/dev/null 2>&1 || { echo "Please install $2 first: $3" >&2; exit 1; }; } need node "Node.js 20 or newer" "https://nodejs.org/" @@ -20,20 +27,42 @@ need curl "curl" "your package manager" major=$(node -p 'process.versions.node.split(".")[0]') [ "$major" -ge 20 ] || { echo "Node.js 20 or newer is needed (found $(node --version))." >&2; exit 1; } +get() { curl --proto =https --proto-redir =https --tlsv1.2 -fsSL "$@"; } + +# The signature names one tag, so "latest" is turned into it first. if [ "$VERSION" = "latest" ]; then - base="https://github.com/$REPO/releases/latest/download" -else - base="https://github.com/$REPO/releases/download/$VERSION" + VERSION=$(get "https://api.github.com/repos/$REPO/releases/latest" | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{const r=JSON.parse(s);if(r.draft||r.prerelease)process.exit(1);process.stdout.write(String(r.tag_name))})') fi +echo "$VERSION" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$' || { echo "\"$VERSION\" is not a CoderHelm release (vX.Y.Z)." >&2; exit 1; } +base="https://github.com/$REPO/releases/download/$VERSION" +identity="https://github.com/$REPO/.github/workflows/release.yml@refs/tags/$VERSION" dir=$(mktemp -d) trap 'rm -rf "$dir"' EXIT -curl -fsSL -o "$dir/coderhelm-selfhost.tgz" "$base/coderhelm-selfhost.tgz" -curl -fsSL -o "$dir/SHA256SUMS" "$base/SHA256SUMS" +get -o "$dir/coderhelm-selfhost.tgz" "$base/coderhelm-selfhost.tgz" +get -o "$dir/SHA256SUMS" "$base/SHA256SUMS" +get -o "$dir/SHA256SUMS.sigstore.json" "$base/SHA256SUMS.sigstore.json" + +if command -v cosign >/dev/null 2>&1; then + cosign verify-blob --bundle "$dir/SHA256SUMS.sigstore.json" \ + --certificate-identity "$identity" --certificate-oidc-issuer "$ISSUER" \ + --certificate-github-workflow-repository "$REPO" --certificate-github-workflow-ref "refs/tags/$VERSION" \ + "$dir/SHA256SUMS" >/dev/null 2>&1 || { echo "The release's signature does not verify. Not running it." >&2; exit 1; } +elif command -v gh >/dev/null 2>&1; then + gh attestation verify "$dir/coderhelm-selfhost.tgz" --repo "$REPO" \ + --signer-workflow "$REPO/.github/workflows/release.yml" --source-ref "refs/tags/$VERSION" \ + --cert-oidc-issuer "$ISSUER" --deny-self-hosted-runners >/dev/null 2>&1 \ + || { echo "The installer has no valid build attestation from CoderHelm's release workflow. Not running it." >&2; exit 1; } +else + echo "Can't check the release's signature: install cosign (https://docs.sigstore.dev/cosign/system_config/installation/) or the GitHub CLI (gh), then run this again." >&2 + exit 1 +fi + want=$(grep ' coderhelm-selfhost.tgz$' "$dir/SHA256SUMS" | cut -d' ' -f1) if command -v sha256sum >/dev/null 2>&1; then got=$(sha256sum "$dir/coderhelm-selfhost.tgz" | cut -d' ' -f1) else got=$(shasum -a 256 "$dir/coderhelm-selfhost.tgz" | cut -d' ' -f1); fi [ -n "$want" ] && [ "$want" = "$got" ] || { echo "The installer's checksum does not match. Not running it." >&2; exit 1; } +echo "Verified CoderHelm $VERSION (signed by $REPO's release workflow)." run() { npx --yes --package "$dir/coderhelm-selfhost.tgz" coderhelm-selfhost "$@" < /dev/tty; } [ -f coderhelm.config.json ] || run init diff --git a/selfhost/launch/bootstrap.mjs b/selfhost/launch/bootstrap.mjs index 40d6e6c6d..5100d879d 100644 --- a/selfhost/launch/bootstrap.mjs +++ b/selfhost/launch/bootstrap.mjs @@ -49,6 +49,9 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; export const STATUS_SCHEMA = 1; + +/** A release tag (installer/lib/release.mjs TAG_RE). */ +export const RELEASE_TAG_RE = /^v\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/; export const STATUS_KEY = "status.json"; /** The phases the guide shows, in order. */ @@ -361,7 +364,7 @@ export function realDeps(env = process.env) { } }, async installCli(tgz) { - return sh("npm", ["install", "-g", "--no-audit", "--no-fund", tgz]); + return sh("npm", ["install", "-g", "--ignore-scripts", "--no-audit", "--no-fund", tgz]); }, async pull(stage) { return sh("coderhelm-selfhost", ["pull", "--stage", stage, "--region", region]); @@ -460,6 +463,10 @@ export async function run({ env = process.env, deps = realDeps(env), tgz = "code }; const fail = (message, fix, extra = {}) => status({ phase: "failed", message, fix, ...extra }); + // The buildspec resolved VERSION and checked this file and the installer + // against the release's signed SHA256SUMS; the installer checks the rest of + // the release the same way before deploying it. + if (!RELEASE_TAG_RE.test(String(version ?? ""))) return fail("The release to install is not a version such as v0.7.0.", "Launch again with a release version."); await status({ phase: "preparing", message: `Downloading CoderHelm ${version}` }); const inst = await deps.installCli(tgz); if (inst.code !== 0) return fail("The installer could not be set up.", "Open the log, then launch again."); diff --git a/selfhost/launch/bootstrap.test.mjs b/selfhost/launch/bootstrap.test.mjs index d25223f66..33c65ffe0 100644 --- a/selfhost/launch/bootstrap.test.mjs +++ b/selfhost/launch/bootstrap.test.mjs @@ -260,3 +260,13 @@ test("updates: off by default; on with a window and time zone from the stack", ( assert.throws(() => updatesFromEnv({ UPDATE_WINDOW: "whenever" }), /maintenance window/); assert.throws(() => updatesFromEnv({ UPDATE_TIMEZONE: "Mars" }), /time zone/); }); + +test("run: a VERSION that isn't a release tag stops before anything is installed", async () => { + for (const bad of ["latest", "v1.2.3;id", "../v1", ""]) { + let installed = false; + const { deps } = fakes({ installCli: async () => ((installed = true), { code: 0 }) }); + const doc = await run({ env: { ...ENV, VERSION: bad }, deps, log: () => {} }); + assert.equal(doc.phase, "failed", bad); + assert.equal(installed, false, bad); + } +});