diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..b64ac1c --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,3 @@ +# Everything in this repository is owned by the maintainer. Add paths above this line when someone +# else takes over an area (the last matching pattern wins). +* @jfcmartins diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..177ec5f --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,8 @@ +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + commit-message: + prefix: "chore(ci)" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..eb6fdd7 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,63 @@ +name: ci + +# Unit tests on the platforms the action supports, and actionlint on the workflows. + +on: + push: + branches: [main] + # A draft pull request runs nothing; marking it ready for review starts the run. + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + # A new push cancels the older pull request run; a push to main always runs to the end. + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + test: + name: Tests (${{ matrix.os }}) + if: github.event_name != 'pull_request' || !github.event.pull_request.draft + runs-on: ${{ matrix.os }} + timeout-minutes: 10 + strategy: + fail-fast: false + matrix: + os: [ubuntu-24.04, ubuntu-24.04-arm, macos-latest] + steps: + - name: Check out the commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install Node + uses: jdx/mise-action@82a612c5ab8bcda7cc5db6b7e81a8e7584c3dc6e # v5.2.3 + with: + install_args: node + + - name: Run the tests + run: npm test + + actionlint: + name: Workflow lint (actionlint) + if: github.event_name != 'pull_request' || !github.event.pull_request.draft + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: Check out the commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install actionlint + uses: jdx/mise-action@82a612c5ab8bcda7cc5db6b7e81a8e7584c3dc6e # v5.2.3 + with: + # actionlint runs shellcheck on `run:` scripts when it is installed. + install_args: actionlint shellcheck + + - name: Lint the workflows + run: actionlint diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml new file mode 100644 index 0000000..a33603d --- /dev/null +++ b/.github/workflows/smoke.yml @@ -0,0 +1,46 @@ +name: smoke + +# Runs the action itself against a published Limen release on real runners. Run it by hand before +# tagging a release of this action, and after a Limen release that changes the CLI's archive. +# It installs only: the bot login needs a Limen control plane that GitHub's runners can reach. + +on: + workflow_dispatch: + inputs: + version: + description: The Limen release to install, for example v0.1.0 + required: true + +permissions: + contents: read + +jobs: + install: + name: Install (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 10 + strategy: + fail-fast: false + matrix: + os: [ubuntu-24.04, ubuntu-24.04-arm, macos-latest, macos-15-intel] + steps: + - name: Check out the action + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install Limen + id: limen + uses: ./ + with: + version: ${{ inputs.version }} + + - name: The CLI runs and is the version asked for + env: + WANT: ${{ steps.limen.outputs.version }} + run: | + set -euo pipefail + got="$(limen --version)" + echo "$got" + [ "$got" = "limen ${WANT#v}" ] + test "$(command -v limen)" = "${{ steps.limen.outputs.path }}/limen" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4e23c4c --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +node_modules/ +.claude/worktrees/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..ce23059 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,17 @@ +# Instructions for coding agents + +`setup-limen`: a GitHub Action (Node 24, no dependencies, no build step) that installs the Limen CLI and logs a job in as a bot, a thin client of `limen login --bot` ([ADR-0019](https://github.com/limen-dev/limen/blob/main/docs/adr/0019-machine-identities.md)). + +## Rules +- **Work in a git worktree:** `git worktree add .claude/worktrees/ -b `. Never edit the main checkout or switch its branch. +- **No dependencies, no `dist/`.** What is in `src/` is what runs. +- **Fail closed.** A missing or wrong checksum, or a failed provenance check, stops the job. Never add a way to skip both. +- **The action never reads the OIDC token or a Limen credential.** Pass arguments as a list, never through a shell. +- **The CLI is Limen's.** Flags come from `limen login --help`; don't invent options. +- **Verify before claiming.** Anything checked only against the stub `limen` or the local release server is *unverified*. +- **Pin every action** in workflows to a full commit SHA with a version comment. +- **Commits:** conventional, small, signed; stage specific files. Don't push or tag unless asked. Pull requests as drafts. + +```sh +mise install && npm test && mise exec -- actionlint +``` diff --git a/README.md b/README.md new file mode 100644 index 0000000..b981a56 --- /dev/null +++ b/README.md @@ -0,0 +1,59 @@ +# setup-limen + +A GitHub Action that installs the [Limen](https://github.com/limen-dev/limen) CLI and, if you ask, logs the job in as a **bot** with its own OIDC token. No SSH key, database password or Limen token is stored in your secrets. The job gets a certificate that lasts 15 minutes by default (an hour at most), and every session is audited with the repository, workflow, run and commit. + +```yaml +permissions: + id-token: write # lets the job ask GitHub for its OIDC token + contents: read + +jobs: + deploy: + runs-on: ubuntu-24.04 + environment: staging + steps: + - uses: limen-dev/setup-limen@v0 + with: + version: v0.1.0 # pin one + proxy: limen.example.com:443 # leave out to only install + - run: limen ssh web-staging-1 -- ./deploy.sh +``` + +## You need + +- **A published Limen release.** The action downloads the CLI from [limen-dev/limen releases](https://github.com/limen-dev/limen/releases). +- **A bot in your policy** that matches the job exactly ([bots guide](https://github.com/limen-dev/limen/blob/main/docs/guides/bots.md)): `method: github_actions`, with `repository`, and `ref` or `environment`. +- **A proxy the runner can reach.** GitHub-hosted runners are on the public internet; for a private proxy use a self-hosted runner. +- **`id-token: write`** on the job, when you pass `proxy`. + +## Inputs and outputs + +| Input | Default | | +|---|---|---| +| `version` | `latest` | Release to install, such as `v0.1.0`. **Pin one**: `latest` is the newest stable release and changes under you. | +| `proxy` | | `host:port` of the Limen proxy. Set it to log in. | +| `bot-name` | | Which bot, if more than one could match. | +| `audience` | | Audience to ask GitHub for. Empty uses the one your control plane expects. | +| `ca-file` | | PEM file with the CA to trust, for a private CA. | +| `verify-attestation` | `true` | Also verify build provenance with `gh attestation verify`. | +| `github-token` | `github.token` | For the GitHub API only. Needs no permissions. | + +Outputs: `version`, `path` (the directory with `limen`, already on `PATH`) and `logged-in`. After a login, `LIMEN_HOME` and `LIMEN_PROXY` are set for later steps. + +## What it does + +- **Verifies, then trusts.** The archive must match the release's `SHA256SUMS` and, by default, its provenance must verify against Limen's `release.yml`. Any failure, or a missing `gh`, stops the job. Turn provenance off only on a runner without `gh`; you then rely on the checksum alone. +- **Exposes only `limen`** on `PATH`, not the server binaries in the same archive. +- **Cleans up.** Credentials live in a private directory under `RUNNER_TEMP`; the post step runs `limen logout` and deletes it, even after a failure. +- **Never sees the OIDC token.** The CLI asks the runner for it. +- **Runs what you read.** Plain Node 24, no dependencies, no `dist/`. `version` and `proxy` are validated. + +Pull request jobs (including forks) **never match a bot**: Limen refuses them, because that job runs code the author chose. Log in from a protected branch or an environment with required reviewers. To be safest, pin the action to a full commit SHA. + +## Status + +- **Verified:** install, checksum and provenance against the real v0.1.0-rc.1 release (served locally, as it is still a draft); unit tests with a stub `limen`. +- **Unverified:** the bot login against a real GitHub token and control plane. Run the [smoke workflow](.github/workflows/smoke.yml) and a real login before the first release. +- Linux and macOS, x64 and arm64. Limen has no Windows build. + +Develop with `mise install && npm test`. Licensed under [Apache-2.0](LICENSE). diff --git a/RELEASING.md b/RELEASING.md new file mode 100644 index 0000000..cebdfc9 --- /dev/null +++ b/RELEASING.md @@ -0,0 +1,10 @@ +# Releasing + +Tags are `vMAJOR.MINOR.PATCH`, plus a moving major tag (`v0`) for `uses:`. + +1. `main` is green and the README's **Status** is true. +2. Run the [smoke workflow](.github/workflows/smoke.yml) against the newest published Limen release. Don't tag if it fails. +3. `git tag -s v0.1.0 -m v0.1.0 && git push origin v0.1.0`, then create a GitHub release from it. Tick "Publish this Action to the GitHub Marketplace" (needs the owner's account). +4. Move the major tag: `git tag -fs v0 -m v0 v0.1.0 && git push -f origin v0`. Only the major tag moves; `vX.Y.Z` tags are protected. + +A change that can break a workflow needs a new major version. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..256250f --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,5 @@ +# Security + +Report vulnerabilities privately through [GitHub's private reporting](https://github.com/limen-dev/setup-limen/security/advisories/new), not in an issue. For Limen itself, report to [limen-dev/limen](https://github.com/limen-dev/limen/security). + +This action runs code it downloads, so it verifies the archive against the release's `SHA256SUMS` and its build provenance, and stops on any failure. It never sees the job's OIDC token, keeps credentials in a private directory that the post step deletes, validates its inputs, and has no runtime dependencies. diff --git a/action.yml b/action.yml new file mode 100644 index 0000000..6078bec --- /dev/null +++ b/action.yml @@ -0,0 +1,55 @@ +name: Set up Limen +description: Install the Limen CLI, verified against the release checksums and provenance, and optionally log the job in as a bot with its GitHub OIDC token. No stored secret. +author: limen-dev +branding: + icon: lock + color: gray-dark + +inputs: + version: + description: >- + The Limen release to install, for example v0.1.0. Pin one. "latest" means the newest + stable release (not a release candidate) and changes under you. + required: false + default: latest + proxy: + description: >- + The Limen proxy to log in to, as host:port, for example limen.example.com:443. Leave it + empty to only install the CLI. + required: false + default: "" + bot-name: + description: Which bot to log in as, if more than one bot rule could match this job's token. + required: false + default: "" + audience: + description: The audience to ask GitHub for. Leave it empty for the one the control plane expects. + required: false + default: "" + ca-file: + description: A PEM file with the CA to trust for the proxy, for a deployment that uses a private CA. + required: false + default: "" + verify-attestation: + description: >- + Check the release's build provenance with `gh attestation verify`, on top of the + checksum. Fails if the GitHub CLI is missing. Turn it off only on runners without gh. + required: false + default: "true" + github-token: + description: Token for the GitHub API (resolving "latest" and verifying provenance). It needs no permissions. + required: false + default: ${{ github.token }} + +outputs: + version: + description: The Limen release that was installed, for example v0.1.0. + path: + description: The directory that holds the limen binary (already on PATH). + logged-in: + description: '"true" if the job logged in as a bot.' + +runs: + using: node24 + main: src/main.mjs + post: src/post.mjs diff --git a/mise.toml b/mise.toml new file mode 100644 index 0000000..b99f952 --- /dev/null +++ b/mise.toml @@ -0,0 +1,5 @@ +# Everything this repository needs. `mise install` fetches all of it. +[tools] +node = "24.22.1" +actionlint = "1.7.12" +shellcheck = "0.11.0" diff --git a/package.json b/package.json new file mode 100644 index 0000000..1088b35 --- /dev/null +++ b/package.json @@ -0,0 +1,12 @@ +{ + "name": "setup-limen", + "version": "0.0.0", + "private": true, + "description": "GitHub Action: install the Limen CLI and log a workflow in as a bot", + "type": "module", + "license": "Apache-2.0", + "engines": { "node": ">=24" }, + "scripts": { + "test": "node --test \"test/*.test.mjs\"" + } +} diff --git a/src/lib/actions.mjs b/src/lib/actions.mjs new file mode 100644 index 0000000..ad4e3a4 --- /dev/null +++ b/src/lib/actions.mjs @@ -0,0 +1,34 @@ +// The few runner features this action uses, with no dependencies: log lines, workflow commands, +// and the GITHUB_ENV / GITHUB_PATH / GITHUB_OUTPUT / GITHUB_STATE files. Every function takes the +// environment, so tests can point it at temporary files. +import { randomUUID } from "node:crypto"; +import { appendFileSync } from "node:fs"; +import { EOL } from "node:os"; + +const escapeData = (s) => String(s).replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A"); + +export const info = (message) => process.stdout.write(`${message}${EOL}`); +export const warning = (message) => process.stdout.write(`::warning::${escapeData(message)}${EOL}`); +export const failure = (message) => process.stdout.write(`::error::${escapeData(message)}${EOL}`); + +// An input, as the runner passes it: INPUT_ with spaces turned into underscores. +export function input(env, name) { + return (env[`INPUT_${name.replace(/ /g, "_").toUpperCase()}`] ?? "").trim(); +} + +function fileCommand(env, variable, key, value) { + const path = env[variable]; + if (!path) return; // not running on a runner (unit tests, a local try-out) + const delimiter = `ghadelimiter_${randomUUID()}`; + appendFileSync(path, `${key}<<${delimiter}${EOL}${value}${EOL}${delimiter}${EOL}`); +} + +export const setEnv = (env, key, value) => fileCommand(env, "GITHUB_ENV", key, value); +export const setOutput = (env, key, value) => fileCommand(env, "GITHUB_OUTPUT", key, value); +export const saveState = (env, key, value) => fileCommand(env, "GITHUB_STATE", key, value); +export const state = (env, key) => env[`STATE_${key}`] ?? ""; + +export function addPath(env, directory) { + if (!env.GITHUB_PATH) return; + appendFileSync(env.GITHUB_PATH, `${directory}${EOL}`); +} diff --git a/src/lib/exec.mjs b/src/lib/exec.mjs new file mode 100644 index 0000000..d62bedf --- /dev/null +++ b/src/lib/exec.mjs @@ -0,0 +1,21 @@ +import { spawn } from "node:child_process"; + +// Run a program with an argument list (never a shell) and collect what it prints. +// `stream` copies the output to the job log as it arrives. +export function exec(command, args, { env, stream = false } = {}) { + return new Promise((resolve, reject) => { + const child = spawn(command, args, { env, stdio: ["ignore", "pipe", "pipe"] }); + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (chunk) => { + stdout += chunk; + if (stream) process.stdout.write(chunk); + }); + child.stderr.on("data", (chunk) => { + stderr += chunk; + if (stream) process.stderr.write(chunk); + }); + child.on("error", reject); + child.on("close", (code) => resolve({ code, stdout, stderr })); + }); +} diff --git a/src/lib/install.mjs b/src/lib/install.mjs new file mode 100644 index 0000000..575991e --- /dev/null +++ b/src/lib/install.mjs @@ -0,0 +1,152 @@ +// Find, download, verify, and unpack a Limen CLI release. Fails closed: a missing checksum, a +// checksum that doesn't match, or a failed provenance check stops the job before anything runs. +import { createHash } from "node:crypto"; +import { access, chmod, copyFile, mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { exec } from "./exec.mjs"; + +export const REPO = "limen-dev/limen"; +export const SIGNER_WORKFLOW = `${REPO}/.github/workflows/release.yml`; +const DOWNLOAD_BASE = `https://github.com/${REPO}/releases/download`; +const API_BASE = "https://api.github.com"; + +// The release builds these four. There is no Windows build. +const TARGETS = { + "linux/x64": "x86_64-unknown-linux-gnu", + "linux/arm64": "aarch64-unknown-linux-gnu", + "darwin/x64": "x86_64-apple-darwin", + "darwin/arm64": "aarch64-apple-darwin", +}; + +export function targetFor(platform, arch) { + const target = TARGETS[`${platform}/${arch}`]; + if (!target) { + throw new Error( + `Limen has no release for ${platform}/${arch}. It builds for Linux and macOS, on x64 and arm64.`, + ); + } + return target; +} + +// "latest", or a tag such as v0.1.0 or v0.2.0-rc.1. A leading "v" is optional. The text becomes +// part of a URL and a path, so anything else is refused. +export function parseVersion(text) { + const value = text.trim() || "latest"; + if (value === "latest") return "latest"; + const match = /^v?(\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?)$/.exec(value); + if (!match) { + throw new Error(`version "${value}" is not a release. Use latest or a tag such as v0.1.0.`); + } + return `v${match[1]}`; +} + +export async function resolveTag(version, { fetchFn = fetch, token = "", apiBase = API_BASE } = {}) { + if (version !== "latest") return version; + const headers = { Accept: "application/vnd.github+json", "User-Agent": "setup-limen" }; + if (token) headers.Authorization = `Bearer ${token}`; + const response = await fetchFn(`${apiBase}/repos/${REPO}/releases/latest`, { + headers, + signal: AbortSignal.timeout(30_000), + }); + if (!response.ok) { + throw new Error( + `could not find the latest Limen release (HTTP ${response.status}). ` + + "There may be no stable release yet; pin one, for example version: v0.1.0-rc.1.", + ); + } + const { tag_name: tag } = await response.json(); + return parseVersion(String(tag)); +} + +// SHA256SUMS is `sha256sum` output: " " per line (a "*" before the name marks binary mode). +export function parseChecksums(text) { + const sums = new Map(); + for (const line of text.split(/\r?\n/)) { + const match = /^([0-9a-fA-F]{64}) [ *](.+)$/.exec(line); + if (match) sums.set(match[2], match[1].toLowerCase()); + } + return sums; +} + +const sha256 = async (path) => createHash("sha256").update(await readFile(path)).digest("hex"); + +async function download(fetchFn, url, path) { + const response = await fetchFn(url, { signal: AbortSignal.timeout(120_000) }); + if (!response.ok) throw new Error(`could not download ${url} (HTTP ${response.status})`); + await writeFile(path, Buffer.from(await response.arrayBuffer())); +} + +const exists = (path) => access(path).then(() => true, () => false); + +// Returns { dir, bin, cached }. `dir` holds only the `limen` binary, so putting it on PATH does +// not also expose the server binaries that ship in the same archive. +export async function install({ + tag, + target, + cacheRoot, + tempRoot, + fetchFn = fetch, + downloadBase = DOWNLOAD_BASE, + attestation = { verify: true, token: "", ghBin: "gh" }, +}) { + const dir = join(cacheRoot, "limen", tag, target); + const bin = join(dir, "limen"); + if (await exists(bin)) return { dir, bin, cached: true }; + + const name = `limen-${tag}-${target}`; + const archive = `${name}.tar.gz`; + const work = await mkdtemp(join(tempRoot, "setup-limen-")); + try { + await download(fetchFn, `${downloadBase}/${tag}/SHA256SUMS`, join(work, "SHA256SUMS")); + const expected = parseChecksums(await readFile(join(work, "SHA256SUMS"), "utf8")).get(archive); + if (!expected) throw new Error(`${archive} is not listed in the release's SHA256SUMS`); + + await download(fetchFn, `${downloadBase}/${tag}/${archive}`, join(work, archive)); + const actual = await sha256(join(work, archive)); + if (actual !== expected) { + throw new Error(`${archive} does not match SHA256SUMS (expected ${expected}, got ${actual})`); + } + + if (attestation.verify) await verifyProvenance(join(work, archive), attestation); + + const tar = await exec("tar", ["-xzf", join(work, archive), "-C", work]); + if (tar.code !== 0) throw new Error(`could not unpack ${archive}: ${tar.stderr.trim()}`); + const unpacked = join(work, name, "limen"); + if (!(await exists(unpacked))) throw new Error(`${archive} has no ${name}/limen`); + + // Land in the cache whole or not at all: a half-copied binary must never look installed. + await mkdir(dir, { recursive: true }); + const partial = join(dir, `limen.partial-${process.pid}`); + await copyFile(unpacked, partial); + await chmod(partial, 0o755); + await rename(partial, bin); + return { dir, bin, cached: false }; + } finally { + await rm(work, { recursive: true, force: true }); + } +} + +async function verifyProvenance(file, { token, ghBin }) { + let result; + try { + result = await exec( + ghBin, + ["attestation", "verify", file, "--repo", REPO, "--signer-workflow", SIGNER_WORKFLOW], + { env: { ...process.env, GH_TOKEN: token } }, + ); + } catch (error) { + if (error.code === "ENOENT") { + throw new Error( + "verify-attestation is on but the GitHub CLI (gh) is not installed on this runner. " + + "Install gh, or set verify-attestation: false to rely on the checksum alone.", + ); + } + throw error; + } + if (result.code !== 0) { + throw new Error( + `the build provenance of ${file.split("/").pop()} did not verify:\n${(result.stderr || result.stdout).trim()}`, + ); + } +} diff --git a/src/lib/login.mjs b/src/lib/login.mjs new file mode 100644 index 0000000..dca6c75 --- /dev/null +++ b/src/lib/login.mjs @@ -0,0 +1,19 @@ +// The bot login: `limen login --bot github_actions`. The CLI asks the runner for the job's OIDC +// token itself (it needs `permissions: id-token: write`), so no token passes through this action. + +// host:port, or [v6]:port. It becomes an argument after `--proxy`, so it may not start with "-". +const PROXY = /^(?:[A-Za-z0-9][A-Za-z0-9.-]*|\[[0-9A-Fa-f:.]+\]):\d{1,5}$/; +const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; + +export function loginArgs({ proxy, botName = "", audience = "", caFile = "" }) { + if (!PROXY.test(proxy)) { + throw new Error(`proxy "${proxy}" is not host:port, for example limen.example.com:443`); + } + if (botName && !NAME.test(botName)) throw new Error(`bot-name "${botName}" is not a bot name`); + if (audience && !/^\S+$/.test(audience)) throw new Error("audience may not contain spaces"); + const args = ["--proxy", proxy, "login", "--bot", "github_actions"]; + if (botName) args.push("--bot-name", botName); + if (audience) args.push("--audience", audience); + if (caFile) args.push("--ca-file", caFile); + return args; +} diff --git a/src/lib/run.mjs b/src/lib/run.mjs new file mode 100644 index 0000000..4891450 --- /dev/null +++ b/src/lib/run.mjs @@ -0,0 +1,85 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import os from "node:os"; +import { join } from "node:path"; + +import { addPath, info, input, saveState, setEnv, setOutput, state, warning } from "./actions.mjs"; +import { exec } from "./exec.mjs"; +import { install, parseVersion, resolveTag, targetFor } from "./install.mjs"; +import { loginArgs } from "./login.mjs"; + +// `deps` lets tests point the download at a local server and the platform at a known value. +export async function main(env, deps = {}) { + const platform = deps.platform ?? os.platform(); + const arch = deps.arch ?? os.arch(); + const token = input(env, "github-token"); + const tempRoot = env.RUNNER_TEMP || os.tmpdir(); + const cacheRoot = env.RUNNER_TOOL_CACHE || join(tempRoot, "tool-cache"); + + const proxy = input(env, "proxy"); + // Check what the login will need before downloading anything. + const args = proxy + ? loginArgs({ + proxy, + botName: input(env, "bot-name"), + audience: input(env, "audience"), + caFile: input(env, "ca-file"), + }) + : null; + if (args && !env.ACTIONS_ID_TOKEN_REQUEST_URL) { + throw new Error( + "the job cannot ask GitHub for an OIDC token. Add `permissions: id-token: write` to the job " + + "(and `contents: read` if it checks out code).", + ); + } + + const target = targetFor(platform, arch); + const tag = await resolveTag(parseVersion(input(env, "version")), { + fetchFn: deps.fetchFn, + token, + apiBase: deps.apiBase, + }); + const verify = input(env, "verify-attestation").toLowerCase() !== "false"; + + const installed = await install({ + tag, + target, + cacheRoot, + tempRoot, + fetchFn: deps.fetchFn, + downloadBase: deps.downloadBase, + attestation: { verify, token, ghBin: deps.ghBin ?? "gh" }, + }); + info(`Limen ${tag} ${installed.cached ? "from the tool cache" : "installed"}: ${installed.bin}`); + addPath(env, installed.dir); + setOutput(env, "version", tag); + setOutput(env, "path", installed.dir); + setOutput(env, "logged-in", "false"); + if (!args) return; + + // Credentials go in a private directory that the post step deletes, not the runner's home. + const home = await mkdtemp(join(tempRoot, "limen-home-")); + saveState(env, "bin", installed.bin); + saveState(env, "home", home); + const loginEnv = { ...env, LIMEN_HOME: home }; + const result = await exec(installed.bin, args, { env: loginEnv, stream: true }); + if (result.code !== 0) throw new Error(`limen login failed (exit ${result.code}); see the output above.`); + + setEnv(env, "LIMEN_HOME", home); + setEnv(env, "LIMEN_PROXY", proxy); + setOutput(env, "logged-in", "true"); + info("Logged in. The credentials are short-lived and are deleted when the job ends."); +} + +// The post step: log out, then delete the credentials directory, even if the job failed. +export async function post(env) { + const home = state(env, "home"); + if (!home) return; + const bin = state(env, "bin"); + try { + const result = await exec(bin, ["logout"], { env: { ...env, LIMEN_HOME: home } }); + if (result.code !== 0) warning(`limen logout exited ${result.code}; deleting the credentials anyway`); + } catch (error) { + warning(`limen logout failed (${error.message}); deleting the credentials anyway`); + } + await rm(home, { recursive: true, force: true }); +} diff --git a/src/main.mjs b/src/main.mjs new file mode 100644 index 0000000..939ac93 --- /dev/null +++ b/src/main.mjs @@ -0,0 +1,9 @@ +import { failure } from "./lib/actions.mjs"; +import { main } from "./lib/run.mjs"; + +try { + await main(process.env); +} catch (error) { + failure(error.message); + process.exitCode = 1; +} diff --git a/src/post.mjs b/src/post.mjs new file mode 100644 index 0000000..c0a9188 --- /dev/null +++ b/src/post.mjs @@ -0,0 +1,9 @@ +import { warning } from "./lib/actions.mjs"; +import { post } from "./lib/run.mjs"; + +try { + await post(process.env); +} catch (error) { + // Cleanup must not turn a finished job red. + warning(`cleanup failed: ${error.message}`); +} diff --git a/test/helpers.mjs b/test/helpers.mjs new file mode 100644 index 0000000..76be4f1 --- /dev/null +++ b/test/helpers.mjs @@ -0,0 +1,70 @@ +// A fake release server: serves SHA256SUMS and an archive holding a stub `limen` shell script. +import { createHash } from "node:crypto"; +import { chmod, mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; +import http from "node:http"; +import os from "node:os"; +import { join } from "node:path"; + +import { exec } from "../src/lib/exec.mjs"; +import { targetFor } from "../src/lib/install.mjs"; + +export const TAG = "v0.1.0"; +export const platform = os.platform(); +export const arch = os.arch(); +export const target = targetFor(platform, arch); + +export const tempDir = (label) => mkdtemp(join(os.tmpdir(), `setup-limen-test-${label}-`)); + +// The stub records "|" per call in $STUB_LOG; STUB_FAIL=1 makes `login` fail. +const STUB = `#!/bin/sh +echo "$LIMEN_HOME|$*" >> "$STUB_LOG" +case "$1" in + --version) echo "limen 0.1.0 (stub)" ;; + --proxy) [ "$STUB_FAIL" = 1 ] && { echo "refused" >&2; exit 3; }; echo "ok" ;; +esac +exit 0 +`; + +export async function buildRelease({ tag = TAG, listed = true, tamper = false } = {}) { + const dir = await tempDir("release"); + const name = `limen-${tag}-${target}`; + await mkdir(join(dir, name), { recursive: true }); + await writeFile(join(dir, name, "limen"), STUB); + await chmod(join(dir, name, "limen"), 0o755); + await writeFile(join(dir, name, "limen-control-plane"), "#!/bin/sh\nexit 0\n"); + const archive = join(dir, `${name}.tar.gz`); + const tar = await exec("tar", ["-C", dir, "-czf", archive, name]); + if (tar.code !== 0) throw new Error(tar.stderr); + const bytes = await readFile(archive); + const hash = createHash("sha256").update(bytes).digest("hex"); + const sums = `${listed ? `${hash} ${name}.tar.gz\n` : ""}${"0".repeat(64)} other.json\n`; + // `tamper` serves different bytes than the ones the checksum was taken from. + const served = tamper ? Buffer.concat([bytes, Buffer.from("x")]) : bytes; + return { tag, name, sums, served }; +} + +export async function serve(release) { + const requests = []; + const server = http.createServer((req, res) => { + requests.push(req.url); + if (req.url === `/${release.tag}/SHA256SUMS`) return res.end(release.sums); + if (req.url === `/${release.tag}/${release.name}.tar.gz`) return res.end(release.served); + res.statusCode = 404; + res.end("not found"); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address(); + return { + base: `http://127.0.0.1:${port}`, + requests, + close: () => new Promise((resolve) => server.close(resolve)), + }; +} + +export async function fakeGh(exitCode) { + const dir = await tempDir("gh"); + const path = join(dir, "gh"); + await writeFile(path, `#!/bin/sh\necho "attestation said no" >&2\nexit ${exitCode}\n`); + await chmod(path, 0o755); + return path; +} diff --git a/test/lib.test.mjs b/test/lib.test.mjs new file mode 100644 index 0000000..59f80b6 --- /dev/null +++ b/test/lib.test.mjs @@ -0,0 +1,68 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { input } from "../src/lib/actions.mjs"; +import { parseChecksums, parseVersion, targetFor } from "../src/lib/install.mjs"; +import { loginArgs } from "../src/lib/login.mjs"; + +test("targetFor maps the platforms the release builds", () => { + assert.equal(targetFor("linux", "x64"), "x86_64-unknown-linux-gnu"); + assert.equal(targetFor("linux", "arm64"), "aarch64-unknown-linux-gnu"); + assert.equal(targetFor("darwin", "x64"), "x86_64-apple-darwin"); + assert.equal(targetFor("darwin", "arm64"), "aarch64-apple-darwin"); +}); + +test("targetFor refuses Windows and other architectures", () => { + assert.throws(() => targetFor("win32", "x64"), /no release for win32\/x64/); + assert.throws(() => targetFor("linux", "ia32"), /no release/); +}); + +test("parseVersion takes latest or a tag, with or without the v", () => { + assert.equal(parseVersion(""), "latest"); + assert.equal(parseVersion(" latest "), "latest"); + assert.equal(parseVersion("0.1.0"), "v0.1.0"); + assert.equal(parseVersion("v0.1.0"), "v0.1.0"); + assert.equal(parseVersion("v0.1.0-rc.1"), "v0.1.0-rc.1"); +}); + +test("parseVersion refuses anything that could change a URL or a path", () => { + for (const bad of ["v1", "v1.2", "../v1.2.3", "v1.2.3/../x", "v1.2.3 && id", "v1.2.3?x=1", "main", "v1.2.3-"]) { + assert.throws(() => parseVersion(bad), /is not a release/, bad); + } +}); + +test("parseChecksums reads sha256sum output, text and binary mode", () => { + const a = "a".repeat(64); + const b = "B".repeat(64); + const sums = parseChecksums(`${a} one.tar.gz\n${b} *two.tar.gz\nnot a line\n`); + assert.equal(sums.get("one.tar.gz"), a); + assert.equal(sums.get("two.tar.gz"), "b".repeat(64)); + assert.equal(sums.size, 2); +}); + +test("loginArgs builds the bot login", () => { + assert.deepEqual(loginArgs({ proxy: "limen.example.com:443" }), [ + "--proxy", "limen.example.com:443", "login", "--bot", "github_actions", + ]); + assert.deepEqual( + loginArgs({ proxy: "[::1]:3443", botName: "deploy-staging", audience: "limen", caFile: "ca.pem" }), + ["--proxy", "[::1]:3443", "login", "--bot", "github_actions", "--bot-name", "deploy-staging", + "--audience", "limen", "--ca-file", "ca.pem"], + ); +}); + +test("loginArgs refuses a proxy or name that could be read as a flag", () => { + for (const proxy of ["", "limen.example.com", "--help:1", "-x:443", "host:port", "a b:443", "https://h:443"]) { + assert.throws(() => loginArgs({ proxy }), /not host:port/, proxy); + } + assert.throws(() => loginArgs({ proxy: "h:1", botName: "--x" }), /not a bot name/); + assert.throws(() => loginArgs({ proxy: "h:1", audience: "a b" }), /spaces/); +}); + +test("input reads the runner's INPUT_ variables", () => { + const env = { INPUT_PROXY: " h:1 ", "INPUT_BOT-NAME": "x", INPUT_VERIFY_ATTESTATION: "false" }; + assert.equal(input(env, "proxy"), "h:1"); + assert.equal(input(env, "bot-name"), "x"); + assert.equal(input(env, "verify attestation"), "false"); + assert.equal(input(env, "missing"), ""); +}); diff --git a/test/run.test.mjs b/test/run.test.mjs new file mode 100644 index 0000000..e76b857 --- /dev/null +++ b/test/run.test.mjs @@ -0,0 +1,187 @@ +import assert from "node:assert/strict"; +import { access, readFile } from "node:fs/promises"; +import { join } from "node:path"; +import { test } from "node:test"; + +import { install } from "../src/lib/install.mjs"; +import { main, post } from "../src/lib/run.mjs"; +import { TAG, arch, buildRelease, fakeGh, platform, serve, target, tempDir } from "./helpers.mjs"; + +const NO_ATTESTATION = { verify: false, token: "", ghBin: "gh" }; + +async function setup(releaseOptions) { + const release = await buildRelease(releaseOptions); + const server = await serve(release); + const dir = await tempDir("work"); + return { release, server, cacheRoot: join(dir, "cache"), tempRoot: dir, dir }; +} + +test("install verifies the checksum, keeps only the limen binary, and caches", async () => { + const { server, cacheRoot, tempRoot } = await setup(); + try { + const args = { tag: TAG, target, cacheRoot, tempRoot, downloadBase: server.base, attestation: NO_ATTESTATION }; + const first = await install(args); + assert.equal(first.cached, false); + await access(first.bin); + await assert.rejects(access(join(first.dir, "limen-control-plane")), "server binaries must not be exposed"); + const requests = server.requests.length; + const second = await install(args); + assert.equal(second.cached, true); + assert.equal(server.requests.length, requests, "a cached install downloads nothing"); + } finally { + await server.close(); + } +}); + +test("install refuses an archive that does not match SHA256SUMS", async () => { + const { server, cacheRoot, tempRoot } = await setup({ tamper: true }); + try { + await assert.rejects( + install({ tag: TAG, target, cacheRoot, tempRoot, downloadBase: server.base, attestation: NO_ATTESTATION }), + /does not match SHA256SUMS/, + ); + await assert.rejects(access(join(cacheRoot, "limen", TAG, target, "limen")), "nothing is installed"); + } finally { + await server.close(); + } +}); + +test("install refuses an archive that SHA256SUMS does not list", async () => { + const { server, cacheRoot, tempRoot } = await setup({ listed: false }); + try { + await assert.rejects( + install({ tag: TAG, target, cacheRoot, tempRoot, downloadBase: server.base, attestation: NO_ATTESTATION }), + /not listed in the release's SHA256SUMS/, + ); + } finally { + await server.close(); + } +}); + +test("install fails clearly on a release that does not exist", async () => { + const { server, cacheRoot, tempRoot } = await setup(); + try { + await assert.rejects( + install({ tag: "v9.9.9", target, cacheRoot, tempRoot, downloadBase: server.base, attestation: NO_ATTESTATION }), + /HTTP 404/, + ); + } finally { + await server.close(); + } +}); + +test("provenance: fails closed without gh, on a failed check, and passes on success", async () => { + const { server, cacheRoot, tempRoot, dir } = await setup(); + try { + const base = { tag: TAG, target, tempRoot, downloadBase: server.base }; + const verify = (ghBin, root) => install({ ...base, cacheRoot: root, attestation: { verify: true, token: "t", ghBin } }); + await assert.rejects(verify(join(dir, "no-such-gh"), cacheRoot), /GitHub CLI \(gh\) is not installed/); + await assert.rejects(verify(await fakeGh(1), cacheRoot), /build provenance .* did not verify[\s\S]*attestation said no/); + await assert.rejects(access(join(cacheRoot, "limen", TAG, target, "limen")), "nothing is installed after a failure"); + const ok = await verify(await fakeGh(0), cacheRoot); + assert.equal(ok.cached, false); + } finally { + await server.close(); + } +}); + +function jobEnv(dir, extra = {}) { + return { + ...process.env, + RUNNER_TEMP: dir, + RUNNER_TOOL_CACHE: join(dir, "cache"), + GITHUB_ENV: join(dir, "github_env"), + GITHUB_PATH: join(dir, "github_path"), + GITHUB_OUTPUT: join(dir, "github_output"), + GITHUB_STATE: join(dir, "github_state"), + STUB_LOG: join(dir, "stub.log"), + INPUT_VERSION: TAG, + "INPUT_VERIFY-ATTESTATION": "false", + ...extra, + }; +} + +const read = (path) => readFile(path, "utf8").catch(() => ""); + +test("main with no proxy installs and does not log in", async () => { + const { server, dir } = await setup(); + try { + const env = jobEnv(dir); + await main(env, { platform, arch, downloadBase: server.base }); + assert.match(await read(env.GITHUB_PATH), /limen\/v0\.1\.0\//); + assert.match(await read(env.GITHUB_OUTPUT), /logged-in<<[^\n]+\nfalse\n/); + assert.equal(await read(env.STUB_LOG), "", "the binary was not run"); + assert.equal(await read(env.GITHUB_STATE), ""); + } finally { + await server.close(); + } +}); + +test("main logs in as a bot with a private LIMEN_HOME, and post removes it", async () => { + const { server, dir } = await setup(); + try { + const env = jobEnv(dir, { + INPUT_PROXY: "limen.example.com:443", + "INPUT_BOT-NAME": "deploy-staging", + "INPUT_CA-FILE": "/tmp/ca.pem", + ACTIONS_ID_TOKEN_REQUEST_URL: "https://token.invalid/", + }); + await main(env, { platform, arch, downloadBase: server.base }); + + const [login] = (await read(env.STUB_LOG)).trim().split("\n"); + const [home, args] = login.split("|"); + assert.equal( + args, + "--proxy limen.example.com:443 login --bot github_actions --bot-name deploy-staging --ca-file /tmp/ca.pem", + ); + assert.match(home, /limen-home-/); + await access(home); + assert.ok((await read(env.GITHUB_ENV)).includes(home), "later steps get the same LIMEN_HOME"); + assert.match(await read(env.GITHUB_ENV), /LIMEN_PROXY<<[^\n]+\nlimen\.example\.com:443\n/); + assert.match(await read(env.GITHUB_OUTPUT), /logged-in<<[^\n]+\ntrue\n/); + + // The post step gets the state the main step saved. + const saved = await read(env.GITHUB_STATE); + const stateEnv = { ...env }; + for (const key of ["bin", "home"]) { + stateEnv[`STATE_${key}`] = new RegExp(`${key}<<[^\\n]+\\n([^\\n]+)\\n`).exec(saved)[1]; + } + await post(stateEnv); + await assert.rejects(access(home), "the credentials directory is gone"); + assert.match((await read(env.STUB_LOG)).trim().split("\n").pop(), /\|logout$/); + } finally { + await server.close(); + } +}); + +test("main reports a refused login and still leaves state for cleanup", async () => { + const { server, dir } = await setup(); + try { + const env = jobEnv(dir, { + INPUT_PROXY: "limen.example.com:443", + ACTIONS_ID_TOKEN_REQUEST_URL: "https://token.invalid/", + STUB_FAIL: "1", + }); + await assert.rejects(main(env, { platform, arch, downloadBase: server.base }), /limen login failed \(exit 3\)/); + assert.match(await read(env.GITHUB_STATE), /home< { + const { server, dir } = await setup(); + try { + const env = jobEnv(dir, { INPUT_PROXY: "limen.example.com:443" }); + delete env.ACTIONS_ID_TOKEN_REQUEST_URL; + await assert.rejects(main(env, { platform, arch, downloadBase: server.base }), /permissions: id-token: write/); + assert.deepEqual(server.requests, []); + } finally { + await server.close(); + } +}); + +test("post does nothing when the job never logged in", async () => { + await post({}); +});