From 0bdd02a980ebac35a129f2260789606459f098d6 Mon Sep 17 00:00:00 2001 From: Jorge Martins <76965647+jfcmartins@users.noreply.github.com> Date: Sun, 1 Nov 2026 23:13:38 +0000 Subject: [PATCH 1/2] feat: install the Limen CLI and log a job in as a bot Downloads a Limen release, checks it against SHA256SUMS and its build provenance, puts only the limen binary on PATH, and optionally runs limen login --bot github_actions with a private LIMEN_HOME that the post step deletes. Plain Node 24, no dependencies, no build step. --- .github/CODEOWNERS | 3 + .github/dependabot.yml | 8 ++ .github/workflows/ci.yml | 63 ++++++++++++ .github/workflows/smoke.yml | 46 +++++++++ .gitignore | 2 + AGENTS.md | 20 ++++ CONTRIBUTING.md | 27 +++++ README.md | 104 ++++++++++++++++++++ RELEASING.md | 11 +++ SECURITY.md | 10 ++ action.yml | 55 +++++++++++ mise.toml | 5 + package.json | 12 +++ src/lib/actions.mjs | 34 +++++++ src/lib/exec.mjs | 21 ++++ src/lib/install.mjs | 152 ++++++++++++++++++++++++++++ src/lib/login.mjs | 19 ++++ src/lib/run.mjs | 86 ++++++++++++++++ src/main.mjs | 9 ++ src/post.mjs | 9 ++ test/helpers.mjs | 70 +++++++++++++ test/lib.test.mjs | 68 +++++++++++++ test/run.test.mjs | 191 ++++++++++++++++++++++++++++++++++++ 23 files changed, 1025 insertions(+) create mode 100644 .github/CODEOWNERS create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/smoke.yml create mode 100644 .gitignore create mode 100644 AGENTS.md create mode 100644 CONTRIBUTING.md create mode 100644 README.md create mode 100644 RELEASING.md create mode 100644 SECURITY.md create mode 100644 action.yml create mode 100644 mise.toml create mode 100644 package.json create mode 100644 src/lib/actions.mjs create mode 100644 src/lib/exec.mjs create mode 100644 src/lib/install.mjs create mode 100644 src/lib/login.mjs create mode 100644 src/lib/run.mjs create mode 100644 src/main.mjs create mode 100644 src/post.mjs create mode 100644 test/helpers.mjs create mode 100644 test/lib.test.mjs create mode 100644 test/run.test.mjs 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..fd44d4e --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,20 @@ +# 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)); the server's rules there decide what this action may assume. + +## 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. Don't add an npm package or a bundler. +- **Fail closed.** A missing or wrong checksum, or a failed provenance check, stops the job. Never add a way to skip both. +- **Secrets stay out of logs.** The action never reads the OIDC token or a Limen credential; keep it that way. Pass arguments as a list, never through a shell. +- **Verify before claiming.** Run it before saying it works. Anything checked only against the stub `limen` or the local release server is labelled *unverified*. +- **The CLI is Limen's.** Flags come from `limen login --help` in limen-dev/limen; don't invent options. +- **Pin every action** in workflows to a full commit SHA with a version comment. +- **Commits:** conventional, small, focused, signed. Stage specific files, never `git add -A`. Don't push or tag unless asked. Pull requests as drafts. + +## Commands +```sh +mise install +npm test +mise exec -- actionlint +``` diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..5e4d849 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,27 @@ +# Contributing + +## Layout + +| Path | What | +|---|---| +| `action.yml` | The action's interface: inputs, outputs, and the `main` and `post` entry points (Node 24). | +| `src/main.mjs`, `src/post.mjs` | The entry points. They only call `src/lib/run.mjs` and report errors. | +| `src/lib/run.mjs` | The flow: install, then log in; and the post-step cleanup. | +| `src/lib/install.mjs` | Resolve the release, download, verify (checksum, provenance), unpack, cache. | +| `src/lib/login.mjs` | The `limen login --bot` command line, with input validation. | +| `src/lib/actions.mjs` | Log lines and the runner's `GITHUB_ENV`, `GITHUB_PATH`, `GITHUB_OUTPUT`, `GITHUB_STATE` files. | +| `test/` | `node:test` suites. A local server stands in for the release and a stub script for `limen`. | + +There is no build step and no `dist/`: the code in `src/` is what runs. Keep it free of dependencies; an action's dependencies run with the job's permissions. If you think one is needed, open an issue first. + +## Tests + +```sh +mise install && npm test +``` + +Anything checked only against the stub `limen` or the local release server is **unverified** against a real Limen and real GitHub. Say so in pull requests and in the README. + +## Commits and pull requests + +Conventional commits, small and focused, signed (the `main` branch requires signatures and linear history). Open pull requests as drafts; CI starts when you mark one ready for review. diff --git a/README.md b/README.md new file mode 100644 index 0000000..d8774f1 --- /dev/null +++ b/README.md @@ -0,0 +1,104 @@ +# 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 the job's own OIDC token. Nothing is stored: no SSH key, no database password, and no Limen token in your repository secrets. The job gets a short-lived certificate (15 minutes by default, at most an hour), and every session it opens 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: actions/checkout@v7 + + - uses: limen-dev/setup-limen@v0 + with: + version: v0.1.0 # pin one + proxy: limen.example.com:443 + + - run: limen ssh web-staging-1 -- ./deploy.sh +``` + +To only install the CLI (to run `limen policy test` in a pull request, say), leave `proxy` out. That job needs no `id-token` permission. + +## Before it works + +1. **A published Limen release.** The action downloads the CLI from [limen-dev/limen releases](https://github.com/limen-dev/limen/releases). Until a release is published (v0.1.0-rc.1 is still a draft) there is nothing to download. +2. **A bot in your Limen policy** that matches this job exactly ([bots guide](https://github.com/limen-dev/limen/blob/main/docs/guides/bots.md), [ADR-0019](https://github.com/limen-dev/limen/blob/main/docs/adr/0019-machine-identities.md)): + ```yaml + kind: bot + version: v1 + metadata: { name: deploy-staging } + spec: + join: + method: github_actions + match: { repository: acme/infra, ref: refs/heads/main, environment: staging } + roles: [deployer] + max_ttl: 15m + ``` +3. **A proxy the runner can reach.** GitHub-hosted runners are on the public internet, so the Limen proxy must be reachable from there. If it is private, use a self-hosted runner inside the network. +4. **`permissions: id-token: write`** on the job when you pass `proxy`. + +## Inputs + +| Input | Default | | +|---|---|---| +| `version` | `latest` | The Limen release to install, such as `v0.1.0`. **Pin one.** `latest` is the newest *stable* release (never a release candidate) and changes under you. | +| `proxy` | | `host:port` of the Limen proxy. Set it to log in; leave it empty to only install. | +| `bot-name` | | Which bot, if more than one rule could match the job's token. | +| `audience` | | The audience to ask GitHub for. Leave it empty for the one your control plane expects. | +| `ca-file` | | A PEM file with the CA to trust, for a deployment with a private CA. | +| `verify-attestation` | `true` | Also check the release's build provenance with `gh attestation verify`. See below. | +| `github-token` | `github.token` | For the GitHub API only (resolving `latest`, verifying provenance). It needs no permissions. | + +## Outputs + +| Output | | +|---|---| +| `version` | The release installed, such as `v0.1.0`. | +| `path` | The directory with the `limen` binary. It is already on `PATH`. | +| `logged-in` | `true` if the job logged in. | + +After a login, `LIMEN_HOME` and `LIMEN_PROXY` are set for the rest of the job, so later steps run `limen ssh`, `limen db connect` and the rest without flags. + +## What it does, and what it refuses + +- **Verifies before it trusts.** The archive must be listed in the release's `SHA256SUMS` and match it, and (by default) its **build provenance** must verify with `gh attestation verify`, pinned to the `limen-dev/limen` `release.yml` workflow. A missing checksum, a mismatch, or a failed provenance check stops the job. If `gh` is missing the job also stops; set `verify-attestation: false` only on a runner that has no `gh`, and know that you then rely on the checksum alone (which comes from the same release). +- **Puts only `limen` on `PATH`.** The archive also holds the server binaries; they are not exposed. +- **Keeps credentials in a private directory** under `RUNNER_TEMP` (not the runner's home) and, in the post step, runs `limen logout` and deletes it, even if the job failed. This matters on self-hosted runners that outlive the job. +- **Never sees the OIDC token.** The CLI asks the runner for it; this action only passes along the proxy, the bot name and the audience. +- **Refuses odd input.** `version` must be `latest` or a tag, and `proxy` must be `host:port`; neither can smuggle in a path, a URL or a flag. +- **Has no dependencies.** It is plain Node (24) with no `node_modules` and no bundled `dist/`, so what you read in `src/` is what runs. + +## Pull requests + +A job triggered by a pull request (including from forks) **never matches a bot**, whatever the rule says. This is Limen's rule, not this action's: that job runs code the author chose. Log in from a push to a protected branch or from a job that targets an **environment with required reviewers**. + +## Pin the action + +A tag can move. For the strongest guarantee, pin the action to a commit: + +```yaml +- uses: limen-dev/setup-limen@ # v0.1.0 +``` + +## Status + +- Install, checksum and provenance checks are **verified against the real v0.1.0-rc.1 release** (archive, `SHA256SUMS` and attestation), served from a local server because that release is still a draft. +- The bot login is **unverified against a real GitHub OIDC token and a real control plane**. It runs `limen login --bot github_actions`, which Limen tests against a stand-in issuer only; the tests here use a stub `limen`. The first real run is the [smoke workflow](.github/workflows/smoke.yml) plus a deploy to a test Limen. +- Linux and macOS, on x64 and arm64. There is no Windows build of Limen. + +## Develop + +```sh +mise install +npm test # no dependencies to install +mise exec -- actionlint +``` + +See [CONTRIBUTING.md](CONTRIBUTING.md) and [RELEASING.md](RELEASING.md). Report vulnerabilities as in [SECURITY.md](SECURITY.md). + +Licensed under the [Apache License 2.0](LICENSE). diff --git a/RELEASING.md b/RELEASING.md new file mode 100644 index 0000000..705433f --- /dev/null +++ b/RELEASING.md @@ -0,0 +1,11 @@ +# Releasing + +Versions are `vMAJOR.MINOR.PATCH` tags, plus a moving major tag (`v0`, later `v1`) that users put in `uses:`. + +1. `main` is green and the README's **Status** section is true. +2. Run the [smoke workflow](.github/workflows/smoke.yml) by hand against the newest published Limen release. Do not tag if it fails. +3. Tag the commit: `git tag -s v0.1.0 -m v0.1.0 && git push origin v0.1.0`. Create a GitHub release from it (generate the notes). +4. Move the major tag to it: `git tag -fs v0 -m v0 v0.1.0 && git push -f origin v0`. Only the major tag moves; `vX.Y.Z` tags never do, and the repository's tag ruleset protects them. +5. Publish to the Marketplace from the release page, if you want it listed. + +A change to the inputs or the behavior that breaks a workflow needs a new major version. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..81b51c7 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,10 @@ +# Security + +Report vulnerabilities privately through GitHub's [private vulnerability reporting](https://github.com/limen-dev/setup-limen/security/advisories/new), not in an issue. For vulnerabilities in Limen itself, report to [limen-dev/limen](https://github.com/limen-dev/limen/security). + +What this action is careful about: +- It runs code it downloaded, so it checks the archive against the release's `SHA256SUMS` and, by default, its build provenance (`gh attestation verify`, pinned to Limen's `release.yml`), and stops on any failure. +- It never sees, logs or stores the job's OIDC token or any Limen credential. The CLI asks the runner for the token itself. +- The login's credentials live in a private directory under `RUNNER_TEMP` and are removed in the post step. +- `version` and `proxy` are validated, and arguments are passed to programs as a list, never through a shell. +- It has no runtime dependencies to compromise. 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..b9de27e --- /dev/null +++ b/src/lib/run.mjs @@ -0,0 +1,86 @@ +import { mkdir, 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. + await mkdir(tempRoot, { recursive: true }); + 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..10476b0 --- /dev/null +++ b/test/run.test.mjs @@ -0,0 +1,191 @@ +import assert from "node:assert/strict"; +import { access, readFile, writeFile } 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({}); + const dir = await tempDir("post"); + await writeFile(join(dir, "keep"), "x"); + await post({ STATE_home: "" }); + await access(join(dir, "keep")); +}); From 93625cda4d6e9c6eacbbb23c86f78cebd6532920 Mon Sep 17 00:00:00 2001 From: Jorge Martins <76965647+jfcmartins@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:10:35 +0000 Subject: [PATCH 2/2] docs: tighten the README and drop files the org already provides CONTRIBUTING.md is the organization default. Removes a redundant mkdir and a pointless test line. --- AGENTS.md | 17 ++++---- CONTRIBUTING.md | 27 ------------- README.md | 101 +++++++++++++--------------------------------- RELEASING.md | 13 +++--- SECURITY.md | 9 +---- src/lib/run.mjs | 3 +- test/run.test.mjs | 6 +-- 7 files changed, 45 insertions(+), 131 deletions(-) delete mode 100644 CONTRIBUTING.md diff --git a/AGENTS.md b/AGENTS.md index fd44d4e..ce23059 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,20 +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)); the server's rules there decide what this action may assume. +`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. Don't add an npm package or a bundler. +- **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. -- **Secrets stay out of logs.** The action never reads the OIDC token or a Limen credential; keep it that way. Pass arguments as a list, never through a shell. -- **Verify before claiming.** Run it before saying it works. Anything checked only against the stub `limen` or the local release server is labelled *unverified*. -- **The CLI is Limen's.** Flags come from `limen login --help` in limen-dev/limen; don't invent options. +- **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, focused, signed. Stage specific files, never `git add -A`. Don't push or tag unless asked. Pull requests as drafts. +- **Commits:** conventional, small, signed; stage specific files. Don't push or tag unless asked. Pull requests as drafts. -## Commands ```sh -mise install -npm test -mise exec -- actionlint +mise install && npm test && mise exec -- actionlint ``` diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 5e4d849..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,27 +0,0 @@ -# Contributing - -## Layout - -| Path | What | -|---|---| -| `action.yml` | The action's interface: inputs, outputs, and the `main` and `post` entry points (Node 24). | -| `src/main.mjs`, `src/post.mjs` | The entry points. They only call `src/lib/run.mjs` and report errors. | -| `src/lib/run.mjs` | The flow: install, then log in; and the post-step cleanup. | -| `src/lib/install.mjs` | Resolve the release, download, verify (checksum, provenance), unpack, cache. | -| `src/lib/login.mjs` | The `limen login --bot` command line, with input validation. | -| `src/lib/actions.mjs` | Log lines and the runner's `GITHUB_ENV`, `GITHUB_PATH`, `GITHUB_OUTPUT`, `GITHUB_STATE` files. | -| `test/` | `node:test` suites. A local server stands in for the release and a stub script for `limen`. | - -There is no build step and no `dist/`: the code in `src/` is what runs. Keep it free of dependencies; an action's dependencies run with the job's permissions. If you think one is needed, open an issue first. - -## Tests - -```sh -mise install && npm test -``` - -Anything checked only against the stub `limen` or the local release server is **unverified** against a real Limen and real GitHub. Say so in pull requests and in the README. - -## Commits and pull requests - -Conventional commits, small and focused, signed (the `main` branch requires signatures and linear history). Open pull requests as drafts; CI starts when you mark one ready for review. diff --git a/README.md b/README.md index d8774f1..b981a56 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 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 the job's own OIDC token. Nothing is stored: no SSH key, no database password, and no Limen token in your repository secrets. The job gets a short-lived certificate (15 minutes by default, at most an hour), and every session it opens is audited with the repository, workflow, run and commit. +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: @@ -12,93 +12,48 @@ jobs: runs-on: ubuntu-24.04 environment: staging steps: - - uses: actions/checkout@v7 - - uses: limen-dev/setup-limen@v0 with: - version: v0.1.0 # pin one - proxy: limen.example.com:443 - + version: v0.1.0 # pin one + proxy: limen.example.com:443 # leave out to only install - run: limen ssh web-staging-1 -- ./deploy.sh ``` -To only install the CLI (to run `limen policy test` in a pull request, say), leave `proxy` out. That job needs no `id-token` permission. +## You need -## Before it works +- **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`. -1. **A published Limen release.** The action downloads the CLI from [limen-dev/limen releases](https://github.com/limen-dev/limen/releases). Until a release is published (v0.1.0-rc.1 is still a draft) there is nothing to download. -2. **A bot in your Limen policy** that matches this job exactly ([bots guide](https://github.com/limen-dev/limen/blob/main/docs/guides/bots.md), [ADR-0019](https://github.com/limen-dev/limen/blob/main/docs/adr/0019-machine-identities.md)): - ```yaml - kind: bot - version: v1 - metadata: { name: deploy-staging } - spec: - join: - method: github_actions - match: { repository: acme/infra, ref: refs/heads/main, environment: staging } - roles: [deployer] - max_ttl: 15m - ``` -3. **A proxy the runner can reach.** GitHub-hosted runners are on the public internet, so the Limen proxy must be reachable from there. If it is private, use a self-hosted runner inside the network. -4. **`permissions: id-token: write`** on the job when you pass `proxy`. - -## Inputs +## Inputs and outputs | Input | Default | | |---|---|---| -| `version` | `latest` | The Limen release to install, such as `v0.1.0`. **Pin one.** `latest` is the newest *stable* release (never a release candidate) and changes under you. | -| `proxy` | | `host:port` of the Limen proxy. Set it to log in; leave it empty to only install. | -| `bot-name` | | Which bot, if more than one rule could match the job's token. | -| `audience` | | The audience to ask GitHub for. Leave it empty for the one your control plane expects. | -| `ca-file` | | A PEM file with the CA to trust, for a deployment with a private CA. | -| `verify-attestation` | `true` | Also check the release's build provenance with `gh attestation verify`. See below. | -| `github-token` | `github.token` | For the GitHub API only (resolving `latest`, verifying provenance). It needs no permissions. | - -## Outputs - -| Output | | -|---|---| -| `version` | The release installed, such as `v0.1.0`. | -| `path` | The directory with the `limen` binary. It is already on `PATH`. | -| `logged-in` | `true` if the job logged in. | - -After a login, `LIMEN_HOME` and `LIMEN_PROXY` are set for the rest of the job, so later steps run `limen ssh`, `limen db connect` and the rest without flags. - -## What it does, and what it refuses - -- **Verifies before it trusts.** The archive must be listed in the release's `SHA256SUMS` and match it, and (by default) its **build provenance** must verify with `gh attestation verify`, pinned to the `limen-dev/limen` `release.yml` workflow. A missing checksum, a mismatch, or a failed provenance check stops the job. If `gh` is missing the job also stops; set `verify-attestation: false` only on a runner that has no `gh`, and know that you then rely on the checksum alone (which comes from the same release). -- **Puts only `limen` on `PATH`.** The archive also holds the server binaries; they are not exposed. -- **Keeps credentials in a private directory** under `RUNNER_TEMP` (not the runner's home) and, in the post step, runs `limen logout` and deletes it, even if the job failed. This matters on self-hosted runners that outlive the job. -- **Never sees the OIDC token.** The CLI asks the runner for it; this action only passes along the proxy, the bot name and the audience. -- **Refuses odd input.** `version` must be `latest` or a tag, and `proxy` must be `host:port`; neither can smuggle in a path, a URL or a flag. -- **Has no dependencies.** It is plain Node (24) with no `node_modules` and no bundled `dist/`, so what you read in `src/` is what runs. +| `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. | -## Pull requests +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. -A job triggered by a pull request (including from forks) **never matches a bot**, whatever the rule says. This is Limen's rule, not this action's: that job runs code the author chose. Log in from a push to a protected branch or from a job that targets an **environment with required reviewers**. +## What it does -## Pin the action +- **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. -A tag can move. For the strongest guarantee, pin the action to a commit: - -```yaml -- uses: limen-dev/setup-limen@ # v0.1.0 -``` +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 -- Install, checksum and provenance checks are **verified against the real v0.1.0-rc.1 release** (archive, `SHA256SUMS` and attestation), served from a local server because that release is still a draft. -- The bot login is **unverified against a real GitHub OIDC token and a real control plane**. It runs `limen login --bot github_actions`, which Limen tests against a stand-in issuer only; the tests here use a stub `limen`. The first real run is the [smoke workflow](.github/workflows/smoke.yml) plus a deploy to a test Limen. -- Linux and macOS, on x64 and arm64. There is no Windows build of Limen. - -## Develop - -```sh -mise install -npm test # no dependencies to install -mise exec -- actionlint -``` - -See [CONTRIBUTING.md](CONTRIBUTING.md) and [RELEASING.md](RELEASING.md). Report vulnerabilities as in [SECURITY.md](SECURITY.md). +- **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. -Licensed under the [Apache License 2.0](LICENSE). +Develop with `mise install && npm test`. Licensed under [Apache-2.0](LICENSE). diff --git a/RELEASING.md b/RELEASING.md index 705433f..cebdfc9 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -1,11 +1,10 @@ # Releasing -Versions are `vMAJOR.MINOR.PATCH` tags, plus a moving major tag (`v0`, later `v1`) that users put in `uses:`. +Tags are `vMAJOR.MINOR.PATCH`, plus a moving major tag (`v0`) for `uses:`. -1. `main` is green and the README's **Status** section is true. -2. Run the [smoke workflow](.github/workflows/smoke.yml) by hand against the newest published Limen release. Do not tag if it fails. -3. Tag the commit: `git tag -s v0.1.0 -m v0.1.0 && git push origin v0.1.0`. Create a GitHub release from it (generate the notes). -4. Move the major tag to it: `git tag -fs v0 -m v0 v0.1.0 && git push -f origin v0`. Only the major tag moves; `vX.Y.Z` tags never do, and the repository's tag ruleset protects them. -5. Publish to the Marketplace from the release page, if you want it listed. +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 to the inputs or the behavior that breaks a workflow needs a new major version. +A change that can break a workflow needs a new major version. diff --git a/SECURITY.md b/SECURITY.md index 81b51c7..256250f 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,10 +1,5 @@ # Security -Report vulnerabilities privately through GitHub's [private vulnerability reporting](https://github.com/limen-dev/setup-limen/security/advisories/new), not in an issue. For vulnerabilities in Limen itself, report to [limen-dev/limen](https://github.com/limen-dev/limen/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). -What this action is careful about: -- It runs code it downloaded, so it checks the archive against the release's `SHA256SUMS` and, by default, its build provenance (`gh attestation verify`, pinned to Limen's `release.yml`), and stops on any failure. -- It never sees, logs or stores the job's OIDC token or any Limen credential. The CLI asks the runner for the token itself. -- The login's credentials live in a private directory under `RUNNER_TEMP` and are removed in the post step. -- `version` and `proxy` are validated, and arguments are passed to programs as a list, never through a shell. -- It has no runtime dependencies to compromise. +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/src/lib/run.mjs b/src/lib/run.mjs index b9de27e..4891450 100644 --- a/src/lib/run.mjs +++ b/src/lib/run.mjs @@ -1,4 +1,4 @@ -import { mkdir, mkdtemp, rm } from "node:fs/promises"; +import { mkdtemp, rm } from "node:fs/promises"; import os from "node:os"; import { join } from "node:path"; @@ -57,7 +57,6 @@ export async function main(env, deps = {}) { if (!args) return; // Credentials go in a private directory that the post step deletes, not the runner's home. - await mkdir(tempRoot, { recursive: true }); const home = await mkdtemp(join(tempRoot, "limen-home-")); saveState(env, "bin", installed.bin); saveState(env, "home", home); diff --git a/test/run.test.mjs b/test/run.test.mjs index 10476b0..e76b857 100644 --- a/test/run.test.mjs +++ b/test/run.test.mjs @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { access, readFile, writeFile } from "node:fs/promises"; +import { access, readFile } from "node:fs/promises"; import { join } from "node:path"; import { test } from "node:test"; @@ -184,8 +184,4 @@ test("main refuses to log in without id-token permission, before downloading", a test("post does nothing when the job never logged in", async () => { await post({}); - const dir = await tempDir("post"); - await writeFile(join(dir, "keep"), "x"); - await post({ STATE_home: "" }); - await access(join(dir, "keep")); });