diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index f0694d4..8c4d9f0 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -25,6 +25,10 @@ jobs: run: shellcheck -S warning lib/pgrun-ci tests/*.sh - name: database action run: node --test tests/database.test.js + - name: migration verification (fake pgrun) + run: bash tests/test_verify.sh + - name: public-repository guard + run: bash tests/test_public_guard.sh - name: python syntax run: python3 -m py_compile lib/pgrun_profile.py - name: profiler diff --git a/README.md b/README.md index f05c207..e25d923 100644 --- a/README.md +++ b/README.md @@ -177,6 +177,16 @@ Your whole test suite, in parallel. Each worker gets its own empty branch with t Don't point your ordinary suite at production-like data: most tests assume empty tables. Write tests for populated data, such as "every model loads its newest rows" or "this report runs", and run them here. +## Migration verification with PgBot (opt-in) + +Set `verify: true` to verify the migration before the run. `pgrun bot verify` runs it on its own disposable PostgreSQL branch of the Safe Copy, and on a PGX branch too. PgBot then reviews the schema change: table rewrites, blocking index builds, `SET NOT NULL`, drops, renames, type changes. + +The summary separates the outcomes: success, informational warnings, dangerous operations (with PgBot's advice), confirmed failures, unsupported on PGX, incomplete reviews and infrastructure errors. `verify-block-on` chooses which of them fail the step; by default `fail,dangerous,incomplete,error`. + +It verifies one migration against the Safe Copy baseline. It does not detect conflicts between parallel migrations from different pull requests or agents against a changing production schema. + +Inputs, verdicts, outputs and how to get the CLI: [docs/verify.md](docs/verify.md). + ## Options | Input | Default | | @@ -198,9 +208,16 @@ Don't point your ordinary suite at production-like data: most tests assume empty | `ttl` | `1h` | Branch lifetime if a runner dies. PGRun caps CI-token branches at `6h`. | | `snapshot-warn-hours` / `snapshot-max-hours` | `24` / `720` | Warn, then fail, on an old Safe Copy. | | `profile-max-exact-rows` / `profile-budget` / `profile-statement-timeout` | `5000000` / `900` / `120` | Bounds for the data checks. | -| `allow-public-repository` | `false` | Production-like mode refuses to run in a public repository, whose logs anyone can read. | - -Output: `result` (`PASS` or `FAIL`). +| `allow-public-repository` | `false` | Production-like mode refuses to run in a public repository, whose logs anyone can read. Verification refuses as well. | +| `verify` | `false` | `true`: PgBot migration verification before the run ([docs/verify.md](docs/verify.md)). | +| `verify-command` | the migrate command | The command verified. | +| `verify-compare-pgx` | `true` | Also run it on PGX and compare schemas. | +| `verify-fail-on` | `critical` | Finding severity that counts as dangerous: `critical`, `warning`, `none`. | +| `verify-block-on` | `fail,dangerous,incomplete,error` | Verdict categories that fail the step, or `none`. | + +Outputs: +- `result`: `PASS` or `FAIL`. +- With `verify: true`: `verify-verdict`, `verify-blocking`, `verify-categories` and `verify-report` (the path of the JSON report). Services and system packages your app needs (Redis, `libvips`, …) stay ordinary steps in your job before this one. The action uses whatever the job provides. diff --git a/action.yml b/action.yml index 057eae4..18c709b 100644 --- a/action.yml +++ b/action.yml @@ -88,11 +88,42 @@ inputs: api-url: description: PGRun API URL. default: https://app.pgrun.dev + verify: + description: >- + true runs PgBot migration verification (pgrun bot verify) before the mode's run: the migration on + disposable PostgreSQL (and PGX) branches of the Safe Copy, its schema change reviewed. Off by default. + default: "false" + verify-command: + description: Migration command to verify. Default — the resolved migrate-command (Rails — bin/rails db:migrate). + default: "" + verify-compare-pgx: + description: Also run the migration on a PGX branch and compare its schema with PostgreSQL's. + default: "true" + verify-fail-on: + description: "Schema-review severity that counts as dangerous: critical, warning or none." + default: critical + verify-block-on: + description: >- + Verdict categories that fail the step (comma list of fail, dangerous, unsupported, incomplete, + error, warning; or none). warning and unsupported only report by default. + default: fail,dangerous,incomplete,error outputs: result: description: PASS or FAIL value: ${{ steps.run.outcome == 'success' && 'PASS' || 'FAIL' }} + verify-verdict: + description: "With verify: true — pass, warning, dangerous, fail, unsupported, incomplete or error." + value: ${{ steps.verify.outputs.verdict }} + verify-blocking: + description: "With verify: true — true when a category in verify-block-on applied." + value: ${{ steps.verify.outputs.blocking }} + verify-categories: + description: "With verify: true — every category that applied, comma-separated." + value: ${{ steps.verify.outputs.categories }} + verify-report: + description: "With verify: true — path of the pgrun-verify JSON report on the runner (no URL or password in it)." + value: ${{ steps.verify.outputs.report }} runs: using: composite @@ -115,6 +146,29 @@ runs: bundler-cache: true working-directory: ${{ inputs.working-directory }} + # Opt-in. pgrun creates and deletes its own verification branches; a + # blocking verdict stops here, before the mode's run. + - name: PGRun — verify the migration + id: verify + if: inputs.verify == 'true' + shell: bash + env: + PGRUN_API_TOKEN: ${{ inputs.token }} + PGRUN_API_URL: ${{ inputs.api-url }} + PGRUN_IN_API_URL: ${{ inputs.api-url }} + PGRUN_IN_PROJECT: ${{ inputs.project }} + PGRUN_IN_MIGRATE_COMMAND: ${{ inputs.migrate-command }} + PGRUN_IN_VERIFY_COMMAND: ${{ inputs.verify-command }} + PGRUN_IN_VERIFY_COMPARE_PGX: ${{ inputs.verify-compare-pgx }} + PGRUN_IN_VERIFY_FAIL_ON: ${{ inputs.verify-fail-on }} + PGRUN_IN_VERIFY_BLOCK_ON: ${{ inputs.verify-block-on }} + PGRUN_IN_WORKING_DIRECTORY: ${{ inputs.working-directory }} + PGRUN_IN_FRAMEWORK: ${{ inputs.framework }} + PGRUN_IN_RAILS_ENV: ${{ inputs.rails-env }} + PGRUN_IN_TTL: ${{ inputs.ttl }} + PGRUN_IN_ALLOW_PUBLIC_REPOSITORY: ${{ inputs.allow-public-repository }} + run: '"$GITHUB_ACTION_PATH/lib/pgrun-ci" verify' + - name: PGRun — ${{ inputs.mode }} id: run shell: bash diff --git a/database/lib.js b/database/lib.js index 0238fd5..4e27bec 100644 --- a/database/lib.js +++ b/database/lib.js @@ -89,7 +89,7 @@ function client(base, token) { if (res.status >= 500 && attempt < tries) { await pause(attempt * 2); continue; } let json = {}; try { json = await res.json(); } catch { /* empty or not JSON */ } - return { status: res.status, json }; + return { status: res.status, json, retryAfter: res.headers.get('retry-after') }; } catch (e) { lastErr = e; if (attempt < tries) await pause(attempt * 2); @@ -301,17 +301,29 @@ async function createBranches(api, project, i, ledger, deadline) { let held = []; let seq = 0; let waited = 0; - const body = (name) => ({ name, ttl: i.ttl, ...(i.data === 'schema-only' ? { template: i.template } : {}) }); + // Sprint 2026-11 §1B: the engine travels WITH the create, so the server + // decides it before provisioning (no create-then-check). The branch name is + // unique per run/attempt/sequence, so it doubles as the idempotency key: a + // retried POST returns the branch the first one made (200, replayed). + const body = (name) => ({ + name, ttl: i.ttl, request_id: name, + ...(i.engine !== 'any' ? { engine: i.engine } : {}), + ...(i.data === 'schema-only' ? { template: i.template } : {}), + }); while (held.length < i.branches) { seq += 1; // never reuse a name: a released one may still be deleting const name = `${ledger.data.prefix}-${seq}`; ledger.add(name); const r = await api('POST', `/api/v1/projects/${enc(project)}/branches`, body(name)); - if (r.status === 201) { held.push(name); continue; } + if (r.status === 201 || (r.status === 200 && r.json && r.json.replayed)) { held.push(name); continue; } // A 4xx answer is a refusal: nothing was created under that name. if (r.status >= 400 && r.status < 500) ledger.remove([name]); const msg = message(r); - const retryable = (r.status === 422 && QUOTA.test(msg)) || (r.status === 409 && r.json.error === 'template_not_ready') || + // Admission control (server 2026-11-14, PGRUN_ADMISSION_CONTROL): 429 capacity_busy means the + // host is momentarily full and nothing was created; wait what the server asks (Retry-After), + // within capacity-wait. 503 capacity_unavailable stays fatal: no host can ever take it. + const busy = r.status === 429 && r.json && r.json.error === 'capacity_busy'; + const retryable = busy || (r.status === 422 && QUOTA.test(msg)) || (r.status === 409 && r.json.error === 'template_not_ready') || (r.status === 422 && /being refreshed/.test(msg)); if (!retryable) throw new Failure(`creating a branch failed (${r.status}): ${msg}`); if (waited >= i.capacityWait) { @@ -324,7 +336,10 @@ async function createBranches(api, project, i, ledger, deadline) { ledger.remove(held.filter((_, n) => results[n] !== 'failed')); held = []; } - const s = 10 + Math.floor(Math.random() * 11); + const asked = busy ? Number(r.retryAfter || (r.json && r.json.retry_after_s)) : NaN; + const s = Number.isFinite(asked) && asked > 0 + ? Math.min(60, Math.max(5, Math.ceil(asked))) + : 10 + Math.floor(Math.random() * 11); await pause(s); waited += s; } diff --git a/docs/security.md b/docs/security.md index 6ca4f16..1d3ca6e 100644 --- a/docs/security.md +++ b/docs/security.md @@ -58,6 +58,7 @@ This is GitHub's model for every Actions secret, and no YAML condition changes i ## Supply chain - The pgrun CLI is downloaded from its GitHub release and checked against a SHA-256 pinned in the action. A mismatch stops the run before the CLI is unpacked. +- Migration verification (`verify: true`) uses a pgrun CLI already on the runner. The action never downloads an unpinned one, and no release with `bot verify` is pinned yet. pgbot, when missing, comes from `pgrun bot install`, which verifies pgrun's pinned SHA-256. The migration runs under `env -u PGRUN_API_TOKEN`. Its output is redacted of URLs and the token, and printed between `::stop-commands::` markers so it cannot issue workflow commands. - `ruby/setup-ruby` is pinned by commit. - The action only sends the token to an `https://` API URL (or localhost, for tests). - The action itself should be pinned by commit SHA in security-sensitive repositories. diff --git a/docs/verify.md b/docs/verify.md new file mode 100644 index 0000000..97bc596 --- /dev/null +++ b/docs/verify.md @@ -0,0 +1,88 @@ +# Migration verification (`verify: true`) + +Opt-in, off by default. With `verify: true` the action runs +`pgrun bot verify --json` before the mode's run (production-like or fast): + +1. pgrun creates its own disposable branches of the project's **Safe Copy**: a PostgreSQL branch (the canonical engine) and, with `verify-compare-pgx: true`, a PGX branch. +2. It runs your migration command on them, with `DATABASE_URL` set to the branch. The PGRun token is not in the migration's environment. +3. PgBot snapshots and lints the schema before and after, and classifies what the migration did: table rewrites, blocking index builds, `SET NOT NULL`, drops, renames, type changes. +4. With PGX, the two resulting schemas are compared. +5. pgrun deletes its branches on every exit path. Their TTL (`ttl`) is the backstop. + +The action reads pgrun's report and turns it into a job summary, annotations and step outputs. A blocking verdict fails the step, and the mode's run is skipped. + +```yaml + - uses: pgrundev/ci-action@ + with: + token: ${{ secrets.PGRUN_API_TOKEN }} + verify: true + # verify-command: npx prisma migrate deploy # default: the migrate command + # verify-block-on: fail,dangerous,incomplete,error +``` + +## What it does not do + +It verifies **one** migration against the project's Safe Copy baseline. It does **not** detect conflicts between parallel migrations from different pull requests or agents against a changing production schema, for example two pull requests that each pass alone but conflict once both are merged. That check is not implemented. + +## Verdicts + +Every category that applied is listed. A run can be both `dangerous` and `warning`. The verdict is the highest-precedence one: + +| Verdict | Summary section | Meaning | Blocks by default | +|---|---|---|---| +| `fail` | ❌ Confirmed failure | The migration exited non-zero on canonical PostgreSQL. | yes | +| `dangerous` | ⚠️ Dangerous operations | The schema review found findings at or above `verify-fail-on`. Each is listed with its advice. | yes | +| `unsupported` | 🧪 Unsupported on PGX | PGX could not run the migration, produced a different schema, or was unavailable for the project. PostgreSQL was fine. | no | +| `incomplete` | ❓ Incomplete | The schema review or lint could not run, for example with an old pgbot. **Never a pass.** | yes | +| `error` | 🛠️ Infrastructure error | A branch never became ready, an API failure, a command that could not start, the CLI missing, or a report the action cannot read. | yes | +| `warning` | ℹ️ Informational warnings | Findings below the threshold, new lint findings, or a verification branch that could not be deleted. | no | +| `pass` | ✅ Success | None of the above. | — | + +`verify-block-on` sets which categories fail the step. The action passes it to pgrun and follows the report's `blocking` field. Warnings never fail the step unless you list `warning`. + +The action also reports these as `error`, decided by `verify-block-on` like any other: no pgrun with `bot verify` on the runner; pgrun exiting without one pgrun-verify 1.x JSON document on stdout; exit 2 (not authenticated or not configured); exit 64 (arguments rejected, usually a CLI that is too old). + +A refusal fails the step whatever `verify-block-on` says. The action refuses on: +- no token; +- `pull_request_target`; +- a public repository without `allow-public-repository: true`; +- an invalid input; +- no migration command; +- a Rails app without its bundle. + +## Inputs + +| Input | Default | | +|---|---|---| +| `verify` | `false` | `true` runs the verification step. | +| `verify-command` | the migrate command | The command pgrun runs on each verification branch (Rails: `bin/rails db:migrate`). It runs in `working-directory` with `RAILS_ENV` = `rails-env`. | +| `verify-compare-pgx` | `true` | Also run on PGX and compare schemas. | +| `verify-fail-on` | `critical` | Severity that makes a finding `dangerous`: `critical`, `warning` or `none`. | +| `verify-block-on` | `fail,dangerous,incomplete,error` | Comma list of categories that fail the step, or `none`. | + +Shared with the rest of the action: `token`, `project`, `api-url`, `ttl`, `working-directory`, `framework`, `rails-env`, `allow-public-repository`. + +## Outputs + +| Output | | +|---|---| +| `verify-verdict` | `pass`, `warning`, `dangerous`, `fail`, `unsupported`, `incomplete` or `error`. | +| `verify-blocking` | `true` or `false`. | +| `verify-categories` | Every category that applied, comma-separated. | +| `verify-report` | Path of the pgrun-verify JSON report on the runner, for `actions/upload-artifact` or your own checks. Connection URLs are redacted from it. Its directory is unique per run, so several runs on one runner never share it. | + +## Getting the CLI + +The action never downloads a CLI it can't check against a SHA-256 it pins. The first pgrun release with `bot verify` is not pinned yet. Until it is, install pgrun in a step before this one, at an exact version. For example, with the npm package, which brings PgBot along: + +```yaml + - run: npm install -g @pgrun/cli@ +``` + +If pgbot is missing, the action runs `pgrun bot install`. That installs pgrun's pinned pgbot release and verifies its SHA-256. + +## Cleanup + +pgrun deletes its verification branches itself, also when cancelled: the action forwards the signal and waits for it. A branch it could not delete is listed under **Verification branches** in the summary, with a warning annotation. Its TTL (`ttl`, default `1h`) expires it. + +The verification step never touches the branches of the production-like or fast run. Their cleanup step works as before. diff --git a/lib/pgrun-ci b/lib/pgrun-ci index e5a8f2a..45f9176 100755 --- a/lib/pgrun-ci +++ b/lib/pgrun-ci @@ -573,6 +573,244 @@ write_summary() { } >> "$summary" } +# ------------------------------------------------------------------ verify +# `pgrun-ci verify`: opt-in (verify: true). Runs `pgrun bot verify --json`, +# which makes its own disposable branches of the Safe Copy (PostgreSQL, plus +# PGX with verify-compare-pgx), runs the migration there, has pgbot review the +# schema change and deletes its branches. This step only reads the report. +# Everything it writes is in its own mktemp directory, so several runs on one +# runner never share a file, and it never touches the run step's state. +VERIFY_CATEGORIES="fail dangerous unsupported incomplete error warning" +VERIFY_DEFAULT_BLOCK_ON="fail,dangerous,incomplete,error" +# The first pgrun release with `bot verify` (pgrun-verify 1.x). Not released +# yet: until its version and checksums are pinned here, the CLI must already +# be on the runner (see docs/verify.md). Nothing unpinned is ever downloaded. +VERIFY_CLI_VERSION="" +verify_cli_sha256() { case "$1" in *) echo "" ;; esac; } + +# Redacts URLs and the token from a whole stream (sanitize keeps 40 lines). +redact() { + local s; s=$(sed -E 's#postgres(ql)?://[^ ]+##g; s/pgrun_(ci_)?[0-9a-f]{8,}//g') + [ -n "${PGRUN_API_TOKEN:-}" ] && s="${s//"$PGRUN_API_TOKEN"/}" + printf '%s\n' "$s" +} + +verify_in_list() { [[ ",$2," == *",$1,"* ]]; } + +# A refusal (guard or bad input): fails the step whatever block-on says. +verify_refuse() { + echo "::error title=PGRun verify::$*" + { echo "verdict=error"; echo "blocking=true"; echo "categories=error"; echo "report="; } >> "${GITHUB_OUTPUT:-/dev/null}" + { echo "## PGRun migration verification — refused"; echo; echo "> $*"; echo; } >> "$summary" + exit 1 +} + +# The report for a failure that left no pgrun-verify document: category error. +verify_synth() { # + jq -n --arg project "$project_in" --arg reason "$1" --arg fail_on "$v_fail_on" --arg block_on "$v_block_on" ' + ($block_on | if . == "none" then [] else split(",") end) as $b | + {kind: "pgrun-verify", version: "1.1.0", source: "pgrun-ci", project: $project, + verdict: "error", categories: ["error"], blocking: ($b | index("error") != null), + policy: {fail_on: $fail_on, block_on: $b}, reasons: [$reason], + summary: {critical: 0, warning: 0, info: 0, new_lint: 0}, cleanup: []}' > "$v_report" +} + +verify_cli() { # a pgrun with `bot verify` and a compatible pgbot; else the reason in $v_dir/why + local why="$v_dir/why" + if ! { command -v pgrun > /dev/null && pgrun bot status --json > "$v_dir/bot.json" 2>/dev/null \ + && jq -e 'type == "object" and has("installed")' "$v_dir/bot.json" > /dev/null 2>&1; }; then + if [ -z "$VERIFY_CLI_VERSION" ] || [ "$(uname -s)" != Linux ]; then + echo "no pgrun CLI with \`bot verify\` on this runner. Install pgrun (with PgBot) in a step before this one; the action downloads only a release whose SHA-256 it pins, and none is pinned yet." > "$why" + return 1 + fi + local arch name + case "$(uname -m)" in x86_64) arch=amd64 ;; aarch64|arm64) arch=arm64 ;; *) echo "unsupported runner architecture $(uname -m)" > "$why"; return 1 ;; esac + name="pgrun_${VERIFY_CLI_VERSION}_linux_${arch}.tar.gz" + mkdir -p "$v_dir/bin" + curl -fsSL --retry 3 -o "$v_dir/$name" "https://github.com/pgrundev/pgrun-cli/releases/download/v$VERIFY_CLI_VERSION/$name" \ + || { echo "could not download the pgrun CLI $VERIFY_CLI_VERSION" > "$why"; return 1; } + echo "$(verify_cli_sha256 "linux_$arch") $v_dir/$name" | sha256sum -c --quiet - > /dev/null 2>&1 \ + || { echo "pgrun CLI checksum mismatch — refusing to run it" > "$why"; return 1; } + tar -xzf "$v_dir/$name" -C "$v_dir/bin" pgrun + export PATH="$v_dir/bin:$PATH" + pgrun bot status --json > "$v_dir/bot.json" 2>/dev/null || { echo "pgrun $VERIFY_CLI_VERSION has no \`bot\` command" > "$why"; return 1; } + fi + if [ "$(jq -r '.installed' "$v_dir/bot.json")" != true ]; then + log "installing pgbot (pgrun bot install: pinned release, SHA-256 verified by pgrun)" + pgrun bot install > "$v_dir/bot-install.log" 2>&1 \ + || { echo "pgbot could not be installed: $(redact < "$v_dir/bot-install.log" | tail -3 | tr '\n' ' ')" > "$why"; return 1; } + fi +} + +verify_on_signal() { + trap '' INT TERM + echo "::warning title=PGRun verify::cancelled — pgrun deletes its verification branches" + # pgrun deletes its branches on a signal: give it the time to. + [ -n "$CHILD" ] && { kill -TERM "$CHILD" 2>/dev/null; wait "$CHILD" 2>/dev/null || true; } + exit 130 +} + +# Markdown for the job summary, from a pgrun-verify report. +VERIFY_SUMMARY_JQ=' +def md: tostring | gsub("[\r\n]+"; " ") | gsub("\\|"; "\\|") | gsub("<"; "<"); +def secs: if . == null then "—" elif . < 10000 then "\((. / 100 | floor) / 10)s" else "\(. / 1000 | floor)s" end; +def catlabel: {pass: "✅ Success", warning: "ℹ️ Informational warnings", dangerous: "⚠️ Dangerous operations", + fail: "❌ Confirmed failure", unsupported: "🧪 Unsupported on PGX", incomplete: "❓ Incomplete", + error: "🛠️ Infrastructure error"}[.] // (. | md); +def meaning: { + fail: "The migration exited non-zero on canonical PostgreSQL: it fails in production too.", + dangerous: "The schema review found operations at or above fail-on `\($fail_on)` — a table rewrite, a blocking index build, SET NOT NULL, a drop, a rename or a type change. They can lock or break production; see each finding and its advice.", + unsupported: "PGX could not run the migration, produced a different schema, or was unavailable for the project. PostgreSQL itself was fine.", + incomplete: "The schema review or lint could not run, so the migration was not reviewed. This is not a pass.", + error: "An infrastructure or tool error stopped the verification (a branch never ready, an API failure, the CLI missing or its report unreadable). Nothing is known about the migration.", + warning: "Informational only: findings below fail-on, new lint findings, or a verification branch that could not be deleted.", + pass: "The migration ran on PostgreSQL and the schema review found nothing at or above fail-on."}[.] // ""; +def run(r): if r == null then "—" else [ + (if r.branch then "branch `\(r.branch | md)`" else empty end), + (if r.engine then "on \(r.engine | md)" else empty end), + (if r.ready_ms != null then "ready in \(r.ready_ms | secs)" else empty end), + (if r.migration_exit_code != null then "migration exit \(r.migration_exit_code) in \(r.migrate_ms | secs)" else empty end), + (if r.unavailable != null then "unavailable: \(r.unavailable | (.message? // .error? // .) | if type == "string" then . else tojson end | md)" else empty end), + (if (r.error // "") != "" then "error: \(r.error | md)" else empty end)] | join(" · ") end; +(.categories // []) as $cats | (.policy.block_on // []) as $block | +"## PGRun migration verification — \(.verdict | catlabel)\(if .blocking then " (blocking)" else "" end)", +"", +"| | |", "|---|---|", +"| Project | \(if (.project // "") == "" then "the token'"'"'s project" else (.project | md) end) |", +"| Verdict | **\(.verdict | md)** |", +"| Categories | \($cats | map(catlabel) | join(", ")) |", +"| Blocking | \(if .blocking then "yes — \($cats | map(select(. as $c | $block | index($c))) | join(", "))" else "no" end) |", +"| Policy | fail-on `\(.policy.fail_on // $fail_on | md)` · block-on `\($block | if length == 0 then "none" else join(",") end | md)` |", +"| PostgreSQL run | \(run(.verification)) |", +(if .pgx != null or .pgx_compatible != null then "| PGX run | \(run(.pgx))\(if .pgx_compatible == true then " · compatible" elif .pgx_compatible == false then " · **not compatible**" else "" end) |" else empty end), +(if (.schema_review_skipped // "") != "" then "| Schema review | skipped: \(.schema_review_skipped | md) |" + elif .schema_review != null then "| Schema review | \(.schema_review.summary // .summary | "\(.critical // 0) critical, \(.warning // 0) warning, \(.info // 0) info") |" else empty end), +(if (.new_lint_findings // []) | length > 0 then "| New lint findings | \(.new_lint_findings | length) |" else empty end), +(if .pgbot_version then "| pgbot | \(.pgbot_version | md) |" else empty end), +(if .duration_ms != null then "| Duration | \(.duration_ms | secs) |" else empty end), +"", +($cats[] | "- **\(catlabel)** — \(meaning)"), +"", +(if (.reasons // []) | length > 0 then ("**Reasons**", "", (.reasons[] | "- \(md)"), "") else empty end), +(if (.schema_review.findings // []) | length > 0 then ( + "### Schema review findings", "", + "| Severity | Check | Object | What happens | Advice |", "|---|---|---|---|---|", + (.schema_review.findings[] | "| \(.severity | md) | `\(.id | md)` | \(.object // "" | md) | \(.detail // "" | md) | \(.advice // "" | md) |"), + "") else empty end), +(if (.new_lint_findings // []) | length > 0 then ( + "### New lint findings", "", + "| Severity | Check | Object | |", "|---|---|---|---|", + (.new_lint_findings[] | "| \(.severity | md) | `\(.id | md)` | \(.object // "" | md) | \(.title // "" | md) |"), + "") else empty end), +(if (.cleanup // []) | length > 0 then ( + "### Verification branches", "", + (.cleanup[] | "- `\(.branch | md)`: \(if .deleted then "deleted" elif .kept then "kept" else "⚠️ **not deleted** — its TTL (`\($ttl)`) expires it\(if (.error // "") != "" then ": \(.error | md)" else "" end)" end)"), + "") else empty end), +"> Verifies this migration against the project'"'"'s Safe Copy baseline. It does not detect conflicts between migrations of parallel pull requests or agents against a changing production schema.", +""' + +# Workflow annotations: error when the category blocks, warning when not. +VERIFY_ANNOTATE_JQ=' +def esc: tostring | gsub("%"; "%25") | gsub("\r"; "%0D") | gsub("\n"; "%0A"); +def rank: {critical: 3, warning: 2, info: 1}[.] // 0; +(.policy.block_on // []) as $block | (.policy.fail_on // $fail_on) as $fo | +def lvl($c): if $block | index($c) then "error" else "warning" end; +(if $fo == "none" then 99 else ($fo | rank) end) as $min | +(.reasons // []) as $why | +(if (.categories // []) | index("fail") then "::\(lvl("fail")) title=PGRun verify::confirmed failure on PostgreSQL: \($why | map(select(test("exited"))) | (first // "the migration failed") | esc)" else empty end), +(.schema_review.findings[]? | select((.severity | rank) >= $min) | + "::\(lvl("dangerous")) title=PGRun verify \(.id | esc | gsub("[:,]"; " "))::\(.object // "" | esc): \(.detail // "" | esc)\(if .advice then " — \(.advice | esc)" else "" end)"), +(.schema_review.findings[]? | select((.severity | rank) < $min and .severity == "warning") | + "::warning title=PGRun verify \(.id | esc | gsub("[:,]"; " "))::\(.object // "" | esc): \(.detail // "" | esc)"), +(if (.categories // []) | index("unsupported") then "::\(lvl("unsupported")) title=PGRun verify::unsupported on PGX: \(.pgx.error // ($why | join("; ")) | esc)" else empty end), +(if (.categories // []) | index("incomplete") then "::\(lvl("incomplete")) title=PGRun verify::incomplete — the migration was not reviewed: \(.schema_review_skipped // ($why | join("; ")) | esc)" else empty end), +(if (.categories // []) | index("error") then "::\(lvl("error")) title=PGRun verify::infrastructure error: \($why | join("; ") | esc)" else empty end), +(.cleanup[]? | select((.deleted | not) and (.kept | not)) | "::warning title=PGRun verify::verification branch \(.branch | esc) could not be deleted; its TTL expires it")' + +verify_main() { + v_fail_on="${PGRUN_IN_VERIFY_FAIL_ON:-critical}" + v_block_on="${PGRUN_IN_VERIFY_BLOCK_ON:-$VERIFY_DEFAULT_BLOCK_ON}"; v_block_on="${v_block_on// /}" + local compare="${PGRUN_IN_VERIFY_COMPARE_PGX:-true}" + [ -n "${PGRUN_API_TOKEN:-}" ] || verify_refuse "no PGRun token: the \`token\` input is empty. A pull request from a fork gets no secrets — run PGRun CI only for branches of this repository, and store the token as the PGRUN_API_TOKEN secret." + [ "${GITHUB_EVENT_NAME:-}" = pull_request_target ] && verify_refuse "refusing to run on pull_request_target: it would hand PR code the PGRun token. Use pull_request." + # Verification runs the migration on a branch of the sanitized Safe Copy. + if [ "${PGRUN_IN_ALLOW_PUBLIC_REPOSITORY:-false}" != true ] && [ -f "${GITHUB_EVENT_PATH:-}" ] \ + && [ "$(jq -r '.repository.private | if . == false then "false" else "" end' "$GITHUB_EVENT_PATH")" = false ]; then + verify_refuse "this repository is public: anyone can read its Actions logs, and verification runs your migration on a branch of the sanitized copy. Use a private repository, or set allow-public-repository: true to accept this." + fi + case "$v_fail_on" in critical|warning|none) ;; *) verify_refuse "verify-fail-on must be critical, warning or none (got: $v_fail_on)" ;; esac + if [ "$v_block_on" != none ]; then + local c; for c in ${v_block_on//,/ }; do + [[ " $VERIFY_CATEGORIES " == *" $c "* ]] || verify_refuse "verify-block-on: unknown category $c (use a comma list of: ${VERIFY_CATEGORIES// /, }; or none)" + done + fi + case "$compare" in true|false) ;; *) verify_refuse "verify-compare-pgx must be true or false" ;; esac + [[ "$ready_timeout" =~ ^[0-9]+$ ]] || verify_refuse "ready-timeout must be a number of seconds" + command -v jq > /dev/null || verify_refuse "jq is required (preinstalled on GitHub-hosted runners)" + + v_dir=$(mktemp -d "$runtime/verify.XXXXXX"); chmod 700 "$v_dir" + v_report="$v_dir/report.json" + cd "$workdir" + framework=$(cat "$runtime/framework" 2>/dev/null || echo none) + [ "$framework_in" != auto ] && framework="$framework_in" + local cmd="${PGRUN_IN_VERIFY_COMMAND:-}"; [ -n "$cmd" ] || cmd=$(migrate_cmd) + [ -n "$cmd" ] || verify_refuse "no migration command to verify: set verify-command (or migrate-command)." + # A missing bundle would read as a failed migration: say what it is instead. + if [ "$framework" = rails ] && ! { command -v bundle > /dev/null && bundle check > /dev/null 2>&1; }; then + verify_refuse "the bundle is not installed. Keep setup-ruby: true (default), or run bundle install before this step." + fi + + local why rc=0 + if ! verify_cli; then + verify_synth "$(cat "$v_dir/why")" + else + local args=(bot verify) + [ -n "$project_in" ] && args+=("$project_in") + args+=(--json --fail-on "$v_fail_on" --block-on "$v_block_on" --ttl "$ttl" --timeout "${ready_timeout}s") + [ "$compare" = true ] && args+=(--compare-pgx) + # The migration gets DATABASE_URL from pgrun, never the PGRun token. + args+=(-- env -u PGRUN_API_TOKEN RAILS_ENV="$rails_env" bash -c "$cmd") + log "verifying the migration: $cmd (fail-on $v_fail_on, block-on $v_block_on$([ "$compare" = true ] && echo ', compared on PGX'))" + trap verify_on_signal INT TERM + bg pgrun "${args[@]}" > "$v_dir/stdout" 2> "$v_dir/stderr" || rc=$? + trap - INT TERM + # Migration output is the customer's: no workflow command in it may run. + local stop; stop=$(od -An -N8 -tx1 /dev/urandom | tr -d ' \n') + echo "::group::pgrun bot verify output (exit $rc)"; echo "::stop-commands::$stop" + redact < "$v_dir/stderr"; echo "::$stop::"; echo "::endgroup::" + if jq -s -e 'length == 1 and (.[0] | type == "object" and .kind == "pgrun-verify" + and ((.version // "") | startswith("1.")) and (.verdict | type == "string") + and (.blocking | type == "boolean") and (.categories | type == "array"))' "$v_dir/stdout" > /dev/null 2>&1; then + # The report is kept for later steps: no URL in it, even from an error message. + jq 'walk(if type == "string" then gsub("postgres(ql)?://[^\\s\"]+"; "") else . end)' "$v_dir/stdout" > "$v_report" + local blocking; blocking=$(jq -r '.blocking' "$v_report") + if { [ "$blocking" = true ] && [ "$rc" = 0 ]; } || { [ "$blocking" = false ] && [ "$rc" != 0 ]; }; then + echo "::warning title=PGRun verify::pgrun exited $rc but its report says blocking=$blocking; the report decides" + fi + else + local tail_err; tail_err=$(redact < "$v_dir/stderr" | grep -v '^[[:space:]]*$' | tail -1 | cut -c1-300) + case "$rc" in + 2) why="pgrun is not authenticated or not configured (exit 2)${tail_err:+: $tail_err}" ;; + 64) why="pgrun rejected the verify arguments (exit 64) — the CLI may be too old for pgrun-verify 1.1${tail_err:+: $tail_err}" ;; + 127) why="pgrun could not be started (exit 127)" ;; + *) why="pgrun exited $rc without a pgrun-verify 1.x JSON report${tail_err:+: $tail_err}" ;; + esac + verify_synth "$why" + fi + fi + rm -f "$v_dir/stdout" + + local verdict blocking cats + verdict=$(jq -r '.verdict' "$v_report"); blocking=$(jq -r '.blocking' "$v_report") + cats=$(jq -r '.categories | join(",")' "$v_report") + { echo "verdict=$verdict"; echo "blocking=$blocking"; echo "categories=$cats"; echo "report=$v_report"; } >> "${GITHUB_OUTPUT:-/dev/null}" + jq -r --arg fail_on "$v_fail_on" --arg ttl "$ttl" "$VERIFY_SUMMARY_JQ" "$v_report" | redact >> "$summary" + jq -r --arg fail_on "$v_fail_on" "$VERIFY_ANNOTATE_JQ" "$v_report" | redact + log "verification: $verdict (categories: ${cats:-none}; blocking: $blocking) — report $v_report" + [ "$blocking" = true ] && exit 1 + exit 0 +} + # --------------------------------------------------------------------- main finish() { local code=$? @@ -602,7 +840,8 @@ main_run() { fi case "$mode" in production-like|fast) ;; *) die "mode must be production-like or fast (got: $mode)" ;; esac if [ "$mode" = production-like ] && [ "${PGRUN_IN_ALLOW_PUBLIC_REPOSITORY:-false}" != true ] \ - && [ -f "${GITHUB_EVENT_PATH:-}" ] && [ "$(jq -r '.repository.private // empty' "$GITHUB_EVENT_PATH")" = false ]; then + && [ -f "${GITHUB_EVENT_PATH:-}" ] && [ "$(jq -r '.repository.private | if . == false then "false" else "" end' "$GITHUB_EVENT_PATH")" = false ]; then + # (jq's `// empty` turns false into empty, so `.repository.private // empty` never matched.) die "this repository is public: anyone can read its Actions logs, and production-like mode runs your migrations and tests on the sanitized copy, which they could print. Use a private repository, or set allow-public-repository: true to accept this." fi case "$engine" in pgx|postgres|any) ;; *) die "engine must be pgx, postgres or any" ;; esac @@ -633,5 +872,6 @@ case "${1:-}" in rm -f "$runtime"/url_* [ -z "$(get summary_written)" ] && { [ -n "$(get result)" ] || record result CANCELLED; write_summary; record summary_written 1; } exit 0 ;; - *) echo "usage: pgrun-ci detect|run|cleanup" >&2; exit 64 ;; + verify) verify_main ;; + *) echo "usage: pgrun-ci detect|run|verify|cleanup" >&2; exit 64 ;; esac diff --git a/tests/database.test.js b/tests/database.test.js index b930ed6..f6bf53a 100644 --- a/tests/database.test.js +++ b/tests/database.test.js @@ -44,7 +44,20 @@ function stub(opts = {}) { if (u.pathname === '/api/v1/projects/shop/branches' && req.method === 'POST') { const b = JSON.parse(body); s.posts = (s.posts || 0) + 1; + (s.bodies = s.bodies || []).push(b); + if (s.replayFirst && s.posts === 1) { + s.seq += 1; + s.branches.set(b.name, { name: b.name, ttl: b.ttl, template: b.template, polls: 0, n: s.seq, deleted: false }); + s.created.push(b.name); + return send(200, { name: b.name, status: 'creating', replayed: true }); + } if (s.failPosts > 0) { s.failPosts -= 1; return send(503, { error: 'unavailable' }); } + if (s.busyPosts > 0) { + s.busyPosts -= 1; + res.writeHead(429, { 'Content-Type': 'application/json', 'Retry-After': '15' }); + return res.end(JSON.stringify({ error: 'capacity_busy', retry_after_s: 15, message: 'host is busy' })); + } + if (s.unavailablePosts) return send(503, { error: 'capacity_unavailable', message: 'no eligible host' }); if (live() >= s.quota) return send(422, { error: `branch quota reached (${live()}/${s.quota} live branches) — delete a branch` }); s.seq += 1; const row = { name: b.name, ttl: b.ttl, template: b.template, polls: 0, n: s.seq, deleted: false }; @@ -377,3 +390,46 @@ test('a server message cannot inject a workflow command', async () => { const lib = require('../database/lib'); assert.strictEqual(lib.sanitize('quota\n::add-mask::x\r\n::stop-commands::y'), 'quota ::add-mask::x ::stop-commands::y'); }); + +// Sprint 2026-11 §1B: the engine is decided by the server BEFORE provisioning, +// so the action must send it; the unique branch name is the idempotency key. +test('create sends the engine and a request_id; engine any sends no engine', async () => { + const api = await stub(); + const r = await run('main.js', job(), api, { project: 'shop', engine: 'pgx' }); + assert.strictEqual(r.code, 0, r.out); + assert.ok(api.bodies.length >= 1); + for (const b of api.bodies) { + assert.strictEqual(b.engine, 'pgx'); + assert.strictEqual(b.request_id, b.name); + } + const api2 = await stub({ engine: 'postgres' }); + const r2 = await run('main.js', job(), api2, { project: 'shop', engine: 'any' }); + assert.strictEqual(r2.code, 0, r2.out); + for (const b of api2.bodies) assert.strictEqual(b.engine, undefined); +}); + +test('a replayed create (200, replayed: true) counts as the branch it names', async () => { + const api = await stub(); + api.replayFirst = true; + const r = await run('main.js', job(), api, { project: 'shop' }); + assert.strictEqual(r.code, 0, r.out); + assert.strictEqual(api.posts, 1, 'no second POST after a replay'); +}); + +test('admission: 429 capacity_busy waits Retry-After and retries; 503 capacity_unavailable fails at once', async () => { + const api = await stub(); + api.busyPosts = 2; + const dir = job(); + const r = await run('main.js', dir, api, { 'project': 'shop' }); + assert.strictEqual(r.code, 0, r.out); + assert.strictEqual(api.posts, 3, 'two busy answers, then created'); + assert.strictEqual(api.created.length, 1, 'nothing extra was created'); + assert.match(r.out, /waiting for capacity/); + + const api2 = await stub(); + api2.unavailablePosts = true; + const r2 = await run('main.js', job(), api2, { 'project': 'shop' }); + assert.notStrictEqual(r2.code, 0); + assert.strictEqual(api2.posts, 1, 'a permanent refusal is not retried'); + assert.match(r2.out, /creating a branch failed \(503\)/); +}); diff --git a/tests/stub/verify/pgrun b/tests/stub/verify/pgrun new file mode 100755 index 0000000..7bad4ab --- /dev/null +++ b/tests/stub/verify/pgrun @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Fake pgrun for tests/test_verify.sh: `bot status`, `bot install` and +# `bot verify` only, no network. Records each call in $FAKE_DIR/calls (argv) +# and $FAKE_DIR/env (whether the token was in its environment, never its value). +# FAKE_DOC report template (__PROJECT__ is replaced); blocking, policy +# and the exit code are recomputed from --block-on like the CLI +# FAKE_EXIT force this exit code FAKE_RAW print this instead of a report +# FAKE_OLD a pgrun without `bot` FAKE_PGBOT=missing pgbot not installed +# FAKE_SLEEP seconds before answering FAKE_RUN_MIGRATION run the command after -- +# FAKE_LEAK print the token and a URL on stderr +set -euo pipefail +dir="${FAKE_DIR:?}" +printf '%s\n' "$*" >> "$dir/calls" +echo "token_in_env=$([ -n "${PGRUN_API_TOKEN:-}" ] && echo yes || echo no)" >> "$dir/env" +[ -n "${FAKE_OLD:-}" ] && [ "${1:-}" = bot ] && { echo "pgrun: unknown command \"bot\"" >&2; exit 64; } +case "${1:-} ${2:-}" in + "version "*) echo "pgrun 0.6.0" ;; + "bot status") + if [ "${FAKE_PGBOT:-}" = missing ] && [ ! -e "$dir/pgbot-installed" ]; then echo '{"installed":false,"min_version":"0.9.0"}' + else echo '{"installed":true,"min_version":"0.9.0","binary":{"version":"0.9.2"}}'; fi ;; + "bot install") touch "$dir/pgbot-installed"; echo "installed pgbot 0.9.2" ;; + "bot verify") + shift 2 + project=""; [ $# -gt 0 ] && [ "${1#-}" = "$1" ] && { project="$1"; shift; } + block_on="fail,dangerous,incomplete,error"; fail_on=critical; cmd=() + while [ $# -gt 0 ]; do + case "$1" in + --block-on) block_on="$2"; shift 2 ;; + --fail-on) fail_on="$2"; shift 2 ;; + --) shift; cmd=("$@"); break ;; + *) shift ;; + esac + done + [ -n "${FAKE_SLEEP:-}" ] && sleep "$FAKE_SLEEP" + if [ -n "${FAKE_RUN_MIGRATION:-}" ]; then + DATABASE_URL="postgres://verify:s3cretpw@branch.example/db" "${cmd[@]}" >&2 || true + fi + [ -n "${FAKE_LEAK:-}" ] && echo "debug: token=$PGRUN_API_TOKEN url=postgres://verify:s3cretpw@branch.example/db" >&2 + echo "pgrun: verifying ${project:-default}" >&2 + if [ -n "${FAKE_RAW+x}" ]; then printf '%s' "$FAKE_RAW"; exit "${FAKE_EXIT:-1}"; fi + doc=$(sed "s/__PROJECT__/${project:-default}/g" "${FAKE_DOC:?}" | jq -c --arg b "$block_on" --arg f "$fail_on" ' + ($b | if . == "none" then [] else split(",") end) as $bl + | .policy = {fail_on: $f, block_on: $bl} + | .blocking = ([.categories[] | select(. as $c | $bl | index($c))] | length > 0) + | .exit = (if .blocking | not then 0 elif [.categories[] | select(. as $c | $bl | index($c)) | select(. != "error")] | length == 0 then 3 else 1 end)') + jq 'del(.exit)' <<< "$doc" + exit "${FAKE_EXIT:-$(jq -r '.exit' <<< "$doc")}" ;; + *) echo "fake pgrun: unsupported: $*" >&2; exit 64 ;; +esac diff --git a/tests/test_lifecycle.sh b/tests/test_lifecycle.sh index fd4c0f6..d8d6824 100644 --- a/tests/test_lifecycle.sh +++ b/tests/test_lifecycle.sh @@ -9,6 +9,10 @@ admin="${TEST_PG_URL:?TEST_PG_URL is required}" export TEST_PG_URL="$admin" pass=0; fail=0 root=$(mktemp -d) +# Hermetic: never inherit the runner's own event file (on GitHub it describes THIS public +# repository, and the public-repository guard would refuse every production-like run). +echo '{"repository":{"private":true}}' > "$root/private_event.json" +export GITHUB_EVENT_PATH="$root/private_event.json" api_pid="" cleanup_all() { [ -n "$api_pid" ] && kill "$api_pid" 2>/dev/null diff --git a/tests/test_public_guard.sh b/tests/test_public_guard.sh new file mode 100755 index 0000000..f65aa95 --- /dev/null +++ b/tests/test_public_guard.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# The production-like run refuses a public repository unless allowed (the guard used +# `.repository.private // empty`, which never matches false — fixed 2026-11-14). +set -u +here="$(cd "$(dirname "$0")" && pwd)"; root="$(dirname "$here")" +pass=0; fail=0 +w=$(mktemp -d); trap 'rm -rf "$w"' EXIT +run() { # + echo "{\"repository\":{\"private\":$1}}" > "$w/event.json" + env -i PATH="$PATH" HOME="$w" RUNNER_TEMP="$w" GITHUB_WORKSPACE="$w" GITHUB_EVENT_PATH="$w/event.json" GITHUB_EVENT_NAME=pull_request \ + GITHUB_OUTPUT="$w/out" GITHUB_STEP_SUMMARY="$w/sum" PGRUN_API_TOKEN=pgrun_test PGRUN_IN_MODE=production-like \ + PGRUN_IN_ALLOW_PUBLIC_REPOSITORY="$2" PGRUN_API_URL=https://127.0.0.1:9 "$root/lib/pgrun-ci" run 2>&1 +} +out=$(run false false); grep -q "this repository is public" <<< "$out" && { pass=$((pass+1)); echo "ok public repo refused"; } || { fail=$((fail+1)); echo "FAIL public repo not refused"; echo "$out" | tail -3; } +out=$(run true false); grep -q "this repository is public" <<< "$out" && { fail=$((fail+1)); echo "FAIL private repo refused"; } || { pass=$((pass+1)); echo "ok private repo not refused by the guard"; } +out=$(run false true); grep -q "this repository is public" <<< "$out" && { fail=$((fail+1)); echo "FAIL allow-public-repository ignored"; } || { pass=$((pass+1)); echo "ok allow-public-repository: true accepted"; } +echo "public guard tests: $pass passed, $fail failed"; [ "$fail" -eq 0 ] diff --git a/tests/test_rails_local.sh b/tests/test_rails_local.sh index 78166e1..e5e5bcd 100755 --- a/tests/test_rails_local.sh +++ b/tests/test_rails_local.sh @@ -13,6 +13,10 @@ ci="$here/../lib/pgrun-ci" : "${RAILS_APP:?}" "${COPY_DB:?}" "${TEST_PG_URL:?}" export STUB_TEMPLATE_DB="$COPY_DB" PATH="$here/stub:$PATH" root=$(mktemp -d); pass=0; fail=0 +# Hermetic: never inherit the runner's own event file (on GitHub it describes THIS public +# repository, and the public-repository guard would refuse every production-like run). +echo '{"repository":{"private":true}}' > "$root/private_event.json" +export GITHUB_EVENT_PATH="$root/private_event.json" export STUB_DIR="$root/stub"; mkdir -p "$STUB_DIR" jq -n '{token: "good", status: 200, body: {project: {name: "app"}, source: {postgres_version: "18.1"}, protect: {status: "active", policy_version: 1}, safe_copy: {status: "ready", updated_at: (now | todate), policy_version: 1}, diff --git a/tests/test_verify.sh b/tests/test_verify.sh new file mode 100644 index 0000000..4d34430 --- /dev/null +++ b/tests/test_verify.sh @@ -0,0 +1,214 @@ +#!/usr/bin/env bash +# Tests for `pgrun-ci verify` (verify: true) against a fake pgrun that prints +# canned pgrun-verify reports. No network, no database. +set -uo pipefail +here=$(cd "$(dirname "$0")" && pwd) +ci="$here/../lib/pgrun-ci" +pass=0; fail=0 +root=$(mktemp -d) +trap 'rm -rf "$root"' EXIT +TOKEN="pgrun_ci_00c0ffee11223344aabbccdd" # a CI token's shape +FAKE_PATH="$here/stub/verify:$PATH" +mkdir -p "$root/app" + +ok() { pass=$((pass + 1)); echo "ok $1"; } +bad() { fail=$((fail + 1)); echo "FAIL $1"; [ -n "${2:-}" ] && sed 's/^/ /' <<< "$2"; } + +# doc [jq edit] — a pgrun-verify 1.1.0 report +doc() { + jq -n --arg v "$2" --argjson c "$3" '{ + kind: "pgrun-verify", version: "1.1.0", project: "__PROJECT__", verdict: $v, categories: $c, + blocking: false, policy: {fail_on: "critical", block_on: []}, reasons: [], + summary: {critical: 0, warning: 0, info: 0, new_lint: 0}, + verification: {engine: "postgres", requested_engine: "postgres", branch: "verify-__PROJECT__-pg", database: "app", + ready_ms: 1200, migrate_ms: 800, migration_exit_code: 0}, + schema_review: {findings: [], summary: {critical: 0, warning: 0, info: 0}}, new_lint_findings: [], + pgx: {engine: "pgx", requested_engine: "pgx", branch: "verify-__PROJECT__-pgx", ready_ms: 900, migrate_ms: 700, migration_exit_code: 0}, + pgx_compatible: true, + cleanup: [{branch: "verify-__PROJECT__-pg", deleted: true}, {branch: "verify-__PROJECT__-pgx", deleted: true}], + pgbot_version: "0.9.2", duration_ms: 5400}' | jq "${4:-.}" > "$1" +} + +CRIT='{id: "table_rewrite", severity: "critical", object: "public.orders", detail: "ALTER COLUMN TYPE rewrites the table under an ACCESS EXCLUSIVE lock", advice: "add a new column, backfill in batches, then swap"}' +WARN='{id: "index_not_concurrent", severity: "warning", object: "public.orders_idx", detail: "CREATE INDEX blocks writes", advice: "use CREATE INDEX CONCURRENTLY"}' +doc "$root/pass.json" pass '["pass"]' +doc "$root/warning.json" warning '["warning"]' ".new_lint_findings = [{id: \"no_pk\", severity: \"warning\", object: \"public.events\", title: \"table without a primary key\"}] | .summary.new_lint = 1 + | .cleanup[1] = {branch: \"verify-__PROJECT__-pgx\", deleted: false, error: \"503 from the API\"} + | .reasons = [\"verification branch verify-__PROJECT__-pgx could not be deleted (its TTL removes it): 503 from the API\"]" +doc "$root/dangerous.json" dangerous '["dangerous","warning"]' ".schema_review.findings = [$CRIT, $WARN] | .schema_review.summary = {critical: 1, warning: 1, info: 0} | .reasons = [\"schema review: 1 critical, 1 warning\"]" +doc "$root/fail.json" fail '["fail"]' '.verification.migration_exit_code = 1 | .verification.error = "PG::UndefinedTable: relation \"widgets\" does not exist" | .reasons = ["the migration exited 1 on postgres"]' +doc "$root/unsupported.json" unsupported '["unsupported"]' '.pgx_compatible = false | .pgx.migration_exit_code = 1 | .pgx.error = "PGX: unsupported statement CREATE EXTENSION" | .reasons = ["the migration exited 1 on PGX but 0 on PostgreSQL"]' +doc "$root/unavailable.json" unsupported '["unsupported"]' '.pgx_compatible = null | .pgx = {engine: "", requested_engine: "pgx", branch: "verify-__PROJECT__-pgx", unavailable: {error: "engine_unavailable", message: "PGX is not enabled for this project"}} | .reasons = ["PGX unavailable: PGX is not enabled for this project"]' +doc "$root/incomplete.json" incomplete '["incomplete"]' 'del(.schema_review) | .schema_review_skipped = "pgbot 0.8.0 has no `schema` command" | .reasons = ["schema review skipped: pgbot 0.8.0 has no `schema` command"]' +doc "$root/error.json" error '["error"]' '.verification = {engine: "", requested_engine: "postgres", branch: "verify-__PROJECT__-pg", ready_ms: 300000, error: "branch was not ready after 300s"} | del(.pgx, .pgx_compatible, .schema_review) | .reasons = ["branch verify-__PROJECT__-pg was not ready after 300s"]' + +# run_verify [VAR=value ...] — the verify step as the composite runs it. +# RUNNER_TEMP is shared by default (one job); outputs and summary are per run. +# Hermetic: never inherit the runner's own event (on GitHub it describes THIS public repository, +# and the public-repository guard would refuse every run). Tests of the guard pass their own. +echo '{"repository":{"private":true}}' > "$root/private.json" +run_verify() { + local name="$1"; shift + local d="$root/run-$name"; mkdir -p "$d" + export FAKE_DIR="$d" + out=$(cd "$root/app" && env PATH="$FAKE_PATH" RUNNER_TEMP="${SHARED_TEMP:-$root/temp}" \ + GITHUB_OUTPUT="$d/out" GITHUB_STEP_SUMMARY="$d/summary.md" GITHUB_EVENT_NAME=pull_request \ + PGRUN_API_TOKEN="$TOKEN" PGRUN_IN_API_URL=https://app.pgrun.dev PGRUN_IN_FRAMEWORK=none \ + PGRUN_IN_MIGRATE_COMMAND='bin/migrate' GITHUB_EVENT_PATH="$root/private.json" "$@" "$ci" verify 2>&1) + code=$? + summary=$(cat "$d/summary.md" 2>/dev/null) + calls=$(cat "$d/calls" 2>/dev/null) +} +output() { grep "^$1=" "$root/run-$2/out" | tail -1 | cut -d= -f2-; } +report_of() { output report "$1"; } + +# ---------------------------------------------------------------- verdicts +# verdict_case [VAR=value...] +verdict_case() { + local name="$1" d="$2" want="$3" verdict="$4" blocking="$5" text="$6" ann="$7"; shift 7 + run_verify "$name" FAKE_DOC="$root/$d.json" "$@" + local rep; rep=$(report_of "$name") + if [ "$code" = "$want" ] && [ "$(output verdict "$name")" = "$verdict" ] && [ "$(output blocking "$name")" = "$blocking" ] \ + && grep -qF -- "$text" <<< "$summary" && grep -qE -- "$ann" <<< "$out" && [ -s "$rep" ] && jq -e . "$rep" > /dev/null; then + ok "$name: exit $want, verdict $verdict, blocking $blocking" + else + bad "$name" "exit $code (want $want) verdict=$(output verdict "$name") blocking=$(output blocking "$name") +$out +$summary" + fi +} + +verdict_case pass pass 0 pass false "✅ Success" "verification: pass" +grep -q '^::error' <<< "$out" && bad "pass: no error annotation" "$out" || ok "pass: no error annotation" +grep -qF "| PostgreSQL run | branch \`verify-default-pg\` · on postgres · ready in 1.2s · migration exit 0 in 0.8s |" <<< "$summary" \ + && grep -qF "· compatible |" <<< "$summary" && ok "pass: summary shows both runs" || bad "pass: summary runs" "$summary" +grep -qF "does not detect conflicts between migrations of parallel pull requests" <<< "$summary" && ok "summary states what verification does not cover" || bad "scope note" "$summary" + +verdict_case warning warning 0 warning false "ℹ️ Informational warnings" "^::warning title=PGRun verify::verification branch verify-default-pgx could not be deleted" +grep -qF "\`verify-default-pgx\`: ⚠️ **not deleted** — its TTL (\`1h\`) expires it: 503 from the API" <<< "$summary" && grep -qF "| warning | \`no_pk\` | public.events | table without a primary key |" <<< "$summary" \ + && ok "warning: undeleted verification branch and new lint listed; the step passes" || bad "warning summary" "$summary" + +verdict_case dangerous dangerous 1 dangerous true "⚠️ Dangerous operations" "^::error title=PGRun verify table_rewrite::public.orders: ALTER COLUMN TYPE rewrites" +grep -qF "| critical | \`table_rewrite\` | public.orders | ALTER COLUMN TYPE rewrites the table under an ACCESS EXCLUSIVE lock | add a new column, backfill in batches, then swap |" <<< "$summary" \ + && grep -qF "ℹ️ Informational warnings" <<< "$summary" && grep -qF "| Blocking | yes — dangerous |" <<< "$summary" \ + && grep -qE "^::warning title=PGRun verify index_not_concurrent::" <<< "$out" \ + && ok "dangerous: findings with advice; dangerous and warning both listed; below-threshold finding is a warning" || bad "dangerous summary" "$summary$out" +verdict_case dangerous-noblock dangerous 0 dangerous false "⚠️ Dangerous operations" "^::warning title=PGRun verify table_rewrite::" PGRUN_IN_VERIFY_BLOCK_ON="fail,error" +grep -q '^::error' <<< "$out" && bad "dangerous not in block-on: no error annotation" "$out" || ok "dangerous not in block-on: warnings only" +verdict_case dangerous-failon-warning dangerous 1 dangerous true "fail-on \`warning\`" "^::error title=PGRun verify index_not_concurrent::" PGRUN_IN_VERIFY_FAIL_ON=warning + +verdict_case fail fail 1 fail true "❌ Confirmed failure" "^::error title=PGRun verify::confirmed failure on PostgreSQL: the migration exited 1 on postgres" +grep -qF 'migration exit 1 in 0.8s · error: PG::UndefinedTable: relation "widgets" does not exist' <<< "$summary" && ok "fail: summary shows the migration error" || bad "fail summary" "$summary" +verdict_case fail-blockon-none fail 0 fail false "❌ Confirmed failure" "^::warning title=PGRun verify::confirmed failure" PGRUN_IN_VERIFY_BLOCK_ON=none +grep -qF "block-on \`none\`" <<< "$summary" && ok "block-on none is reported" || bad "block-on none" "$summary" + +verdict_case unsupported unsupported 0 unsupported false "🧪 Unsupported on PGX" "^::warning title=PGRun verify::unsupported on PGX: PGX: unsupported statement" +grep -qF "**not compatible**" <<< "$summary" && ok "unsupported: PGX not compatible in the summary" || bad "unsupported summary" "$summary" +verdict_case unsupported-blocking unsupported 1 unsupported true "🧪 Unsupported on PGX" "^::error title=PGRun verify::unsupported on PGX" PGRUN_IN_VERIFY_BLOCK_ON="fail,dangerous,unsupported,incomplete,error" +verdict_case pgx-unavailable unavailable 0 unsupported false "unavailable: PGX is not enabled for this project" "^::warning title=PGRun verify::unsupported on PGX" + +verdict_case incomplete incomplete 1 incomplete true "❓ Incomplete" "^::error title=PGRun verify::incomplete — the migration was not reviewed: pgbot 0.8.0" +grep -qF "| Schema review | skipped: pgbot 0.8.0 has no \`schema\` command |" <<< "$summary" && ok "incomplete: the skip reason is shown, never a pass" || bad "incomplete summary" "$summary" + +verdict_case error-exit3 error 1 error true "🛠️ Infrastructure error" "^::error title=PGRun verify::infrastructure error: branch verify-default-pg was not ready after 300s" +grep -q "exit 3" <<< "$out" && ok "exit 3 (infrastructure only) is read from the report" || bad "exit 3" "$out" +verdict_case error-noblock error 0 error false "🛠️ Infrastructure error" "^::warning title=PGRun verify::infrastructure error" PGRUN_IN_VERIFY_BLOCK_ON="fail,dangerous" + +# ------------------------------------------------- unreadable report, no CLI +verdict_case unparseable pass 1 error true "pgrun exited 1 without a pgrun-verify 1.x JSON report" "^::error title=PGRun verify::infrastructure error" FAKE_RAW="panic: something went wrong" +jq -e '.source == "pgrun-ci" and .categories == ["error"]' "$(report_of unparseable)" > /dev/null && ok "unparseable: the action writes an error report" || bad "unparseable report" +verdict_case unparseable-noblock pass 0 error false "🛠️ Infrastructure error" "infrastructure error" FAKE_RAW="not json" PGRUN_IN_VERIFY_BLOCK_ON="fail,dangerous,incomplete" +verdict_case two-documents pass 1 error true "without a pgrun-verify 1.x JSON report" "infrastructure error" FAKE_RAW='{"kind":"pgrun-verify"} {"kind":"pgrun-verify"}' FAKE_EXIT=0 +verdict_case wrong-kind pass 1 error true "without a pgrun-verify 1.x JSON report" "infrastructure error" FAKE_RAW='{"kind":"pgbot-report","verdict":"pass","blocking":false,"categories":[]}' FAKE_EXIT=0 +verdict_case future-major pass 1 error true "without a pgrun-verify 1.x JSON report" "infrastructure error" FAKE_RAW='{"kind":"pgrun-verify","version":"2.0.0","verdict":"pass","blocking":false,"categories":["pass"]}' FAKE_EXIT=0 +verdict_case auth-exit2 pass 1 error true "pgrun is not authenticated or not configured (exit 2)" "infrastructure error" FAKE_RAW="" FAKE_EXIT=2 +verdict_case old-cli pass 1 error true "no pgrun CLI with \`bot verify\` on this runner" "infrastructure error" FAKE_OLD=1 +grep -q "bot verify" <<< "$calls" && bad "old CLI: verify never attempted" "$calls" || ok "old CLI: verify never attempted" + +# pgrun not on PATH at all: only system tools and jq. +tools="$root/tools"; mkdir -p "$tools"; ln -sf "$(command -v jq)" "$tools/jq" +run_verify missing PGRUN_IN_VERIFY_BLOCK_ON=fail,dangerous,incomplete,error FAKE_DOC="$root/pass.json" PATH="/usr/bin:/bin:/usr/sbin:/sbin:$tools" +[ "$code" = 1 ] && [ "$(output verdict missing)" = error ] && grep -q "no pgrun CLI with \`bot verify\`" <<< "$summary" && [ -z "$calls" ] \ + && ok "CLI missing: infrastructure error, nothing downloaded unpinned" || bad "CLI missing" "$out$summary" +run_verify missing-noblock PGRUN_IN_VERIFY_BLOCK_ON=fail,dangerous FAKE_DOC="$root/pass.json" PATH="/usr/bin:/bin:/usr/sbin:/sbin:$tools" +[ "$code" = 0 ] && [ "$(output blocking missing-noblock)" = false ] && ok "CLI missing with error not in block-on: reported, not failed" || bad "CLI missing noblock" "$out" + +run_verify pgbot-missing FAKE_DOC="$root/pass.json" FAKE_PGBOT=missing +[ "$code" = 0 ] && grep -q "^bot install" <<< "$calls" && grep -q "^bot verify" <<< "$calls" && ok "pgbot missing: pgrun bot install (pinned, verified by pgrun), then verify" || bad "pgbot install" "$out$calls" + +# ------------------------------------------------------------ argv, token +run_verify args FAKE_DOC="$root/pass.json" PGRUN_IN_PROJECT=shop PGRUN_IN_TTL=6h +argv=$(grep '^bot verify' <<< "$calls") +[ "$argv" = "bot verify shop --json --fail-on critical --block-on fail,dangerous,incomplete,error --ttl 6h --timeout 300s --compare-pgx -- env -u PGRUN_API_TOKEN RAILS_ENV=test bash -c bin/migrate" ] \ + && ok "argv: project, policy, ttl, compare-pgx; migrate-command is the default command" || bad "argv" "$argv" +run_verify args-custom FAKE_DOC="$root/pass.json" PGRUN_IN_VERIFY_COMPARE_PGX=false PGRUN_IN_VERIFY_COMMAND='npx prisma migrate deploy' PGRUN_IN_VERIFY_BLOCK_ON='fail, error' +argv=$(grep '^bot verify' <<< "$calls") +[ "$argv" = "bot verify --json --fail-on critical --block-on fail,error --ttl 1h --timeout 300s -- env -u PGRUN_API_TOKEN RAILS_ENV=test bash -c npx prisma migrate deploy" ] \ + && ok "argv: verify-command, no compare-pgx, block-on spaces trimmed" || bad "argv custom" "$argv" + +run_verify token FAKE_DOC="$root/dangerous.json" FAKE_LEAK=1 FAKE_RUN_MIGRATION=1 \ + PGRUN_IN_VERIFY_COMMAND='echo "migration sees token: ${PGRUN_API_TOKEN:-none}"; echo "url: $DATABASE_URL"; echo "::error::injected by the migration"' +all="$out$summary$calls$(cat "$(report_of token)")" +if grep -qF "$TOKEN" <<< "$all"; then bad "token never in argv, logs, summary or report" "$all"; else ok "token never in argv, logs, summary or report"; fi +grep -q "token_in_env=yes" "$root/run-token/env" && grep -q "migration sees token: none" <<< "$out" && ok "pgrun gets the token by env; the migration does not" || bad "token env" "$out" +grep -q "s3cretpw\|postgres://" <<< "$out$summary" && bad "no branch URL in logs or summary" "$out" || ok "no branch URL in logs or summary" +awk '/^::stop-commands::/ { s = 1 } /^::error::injected/ { if (!s) bad = 1 } /^::[0-9a-f]+::$/ { s = 0 } END { exit bad }' <<< "$out" && grep -q '^::stop-commands::' <<< "$out" \ + && ok "migration output cannot issue workflow commands" || bad "stop-commands" "$out" + +# ---------------------------------------------------------------- refusals +run_verify no-token FAKE_DOC="$root/pass.json" PGRUN_API_TOKEN= +[ "$code" = 1 ] && grep -q "no PGRun token" <<< "$out" && [ -z "$calls" ] && ok "no token: refused before pgrun runs" || bad "no token" "$out" +run_verify prt FAKE_DOC="$root/pass.json" GITHUB_EVENT_NAME=pull_request_target +[ "$code" = 1 ] && grep -q "refusing to run on pull_request_target" <<< "$out" && [ -z "$calls" ] && ok "pull_request_target: refused" || bad "prt" "$out" +echo '{"repository":{"private":false}}' > "$root/public.json" +run_verify public FAKE_DOC="$root/pass.json" GITHUB_EVENT_PATH="$root/public.json" +[ "$code" = 1 ] && grep -q "this repository is public" <<< "$out" && [ -z "$calls" ] && ok "public repository: refused" || bad "public" "$out" +run_verify public-allowed FAKE_DOC="$root/pass.json" GITHUB_EVENT_PATH="$root/public.json" PGRUN_IN_ALLOW_PUBLIC_REPOSITORY=true +[ "$code" = 0 ] && ok "public repository with allow-public-repository: runs" || bad "public allowed" "$out" +run_verify bad-failon FAKE_DOC="$root/pass.json" PGRUN_IN_VERIFY_FAIL_ON=high +[ "$code" = 1 ] && grep -q "verify-fail-on must be" <<< "$out" && [ -z "$calls" ] && ok "invalid verify-fail-on: refused" || bad "bad fail-on" "$out" +run_verify bad-blockon FAKE_DOC="$root/pass.json" PGRUN_IN_VERIFY_BLOCK_ON="fail,oops" +[ "$code" = 1 ] && grep -q "unknown category oops" <<< "$out" && [ -z "$calls" ] && ok "invalid verify-block-on: refused" || bad "bad block-on" "$out" +run_verify no-command FAKE_DOC="$root/pass.json" PGRUN_IN_MIGRATE_COMMAND= +[ "$code" = 1 ] && grep -q "no migration command to verify" <<< "$out" && ok "no command: refused" || bad "no command" "$out" +[ ! -e "$root/temp/pgrun-ci/state" ] && ok "verify never writes the run step's state (its cleanup prefix stays the run's own)" || bad "state touched" "$(cat "$root/temp/pgrun-ci/state")" + +# -------------------------------------------------------------- concurrency +# N runs at once on ONE runner temp dir (the worst case: one job), each its own +# project, verdict and timing. Reports, outputs and cleanup must stay apart. +N=8; verdicts=(pass dangerous warning fail unsupported incomplete error pass) +export SHARED_TEMP="$root/shared" +for i in $(seq 1 "$N"); do + ( run_verify "conc-$i" FAKE_DOC="$root/${verdicts[$((i - 1))]}.json" PGRUN_IN_PROJECT="proj$i" FAKE_SLEEP="0.$((RANDOM % 9))" + echo "$code" > "$root/run-conc-$i/code" ) & +done +wait +unset SHARED_TEMP +reports=(); cerr="" +for i in $(seq 1 "$N"); do + v="${verdicts[$((i - 1))]}"; rep=$(report_of "conc-$i"); reports+=("$rep") + s=$(cat "$root/run-conc-$i/summary.md") + [ "$(jq -r .project "$rep")" = "proj$i" ] || cerr+="run $i: report project $(jq -r .project "$rep"); " + [ "$(output verdict "conc-$i")" = "$v" ] || cerr+="run $i: verdict $(output verdict "conc-$i") want $v; " + [ "$(jq -r '[.cleanup[].branch] | join(" ")' "$rep")" = "verify-proj$i-pg verify-proj$i-pgx" ] || cerr+="run $i: cleanup $(jq -c .cleanup "$rep"); " + grep -q "verify-proj$i-pg" <<< "$s" || cerr+="run $i: own branch missing from summary; " + for j in $(seq 1 "$N"); do [ "$j" = "$i" ] && continue; grep -q "proj$j\b" <<< "$s" && cerr+="run $i: summary mentions proj$j; "; done + case "$v" in pass|warning|unsupported) want=0 ;; *) want=1 ;; esac + [ "$(cat "$root/run-conc-$i/code")" = "$want" ] || cerr+="run $i: exit $(cat "$root/run-conc-$i/code") want $want; " +done +[ "$(printf '%s\n' "${reports[@]}" | sort -u | wc -l | tr -d ' ')" = "$N" ] || cerr+="report paths collide: ${reports[*]}; " +[ -z "$cerr" ] && ok "concurrency: $N parallel runs on one runner keep their reports, outputs, verdicts and cleanup apart" || bad "concurrency" "$cerr" + +# ---------------------------------------------- verify: false is a no-op +python3 - "$here/../action.yml" <<'PY' && ok "action.yml: verify defaults to false and gates the only step that runs verify" || bad "action.yml verify gating" +import sys, yaml +a = yaml.safe_load(open(sys.argv[1])) +assert a["inputs"]["verify"]["default"] == "false" +steps = a["runs"]["steps"] +v = [s for s in steps if "verify" in s.get("run", "") and "pgrun-ci\" verify" in s["run"]] +assert len(v) == 1 and v[0]["if"] == "inputs.verify == 'true'", v +assert all("VERIFY" not in k for s in steps if s is not v[0] for k in (s.get("env") or {})) +PY + +echo "verify tests: $pass passed, $fail failed" +[ "$fail" -eq 0 ]