diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index fd5540e..d353423 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -17,7 +17,7 @@ workflows: '.github/workflows/container-remediation.yml': - 'actions/checkout@v4.2.2' - 'actions/checkout@v4.3.1' - - 'actions/create-github-app-token@v1.12.0' + - 'actions/create-github-app-token@v3.3.0' - 'actions/download-artifact@v4.3.0' - 'actions/setup-go@v5.6.0' - 'actions/setup-node@v4.4.0' @@ -35,8 +35,13 @@ workflows: - 'actions/checkout@v4.2.2' '.github/workflows/pr-risk.yml': - 'actions/checkout@v4.2.2' - - 'actions/create-github-app-token@v1.12.0' + - 'actions/create-github-app-token@v3.3.0' - 'actions/setup-node@v4.4.0' + '.github/workflows/sandboxed-agent-tests.yml': + - 'actions/checkout@v4.2.2' + '.github/workflows/sandboxed-agent.yml': + - 'actions/checkout@v4.4.0' + - 'actions/create-github-app-token@v3.3.0' '.github/workflows/semgrep-self-test.yml': [] '.github/workflows/semgrep-tests.yml': - 'actions/checkout@v4.2.2' @@ -51,7 +56,7 @@ workflows: '.github/workflows/vuln-remediation.yml': - 'actions/checkout@v4.2.2' - 'actions/checkout@v4.4.0' - - 'actions/create-github-app-token@v1.12.0' + - 'actions/create-github-app-token@v3.3.0' - 'actions/download-artifact@v4.3.0' - 'actions/setup-go@v5.6.0' - 'actions/setup-node@v4.4.0' @@ -94,6 +99,11 @@ dependencies: commit: 'sha1-d72941d797fd3113feb6b93fd0dec494b13a2547' owner_id: 44036562 repo_id: 642580244 + 'actions/create-github-app-token@v3.3.0': + ref: 'v3.3.0' + commit: 'sha1-64ab729a6294000f5aa4a4bc0b73d1f32bc45510' + owner_id: 44036562 + repo_id: 642580244 'actions/download-artifact@v4.3.0': ref: 'v4.3.0' commit: 'sha1-d3f86a106a0bac45b974a628896c90dbdf5c8093' diff --git a/.github/workflows/container-remediation.yml b/.github/workflows/container-remediation.yml index 503de4e..0ae6e2e 100644 --- a/.github/workflows/container-remediation.yml +++ b/.github/workflows/container-remediation.yml @@ -224,7 +224,7 @@ jobs: - name: Generate Go module read token id: module-token if: steps.go-private.outputs.repos != '' - uses: actions/create-github-app-token@v1.12.0 + uses: actions/create-github-app-token@v3.3.0 with: app-id: ${{ secrets.ADMIN_APP_ID }} private-key: ${{ secrets.ADMIN_APP_PRIVATE_KEY }} @@ -498,7 +498,7 @@ jobs: - name: Generate app token id: app-token - uses: actions/create-github-app-token@v1.12.0 + uses: actions/create-github-app-token@v3.3.0 with: app-id: ${{ secrets.ADMIN_APP_ID }} private-key: ${{ secrets.ADMIN_APP_PRIVATE_KEY }} diff --git a/.github/workflows/pr-risk.yml b/.github/workflows/pr-risk.yml index 4ee428c..fbbc4ab 100644 --- a/.github/workflows/pr-risk.yml +++ b/.github/workflows/pr-risk.yml @@ -152,7 +152,7 @@ jobs: id: app-token if: ${{ !cancelled() && (steps.gather.outputs.eligible == 'true' || steps.gather.outputs.commented == 'true') }} # Pinned to a commit because this step is handed the app's private key. d72941d is v1.12.0. - uses: actions/create-github-app-token@v1.12.0 + uses: actions/create-github-app-token@v3.3.0 with: app-id: ${{ secrets.ADMIN_APP_ID }} private-key: ${{ secrets.ADMIN_APP_PRIVATE_KEY }} diff --git a/.github/workflows/sandboxed-agent-tests.yml b/.github/workflows/sandboxed-agent-tests.yml new file mode 100644 index 0000000..984bccd --- /dev/null +++ b/.github/workflows/sandboxed-agent-tests.yml @@ -0,0 +1,45 @@ +name: Sandboxed Agent Tests + +on: + pull_request: + paths: + - .github/workflows/sandboxed-agent.yml + - .github/workflows/sandboxed-agent-tests.yml + - .github/workflows/sandboxed-agent/** + - scripts/test_sandboxed_agent.py + push: + branches: [main] + paths: + - .github/workflows/sandboxed-agent.yml + - .github/workflows/sandboxed-agent-tests.yml + - .github/workflows/sandboxed-agent/** + - scripts/test_sandboxed_agent.py + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4.2.2 + - run: | + python3 -m venv /tmp/sandboxed-agent-tests + /tmp/sandboxed-agent-tests/bin/pip install PyYAML==6.0.3 + /tmp/sandboxed-agent-tests/bin/python -m unittest discover -s scripts -p test_sandboxed_agent.py + + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4.2.2 + - name: shellcheck and actionlint + run: | + set -euo pipefail + tarball=actionlint_1.7.7_linux_amd64.tar.gz + curl -fsSLO "https://github.com/rhysd/actionlint/releases/download/v1.7.7/$tarball" + echo "023070a287cd8cccd71515fedc843f1985bf96c436b7effaecce67290e7e0757 $tarball" | sha256sum -c - + tar -xzf "$tarball" actionlint + shellcheck .github/workflows/sandboxed-agent/*.sh + node --check .github/workflows/sandboxed-agent/mint-token.mjs + node --check .github/workflows/sandboxed-agent/checks-relay.mjs + ./actionlint .github/workflows/sandboxed-agent.yml .github/workflows/sandboxed-agent-tests.yml diff --git a/.github/workflows/sandboxed-agent.yml b/.github/workflows/sandboxed-agent.yml new file mode 100644 index 0000000..46d8386 --- /dev/null +++ b/.github/workflows/sandboxed-agent.yml @@ -0,0 +1,363 @@ +name: Sandboxed agent + +# Runs Pi with --approve against the caller's repository inside a Docker Sandbox: a microVM +# with its own kernel, filesystem and Docker daemon, on the GitHub-hosted runner. The agent has +# root inside the sandbox and no way out of it except the network, through sbx's proxy. +# +# Credentials never enter the sandbox. The sbx proxy adds them to matching requests on the way +# out, and the agent only ever sees placeholders: +# - GitHub: installation tokens of the kernel-internal app, limited to the caller's repository +# and `app-permissions`. The proxy fetches them by running mint-token.mjs on the runner, which +# reads the app key from a file the sandbox can't reach. +# - The model provider: short-lived OpenAI or OpenRouter credentials from workload identity +# federation (the llm-credentials action), re-read on every request. +# +# The agent works on its own clone of the caller's checkout and pushes branches through the +# proxy. It reads check runs through a read-only relay on the runner, because the app has no +# checks permission. With `merge: true`, the agent stops at `ready:` and this workflow merges +# the pull request only after Cursor Bugbot and every other check pass on its head commit. +# +# Outcome: the agent writes one line to $OUTCOME_FILE inside the sandbox: +# no-updates nothing to change (with `evergreen-branch`, no pull request from it may be open) +# ready: with `merge: true`, the pull request is ready for the merge gate +# merged: with `merge: false`, the agent merged the pull request itself +# +# Callers grant `id-token: write` for the model credentials, plus read access to actions, +# checks, contents, pull requests and statuses for the checkout, the relay and the merge gate. + +on: + workflow_call: + inputs: + prompt-file: + description: Path of the prompt in the caller's repository. `${OUTCOME_FILE}`, `${GITHUB_REPOSITORY}` and the variables named in `prompt-vars` are substituted. + type: string + required: true + prompt-vars: + description: Space-separated names from `env` to substitute in the prompt + type: string + required: false + default: '' + app-permissions: + description: JSON permissions for the agent's GitHub App token, such as {"contents":"write","pull_requests":"write"}. The token is limited to the caller's repository. + type: string + required: true + env: + description: Non-secret NAME=value lines set for the agent + type: string + required: false + default: '' + setup: + description: Bash run inside the sandbox, in the checkout, after Node.js and Pi are installed and before the agent starts + type: string + required: false + default: '' + merge: + description: Merge the agent's `ready:` pull request once Cursor Bugbot and every other check pass + type: boolean + required: false + default: false + evergreen-branch: + description: With a `no-updates` outcome, fail if a pull request from this branch is still open + type: string + required: false + default: '' + model: + description: Pi model as provider/id, on OpenAI or OpenRouter. Defaults to the PI_PREFERRED_MODEL variable. + type: string + required: false + default: ${{ vars.PI_PREFERRED_MODEL }} + thinking: + description: Pi thinking level + type: string + required: false + default: max + timeout-minutes: + description: Job timeout + type: number + required: false + default: 180 + security-workflows-ref: + description: Ref of kernel/security-workflows to fetch this workflow's scripts from + type: string + required: false + default: main + secrets: + ADMIN_APP_ID: + required: true + ADMIN_APP_PRIVATE_KEY: + required: true + # A Docker account personal access token with read scope; sbx requires a signed-in user. + DOCKER_USERNAME: + required: true + DOCKER_PAT: + required: true + # Secret NAME=value lines set for the agent, such as API keys for its tools. + AGENT_SECRETS: + required: false + outputs: + outcome: + description: no-updates, or merged: + value: ${{ jobs.agent.outputs.outcome }} + +jobs: + agent: + runs-on: ubuntu-24.04 + timeout-minutes: ${{ inputs.timeout-minutes }} + permissions: + actions: read + checks: read + contents: read + pull-requests: read + statuses: read + id-token: write + outputs: + outcome: ${{ steps.outcome.outputs.outcome }} + env: + SBX_VERSION: 0.54.0 + SBX_DEB_SHA256: 2ed91c566a2001a03c337058f056cf8ddcf700944482f1092e8cd70a5d84af7f + SANDBOX: agent + STATE: ${{ github.workspace }}/../sandboxed-agent + OUTCOME_FILE: /home/agent/outcome + CHECKS_RELAY_PORT: '8378' + steps: + - name: Check the model provider + env: + MODEL: ${{ inputs.model }} + run: | + case "${MODEL%%/*}" in + openai | openrouter) ;; + *) echo "::error::The sandboxed agent supports OpenAI and OpenRouter models, not '$MODEL'" >&2; exit 1 ;; + esac + mkdir -p "$STATE" + chmod 700 "$STATE" + + - name: Checkout + uses: actions/checkout@v4.4.0 + with: + fetch-depth: 0 + persist-credentials: false + + # Checked out rather than referenced as kernel/security-workflows/...@, because `uses` + # can't take an expression and the scripts must follow security-workflows-ref. It lands in + # the workspace, which the sandbox can read; nothing secret is kept there. Keys and tokens + # stay in $STATE, outside it. + - name: Fetch sandboxed agent scripts + uses: actions/checkout@v4.4.0 + with: + repository: kernel/security-workflows + ref: ${{ inputs.security-workflows-ref }} + path: .sandboxed-agent + sparse-checkout: | + .github/actions/llm-credentials + .github/workflows/sandboxed-agent + persist-credentials: false + + - name: Model credentials + uses: ./.sandboxed-agent/.github/actions/llm-credentials + with: + model: ${{ inputs.model }} + openai-identity-provider-id: ${{ vars.OPENAI_IDENTITY_PROVIDER_ID }} + openai-service-account-id: ${{ vars.OPENAI_SERVICE_ACCOUNT_ID }} + openai-audience: ${{ vars.OPENAI_WIF_AUDIENCE }} + openrouter-federation-policy-id: ${{ vars.OPENROUTER_FEDERATION_POLICY_ID }} + + - name: Install Docker Sandboxes + env: + DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }} + DOCKER_PAT: ${{ secrets.DOCKER_PAT }} + run: | + if [ -z "$DOCKER_USERNAME" ] || [ -z "$DOCKER_PAT" ]; then + echo "::error::DOCKER_USERNAME and DOCKER_PAT are empty. sbx needs a signed-in Docker account; pass a read-scoped personal access token this repository can read." >&2 + exit 1 + fi + deb="$STATE/sbx.deb" + curl -fsSL "https://github.com/docker/sbx-releases/releases/download/v$SBX_VERSION/DockerSandboxes-linux-amd64-ubuntu2404.deb" -o "$deb" + echo "$SBX_DEB_SHA256 $deb" | sha256sum -c --quiet + sudo apt-get update -qq + sudo apt-get install -y -qq "$deb" >/dev/null + # The runner user may use KVM; nothing else changes on the host. + sudo setfacl -m "u:$USER:rw" /dev/kvm + echo "$DOCKER_PAT" | sbx login --username "$DOCKER_USERNAME" --password-stdin + # The agent researches release notes on the web, so egress is open. Credentials still + # only reach the hosts sbx attaches them to. + sbx policy init allow-all + sbx policy allow network "localhost:$CHECKS_RELAY_PORT" + + - name: Agent GitHub credentials + env: + APP_ID: ${{ secrets.ADMIN_APP_ID }} + APP_PRIVATE_KEY: ${{ secrets.ADMIN_APP_PRIVATE_KEY }} + APP_PERMISSIONS: ${{ inputs.app-permissions }} + RELAY_TOKEN: ${{ github.token }} + run: | + umask 077 + scripts="$GITHUB_WORKSPACE/.sandboxed-agent/.github/workflows/sandboxed-agent" + printf '%s' "$APP_PRIVATE_KEY" > "$STATE/app-key.pem" + # shellcheck disable=SC2016 # the inline Node.js script is single-quoted on purpose + installation_id=$(node -e ' + const { createSign } = require("node:crypto"); + const now = Math.floor(Date.now() / 1000); + const enc = (v) => Buffer.from(JSON.stringify(v)).toString("base64url"); + const u = `${enc({ alg: "RS256", typ: "JWT" })}.${enc({ iat: now - 60, exp: now + 300, iss: process.env.APP_ID })}`; + const s = createSign("RSA-SHA256"); s.update(u); + const key = require("node:fs").readFileSync(process.argv[1], "utf8").replaceAll("\\n", "\n"); + fetch(`https://api.github.com/repos/${process.env.GITHUB_REPOSITORY}/installation`, { + headers: { Authorization: `Bearer ${u}.${s.sign(key, "base64url")}`, Accept: "application/vnd.github+json", "User-Agent": "sandboxed-agent" }, + }).then((r) => r.json()).then((j) => { if (!j.id) throw new Error("no installation for this repository"); console.log(j.id); }); + ' "$STATE/app-key.pem") + jq -n \ + --arg appId "$APP_ID" --arg installationId "$installation_id" \ + --arg repository "${GITHUB_REPOSITORY#*/}" --argjson permissions "$APP_PERMISSIONS" \ + --arg keyFile "$STATE/app-key.pem" --arg tokensFile "$STATE/tokens" \ + '{$appId, $installationId, $repository, $permissions, $keyFile, $tokensFile}' > "$STATE/mint.json" + # Installation tokens last an hour; the proxy fetches a new one every 30 minutes. + sbx secret set github --command "$(command -v node) $scripts/mint-token.mjs $STATE/mint.json" --refresh 30m + + printf '%s' "$RELAY_TOKEN" | GITHUB_REPOSITORY="$GITHUB_REPOSITORY" \ + setsid node "$scripts/checks-relay.mjs" >>"$STATE/checks-relay.log" 2>&1 & + echo "$!" > "$STATE/checks-relay.pid" + + - name: Agent model credentials + env: + MODEL: ${{ inputs.model }} + run: | + if [ "${MODEL%%/*}" = openai ]; then + sbx secret set openai --command "$(command -v jq) -r .openai.key $HOME/.pi/agent/auth.json" --refresh on-demand + fi + if [ -n "${OPENROUTER_ACCESS_TOKEN_FILE:-}" ]; then + sbx secret set openrouter --command "cat $OPENROUTER_ACCESS_TOKEN_FILE" --refresh on-demand + fi + + - name: Agent environment + env: + AGENT_ENV: ${{ inputs.env }} + AGENT_SECRETS: ${{ secrets.AGENT_SECRETS }} + run: | + umask 077 + { + echo "GITHUB_REPOSITORY=$GITHUB_REPOSITORY" + echo "OUTCOME_FILE=$OUTCOME_FILE" + echo "CHECKS_RELAY_URL=http://host.docker.internal:$CHECKS_RELAY_PORT" + echo "CI=true" + echo "GIT_TERMINAL_PROMPT=0" + echo "PI_TELEMETRY=0" + echo "PI_SKIP_VERSION_CHECK=1" + # The proxy replaces these placeholders with the real model credentials. + echo "OPENAI_API_KEY=proxy-managed" + echo "OPENROUTER_API_KEY=proxy-managed" + echo "OPENROUTER_ACCESS_TOKEN_FILE=/home/agent/.openrouter-token" + printf '%s\n' "$AGENT_ENV" "$AGENT_SECRETS" | grep -E '^[A-Za-z_][A-Za-z0-9_]*=' || true + } > "$STATE/agent.env" + + - name: Create the sandbox + run: | + sbx create --name "$SANDBOX" --clone --no-progress shell . + sbx exec --env-file "$STATE/agent.env" "$SANDBOX" bash -c 'printf proxy-managed > ~/.openrouter-token' + sbx exec -i --env-file "$STATE/agent.env" "$SANDBOX" bash -s \ + < "$GITHUB_WORKSPACE/.sandboxed-agent/.github/workflows/sandboxed-agent/sandbox-setup.sh" + + - name: Caller setup + if: inputs.setup != '' + env: + SETUP: ${{ inputs.setup }} + run: printf '%s\n' "$SETUP" | sbx exec -i --env-file "$STATE/agent.env" "$SANDBOX" bash -euo pipefail -s + + - name: Run the agent + env: + PROMPT_FILE: ${{ inputs.prompt-file }} + PROMPT_VARS: ${{ inputs.prompt-vars }} + AGENT_ENV: ${{ inputs.env }} + MODEL: ${{ inputs.model }} + THINKING: ${{ inputs.thinking }} + run: | + while IFS='=' read -r name value; do + [[ "$name" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] && export "$name=$value" + done <<<"$AGENT_ENV" + # shellcheck disable=SC2016 # envsubst expands these, not this shell + vars='${GITHUB_REPOSITORY} ${OUTCOME_FILE}' + for name in $PROMPT_VARS; do vars="$vars \${$name}"; done + envsubst "$vars" < "$PROMPT_FILE" | sbx exec -i "$SANDBOX" bash -c 'cat > /home/agent/prompt.md' + # shellcheck disable=SC2016 # the sandbox shell expands these + sbx exec --env-file "$STATE/agent.env" -e MODEL="$MODEL" -e THINKING="$THINKING" "$SANDBOX" \ + bash -c 'pi --print --no-session --approve --model "$MODEL" --thinking "$THINKING" @/home/agent/prompt.md' + + - name: Read the outcome + id: read-outcome + run: | + # shellcheck disable=SC2016 # expanded by the sandbox shell + outcome=$(sbx exec "$SANDBOX" bash -c 'cat "$1" 2>/dev/null' bash "$OUTCOME_FILE" | tr -d '\r\n' || true) + if ! [[ "$outcome" =~ ^(no-updates|ready:[0-9]+|merged:[0-9]+)$ ]]; then + echo "::error::The agent exited without writing no-updates, ready: or merged: to $OUTCOME_FILE" >&2 + exit 1 + fi + echo "outcome=$outcome" >> "$GITHUB_OUTPUT" + + - name: Merge token + id: merge-token + if: inputs.merge && startsWith(steps.read-outcome.outputs.outcome, 'ready:') + uses: actions/create-github-app-token@v3.3.0 + with: + app-id: ${{ secrets.ADMIN_APP_ID }} + private-key: ${{ secrets.ADMIN_APP_PRIVATE_KEY }} + permission-contents: write + permission-pull-requests: write + permission-workflows: ${{ fromJSON(inputs.app-permissions).workflows || '' }} + + - name: Check and merge + id: outcome + env: + OUTCOME: ${{ steps.read-outcome.outputs.outcome }} + MERGE: ${{ inputs.merge }} + EVERGREEN_BRANCH: ${{ inputs.evergreen-branch }} + GH_TOKEN: ${{ github.token }} + MERGE_TOKEN: ${{ steps.merge-token.outputs.token }} + run: | + pr=${OUTCOME#*:} + case "$OUTCOME:$MERGE" in + no-updates:*) + if [ -n "$EVERGREEN_BRANCH" ]; then + open=$(gh pr list --repo "$GITHUB_REPOSITORY" --head "$EVERGREEN_BRANCH" --state open --json number --jq '.[0].number // ""') + if [ -n "$open" ]; then + echo "::error::The agent reported no updates while #$open from $EVERGREEN_BRANCH is open" >&2 + exit 1 + fi + fi + ;; + ready:*:true) + bash "$GITHUB_WORKSPACE/.sandboxed-agent/.github/workflows/sandboxed-agent/merge-gate.sh" "$pr" + OUTCOME="merged:$pr" + ;; + merged:*:false) + state=$(gh pr view "$pr" --repo "$GITHUB_REPOSITORY" --json state --jq .state) + if [ "$state" != MERGED ]; then + echo "::error::The agent reported $OUTCOME, but #$pr is $state" >&2 + exit 1 + fi + ;; + *) + echo "::error::Outcome $OUTCOME doesn't match merge: $MERGE" >&2 + exit 1 + ;; + esac + echo "outcome=$OUTCOME" >> "$GITHUB_OUTPUT" + + - name: Tear down + if: always() + run: | + sbx rm --force "$SANDBOX" >/dev/null 2>&1 || true + sbx secret rm github >/dev/null 2>&1 || true + if [ -f "$STATE/checks-relay.pid" ]; then + kill "$(cat "$STATE/checks-relay.pid")" 2>/dev/null || true + fi + if [ -f "$STATE/tokens" ]; then + while IFS= read -r token; do + curl -fsS -o /dev/null -X DELETE -H "Authorization: Bearer $token" https://api.github.com/installation/token || true + done < "$STATE/tokens" + fi + rm -f "$STATE/app-key.pem" "$STATE/tokens" "$STATE/agent.env" + + - name: Stop model credentials + if: always() + uses: ./.sandboxed-agent/.github/actions/llm-credentials + with: + stop: true diff --git a/.github/workflows/sandboxed-agent/checks-relay.mjs b/.github/workflows/sandboxed-agent/checks-relay.mjs new file mode 100644 index 0000000..05c44e1 --- /dev/null +++ b/.github/workflows/sandboxed-agent/checks-relay.mjs @@ -0,0 +1,46 @@ +#!/usr/bin/env node + +// Read-only view of a commit's check runs and statuses for the agent. The GitHub App has no +// checks permission and the sandbox proxy replaces any GitHub credential the agent sends, so +// this relay answers with the job's read-only GITHUB_TOKEN, read from stdin. +// +// GET /check-runs/ check runs on the commit, latest attempt of each +// GET /status/ the commit's combined status +// +// Environment: GITHUB_REPOSITORY, CHECKS_RELAY_PORT. + +import { readFileSync } from "node:fs"; +import { createServer } from "node:http"; + +const token = readFileSync(0, "utf8").trim(); +const { GITHUB_REPOSITORY: repository, CHECKS_RELAY_PORT: port } = process.env; +if (!token || !repository || !port) { + throw new Error("a token on stdin, GITHUB_REPOSITORY and CHECKS_RELAY_PORT are required"); +} + +const routes = { + "check-runs": (sha) => `commits/${sha}/check-runs?filter=latest&per_page=100`, + status: (sha) => `commits/${sha}/status`, +}; + +createServer(async (request, response) => { + const match = /^\/(check-runs|status)\/([0-9a-f]{40})$/.exec(request.url ?? ""); + if (request.method !== "GET" || !match) { + response.writeHead(404).end(); + return; + } + try { + const upstream = await fetch(`https://api.github.com/repos/${repository}/${routes[match[1]](match[2])}`, { + headers: { + Accept: "application/vnd.github+json", + Authorization: `Bearer ${token}`, + "X-GitHub-Api-Version": "2022-11-28", + "User-Agent": "sandboxed-agent-checks-relay", + }, + }); + response.writeHead(upstream.status, { "Content-Type": "application/json" }).end(await upstream.text()); + } catch (error) { + console.error(error.message); + response.writeHead(502).end(); + } +}).listen(Number(port), "127.0.0.1"); diff --git a/.github/workflows/sandboxed-agent/merge-gate.sh b/.github/workflows/sandboxed-agent/merge-gate.sh new file mode 100644 index 0000000..bf494c3 --- /dev/null +++ b/.github/workflows/sandboxed-agent/merge-gate.sh @@ -0,0 +1,54 @@ +#!/bin/bash +# Merges the agent's pull request once Cursor Bugbot and every other check have passed on its +# head commit. Runs on the runner, outside the sandbox, so the agent can't skip it. +# +# merge-gate.sh PR_NUMBER +# +# GH_TOKEN reads checks and statuses (the job's GITHUB_TOKEN). MERGE_TOKEN is an app token that +# can merge. CHECKS_TIMEOUT_MINUTES bounds the wait for pending checks (default 30). +set -euo pipefail + +pr=$1 +: "${GH_TOKEN:?}" "${MERGE_TOKEN:?}" "${GITHUB_REPOSITORY:?}" +deadline=$(( $(date +%s) + ${CHECKS_TIMEOUT_MINUTES:-30} * 60 )) + +state=$(gh pr view "$pr" --repo "$GITHUB_REPOSITORY" --json state --jq .state) +if [ "$state" != OPEN ]; then + echo "::error::Pull request #$pr is $state; the agent must leave merging to the workflow" >&2 + exit 1 +fi +head=$(gh pr view "$pr" --repo "$GITHUB_REPOSITORY" --json headRefOid --jq .headRefOid) + +while :; do + runs=$(gh api "repos/$GITHUB_REPOSITORY/commits/$head/check-runs?filter=latest&per_page=100") + pending=$(jq -r '[.check_runs[] | select(.status != "completed") | .name] | join(", ")' <<<"$runs") + bugbot=$(jq -r '[.check_runs[] | select(.name == "Cursor Bugbot")] | sort_by(.completed_at) | last | .status // "missing"' <<<"$runs") + if [ -z "$pending" ] && [ "$bugbot" != missing ]; then + break + fi + if [ "$(date +%s)" -ge "$deadline" ]; then + echo "::error::Checks on $head still pending: ${pending:-Cursor Bugbot has not started}" >&2 + exit 1 + fi + sleep 30 +done + +bugbot=$(jq -r '[.check_runs[] | select(.name == "Cursor Bugbot")] | sort_by(.completed_at) | last | .conclusion // ""' <<<"$runs") +failed=$(jq -r '[.check_runs[] | select(.conclusion | IN("success", "neutral", "skipped") | not) | "\(.name)=\(.conclusion)"] | join(", ")' <<<"$runs") +status=$(gh api "repos/$GITHUB_REPOSITORY/commits/$head/status") +if [ "$bugbot" != success ] || [ -n "$failed" ]; then + echo "::error::Not merging #$pr: Cursor Bugbot=${bugbot:-missing}; failed checks: ${failed:-none}" >&2 + exit 1 +fi +if [ "$(jq -r .total_count <<<"$status")" -gt 0 ] && [ "$(jq -r .state <<<"$status")" != success ]; then + echo "::error::Not merging #$pr: commit statuses are $(jq -r .state <<<"$status")" >&2 + exit 1 +fi + +GH_TOKEN=$MERGE_TOKEN gh pr merge "$pr" --repo "$GITHUB_REPOSITORY" --squash --delete-branch --match-head-commit "$head" +state=$(gh pr view "$pr" --repo "$GITHUB_REPOSITORY" --json state --jq .state) +if [ "$state" != MERGED ]; then + echo "::error::Pull request #$pr is $state after merging" >&2 + exit 1 +fi +echo "Merged #$pr at $head" diff --git a/.github/workflows/sandboxed-agent/mint-token.mjs b/.github/workflows/sandboxed-agent/mint-token.mjs new file mode 100644 index 0000000..597e5da --- /dev/null +++ b/.github/workflows/sandboxed-agent/mint-token.mjs @@ -0,0 +1,47 @@ +#!/usr/bin/env node + +// Prints a GitHub App installation token limited to one repository and a fixed set of +// permissions. The sbx daemon runs this on the runner whenever the sandbox's GitHub credential +// needs refreshing, so the private key never enters the sandbox. +// +// mint-token.mjs CONFIG_JSON +// +// CONFIG_JSON holds appId, installationId, repository, permissions, keyFile and tokensFile. +// Every token is appended to tokensFile so the workflow can revoke them when the job ends. + +import { createSign } from "node:crypto"; +import { appendFileSync, readFileSync } from "node:fs"; + +const config = JSON.parse(readFileSync(process.argv[2], "utf8")); +const { appId, installationId, repository, permissions, keyFile, tokensFile } = config; +if (!appId || !installationId || !repository || !permissions || !keyFile || !tokensFile) { + throw new Error("appId, installationId, repository, permissions, keyFile and tokensFile are required"); +} + +const now = Math.floor(Date.now() / 1000); +const encode = (value) => Buffer.from(JSON.stringify(value)).toString("base64url"); +const unsigned = `${encode({ alg: "RS256", typ: "JWT" })}.${encode({ iat: now - 60, exp: now + 9 * 60, iss: appId })}`; +const signer = createSign("RSA-SHA256"); +signer.update(unsigned); +const jwt = `${unsigned}.${signer.sign(readFileSync(keyFile, "utf8").replaceAll("\\n", "\n"), "base64url")}`; + +const response = await fetch(`https://api.github.com/app/installations/${installationId}/access_tokens`, { + method: "POST", + headers: { + Accept: "application/vnd.github+json", + Authorization: `Bearer ${jwt}`, + "X-GitHub-Api-Version": "2022-11-28", + "User-Agent": "sandboxed-agent", + }, + body: JSON.stringify({ repositories: [repository], permissions }), +}); +if (!response.ok) { + throw new Error(`GitHub App token request failed with HTTP ${response.status}`); +} +const result = await response.json(); +if (!result.token) { + throw new Error("GitHub App token response had no token"); +} +appendFileSync(tokensFile, `${result.token}\n`, { mode: 0o600 }); +process.stderr.write(`minted a token for ${repository} with ${JSON.stringify(result.permissions)}\n`); +process.stdout.write(result.token); diff --git a/.github/workflows/sandboxed-agent/sandbox-setup.sh b/.github/workflows/sandboxed-agent/sandbox-setup.sh new file mode 100644 index 0000000..b3c2971 --- /dev/null +++ b/.github/workflows/sandboxed-agent/sandbox-setup.sh @@ -0,0 +1,67 @@ +#!/bin/bash +# Runs inside the sandbox, as its agent user, before the caller's setup. Installs Node.js, Pi and +# Pi Web Access, and the gh and trigger-bugbot helpers, and sets the commit identity. +# +# Needs CHECKS_RELAY_URL, the runner's read-only check-run relay. +set -euo pipefail + +: "${CHECKS_RELAY_URL:?}" +export PI_TELEMETRY=0 + +# Node.js 22, verified against nodejs.org's checksums. +tmp=$(mktemp -d) +base=https://nodejs.org/dist/latest-v22.x +curl -fsSL "$base/SHASUMS256.txt" -o "$tmp/SHASUMS256.txt" +tarball=$(awk '/linux-x64\.tar\.gz$/ { print $2 }' "$tmp/SHASUMS256.txt") +curl -fsSL "$base/$tarball" -o "$tmp/$tarball" +(cd "$tmp" && grep " $tarball\$" SHASUMS256.txt | sha256sum -c --quiet) +sudo tar -xzf "$tmp/$tarball" -C /usr/local --strip-components=1 +rm -rf "$tmp" +node --version + +sudo npm install -g --ignore-scripts --silent @earendil-works/pi-coding-agent +pi install npm:pi-web-access@latest +pi --version + +git config --global user.name "kernel-internal[bot]" +git config --global user.email "260533166+kernel-internal[bot]@users.noreply.github.com" + +# The sandbox's GitHub credential is the app's, which can't read check runs. `gh pr checks` +# reads them from the relay instead; every other gh command is passed through. +sudo tee /usr/local/bin/gh >/dev/null < 0' <<<"\$runs" >/dev/null; then + exit 8 + fi + jq -e '[.check_runs[] | select(.conclusion | IN("success", "neutral", "skipped") | not)] | length == 0' <<<"\$runs" >/dev/null + exit +fi +exec /usr/bin/gh "\$@" +EOF + +sudo tee /usr/local/bin/trigger-bugbot >/dev/null <<'EOF' +#!/bin/bash +set -euo pipefail +: "${CURSOR_API_KEY:?CURSOR_API_KEY is not set in this sandbox}" +pr_number="${1:-}" +if [ -z "$pr_number" ] || [[ "$pr_number" = -* ]]; then + echo "A pull request number is required" >&2 + exit 1 +fi +pr_url="$(gh pr view "$pr_number" --json url --jq .url)" +response="$(curl --silent --show-error --fail-with-body \ + --request POST \ + --url https://api.cursor.com/bugbot/review \ + --user "$CURSOR_API_KEY:" \ + --header 'Content-Type: application/json' \ + --data "$(jq -cn --arg prUrl "$pr_url" '{prUrl: $prUrl}')")" +jq -e '.outcome == "success"' <<<"$response" >/dev/null +jq -r '"Queued Cursor Bugbot review (request_id: \(.request_id))"' <<<"$response" +EOF +sudo chmod 755 /usr/local/bin/gh /usr/local/bin/trigger-bugbot diff --git a/.github/workflows/vuln-remediation.yml b/.github/workflows/vuln-remediation.yml index f0bdddd..8b99906 100644 --- a/.github/workflows/vuln-remediation.yml +++ b/.github/workflows/vuln-remediation.yml @@ -43,15 +43,18 @@ jobs: steps: - name: Generate app token id: app-token - uses: actions/create-github-app-token@v1.12.0 + uses: actions/create-github-app-token@v3.3.0 with: app-id: ${{ secrets.ADMIN_APP_ID }} private-key: ${{ secrets.ADMIN_APP_PRIVATE_KEY }} + permission-contents: read - name: Checkout repository uses: actions/checkout@v4.4.0 with: token: ${{ steps.app-token.outputs.token }} + # The Socket CLI installed and run below never needs git credentials. + persist-credentials: false - name: Install Socket CLI run: npm install -g @socketsecurity/cli @@ -242,7 +245,7 @@ jobs: - name: Generate private module read token id: read-token if: steps.check.outputs.skip != 'true' - uses: actions/create-github-app-token@v1.12.0 + uses: actions/create-github-app-token@v3.3.0 with: app-id: ${{ secrets.ADMIN_APP_ID }} private-key: ${{ secrets.ADMIN_APP_PRIVATE_KEY }} @@ -699,7 +702,7 @@ jobs: - name: Generate app token id: app-token - uses: actions/create-github-app-token@v1.12.0 + uses: actions/create-github-app-token@v3.3.0 with: app-id: ${{ secrets.ADMIN_APP_ID }} private-key: ${{ secrets.ADMIN_APP_PRIVATE_KEY }} diff --git a/README.md b/README.md index c63c781..372711f 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,52 @@ input. It must be an `anthropic/` or `openai/` model. There is no API key to pas [`llm-credentials`](#llm-credentials-action) action exchanges the job's GitHub OIDC token for short-lived provider credentials, which is why the caller grants `id-token: write`. +### `sandboxed-agent.yml` + +Runs Pi with `--approve` against the caller's repository inside a +[Docker Sandbox](https://docs.docker.com/ai/sandboxes/): a microVM with its own kernel, filesystem +and Docker daemon, on the GitHub-hosted runner. The agent has sudo and Docker inside the sandbox, +and no credentials. The sandbox proxy adds them to outbound requests: + +- **GitHub:** kernel-internal installation tokens, limited to the caller's repository and + `app-permissions`. They are minted on the runner from a key file the sandbox can't reach. +- **The model:** OpenAI or OpenRouter credentials from workload identity federation. + +The agent pushes branches and opens pull requests through the proxy, and reads check runs +through a read-only relay. With `merge: true` it ends by writing `ready:`, and the workflow +merges only after Cursor Bugbot and every other check pass on that pull request's head commit. + +```yaml +jobs: + update: + permissions: + actions: read + checks: read + contents: read + pull-requests: read + statuses: read + id-token: write + uses: kernel/security-workflows/.github/workflows/sandboxed-agent.yml@main + with: + prompt-file: .github/workflows/my-agent-prompt.md # ${OUTCOME_FILE} is substituted + app-permissions: '{"contents":"write","pull_requests":"write"}' + merge: true + evergreen-branch: automation/my-agent + setup: | # optional, runs in the sandbox + curl -LsSf https://astral.sh/uv/install.sh | sudo env UV_INSTALL_DIR=/usr/local/bin sh + secrets: + ADMIN_APP_ID: ${{ secrets.ADMIN_APP_ID }} + ADMIN_APP_PRIVATE_KEY: ${{ secrets.ADMIN_APP_PRIVATE_KEY }} + DOCKER_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} # sbx needs a signed-in Docker account + DOCKER_PAT: ${{ secrets.DOCKERHUB_TOKEN }} + AGENT_SECRETS: | # optional NAME=value lines + CURSOR_API_KEY=${{ secrets.CURSOR_API_KEY }} +``` + +The prompt tells the agent to write `no-updates`, `ready:` (with `merge: true`) or +`merged:` to `${OUTCOME_FILE}`. Anthropic models aren't supported yet: their federation +hands the agent an identity token to exchange itself, which the proxy can't do for it. + ## Actions ### `actions-lock-check.yml` diff --git a/scripts/test_sandboxed_agent.py b/scripts/test_sandboxed_agent.py new file mode 100644 index 0000000..d0b0057 --- /dev/null +++ b/scripts/test_sandboxed_agent.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""Credential-boundary and merge-gate tests for .github/workflows/sandboxed-agent.yml.""" +from __future__ import annotations + +import json +import os +import subprocess +import tempfile +import unittest +from pathlib import Path + +import yaml + +ROOT = Path(__file__).resolve().parents[1] +WORKFLOW = yaml.safe_load((ROOT / ".github/workflows/sandboxed-agent.yml").read_text()) +JOB = WORKFLOW["jobs"]["agent"] +MERGE_GATE = ROOT / ".github/workflows/sandboxed-agent/merge-gate.sh" + + +def step(name: str) -> dict: + for entry in JOB["steps"]: + if entry.get("name") == name: + return entry + raise AssertionError(f"missing step: {name}") + + +class CredentialBoundaryTest(unittest.TestCase): + def test_app_key_reaches_only_the_minting_steps(self): + users = {entry["name"] for entry in JOB["steps"] if "ADMIN_APP_PRIVATE_KEY" in yaml.safe_dump(entry)} + self.assertEqual(users, {"Agent GitHub credentials", "Merge token"}) + + def test_sandbox_steps_get_no_github_credential(self): + for entry in JOB["steps"]: + text = yaml.safe_dump(entry) + if "sbx exec" in entry.get("run", "") or "sbx create" in entry.get("run", ""): + self.assertNotRegex(text, r"secrets\.ADMIN|github\.token|outputs\.token", entry["name"]) + + def test_state_is_outside_the_workspace_the_sandbox_reads(self): + self.assertEqual(JOB["env"]["STATE"], "${{ github.workspace }}/../sandboxed-agent") + run = step("Agent GitHub credentials")["run"] + self.assertIn('> "$STATE/app-key.pem"', run) + self.assertIn("umask 077", run) + + def test_agent_token_is_limited_to_the_caller_repository(self): + run = step("Agent GitHub credentials")["run"] + self.assertIn('--arg repository "${GITHUB_REPOSITORY#*/}"', run) + self.assertIn("--argjson permissions \"$APP_PERMISSIONS\"", run) + self.assertIn("sbx secret set github --command", run) + + def test_job_token_is_read_only(self): + self.assertEqual( + JOB["permissions"], + {"actions": "read", "checks": "read", "contents": "read", "pull-requests": "read", "statuses": "read", "id-token": "write"}, + ) + + def test_merge_token_only_for_a_ready_outcome(self): + merge = step("Merge token") + self.assertEqual(merge["if"], "inputs.merge && startsWith(steps.read-outcome.outputs.outcome, 'ready:')") + self.assertNotIn("repositories", merge["with"]) + + def test_teardown_always_runs_and_revokes(self): + teardown = step("Tear down") + self.assertEqual(teardown["if"], "always()") + self.assertIn("installation/token", teardown["run"]) + self.assertIn("sbx rm --force", teardown["run"]) + + +class MergeGateTest(unittest.TestCase): + HEAD = "a" * 40 + + def run_gate(self, *, state="OPEN", runs, statuses=None, after_merge="MERGED"): + with tempfile.TemporaryDirectory() as tmp: + tmp = Path(tmp) + (tmp / "runs.json").write_text(json.dumps({"check_runs": runs})) + (tmp / "status.json").write_text(json.dumps(statuses or {"total_count": 0, "state": "pending"})) + (tmp / "state").write_text(state) + gh = tmp / "gh" + gh.write_text(f"""#!/bin/bash +echo "GH_TOKEN=$GH_TOKEN $*" >> {tmp}/calls +case "$*" in + "pr view"*"--jq .state") cat {tmp}/state ;; + "pr view"*"--jq .headRefOid") echo {self.HEAD} ;; + api*check-runs*) cat {tmp}/runs.json ;; + api*/status) cat {tmp}/status.json ;; + "pr merge"*) echo {after_merge} > {tmp}/state ;; +esac +""") + gh.chmod(0o755) + (tmp / "sleep").write_text("#!/bin/bash\nexit 0\n") + (tmp / "sleep").chmod(0o755) + env = { + **os.environ, + "PATH": f"{tmp}:{os.environ['PATH']}", + "GH_TOKEN": "read-token", + "MERGE_TOKEN": "merge-token", + "GITHUB_REPOSITORY": "kernel/example", + "CHECKS_TIMEOUT_MINUTES": "0", + } + result = subprocess.run(["bash", str(MERGE_GATE), "7"], env=env, capture_output=True, text=True) + calls = (tmp / "calls").read_text() if (tmp / "calls").exists() else "" + return result, calls + + def run_(self, name, conclusion="success", status="completed", completed_at="2026-01-01T00:00:00Z"): + return {"name": name, "status": status, "conclusion": conclusion, "completed_at": completed_at} + + def test_merges_when_bugbot_and_checks_pass(self): + result, calls = self.run_gate(runs=[self.run_("Cursor Bugbot"), self.run_("test")]) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn(f"GH_TOKEN=merge-token pr merge 7 --repo kernel/example --squash --delete-branch --match-head-commit {self.HEAD}", calls) + self.assertNotIn("GH_TOKEN=merge-token api", calls) + + def test_refuses_without_a_green_bugbot(self): + for runs in ( + [self.run_("test")], + [self.run_("Cursor Bugbot", conclusion="neutral"), self.run_("test")], + [self.run_("Cursor Bugbot", conclusion="failure")], + ): + result, calls = self.run_gate(runs=runs) + self.assertEqual(result.returncode, 1) + self.assertNotIn("pr merge", calls) + + def test_refuses_with_a_failing_or_pending_check(self): + for runs in ( + [self.run_("Cursor Bugbot"), self.run_("test", conclusion="failure")], + [self.run_("Cursor Bugbot"), self.run_("test", status="in_progress", conclusion=None)], + ): + result, calls = self.run_gate(runs=runs) + self.assertEqual(result.returncode, 1) + self.assertNotIn("pr merge", calls) + + def test_refuses_with_failing_commit_statuses(self): + result, calls = self.run_gate(runs=[self.run_("Cursor Bugbot")], statuses={"total_count": 1, "state": "failure"}) + self.assertEqual(result.returncode, 1) + self.assertNotIn("pr merge", calls) + + def test_refuses_a_pull_request_the_agent_already_merged(self): + result, calls = self.run_gate(state="MERGED", runs=[self.run_("Cursor Bugbot")]) + self.assertEqual(result.returncode, 1) + self.assertNotIn("pr merge", calls) + + +if __name__ == "__main__": + unittest.main()